text:
package cloud_controller_ng
/*
* File Generated by enaml generator
* !!! Please do not edit this file !!!
*/
type ResourcePool struct {

	/*FogAwsStorageOptions - Descr: Storage options passed to fog for aws blobstores. See http://docs.cloudfoundry.org/deploying/common/cc-blobstore-config.html#fog-aws-sse for example configuration. Default: map[]
*/
	FogAwsStorageOptions interface{} `yaml:"fog_aws_storage_options,omitempty"`

	/*Cdn - Descr: Private key for signing download URIs Default:
*/
	Cdn *ResourcePoolCdn `yaml:"cdn,omitempty"`

	/*ResourceDirectoryKey - Descr: Directory (bucket) used store app resources.  It does not have be pre-created. Default: cc-resources
*/
	ResourceDirectoryKey interface{} `yaml:"resource_directory_key,omitempty"`

	/*MinimumSize - Descr: Minimum size of a resource to add to the pool Default: 65536
*/
	MinimumSize interface{} `yaml:"minimum_size,omitempty"`

	/*MaximumSize - Descr: Maximum size of a resource to add to the pool Default: 536870912
*/
	MaximumSize interface{} `yaml:"maximum_size,omitempty"`

	/*BlobstoreType - Descr: The type of blobstore backing to use. Valid values: ['fog', 'webdav'] Default: fog
*/
	BlobstoreType interface{} `yaml:"blobstore_type,omitempty"`

	/*FogConnection - Descr: Fog connection hash Default: <nil>
*/
	FogConnection interface{} `yaml:"fog_connection,omitempty"`

	/*WebdavConfig - Descr: The basic auth user that CC uses to connect to the admin endpoint on webdav Default:
*/
	WebdavConfig *ResourcePoolWebdavConfig `yaml:"webdav_config,omitempty"`

}


text:
using MQTTnet.Client;
using MQTTnet.Server;
using System;
using System.Threading.Tasks;

namespace MQTTnet.Core.Tests
{
    public static class TestServerExtensions
    {
        /// <summary>
        /// publishes a message with a client and waits in the server until a message with the same topic is received
        /// </summary>
        /// <returns></returns>
        public static async Task PublishAndWaitForAsync(this IMqttClient client, IMqttServer server, MqttApplicationMessage message)
        {
            var tcs = new TaskCompletionSource<object>();

            void Handler(object sender, MqttApplicationMessageReceivedEventArgs args)
            {
                if (args.ApplicationMessage.Topic == message.Topic)
                {
                    tcs.SetResult(true);
                }
            }

            server.ApplicationMessageReceived += Handler;

            try
            {
                await client.PublishAsync(message).ConfigureAwait(false);
                await tcs.Task.ConfigureAwait(false);
            }
            finally
            {
                server.ApplicationMessageReceived -= Handler;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: export { InsertPage24 as default } from "../../";


text:
"""Basic http server for tests to simulate PyPI or custom indexes
"""

import os
import time
import threading
import http.server
import urllib.parse
import urllib.request

class IndexServer(http.server.HTTPServer):
    """Basic single-threaded http server simulating a package index

    You can use this server in unittest like this::
        s = IndexServer()
        s.start()
        index_url = s.base_url() + 'mytestindex'
        # do some test requests to the index
        # The index files should be located in setuptools/tests/indexes
        s.stop()
    """

    def __init__(
            self, server_address=('', 0),
            RequestHandlerClass=http.server.SimpleHTTPRequestHandler):
        http.server.HTTPServer.__init__(
            self, server_address, RequestHandlerClass)
        self._run = True

    def start(self):
        self.thread = threading.Thread(target=self.serve_forever)
        self.thread.start()

    def stop(self):
        "Stop the server"

        # Let the server finish the last request and wait for a new one.
        time.sleep(0.1)

        self.shutdown()
        self.thread.join()
        self.socket.close()

    def base_url(self):
        port = self.server_port
        return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port

class RequestRecorder(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        requests = vars(self.server).setdefault('requests', [])
        requests.append(self)
        self.send_response(200, 'OK')

class MockServer(http.server.HTTPServer, threading.Thread):
    """
    A simple HTTP Server that records the requests made to it.
    """

    def __init__(
            self, server_address=('', 0),
            RequestHandlerClass=RequestRecorder):
        http.server.HTTPServer.__init__(
            self, server_address, RequestHandlerClass)
        threading.Thread.__init__(self)
        self.daemon = True
        self.requests = []

    def run(self):
        self.serve_forever()

    @property
    def netloc(self):
        return 'localhost:%s' % self.server_port

    @property
    def url(self):
        return 'http://%s/' % self.netloc

def path_to_url(path, authority=None):
    """ Convert a path to a file: URL. """
    path = os.path.normpath(os.path.abspath(path))
    base = 'file:'
    if authority is not None:
        base += '//' + authority
    url = urllib.parse.urljoin(base, urllib.request.pathname2url(path))
    return url


text:
<?php

namespace ENC\Bundle\ApplicationServiceAbstractBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class ApplicationServicePass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        // Get Suscribers
        $subscribersIDs = array_keys( $container->findTaggedServiceIds('application_service_abstract.event_subscriber'));
        $eventDispatcherDefinition = $container->getDefinition('application_service_abstract.event_dispatcher');

        foreach ($subscribersIDs as $subscriberID) {
            $eventDispatcherDefinition->addMethodCall('addSubscriber', array(new Reference($subscriberID)));
        }
    }
}


text:
"use strict";

ui.jqFiles = dom.empty;

ui.listUpdate = function() {
	ui.jqFiles = dom.playlistList.children();
	return ui;
};

ui.indexFile = function() {
	dom.playlistNavIndex.text( 1 + ui.jqFiles.index( ui.jqFileSelected ) );
	return ui;
};

ui.totalFiles = function() {
	dom.playlistNavTotal.text( ui.jqFiles.length );
	return ui;
};


text:
import DS from 'ember-data';

export default DS.Model.extend({

	value:DS.attr('number',{defaultValue:null}),

	bars: DS.hasMany('acceptance.lists.embedded-updates.bar',{async:true}),

});


text:
package org.apache.carbondata.core.scan.expression;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.carbondata.core.metadata.datatype.DataType;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.scan.expression.exception.FilterIllegalMemberException;

import org.junit.BeforeClass;
import org.junit.Test;

import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.pentaho.di.core.util.Assert.assertFalse;
import static org.pentaho.di.core.util.Assert.assertNull;

public class ExpressionResultTest {
  private static final double DELTA = 1e-15;
  private static ExpressionResult expressionResult;

  @BeforeClass public static void setUp() {
    expressionResult = new ExpressionResult(DataType.INT, null);
  }

  @Test public void testGetIntForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getInt());
  }

  @Test public void testGetIntForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "5");
    int actualValue = expressionResultForString.getInt();
    int expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetIntForNumberFormatException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "FOOBAR");
    expressionResultForString.getInt();
  }

  @Test public void testGetIntForDouble() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.DOUBLE, 5.0);
    int actualValue = expressionResultForDouble.getInt();
    int expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetIntForInt() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.INT, 5);
    int actualValue = expressionResultForInt.getInt();
    int expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetIntForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForInt.getInt();
  }

  @Test(expected = FilterIllegalMemberException.class) public void testGetIntForClassCastException()
      throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.INT, "STRING");
    expressionResultForInt.getInt();
  }

  @Test public void testGetShortForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getShort());
  }

  @Test public void testGetShortForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "5");
    short actualValue = expressionResultForString.getShort();
    short expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetShortForNumberFormatException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "FOOBAR");
    expressionResultForString.getShort();
  }

  @Test public void testGetShortForDouble() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.DOUBLE, 5.0);
    short actualValue = expressionResultForDouble.getShort();
    short expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetShortForInt() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.INT, 5);
    short actualValue = expressionResultForInt.getShort();
    short expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetShortForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForInt.getShort();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetShortForClassCastException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.INT, "STRING");
    expressionResultForInt.getShort();
  }

  @Test public void testGetStringForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getString());
  }

  @Test public void testGetStringForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "5");
    String actualValue = expressionResultForString.getString();
    String expectedValue = "5";
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetStringForException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.INT, "5");
    String actualValue = expressionResultForString.getString();
    String expectedValue = "5";
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetDoubleForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getDouble());
  }

  @Test public void testGetDoubleForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "5");
    double actualValue = expressionResultForString.getDouble();
    double expectedValue = 5;
    assertEquals(expectedValue, actualValue, DELTA);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetDoubleForNumberFormatException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "FOOBAR");
    expressionResultForString.getDouble();
  }

  @Test public void testGetDoubleForInt() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.INT, 5);
    double actualValue = expressionResultForDouble.getDouble();
    double expectedValue = 5.0;
    assertEquals(expectedValue, actualValue, DELTA);
  }

  @Test public void testGetDoubleForDouble() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.DOUBLE, 5.0);
    double actualValue = expressionResultForDouble.getDouble();
    double expectedValue = 5;
    assertEquals(expectedValue, actualValue, DELTA);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetDoubleForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForDouble.getDouble();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetDoubleForClassCastException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.DOUBLE, "STRING");
    expressionResultForDouble.getDouble();
  }

  @Test public void testGetLongForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getLong());
  }

  @Test public void testGetLongForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "5");
    long actualValue = expressionResultForString.getLong();
    long expectedValue = 5;
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetLongForNumberFormatException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "FOOBAR");
    expressionResultForString.getLong();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetLongForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForLong = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForLong.getLong();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetLongForClassCastException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForLong = new ExpressionResult(DataType.LONG, "STRING");
    expressionResultForLong.getLong();
  }

  @Test public void testGetDecimalForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getDecimal());
  }

  @Test public void testGetDecimalForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "5");
    BigDecimal actualValue = expressionResultForString.getDecimal();
    BigDecimal expectedValue = new BigDecimal(5.00);
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetDecimalForNumberFormatException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "FOOBAR");
    expressionResultForString.getDecimal();
  }

  @Test public void testGetDecimalForInt() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForInt = new ExpressionResult(DataType.INT, 5);
    BigDecimal actualValue = expressionResultForInt.getDecimal();
    BigDecimal expectedValue = new BigDecimal(5);
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetDecimalForDouble() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDouble = new ExpressionResult(DataType.DOUBLE, 5);
    BigDecimal actualValue = expressionResultForDouble.getDecimal();
    BigDecimal expectedValue = new BigDecimal(5);
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetDecimalForDecimal() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForDecimal = new ExpressionResult(DataType.DECIMAL, 5);
    BigDecimal actualValue = expressionResultForDecimal.getDecimal();
    BigDecimal expectedValue = new BigDecimal(5);
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetDecimalForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForFloat = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForFloat.getDecimal();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetDecimalForClassCastException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForException = new ExpressionResult(DataType.LONG, "STRING");
    expressionResultForException.getDecimal();
  }

  @Test public void testGetTimeForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getTime());
  }

  @Test public void testGetTimeForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString =
        new ExpressionResult(DataType.STRING, "2016-11-07 10:15:09");
    long actualValue = expressionResultForString.getTime();
    long expectedValue = getTime("2016-11-07 10:15:09");
    assertEquals(expectedValue, actualValue);
  }

  public Long getTime(String value) throws FilterIllegalMemberException {
    if (value == null) {
      return null;
    }
    SimpleDateFormat parser =
        new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP_DEFAULT_FORMAT);
    Date dateToStr;
    try {
      dateToStr = parser.parse(value.toString());
      return dateToStr.getTime();
    } catch (ParseException e) {
      throw new FilterIllegalMemberException("Cannot convert value to Time/Long type value");
    }
  }

  @Test(expected = FilterIllegalMemberException.class) public void testGetTimeForParseException()
      throws FilterIllegalMemberException {
    ExpressionResult expressionResultForParseException =
        new ExpressionResult(DataType.STRING, "FOOBAR");
    expressionResultForParseException.getTime();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetTimeForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForFloat = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForFloat.getTime();
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetTimeForClassCastException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForException = new ExpressionResult(DataType.LONG, "STRING");
    expressionResultForException.getTime();
  }

  @Test public void testGetBooleanForNull() throws FilterIllegalMemberException {
    assertNull(expressionResult.getBoolean());
  }

  @Test public void testGetBooleanForString() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.STRING, "true");
    boolean actualValue = expressionResultForString.getBoolean();
    boolean expectedValue = true;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetBooleanForBoolean() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForString = new ExpressionResult(DataType.BOOLEAN, "true");
    boolean actualValue = expressionResultForString.getBoolean();
    boolean expectedValue = true;
    assertEquals(expectedValue, actualValue);
  }

  @Test(expected = FilterIllegalMemberException.class)
  public void testGetBooleanForIllegalMemberException() throws FilterIllegalMemberException {
    ExpressionResult expressionResultForFloat = new ExpressionResult(DataType.FLOAT, 25.36);
    expressionResultForFloat.getBoolean();
  }

  @Test public void testGetList() {
    ExpressionResult obj = new ExpressionResult(DataType.STRING, "test");
    List<ExpressionResult> actualValue = obj.getList();
    List<ExpressionResult> expected = new ArrayList<>();
    expected.add(0, obj);
    assertEquals(expected, actualValue);
  }

  @Test public void testHashCode() {
    ExpressionResult obj = new ExpressionResult(DataType.INT, 1);
    int actualValue = obj.hashCode();
    int expectedValue = 80;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testHashCodeForNull() {
    ExpressionResult obj = new ExpressionResult(null);
    int actualValue = obj.hashCode();
    int expectedValue = 31;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testHashCodeForNul() {
    ExpressionResult obj = new ExpressionResult(DataType.DOUBLE, null);
    int actualValue = obj.hashCode();
    int expectedValue = 31;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testEqualsForObjNOtInstanceOfExpressionResult() {
    ExpressionResult expressionResult = new ExpressionResult(DataType.INT, 5);
    List obj = new ArrayList();
    obj.add(0, 0);
    obj.add(1, 1);
    boolean result = expressionResult.equals(obj);
    assertFalse(result);
  }

  @Test public void testEqualsForString() {
    ExpressionResult expressionResult = new ExpressionResult(DataType.STRING, "5");
    ExpressionResult objToCompare = new ExpressionResult(DataType.STRING, "6");
    boolean result = expressionResult.equals(objToCompare);
    assertFalse(result);
  }

  @Test public void testEqualsForShort() {
    ExpressionResult expressionResult = new ExpressionResult(DataType.SHORT, 5);
    ExpressionResult objToCompare = new ExpressionResult(DataType.SHORT, 6);
    boolean result = expressionResult.equals(objToCompare);
    assertFalse(result);
  }

  @Test public void testEqualsForInt() {
    ExpressionResult expressionResult = new ExpressionResult(DataType.INT, 5);
    ExpressionResult objToCompare = new ExpressionResult(DataType.INT, 6);
    boolean result = expressionResult.equals(objToCompare);
    assertFalse(result);
  }

  @Test public void testEqualsForDecimal() {
    ExpressionResult expressionResult = new ExpressionResult(DataType.DECIMAL, 5);
    ExpressionResult objToCompare = new ExpressionResult(DataType.DECIMAL, 6);
    boolean result = expressionResult.equals(objToCompare);
    assertFalse(result);
  }

  @Test public void testEqualsForDouble() {
    ExpressionResult expressionResult = new ExpressionResult(DataType.DOUBLE, 5.89);
    ExpressionResult objToCompare = new ExpressionResult(DataType.DOUBLE, 6.90);
    boolean result = expressionResult.equals(objToCompare);
    assertFalse(result);
  }

  @Test public void testEqualsForException() {
    ExpressionResult expressionResult =
        new ExpressionResult(DataType.TIMESTAMP, "2016-11-07 10:15:09");
    ExpressionResult objToCompare = new ExpressionResult(DataType.DOUBLE, "2016-11-06 10:15:09");
    boolean result = expressionResult.equals(objToCompare);
    assertFalse(result);
  }

  @Test public void testEqualsForLongAndTimeStamp() {
    ExpressionResult expressionResult =
        new ExpressionResult(DataType.TIMESTAMP, new Long(11111111111111111L));
    ExpressionResult objToCompare =
        new ExpressionResult(DataType.LONG, new Long(11111111111111111L));
    boolean result = expressionResult.equals(objToCompare);
    assertTrue(result);
  }

  @Test public void compareToForInt() {
    ExpressionResult obj = new ExpressionResult(DataType.INT, 5);
    ExpressionResult expressionResult = new ExpressionResult(DataType.INT, 6);
    int actualValue = expressionResult.compareTo(obj);
    int expectedValue = 1;
    assertEquals(expectedValue, actualValue);

  }

  @Test public void compareToForDecimal() {
    ExpressionResult obj = new ExpressionResult(DataType.DECIMAL, 5);
    ExpressionResult expressionResult = new ExpressionResult(DataType.DECIMAL, 6);
    int actualValue = expressionResult.compareTo(obj);
    int expectedValue = 1;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void compareToForException() {
    ExpressionResult obj = new ExpressionResult(DataType.INT, 5);
    ExpressionResult expressionResult = new ExpressionResult(DataType.DECIMAL, 6);
    int actualValue = expressionResult.compareTo(obj);
    int expectedValue = -1;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void compareToForTimestamp() {
    ExpressionResult obj = new ExpressionResult(DataType.TIMESTAMP, "2016-11-07 10:15:09");
    ExpressionResult expressionResult =
        new ExpressionResult(DataType.TIMESTAMP, "2016-11-07 10:15:09");
    int actualValue = expressionResult.compareTo(obj);
    int expectedValue = 0;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testGetListAsString() throws FilterIllegalMemberException {
    ExpressionResult obj = new ExpressionResult(DataType.INT, 6);
    List<String> actualValue = obj.getListAsString();
    List<String> expectedValue = new ArrayList<>();
    expectedValue.add("6");
    assertThat(actualValue, is(equalTo(expectedValue)));
  }

  @Test public void compareToForString() {
    ExpressionResult obj = new ExpressionResult(DataType.STRING, "2016");
    ExpressionResult expressionResult = new ExpressionResult(DataType.STRING, "2016");
    int actualValue = expressionResult.compareTo(obj);
    int expectedValue = 0;
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testIsNullForNull() {
    ExpressionResult obj = new ExpressionResult(DataType.STRING, null);
    boolean actualValue = obj.isNull();
    assertTrue(actualValue);
  }

  @Test public void testIsNullForNotNull() {
    ExpressionResult obj = new ExpressionResult(DataType.STRING, "test");
    boolean actualValue = obj.isNull();
    assertFalse(actualValue);
  }
}


text:
/*
  Extend Leaflet's TileLayer, which has a fixed template URL string,
  to accept a user-defined function `urlFun` instead, which takes an
  object as input and must return a ready-to-use URL string.

  Example of use: ./tilelayer_urlfun.html - A map is defined only in
  certain parts of the world. Where the map is defined, `urlFun`
  returns an URL.  Where the map is not defined, `urlFun` returns an
  empty string.

  (c) 2015 Alpstein Tourismus GmbH & CO KG

  http://www.outdooractive.com
  guillaume.lathoud@outdooractive.com
*/

/*global L*/

(function () {

    var TL = L.TileLayer;

    L.TileLayerUrlFun = TL.extend({

        initialize : function ( /*function: <cfg object> => <string>*/urlFun, /*?object?*/options )
        {
            this._oaUrlFun  = urlFun;
            this._oaOptions = options;

            TL.prototype.initialize.call( this, null, options );
        }

        , getTileUrl : function ( coords )
        {
            var cfg = _oaGetUrlCfg.call( this, coords, this._oaOptions );
            return this._oaUrlFun( cfg );
        }

    });

    L.tileLayerUrlFun = function ( urlFun, options ) {
        return new L.TileLayerUrlFun( urlFun, options );
    };

    // --- Details

    var _UNDERLAYER = '_UL', _SEP = '\x1F';
    function _oaGetUrlCfg( coords, options )
    {
        // Include the logic of the `TileLayer.getTileUrl`
        // implementation without copying the code.

        var _underLayer = this[ _UNDERLAYER ]  ||  (
            this[ _UNDERLAYER ] =
                L.tileLayer( [ '{s}', '{x}', '{y}', '{z}' ].join( _SEP )
                             , options
                           )
        )

        ,   arr = _underLayer.getTileUrl( coords ).split( _SEP )
        ,     i = 0
        ,   ret = { s : arr[ i++ ], x : +arr[ i++ ], y : +arr[ i++ ], z : +arr[ i++ ] }
        ;

        // Copy the remaining information (e.g. `id` in the
        // `main` example).
        for (var k in options) { if (!(k in ret)) {
            ret[ k ] = options[ k ];
        }}

        return ret;
    }

})();


text:
Push-Location $PSScriptRoot

.\start_rabbit.ps1

Pop-Location

docker inspect func-resty > $null 2> $null

if (! $?) {
       echo "Starting OpenResty"

       docker run -d -p 8680:80 --link func-rabbit --restart always --hostname func-resty --name func-resty funcatron/frontend:latest
       }


text:
'use strict';

import nls = require('vs/nls');
import platform = require('vs/base/common/platform');
import winjs = require('vs/base/common/winjs.base');
import lifecycle = require('vs/base/common/lifecycle');
import types = require('vs/base/common/types');
import actions = require('vs/base/common/actions');
import errors = require('vs/base/common/errors');
import mime = require('vs/base/common/mime');
import paths = require('vs/base/common/paths');
import ee = require('vs/base/common/eventEmitter');
import wbevents = require('vs/workbench/browser/events');
import WorkbenchEditorCommon = require('vs/workbench/common/editor');
import git = require('vs/workbench/parts/git/common/git');
import model = require('vs/workbench/parts/git/common/gitModel');
import giteditorinputs = require('vs/workbench/parts/git/browser/gitEditorInputs');
import operations = require('vs/workbench/parts/git/browser/gitOperations');
import filesCommon = require('vs/workbench/parts/files/common/files');
import { IFileService, EventType as FileEventType, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
import async = require('vs/base/common/async');
import severity from 'vs/base/common/severity';
import {IOutputService} from 'vs/workbench/parts/output/common/output';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IConfigurationService, IConfigurationServiceEvent, ConfigurationServiceEventTypes} from 'vs/platform/configuration/common/configuration';
import {IEventService} from 'vs/platform/event/common/event';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService} from 'vs/platform/message/common/message';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';

function toReadablePath(path: string): string {
	if (!platform.isWindows) {
		return path;
	}

	return path.replace(/\//g, '\\');
}

class EditorInputCache
{
	private gitService: git.IGitService;
	private fileService: IFileService;
	private eventService: IEventService;
	private instantiationService: IInstantiationService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private cache: { [key: string]: winjs.TPromise<WorkbenchEditorCommon.EditorInput> };
	private toDispose: lifecycle.IDisposable[];

	constructor(gitService: git.IGitService, // gitService passed as argument, not by injection
		@IInstantiationService instantiationService: IInstantiationService,
		@IFileService fileService: IFileService,
		@IEventService eventService: IEventService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IWorkspaceContextService contextService: IWorkspaceContextService
	) {
		this.instantiationService = instantiationService;
		this.fileService = fileService;
		this.eventService = eventService;
		this.editorService = editorService;
		this.contextService = contextService;

		this.gitService = gitService;

		this.cache = {};
		this.toDispose = [];

		this.toDispose.push(this.gitService.getModel().addListener2('fileStatus:dispose', (fileStatus: git.IFileStatus) => this.onFileStatusDispose(fileStatus)));
	}

	public getInput(status: git.IFileStatus): winjs.TPromise<WorkbenchEditorCommon.EditorInput> {
		var result = this.cache[status.getId()];

		if (result) {
			return result;
		}

		result = this.createInput(status);
		this.cache[status.getId()] = result;
		return result;
	}

	private createInput(status: git.IFileStatus): winjs.TPromise<WorkbenchEditorCommon.EditorInput> {
		return winjs.TPromise.join<WorkbenchEditorCommon.EditorInput>([this.createLeftInput(status), this.createRightInput(status)]).then((result) => {
			var leftInput = result[0];
			var rightInput = result[1];

			var fileSegment: string;
			var folderSegment: string;

			if (status.getStatus() === git.Status.INDEX_RENAMED) {
				let pathComponents = status.getRename().split('/');
				fileSegment = pathComponents[pathComponents.length - 1];
				folderSegment = toReadablePath(pathComponents.slice(0, pathComponents.length - 1).join('/'));
			} else {
				let pathComponents = status.getPathComponents();
				fileSegment = pathComponents[pathComponents.length - 1];
				folderSegment = toReadablePath(pathComponents.slice(0, pathComponents.length - 1).join('/'));
			}

			if (!leftInput) {
				if (!rightInput) {
					var error = new Error(nls.localize('cantOpen', "Can't open this git resource."));
					(<git.IGitServiceError> error).gitErrorCode = git.GitErrorCodes.CantOpenResource;
					return winjs.Promise.wrapError(error);
				}

				return winjs.Promise.as(rightInput);
			}

			switch (status.getStatus()) {
				case git.Status.INDEX_MODIFIED:
					return winjs.Promise.as(new giteditorinputs.GitIndexDiffEditorInput(fileSegment, nls.localize('gitIndexChanges', "{0} - Changes on index", folderSegment), leftInput, rightInput, status));
				case git.Status.INDEX_RENAMED:
					return winjs.Promise.as(new giteditorinputs.GitIndexDiffEditorInput(fileSegment, nls.localize('gitIndexChangesRenamed', "{0} - Renamed - Changes on index", folderSegment), leftInput, rightInput, status));
				case git.Status.MODIFIED:
					return winjs.Promise.as(new giteditorinputs.GitWorkingTreeDiffEditorInput(fileSegment, nls.localize('workingTreeChanges', "{0} - Changes on working tree", folderSegment), leftInput, rightInput, status));
				default:
					return winjs.Promise.as(new giteditorinputs.GitDiffEditorInput(fileSegment, nls.localize('gitMergeChanges', "{0} - Merge changes", folderSegment), leftInput, rightInput, status));
			}
		}).then((editorInput) => {
			return editorInput;
		}, (errs) => {
			return winjs.Promise.wrapError(types.isArray(errs) ? errs[0] || errs[1] : errs);
		});
	}

	private createLeftInput(status: git.IFileStatus): winjs.Promise {
		var path = status.getPath();
		var model = this.gitService.getModel();

		switch (status.getStatus()) {
			case git.Status.INDEX_MODIFIED:
			case git.Status.INDEX_RENAMED:
				return this.gitService.show(path, status, 'HEAD', status.getMimetype());

			case git.Status.MODIFIED:
				var indexStatus = model.getStatus().find(path, git.StatusType.INDEX);

				if (indexStatus && indexStatus.getStatus() === git.Status.INDEX_RENAMED) {
					return this.gitService.show(indexStatus.getRename(), status, '~', status.getMimetype());
				}

				if (indexStatus) {
					return this.gitService.show(path, status, '~', status.getMimetype());
				}

				return this.gitService.show(path, status, 'HEAD', status.getMimetype());

			default:
				return winjs.Promise.as(null);
		}
	}

	private createRightInput(status: git.IFileStatus): winjs.Promise {
		var path = status.getPath();
		var resource = this.contextService.toResource(path);
		var model = this.gitService.getModel();

		switch (status.getStatus()) {
			case git.Status.INDEX_MODIFIED:
			case git.Status.INDEX_ADDED:
			case git.Status.INDEX_COPIED:
				return this.gitService.show(path, status, '~', status.getMimetype());

			case git.Status.INDEX_RENAMED:
				return this.gitService.show(status.getRename(), status, '~', status.getMimetype());

			case git.Status.INDEX_DELETED:
			case git.Status.DELETED:
				return this.gitService.show(path, status, 'HEAD', status.getMimetype());

			case git.Status.MODIFIED:
			case git.Status.UNTRACKED:
			case git.Status.IGNORED:
				var indexStatus = model.getStatus().find(path, git.StatusType.INDEX);

				if (indexStatus && indexStatus.getStatus() === git.Status.INDEX_RENAMED) {
					return this.editorService.inputToType({ resource: this.contextService.toResource(indexStatus.getRename()) });
				}

				return this.editorService.inputToType({ resource: resource });

			case git.Status.BOTH_MODIFIED:
				return this.editorService.inputToType({ resource: resource });

			default:
				return winjs.Promise.as(null);
		}
	}

	private onFileStatusDispose(fileStatus: git.IFileStatus): void {
		var id = fileStatus.getId();
		var editorInputPromise = this.cache[id];

		if (editorInputPromise) {
			editorInputPromise.done((editorInput) => { this.eventuallyDispose(editorInput); });
			delete this.cache[id];
		}
	}

	/**
	 * If the disposed status is the same as this input's status, we must try to dispose the input.
	 * But we should not do it while the input is still open. This method will eventually call dispose
	 * when the editor input goes out of the visible editors.
	 */
	private eventuallyDispose(editorInput: WorkbenchEditorCommon.EditorInput): void {
		if (!this.maybeDispose(editorInput)) {
			var listener = this.eventService.addListener2(wbevents.EventType.EDITOR_INPUT_CHANGED, () => {
				if (this.maybeDispose(editorInput)) {
					listener.dispose();
				}
			});
		}
	}

	private maybeDispose(editorInput: WorkbenchEditorCommon.EditorInput): boolean {
		if (!this.editorService.getVisibleEditors().some((editor) => editor.input && editor.input.matches(editorInput))) {
			editorInput.dispose();
			return true;
		}

		return false;
	}

	public dispose(): void {
		Object.keys(this.cache).forEach(key => {
			this.cache[key].done((editorInput) => { editorInput.dispose(); });
			delete this.cache[key];
		});

		this.toDispose = lifecycle.disposeAll(this.toDispose);
	}
}

export class AutoFetcher implements git.IAutoFetcher, lifecycle.IDisposable
{
	private static MIN_TIMEOUT = 2 * 60 * 1000; // every two minutes
	private static MAX_TIMEOUT = 5 * 60 * 1000; // every five minutes

	private _state: git.AutoFetcherState;
	private gitService: git.IGitService;
	private eventService: IEventService;
	private messageService: IMessageService;
	private configurationService: IConfigurationService;
	private instantiationService: IInstantiationService;
	private currentRequest: winjs.Promise;
	private timeout: number;
	private toDispose: lifecycle.IDisposable[];
	private gitServiceStateDisposable: lifecycle.IDisposable;

	constructor(gitService: git.IGitService, // gitService passed as argument, not by injection
		@IEventService eventService: IEventService,
		@IMessageService messageService: IMessageService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IConfigurationService configurationService: IConfigurationService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		this._state = git.AutoFetcherState.Disabled;
		this.gitService = gitService;
		this.eventService = eventService;
		this.messageService = messageService;
		this.configurationService = configurationService;
		this.instantiationService = instantiationService;
		this.currentRequest = null;
		this.timeout = AutoFetcher.MIN_TIMEOUT;

		this.toDispose = [];
		this.toDispose.push(this.configurationService.addListener2(ConfigurationServiceEventTypes.UPDATED, e => this.onConfiguration(e.config.git)));
		configurationService.loadConfiguration('git').done(c => this.onConfiguration(c));
	}

	public get state(): git.AutoFetcherState {
		return this._state;
	}

	private onConfiguration(config: git.IGitConfiguration): void {
		if (config.autofetch === false) {
			this.disable();
		} else {
			this.enable();
		}
	}

	public enable(): void {
		if (this._state !== git.AutoFetcherState.Disabled) {
			return;
		}

		this.gitServiceStateDisposable = this.gitService.addListener2(git.ServiceEvents.STATE_CHANGED, (e) => this.onGitServiceStateChange(e));
		this._state = git.AutoFetcherState.Active;
		this.onGitServiceStateChange(this.gitService.getState());
	}

	public disable(): void {
		if (this.gitServiceStateDisposable) {
			this.gitServiceStateDisposable.dispose();
			this.gitServiceStateDisposable = null;
		}

		this.deactivate();
		this._state = git.AutoFetcherState.Disabled;
	}

	private onGitServiceStateChange(state: git.ServiceState): void {
		if (state === git.ServiceState.OK) {
			this.activate();
		} else {
			this.deactivate();
		}
	}

	public activate(): void {
		if (this.currentRequest) {
			this.currentRequest.cancel();
		}

		this._state = git.AutoFetcherState.Active;
		this.loop();
	}

	public deactivate(): void {
		if (!this.currentRequest) {
			return;
		}

		this._state = git.AutoFetcherState.Inactive;
		this.currentRequest.cancel();
		this.currentRequest = null;
	}

	private loop(): void {
		this._state = git.AutoFetcherState.Fetching;
		this.currentRequest = this.gitService.fetch().then(() => {
			this.timeout = AutoFetcher.MIN_TIMEOUT;
		}, (err) => {
			if (errors.isPromiseCanceledError(err)) {
				return winjs.Promise.wrapError(err);
			} else if (err.gitErrorCode === git.GitErrorCodes.AuthenticationFailed) {
				return winjs.Promise.wrapError(err);
			} else {
				this.timeout = Math.min(Math.round(this.timeout * 1.2), AutoFetcher.MAX_TIMEOUT); // backoff
			}
		});

		this.currentRequest.then(() => {
			this._state = git.AutoFetcherState.Active;
			this.currentRequest = winjs.Promise.timeout(this.timeout);
			return this.currentRequest;
		}).then(() => this.loop(), (err) => this.deactivate());
	}

	public dispose(): void {
		this.disable();
	}
}

interface IGitCredentialRequest {
	guid: string;
	scope: git.IGitCredentialScope;
}

export class GitService extends ee.EventEmitter
	implements
		git.IGitService {

	static ID = 'Monaco.IDE.UI.Services.GitService';

	public serviceId = git.IGitService;
	private eventService: IEventService;
	private contextService: IWorkspaceContextService;
	private messageService: IMessageService;
	private instantiationService:IInstantiationService;
	private editorService: IWorkbenchEditorService;
	private lifecycleService: ILifecycleService;
	private outputService: IOutputService;
	private raw: git.IRawGitService;

	private state: git.ServiceState;
	private operations: git.IGitOperation[];
	private model: git.IModel;
	private inputCache: EditorInputCache;
	private remoteListenerUnbind:ee.ListenerUnbind;
	private toDispose: lifecycle.IDisposable[];
	private needsRefresh: boolean;
	private refreshDelayer: async.ThrottledDelayer;
	private autoFetcher: AutoFetcher;

	constructor(raw: git.IRawGitService, @IInstantiationService instantiationService: IInstantiationService, @IEventService eventService: IEventService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IOutputService outputService: IOutputService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ILifecycleService lifecycleService: ILifecycleService) {
		super();

		this.instantiationService = instantiationService;
		this.eventService = eventService;
		this.messageService = messageService;
		this.editorService = editorService;
		this.outputService = outputService;
		this.contextService = contextService;
		this.lifecycleService = lifecycleService;

		this.raw = raw;
		this.state = git.ServiceState.NotInitialized;
		this.operations = [];
		this.model = new model.Model();
		this.toDispose = [];

		this.needsRefresh = false;
		this.refreshDelayer = new async.PeriodThrottledDelayer(500, 10000);
		this.autoFetcher = this.instantiationService.createInstance(AutoFetcher, this);

		this.registerListeners();

		this.inputCache = this.instantiationService.createInstance(EditorInputCache, this);

		this.triggerStatus(true); // trigger initial status
	}

	private registerListeners():void {
		this.toDispose.push(this.eventService.addListener2(FileEventType.FILE_CHANGES,(e) => this.onFileChanges(e)));
		this.toDispose.push(this.eventService.addListener2(filesCommon.EventType.FILE_SAVED, (e) => this.onLocalFileChange(e)));
		this.toDispose.push(this.eventService.addListener2(filesCommon.EventType.FILE_REVERTED, (e) => this.onLocalFileChange(e)));
		this.lifecycleService.onShutdown.add(this.dispose, this);
	}

	private triggerStatus(force: boolean = false): void {
		if (this.isInitialized() && !this.isIdle() && !force) {
			this.refreshDelayer.cancel();
			return;
		}

		var onError = async.once<any, void>(e => {
			if (!errors.isPromiseCanceledError(e)) {
				this.messageService.show(severity.Error, e);
			}
		});

		this.refreshDelayer.trigger(() => this.status()).done(null, onError);
	}

	private onLocalFileChange(e:filesCommon.LocalFileChangeEvent): void {
		var shouldTriggerStatus = e.gotUpdated() && paths.basename(e.getAfter().resource.fsPath) === '.gitignore';

		if (!shouldTriggerStatus) {
			return;
		}

		this.triggerStatus();
	}

	private onFileChanges(e: FileChangesEvent): void {
		var isIdle = this.isIdle();

		var shouldTriggerStatus = e.changes.some(c => {
			var workspacePath = this.contextService.toWorkspaceRelativePath(c.resource);
			if (!workspacePath) {
				return false; // ignore out of workspace files
			}

			// for .gitindex, the service must be idle
			if ('.git/index' === workspacePath) {
				return isIdle;
			}

			// for anything other that .git*
			if (!/^\.git/.test(workspacePath)) {
				return true;
			}

			// added or deleted .git folder
			if (workspacePath === '.git') {
				return c.type === FileChangeType.ADDED || c.type === FileChangeType.DELETED;
			}

			return ['.git/index.lock', '.git/FETCH_HEAD', '.gitignore', '.gitmodules'].indexOf(workspacePath) === -1;
		});

		if (!shouldTriggerStatus) {
			return;
		}

		this.triggerStatus();
	}

	private onGitServiceOperationEnd(e: { operation: git.IGitOperation; }): void {
		if (e.operation.id === git.ServiceOperations.COMMAND) {
			this.triggerStatus();
		}
	}

	public getState(): git.ServiceState {
		return this.state;
	}

	public getModel(): git.IModel {
		return this.model;
	}

	public status(): winjs.Promise {
		return this.run(git.ServiceOperations.STATUS, () => this.raw.status());
	}

	public init(): winjs.Promise {
		return this.run(git.ServiceOperations.INIT, () => this.raw.init());
	}

	public add(files?: git.IFileStatus[]): winjs.Promise {
		return this.run(git.ServiceOperations.ADD, () => this.raw.add(GitService.toPaths(files)));
	}

	public stage(filePath: string, content: string): winjs.Promise {
		return this.run(git.ServiceOperations.STAGE, () => this.raw.stage(filePath, content));
	}

	public branch(name: string, checkout: boolean = false): winjs.Promise {
		return this.run(git.ServiceOperations.BRANCH, () => this.raw.branch(name, checkout));
	}

	public checkout(treeish: string = '', files: git.IFileStatus[] = null): winjs.Promise {
		return this.run(git.ServiceOperations.CHECKOUT, () => this.raw.checkout(treeish, GitService.toPaths(files)));
	}

	public clean(files: git.IFileStatus[]): winjs.Promise {
		return this.run(git.ServiceOperations.CLEAN, () => this.raw.clean(files.map((s) => s.getPath())));
	}

	public undo(): winjs.Promise {
		return this.run(git.ServiceOperations.UNDO, () => this.raw.undo());
	}

	public reset(treeish: string, hard?: boolean): winjs.Promise {
		return this.run(git.ServiceOperations.RESET, () => this.raw.reset(treeish, hard));
	}

	public revertFiles(treeish: string, files?: git.IFileStatus[]): winjs.Promise {
		return this.run(git.ServiceOperations.RESET, () => this.raw.revertFiles(treeish, (files || []).map((s) => s.getPath())));
	}

	public fetch(): winjs.Promise {
		return this.run(git.ServiceOperations.BACKGROUND_FETCH, () => this.raw.fetch());
	}

	public pull(): winjs.Promise {
		return this.run(git.ServiceOperations.PULL, () => this.raw.pull());
	}

	public push(): winjs.Promise {
		return this.run(git.ServiceOperations.PUSH, () => this.raw.push());
	}

	public sync(): winjs.Promise {
		return this.run(git.ServiceOperations.SYNC, () => this.raw.sync());
	}

	public commit(message:string, amend: boolean = false, stage: boolean = false): winjs.Promise {
		return this.run(git.ServiceOperations.COMMIT, () => this.raw.commit(message, amend, stage));
	}

	public detectMimetypes(path: string, treeish: string = '~'): winjs.Promise {
		return this.raw.detectMimetypes(path, treeish);
	}

	private run(operationId: string, fn: () => winjs.Promise): winjs.Promise {
		return this.raw.serviceState().then(state => {
			if (state === git.RawServiceState.GitNotFound) {
				this.transition(git.ServiceState.NoGit);
				return winjs.Promise.as(null);
			} else if (state === git.RawServiceState.Disabled) {
				this.transition(git.ServiceState.Disabled);
				return winjs.Promise.as(null);
			} else {
				return this._run(operationId, fn);
			}
		});
	}

	private _run(operationId: string, fn: () => winjs.Promise): winjs.Promise {
		var operation = new operations.GitOperation(operationId, fn);

		this.operations.push(operation);
		this.emit(git.ServiceEvents.OPERATION_START, operation);
		this.emit(git.ServiceEvents.OPERATION, operation);

		var onDone = (error: any = null) => {
			var index = this.operations.indexOf(operation);

			if (index > -1) {
				this.operations.splice(index, 1);
			}

			var e = { operation: operation, error: error };
			this.emit(git.ServiceEvents.OPERATION_END, e);
			this.onGitServiceOperationEnd(e);
			this.emit(git.ServiceEvents.OPERATION, operation);
		};

		return operation.run().then((status: git.IRawStatus) => {
			this.model.update(status);

			onDone();

			if (status) {
				this.transition(types.isUndefinedOrNull(status.state) ? git.ServiceState.OK : status.state);
			} else {
				this.transition(git.ServiceState.NotARepo);
			}

			return this.model;
		}, (e) => {
			onDone(e);

			if (errors.isPromiseCanceledError(e)) {
				return winjs.Promise.wrapError(e);
			}

			var gitErrorCode: string = e.gitErrorCode || null;

			if (gitErrorCode === git.GitErrorCodes.NotAtRepositoryRoot) {
				this.transition(git.ServiceState.NotAtRepoRoot);
				return winjs.Promise.as(this.model);
			}

			this.emit(git.ServiceEvents.ERROR, e);
			this.transition(git.ServiceState.OK);

			if (gitErrorCode === git.GitErrorCodes.NoUserNameConfigured || gitErrorCode === git.GitErrorCodes.NoUserEmailConfigured) {
				this.messageService.show(severity.Warning, nls.localize('configureUsernameEmail', "Please configure your git user name and e-mail."));

				return winjs.Promise.as(null);

			} else if (gitErrorCode === git.GitErrorCodes.BadConfigFile) {
				this.messageService.show(severity.Error, nls.localize('badConfigFile', "Git {0}", e.message));
				return winjs.Promise.as(null);

			} else if (gitErrorCode === git.GitErrorCodes.UnmergedChanges) {
				this.messageService.show(severity.Warning, nls.localize('unmergedChanges', "You should first resolve the unmerged changes before committing your changes."));
				return winjs.Promise.as(null);
			}

			var error: Error;
			var showOutputAction = new actions.Action('show.gitOutput', nls.localize('showOutput', "Show Output"), null, true, () => this.outputService.showOutput('Git'));
			var cancelAction = new actions.Action('close.message', nls.localize('cancel', "Cancel"), null, true, ()=>winjs.Promise.as(true));

			error = errors.create(
				nls.localize('checkNativeConsole', "There was an issue running a git operation. Please review the output or use a console to check the state of your repository."),
				{ actions: [showOutputAction, cancelAction] }
			);

			(<any>error).gitErrorCode = gitErrorCode;
			return winjs.Promise.wrapError(error);
		});
	}

	private transition(state: git.ServiceState): void {
		var oldState = this.state;

		this.state = state;

		if (state !== oldState) {
			this.emit(git.ServiceEvents.STATE_CHANGED, state);
		}
	}

	public buffer(path: string, treeish: string = '~'): winjs.TPromise<string> {
		return this.raw.show(path, treeish);
	}

	public show(path: string, status: git.IFileStatus, treeish: string = '~', mimetype: string = 'text/plain'): winjs.Promise {
		return this.detectMimetypes(path, treeish).then((mimetypes:string[]) => {
			var pathComponents = status.getPathComponents();
			var fileSegment = pathComponents[pathComponents.length - 1];
			var folderSegment = toReadablePath(pathComponents.slice(0, pathComponents.length - 1).join('/'));

			var description:string;

			if (treeish === '~') {
				description = nls.localize('changesFromIndex', "{0} - Changes on index", folderSegment);
			} else {
				description = nls.localize('changesFromTree', "{0} - Changes on {1}", folderSegment, treeish);
			}

			if (mime.isUnspecific(mimetypes)) {
				mimetypes = mime.guessMimeTypes(path); // guess from path if our detection did not yield results
			}

			// Binary: our story is weak here for binary files on the index. Since we run nativelyx, we do not have a way currently
			// to e.g. show images as binary inside the renderer because images need to be served through a URL to show. We could revisit this by
			// allowing to use data URLs for resource inputs to render them. However, this would mean potentially loading a large file into memory
			//
			// Our solution now is to detect binary files and immediately return an input that is flagged as binary unknown mime type.
			if (mime.isBinaryMime(mime.guessMimeTypes(path)) || mimetypes.indexOf(mime.MIME_BINARY) >= 0) {
				return winjs.Promise.as(this.instantiationService.createInstance(giteditorinputs.GitIndexEditorInput, fileSegment, description, null /* no URL */, mime.MIME_BINARY, status));
			}

			// Text
			return winjs.Promise.as(this.instantiationService.createInstance(giteditorinputs.NativeGitIndexStringEditorInput, fileSegment, description, mimetypes.join(', '), status, path, treeish));
		});
	}

	public getInput(status: git.IFileStatus): winjs.TPromise<WorkbenchEditorCommon.EditorInput> {
		return this.inputCache.getInput(status).then(null, (err) => {
			if (err.gitErrorCode = git.GitErrorCodes.CantOpenResource) {
				this.messageService.show(severity.Warning, nls.localize('cantOpenResource', "Can't open this git resource."));
				return winjs.Promise.as(null);
			}

			return winjs.Promise.wrapError(err);
		});
	}

	public isInitialized(): boolean {
		return this.state === git.ServiceState.OK;
	}

	public isIdle(): boolean {
		return this.isInitialized() && !this.operations.some(op => op.id !== git.ServiceOperations.BACKGROUND_FETCH);
	}

	public getRunningOperations(): git.IGitOperation[] {
		return this.operations;
	}

	public onOutput(): winjs.Promise {
		return this.raw.onOutput();
	}

	public getAutoFetcher(): git.IAutoFetcher {
		return this.autoFetcher;
	}

	private static toPaths(files: git.IFileStatus[]): string[] {
		if (!files) {
			return null;
		}

		return files.map((status) => {
			/*	In the case that a file was renamed in the index and (changed || deleted) in the
				working tree, we must use its new name, running the checkout command.
			*/

			switch (status.getStatus()) {
				case git.Status.MODIFIED:
				case git.Status.DELETED:
					if (status.getRename()) {
						return status.getRename();
					}

				default:
					return status.getPath();
			}
		});
	}

	public dispose(): void {
		if (this.model) {
			this.model.dispose();
			this.model = null;
		}

		if (this.remoteListenerUnbind) {
			this.remoteListenerUnbind();
			this.remoteListenerUnbind = null;
		}

		super.dispose();
	}
}


text:
from __future__ import print_function
from abc import ABCMeta
from abc import abstractmethod
import os

class CompilerOptions(object):
    def __init__(self, build_dir, type='build', config='release', platform='x64', verbose=False):
        self.build_dir = build_dir
        self.compile_type = type
        self.build_config = config
        self.build_platform = platform
        self.verbose = verbose
    def __str__(self):
        str = []
        str.append('build dir     : %s' % self.build_dir)
        str.append('compile type  : %s' % self.compile_type)
        str.append('build config  : %s' % self.build_config)
        str.append('build platform: %s' % self.build_platform)
        str.append('verbose       : %s' % self.verbose)
        return '\n'.join(str)

class BaseCompiler(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def compile(self, options):
        '''
        The actual method to dispatch a call to the native compiler
        @param sb A sandbox object.
        @param type Whether to build, clean or rebuild
        @param config Type of compile to execute; release or debug
        '''
        return NotImplemented


text:
import os.path as op

import numpy as np
import pytest

from mne.datasets import testing
from mne.utils import _TempDir, _url_to_local_path, buggy_mkl_svd

def test_buggy_mkl():
    """Test decorator for buggy MKL issues."""
    from unittest import SkipTest

    @buggy_mkl_svd
    def foo(a, b):
        raise np.linalg.LinAlgError('SVD did not converge')
    with pytest.warns(RuntimeWarning, match='convergence error'):
        with pytest.raises(SkipTest):
            foo(1, 2)

    @buggy_mkl_svd
    def bar(c, d, e):
        raise RuntimeError('SVD did not converge')
    pytest.raises(RuntimeError, bar, 1, 2, 3)

def test_tempdir():
    """Test TempDir."""
    tempdir2 = _TempDir()
    assert (op.isdir(tempdir2))
    x = str(tempdir2)
    del tempdir2
    assert (not op.isdir(x))

def test_datasets(monkeypatch, tmp_path):
    """Test dataset config."""
    # gh-4192
    fake_path = tmp_path / 'MNE-testing-data'
    fake_path.mkdir()
    with open(fake_path / 'version.txt', 'w') as fid:
        fid.write('9999.9999')
    monkeypatch.setenv('_MNE_FAKE_HOME_DIR', str(tmp_path))
    monkeypatch.setenv('MNE_DATASETS_TESTING_PATH', str(tmp_path))
    got_path = str(testing.data_path(download=False, verbose='debug'))
    assert got_path == str(fake_path)

def test_url_to_local_path():
    """Test URL to local path."""
    assert _url_to_local_path('http://google.com/home/why.html', '.') == \
        op.join('.', 'home', 'why.html')


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Composition;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.UseCompoundAssignment;

namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment
{
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    internal class CSharpUseCompoundAssignmentCodeFixProvider
        : AbstractUseCompoundAssignmentCodeFixProvider<SyntaxKind, AssignmentExpressionSyntax, ExpressionSyntax>
    {
        [ImportingConstructor]
        public CSharpUseCompoundAssignmentCodeFixProvider()
            : base(Utilities.Kinds)
        {
        }

        protected override SyntaxToken Token(SyntaxKind kind)
            => SyntaxFactory.Token(kind);

        protected override AssignmentExpressionSyntax Assignment(
            SyntaxKind assignmentOpKind, ExpressionSyntax left, SyntaxToken syntaxToken, ExpressionSyntax right)
        {
            return SyntaxFactory.AssignmentExpression(assignmentOpKind, left, syntaxToken, right);
        }
    }
}


text:
class Categorization < ActiveRecord::Base
  # ====== ASSOCIATIONS ======
  belongs_to :project, required: true
  belongs_to :category, required: true
end


text:
package com.ivanmagda.popularmovies.utilities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Provide utility methods for working with Movie dates.
 */
public final class MovieDateUtils {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    private MovieDateUtils() {
    }

    public static Date fromString(String string) {
        try {
            return DATE_FORMAT.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

}


text:
/** @constructor */
ScalaJS.c.scala_io_UTF8Codec$ = (function() {
  ScalaJS.c.java_lang_Object.call(this);
  this.UNI$undREPLACEMENT$undCHAR$1 = 0;
  this.UNI$undREPLACEMENT$undBYTES$1 = null
});
ScalaJS.c.scala_io_UTF8Codec$.prototype = new ScalaJS.inheritable.java_lang_Object();
ScalaJS.c.scala_io_UTF8Codec$.prototype.constructor = ScalaJS.c.scala_io_UTF8Codec$;
ScalaJS.c.scala_io_UTF8Codec$.prototype.UNI$undREPLACEMENT$undCHAR__I = (function() {
  return this.UNI$undREPLACEMENT$undCHAR$1
});
ScalaJS.c.scala_io_UTF8Codec$.prototype.UNI$undREPLACEMENT$undBYTES__AB = (function() {
  return this.UNI$undREPLACEMENT$undBYTES$1
});
ScalaJS.c.scala_io_UTF8Codec$.prototype.init___ = (function() {
  ScalaJS.c.java_lang_Object.prototype.init___.call(this);
  ScalaJS.moduleInstances.scala_io_UTF8Codec = this;
  this.UNI$undREPLACEMENT$undCHAR$1 = 65533;
  this.UNI$undREPLACEMENT$undBYTES$1 = ScalaJS.asArrayOf.scala_Byte(ScalaJS.modules.scala_Array().apply__Lscala_collection_Seq__Lscala_reflect_ClassTag__O(ScalaJS.modules.scala_Predef().wrapByteArray__AB__Lscala_collection_mutable_WrappedArray(ScalaJS.makeNativeArrayWrapper(ScalaJS.data.scala_Byte.getArrayOf(), [-17, -65, -67])), ScalaJS.modules.scala_reflect_ClassTag().Byte__Lscala_reflect_ClassTag()), 1);
  return this
});
ScalaJS.c.scala_io_UTF8Codec$.prototype.UNI$undREPLACEMENT$undBYTES__ = (function() {
  return this.UNI$undREPLACEMENT$undBYTES__AB()
});
ScalaJS.c.scala_io_UTF8Codec$.prototype.UNI$undREPLACEMENT$undCHAR__ = (function() {
  return ScalaJS.bI(this.UNI$undREPLACEMENT$undCHAR__I())
});
/** @constructor */
ScalaJS.inheritable.scala_io_UTF8Codec$ = (function() {
  /*<skip>*/
});
ScalaJS.inheritable.scala_io_UTF8Codec$.prototype = ScalaJS.c.scala_io_UTF8Codec$.prototype;
ScalaJS.is.scala_io_UTF8Codec$ = (function(obj) {
  return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_io_UTF8Codec$)))
});
ScalaJS.as.scala_io_UTF8Codec$ = (function(obj) {
  if ((ScalaJS.is.scala_io_UTF8Codec$(obj) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwClassCastException(obj, "scala.io.UTF8Codec")
  }
});
ScalaJS.isArrayOf.scala_io_UTF8Codec$ = (function(obj, depth) {
  return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_io_UTF8Codec$)))
});
ScalaJS.asArrayOf.scala_io_UTF8Codec$ = (function(obj, depth) {
  if ((ScalaJS.isArrayOf.scala_io_UTF8Codec$(obj, depth) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwArrayCastException(obj, "Lscala.io.UTF8Codec;", depth)
  }
});
ScalaJS.data.scala_io_UTF8Codec$ = new ScalaJS.ClassTypeData({
  scala_io_UTF8Codec$: 0
}, false, "scala.io.UTF8Codec$", ScalaJS.data.java_lang_Object, {
  scala_io_UTF8Codec$: 1,
  java_lang_Object: 1
});
ScalaJS.c.scala_io_UTF8Codec$.prototype.$classData = ScalaJS.data.scala_io_UTF8Codec$;
ScalaJS.moduleInstances.scala_io_UTF8Codec = undefined;
ScalaJS.modules.scala_io_UTF8Codec = (function() {
  if ((!ScalaJS.moduleInstances.scala_io_UTF8Codec)) {
    ScalaJS.moduleInstances.scala_io_UTF8Codec = new ScalaJS.c.scala_io_UTF8Codec$().init___()
  };
  return ScalaJS.moduleInstances.scala_io_UTF8Codec
});
//@ sourceMappingURL=UTF8Codec$.js.map


text:
#ifndef __DFWAVELET_H
#define __DFWAVELET_H

#include "misc/cppwrap.h"

struct dfwavelet_plan_s;

extern struct dfwavelet_plan_s* prepare_dfwavelet_plan(int numdims, long* imSize, long* minSize_tr, _Complex float* res, int use_gpu);

extern void dfwavelet_forward(struct dfwavelet_plan_s* plan, _Complex float* out_wcdf1, _Complex float* out_wcdf2, _Complex float* out_wcn, _Complex float* in_vx, _Complex float* in_vy, _Complex float* in_vz);

extern void dfwavelet_inverse(struct dfwavelet_plan_s* plan, _Complex float* out_vx, _Complex float* out_vy, _Complex float* out_vz, _Complex float* in_wcdf1, _Complex float* in_wcdf2, _Complex float* in_wcn);

extern void dfsoft_thresh(struct dfwavelet_plan_s* plan, float dfthresh, float nthresh, _Complex float* wcdf1, _Complex float* wcdf2, _Complex float* wcn);

extern void dfwavelet_thresh(struct dfwavelet_plan_s* plan, float dfthresh, float nthresh,_Complex float* out_vx, _Complex float* out_vy, _Complex float* out_vz, _Complex float* in_vx,_Complex float* in_vy, _Complex float* in_vz);

extern void dfwavelet_new_randshift(struct dfwavelet_plan_s* plan);
extern void dfwavelet_clear_randshift(struct dfwavelet_plan_s* plan);
extern void dfwavelet_free(struct dfwavelet_plan_s* plan);
extern void print_plan(struct dfwavelet_plan_s* plan);

#include "misc/cppwrap.h"
#endif // __WAVELET_H


text:
import argparse
import re

def start(output):
    with open(output, 'w') as fo:
        info = ['cell','run','barcode','lesion','position','refnt','coverage']
        muts = ['A','G','C','T','N','-','+','*']
        fo.write(','.join(info + muts))
        fo.write('\n')

def extract(inputs, output, sample_codes):
    for input in inputs:
        muts = ['A','G','C','T','N','-','+','*']
        with open(input,'r') as fi, open(output,'a') as fo:
            nextLines = []
            while True:
                line = fi.readline().split("\t")
                if line == [""]: break

                sample = str(input)[input.rfind('/')+1:-15]
                cell = sample_codes[sample][:-2]
                run = sample_codes[sample][-1]
                barcode = str(input)[-14:-11]
                lesion = str(input)[-10:-7]
                pos = str(line[1])
                refnt = str(line[2])
                coverage = str(line[3])

                readbase = str(line[4])

                # [,.] are matches
                # [*] is del
                # [ACGTNacgtn] are mismatches
                # remove number and nt following +/- and record for insertions and deletions
                # remove char following ^ as quality score
                eor = r'(\^)[\x00-\x7F]' # just remove/ignore; ASCII char
                eol = r'\$' # just remove/ignore
                indel = r'[+-][0-9]{1,}' # greedy match, for most possible matches in case indel is more than 1 digit number long
                # starting from the NEXT position...? so remove and record for next few positions?
                delnt = r'\*'
                match = r'[\,\.]'
                mismt = r'[ACGTNacgtn]'

                percentages = {}
                for key in muts:
                    percentages[key] = 0

                num_indel = [(x.start(),x.end()) for x in re.finditer(indel,readbase)] # indices of beginnings
                to_remove = []
                for s,e in num_indel:
                    nt_counts = int(readbase[s+1:e]) # number of nt affected by indel, starting from the character after +/-
                    to_remove.append((s+1,e+nt_counts)) # to account for nt affected by indel

                new_bases = ''
                last_pos = 0
                for s,e in to_remove:
                    new_bases = new_bases + readbase[last_pos:s]
                    last_pos = e
                new_bases = new_bases + readbase[last_pos:]
                new_bases.upper()
                for nt in new_bases:
                    if (nt == '.') | (nt == ','):
                        percentages[refnt] = percentages[refnt] + 1
                    elif nt in muts:
                        percentages[nt] = percentages[nt] + 1

                total = sum([percentages[i] for i in ['A','C','G','T','N','*']])
                print(pos,readbase,[percentages[key] for key in muts])
                for key in muts:
                    percentages[key] = percentages[key] / float(total)

                l_out = ','.join([cell, run, barcode, lesion, pos, refnt, coverage] + [str(percentages[i]) for i in muts])

                # Write to file
                fo.write(l_out+'\n')

def main():
    parser = argparse.ArgumentParser(
        description = ("Takes in pileup files with mutation data and  "
                        "extracts necessary information regarding bases, "
                        "coverage, and percentage of mutations.")
    )
    parser.add_argument("-i", "--inputs",
                        action = "store",
                        type = str,
                        dest = "inputs",
                        help = "File path to pileup files with mutation data.",
                        required = True)
    parser.add_argument("-o", "--output",
                        action = "store",
                        type = str,
                        dest = "output",
                        help = "Destination file for output.",
                        required = True)

    args = parser.parse_args()
    inp = args.inputs.split(',') # is a list of input files
    out = args.output

    scs = dict([('D15-10283','AB1157-1'), ('D15-10284','AB1157-2'), ('D15-10285','AB1157-3'),
                ('D15-10286','mutY-1'), ('D15-10287','mutY-2'), ('D15-10288','mutY-3'),
                ('D15-10289','mutYSOS-1'), ('D15-10290','mutYSOS-2'), ('D15-10291','mutYSOS-3'),])

    start(out)
    extract(inp, out, scs)

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Installation-guides on MongoDB Node.js Driver</title>
    <link>/node-mongodb-native/3.3/installation-guide/</link>
    <description>Recent content in Installation-guides on MongoDB Node.js Driver</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Tue, 17 Mar 2015 15:36:56 +0000</lastBuildDate>

	<atom:link href="/node-mongodb-native/3.3/installation-guide/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Installation Guide</title>
      <link>/node-mongodb-native/3.3/installation-guide/installation-guide/</link>
      <pubDate>Tue, 17 Mar 2015 15:36:56 +0000</pubDate>

      <guid>/node-mongodb-native/3.3/installation-guide/installation-guide/</guid>
      <description>Installation The recommended way to get started using the Node.js 2.0 driver is by using NPM (Node Package Manager) to install the dependency in your project.
MongoDB Driver After you&rsquo;ve created your project with npm init, you can install the MongoDB driver and its dependencies with the command:
npm install mongodb --save  This will download the MongoDB driver and add a dependency entry in your package.json file.
Troubleshooting The MongoDB driver depends on several other packages, including:</description>
    </item>

  </channel>
</rss>


text:
from .models import Country, Person
from django.http import HttpResponse
from rest_framework import viewsets
from friends.serializers import CountrySerializer, PersonSerializer

def index(request):
    persons = Person.objects.all()
    pcnt = persons.count()

    ccnt = 0
    for p in persons:
        ccnt += p.countries.count()

    return HttpResponse(
            'Currently, we have {} friend(s) registered, visited {} countries.'
            .format(pcnt, ccnt))

class CountryViewSet(viewsets.ModelViewSet):
    queryset = Country.objects.all()
    serializer_class = CountrySerializer

class PersonViewSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

# vim: set ts=4 sts=4 sw=4 et: