text:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using BohFoundation.ApplicantsRepository.Repositories.Interfaces;
using BohFoundation.AzureStorage.BlobStorageStreamProvider;
using BohFoundation.AzureStorage.BlobStorageStreamProvider.Interfaces;
using BohFoundation.Domain.Dtos.Applicant.Academic;
using BohFoundation.Domain.Dtos.Common;
using BohFoundation.Utilities.Context.Interfaces;
using BohFoundation.WebApi.Filters;
using BohFoundation.WebApi.Models;
using Microsoft.WindowsAzure.Storage.Blob;

namespace BohFoundation.WebApi.Controllers.Applicant.Transcript
{
    //toDo not tested!

    [RequireApplicant]
    [Route("api/applicant/transcript")]
    public class TranscriptUploadController : ApiController
    {
        private readonly ITranscriptReferenceRepository _transcriptReferenceRepository;
        private readonly string _containerName;
        private readonly Lazy<Task<CloudBlobContainer>> _blobContainer;

        public TranscriptUploadController(IClaimsInformationGetters claimsInformationGetters, IBlobHelper blobHelper, ITranscriptReferenceRepository transcriptReferenceRepository)
        {
            _transcriptReferenceRepository = transcriptReferenceRepository;

            const string transcriptsName = "transcripts-";

            var usersGraduatingYear = claimsInformationGetters.GetApplicantsGraduatingYear();
            _containerName = transcriptsName + usersGraduatingYear;

            _blobContainer = new Lazy<Task<CloudBlobContainer>>(async () => await blobHelper.GetBlobContainer(_containerName));
        }

        public async Task<IHttpActionResult> Post()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var container = await _blobContainer.Value;

                //Create a AzureBlobStorageMultipartProvider and process the request
                var streamProvider = new AzureBlobStorageMultipartProvider(container, Path.GetTempPath());
                await Request.Content.ReadAsMultipartAsync(streamProvider);

                var dto = new TranscriptBlobReferenceDto { BlobContainerName = streamProvider.Container, ReferenceToTranscriptPdf = streamProvider.Reference };
                _transcriptReferenceRepository.UpsertTranscriptReference(dto);
            }
            catch (Exception)
            {
                return InternalServerError();
            }

            return Ok();
        }

        public IHttpActionResult Get()
        {
            LastUpdatedDto lastUpdatedDto;
            try
            {
                lastUpdatedDto = _transcriptReferenceRepository.LastUpdatedTranscript();
            }
            catch (Exception)
            {
                return InternalServerError();
            }
            return Ok(new ServerMessage(lastUpdatedDto));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var util = require("util");
var choreography = require("temboo/core/choreography");

/*
    GetActivityStats
    Gets user's activity statistics.
*/

var GetActivityStats = function(session) {
    /*
        Create a new instance of the GetActivityStats Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Fitbit/Statistics/GetActivityStats"
    GetActivityStats.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new GetActivityStatsResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new GetActivityStatsInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the GetActivityStats
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var GetActivityStatsInputSet = function() {
    GetActivityStatsInputSet.super_.call(this);
        /*
        Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.)
        */
        this.set_AccessTokenSecret = function(value) {
            this.setInput("AccessTokenSecret", value);
        }

        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the ConsumerKey input for this Choreo. ((required, string) The Consumer Key provided by Fitbit.)
        */
        this.set_ConsumerKey = function(value) {
            this.setInput("ConsumerKey", value);
        }

        /*
        Set the value of the ConsumerSecret input for this Choreo. ((required, string) The Consumer Secret provided by Fitbit.)
        */
        this.set_ConsumerSecret = function(value) {
            this.setInput("ConsumerSecret", value);
        }

        /*
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that you want the response to be in: xml or json. Defaults to json.)
        */
        this.set_ResponseFormat = function(value) {
            this.setInput("ResponseFormat", value);
        }

        /*
        Set the value of the UserID input for this Choreo. ((optional, string) The user's encoded id. Defaults to "-" (dash) which will return data for the user associated with the token credentials provided.)
        */
        this.set_UserID = function(value) {
            this.setInput("UserID", value);
        }

}

/*
A ResultSet with methods tailored to the values returned by the GetActivityStats Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var GetActivityStatsResultSet = function(resultStream) {
    GetActivityStatsResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Fitbit.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(GetActivityStats, choreography.Choreography);
util.inherits(GetActivityStatsInputSet, choreography.InputSet);
util.inherits(GetActivityStatsResultSet, choreography.ResultSet);
exports.GetActivityStats = GetActivityStats;

/*
    GetTimeSeriesByDateRange
    Gets time series data for a given resource based on a date range you specify.
*/

var GetTimeSeriesByDateRange = function(session) {
    /*
        Create a new instance of the GetTimeSeriesByDateRange Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Fitbit/Statistics/GetTimeSeriesByDateRange"
    GetTimeSeriesByDateRange.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new GetTimeSeriesByDateRangeResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new GetTimeSeriesByDateRangeInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the GetTimeSeriesByDateRange
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var GetTimeSeriesByDateRangeInputSet = function() {
    GetTimeSeriesByDateRangeInputSet.super_.call(this);
        /*
        Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.)
        */
        this.set_AccessTokenSecret = function(value) {
            this.setInput("AccessTokenSecret", value);
        }

        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the ConsumerKey input for this Choreo. ((required, string) The Consumer Key provided by Fitbit.)
        */
        this.set_ConsumerKey = function(value) {
            this.setInput("ConsumerKey", value);
        }

        /*
        Set the value of the ConsumerSecret input for this Choreo. ((required, string) The Consumer Secret provided by Fitbit.)
        */
        this.set_ConsumerSecret = function(value) {
            this.setInput("ConsumerSecret", value);
        }

        /*
        Set the value of the EndDate input for this Choreo. ((required, date) The end date of the date range for the data you want to retrieve (in the format yyyy-MM-dd). You can also specify the value 'today'.)
        */
        this.set_EndDate = function(value) {
            this.setInput("EndDate", value);
        }

        /*
        Set the value of the ResourcePath input for this Choreo. ((required, string) The resource path that you want to access (for example: activities/log/distance). See Choreo documentation for a full list of resource paths.)
        */
        this.set_ResourcePath = function(value) {
            this.setInput("ResourcePath", value);
        }

        /*
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that you want the response to be in: xml or json. Defaults to json.)
        */
        this.set_ResponseFormat = function(value) {
            this.setInput("ResponseFormat", value);
        }

        /*
        Set the value of the StartDate input for this Choreo. ((required, date) The start date of the date range for the data you want to retrieve (in the format yyyy-MM-dd). You can also specify the value 'today'.)
        */
        this.set_StartDate = function(value) {
            this.setInput("StartDate", value);
        }

        /*
        Set the value of the UserID input for this Choreo. ((optional, string) The user's encoded id. Defaults to "-" (dash) which will return data for the user associated with the token credentials provided.)
        */
        this.set_UserID = function(value) {
            this.setInput("UserID", value);
        }

}

/*
A ResultSet with methods tailored to the values returned by the GetTimeSeriesByDateRange Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var GetTimeSeriesByDateRangeResultSet = function(resultStream) {
    GetTimeSeriesByDateRangeResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Fitbit.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(GetTimeSeriesByDateRange, choreography.Choreography);
util.inherits(GetTimeSeriesByDateRangeInputSet, choreography.InputSet);
util.inherits(GetTimeSeriesByDateRangeResultSet, choreography.ResultSet);
exports.GetTimeSeriesByDateRange = GetTimeSeriesByDateRange;

/*
    GetTimeSeriesByPeriod
    Gets time series data for a given resource based on a date range period you specify.
*/

var GetTimeSeriesByPeriod = function(session) {
    /*
        Create a new instance of the GetTimeSeriesByPeriod Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Fitbit/Statistics/GetTimeSeriesByPeriod"
    GetTimeSeriesByPeriod.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new GetTimeSeriesByPeriodResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new GetTimeSeriesByPeriodInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the GetTimeSeriesByPeriod
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var GetTimeSeriesByPeriodInputSet = function() {
    GetTimeSeriesByPeriodInputSet.super_.call(this);
        /*
        Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.)
        */
        this.set_AccessTokenSecret = function(value) {
            this.setInput("AccessTokenSecret", value);
        }

        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the ConsumerKey input for this Choreo. ((required, string) The Consumer Key provided by Fitbit.)
        */
        this.set_ConsumerKey = function(value) {
            this.setInput("ConsumerKey", value);
        }

        /*
        Set the value of the ConsumerSecret input for this Choreo. ((required, string) The Consumer Secret provided by Fitbit.)
        */
        this.set_ConsumerSecret = function(value) {
            this.setInput("ConsumerSecret", value);
        }

        /*
        Set the value of the EndDate input for this Choreo. ((required, date) The end date of the period for the data you want to retrieve (in the format yyyy-MM-dd). You can also specify the value 'today'.)
        */
        this.set_EndDate = function(value) {
            this.setInput("EndDate", value);
        }

        /*
        Set the value of the Period input for this Choreo. ((optional, string) The date range period. Valid values are: 1d, 7d, 30d, 1w, 1m, 3m, 6m, 1y, max. Defaults to 'max'.)
        */
        this.set_Period = function(value) {
            this.setInput("Period", value);
        }

        /*
        Set the value of the ResourcePath input for this Choreo. ((required, string) The resource path that you want to access (for example: activities/log/distance). See Choreo documentation for a full list of resource paths.)
        */
        this.set_ResourcePath = function(value) {
            this.setInput("ResourcePath", value);
        }

        /*
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that you want the response to be in: xml or json. Defaults to json.)
        */
        this.set_ResponseFormat = function(value) {
            this.setInput("ResponseFormat", value);
        }

        /*
        Set the value of the UserID input for this Choreo. ((optional, string) The user's encoded id. Defaults to "-" (dash) which will return data for the user associated with the token credentials provided.)
        */
        this.set_UserID = function(value) {
            this.setInput("UserID", value);
        }

}

/*
A ResultSet with methods tailored to the values returned by the GetTimeSeriesByPeriod Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var GetTimeSeriesByPeriodResultSet = function(resultStream) {
    GetTimeSeriesByPeriodResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Fitbit.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(GetTimeSeriesByPeriod, choreography.Choreography);
util.inherits(GetTimeSeriesByPeriodInputSet, choreography.InputSet);
util.inherits(GetTimeSeriesByPeriodResultSet, choreography.ResultSet);
exports.GetTimeSeriesByPeriod = GetTimeSeriesByPeriod;

/******************************************************************************
Begin output wrapper classes
******************************************************************************/

/**
 * Utility function, to retrieve the array-type sub-item specified by the key from the parent (array) specified by the item.
 * Returns an empty array if key is not present.
 */
function getSubArrayByKey(item, key) {
	var val = item[key];
	if(val == null) {
		val = new Array();
	}
	return val;
}


text:
FROM alpine:3.8 as builder

RUN apk update && \
    apk add git py2-setuptools py2-pip build-base openjdk8-jre perl && \
    pip install nltk==3.4 pytest

WORKDIR /opt
RUN git clone https://github.com/arne-cl/feng-hirst-rst-parser.git

# The Feng's original README claims that liblbfgs is included, but it's not
WORKDIR /opt/feng-hirst-rst-parser/tools/crfsuite
RUN wget https://github.com/downloads/chokkan/liblbfgs/liblbfgs-1.10.tar.gz && \
    tar xfvz liblbfgs-1.10.tar.gz && \
    rm liblbfgs-1.10.tar.gz

WORKDIR /opt/feng-hirst-rst-parser/tools/crfsuite/liblbfgs-1.10
RUN ./configure --prefix=$HOME/local && \
    make && \
    make install

WORKDIR /opt/feng-hirst-rst-parser/tools/crfsuite/crfsuite-0.12
# Can't put chmod and ./configure in the same layer (to avoid "is busy" error)
RUN chmod +x configure install-sh
RUN ./configure --prefix=$HOME/local --with-liblbfgs=$HOME/local && \
    make && \
    make install && \
    cp /root/local/bin/crfsuite /opt/feng-hirst-rst-parser/tools/crfsuite/crfsuite-stdin && \
    chmod +x /opt/feng-hirst-rst-parser/tools/crfsuite/crfsuite-stdin

FROM alpine:3.8

RUN apk update && \
    apk add py2-pip openjdk8-jre-base perl && \
    pip install nltk==3.4 pytest

WORKDIR /opt/feng-hirst-rst-parser
COPY --from=builder /opt/feng-hirst-rst-parser .

WORKDIR /root/local
COPY --from=builder /root/local .

WORKDIR /opt/feng-hirst-rst-parser/src

ENTRYPOINT ["/opt/feng-hirst-rst-parser/src/parser_wrapper.py"]
CMD ["../texts/input_long.txt"]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;

namespace Archimedes.Geometry.Rendering
{
    /// <summary>
    /// Threadsafe Drawing Group
    /// </summary>
    public class DrawingGroup : IDrawable
    {
        #region Fields

        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private readonly List<IDrawable> _grpdrawings = new List<IDrawable>();
        private readonly object _drawingsSync = new object();

        #endregion

        public string Name { get; set; }

        public DrawingGroup(string uname) {
            Name = uname;
        }

        #region Drawable Handling

        public void Add(IDrawable drawable)
        {
            if (drawable == null) throw new ArgumentNullException("drawable");
            lock (_drawingsSync) {
                _grpdrawings.Add(drawable);
            }
        }

        public void AddRange(IEnumerable<IDrawable> drawables) {
            lock (_drawingsSync) {
                foreach (var drawable in drawables)
                {
                    if (drawable != null)
                    {
                        Add(drawable);
                    }
                }
            }
        }

        /// <summary>
        /// Remove the given Element
        /// </summary>
        /// <param name="d"></param>
        public void Remove(IDrawable d) {
            lock (_drawingsSync) {
                _grpdrawings.Remove(d);
            }
        }

        /// <summary>
        /// Clear all Elements
        /// </summary>
        public void Clear() {
            lock (_drawingsSync) {
                _grpdrawings.Clear();
            }
        }

        /// <summary>
        /// Element Count
        /// </summary>
        public int Count {
            get {
                lock (_drawingsSync) {
                    return _grpdrawings.Count;
                }
            }
        }

        /// <summary>
        /// Get an immutable snapshot of all Drawing Elements currently contained in this Group
        /// </summary>
        /// <returns></returns>
        public IEnumerable<IDrawable> GetSnapshot() {
            lock (_drawingsSync) {
                return new List<IDrawable>(_grpdrawings);
            }
        }

        #endregion

        /// <summary>
        /// Draws all Elements to the given Gfx Context
        /// </summary>
        /// <param name="g"></param>
        public void Draw(System.Drawing.Graphics g) {
            foreach (var d in GetSnapshot()) {
                try {
                    d.Draw(g);
                } catch (Exception e) {
                    Log.Warn("Could not draw " + d + "!", e);
                }
            }
        }
    }
}


text:
import re
import unittest

import encoder
import optimizer

class DummyCodec(encoder.Codec):
  def __init__(self):
    super(DummyCodec, self).__init__('dummy')
    self.extension = 'fake'
    self.option_set = encoder.OptionSet(
      encoder.Option('score',  ['0', '5', '10']),
    )

  def StartEncoder(self, context):
    return encoder.Encoder(context,
                           encoder.OptionValueSet(self.option_set,
                                                  "--score=5"))

  def Execute(self, parameters, rate, videofile, workdir):
    # pylint: disable=W0613
    m = re.search(r'--score=(\d+)', parameters.ToString())
    if m:
      return {'psnr': int(m.group(1)), 'bitrate': 100}
    else:
      return {'psnr': -100, 'bitrate': 100}

class DummyVideofile(encoder.Videofile):
  def __init__(self, filename, clip_time):
    super(DummyVideofile, self).__init__(filename)
    self.clip_time = clip_time

  def ClipTime(self):
    return self.clip_time

def Returns1(target_bitrate, result):
  """Score function that returns a constant value."""
  # pylint: disable=W0613
  return 1.0

def ReturnsClipTime(target_bitrate, result):
  # pylint: disable=W0613
  return float(result['cliptime'])

class TestOptimizer(unittest.TestCase):
  def setUp(self):
    self.codec = DummyCodec()
    self.file_set = None
    self.cache_class = encoder.EncodingMemoryCache
    self.score_function = None
    self.videofile = DummyVideofile('foofile_640_480_30.yuv', clip_time=1)

  def StdOptimizer(self):
    return optimizer.Optimizer(self.codec, self.file_set,
                               cache_class=self.cache_class)

  def testInit(self):
    optimizer.Optimizer(self.codec, self.file_set,
                        cache_class=self.cache_class)

  def test_AlternateScorer(self):
    my_optimizer = optimizer.Optimizer(self.codec, self.file_set,
                                       cache_class=self.cache_class,
                                       score_function=Returns1)
    my_optimizer.BestEncoding(100, self.videofile).Execute().Store()
    self.assertEqual(1,
        my_optimizer.Score(my_optimizer.BestEncoding(100, self.videofile)))

  def test_FirstBestEncodingNoScore(self):
    my_optimizer = self.StdOptimizer()
    encoding = my_optimizer.BestEncoding(100, self.videofile)
    self.assertIsNone(encoding.Result())

  def test_BestEncodingOneAlternative(self):
    my_optimizer = self.StdOptimizer()
    my_optimizer.BestEncoding(100, self.videofile).Store()
    encoding = my_optimizer.BestEncoding(100, self.videofile)
    self.assertEqual(encoding.videofile, self.videofile)

  def test_BestEncodingExecuteGivesScore(self):
    my_optimizer = self.StdOptimizer()
    my_optimizer.BestEncoding(100, self.videofile).Execute().Store()
    self.assertEqual(5, my_optimizer.Score(
        my_optimizer.BestEncoding(100, self.videofile)))

  def test_BestEncodingOtherSpeedNoScore(self):
    my_optimizer = self.StdOptimizer()
    my_optimizer.BestEncoding(100, self.videofile).Execute().Store()
    self.assertIsNone(my_optimizer.BestEncoding(200, self.videofile).Result())

  def test_AutoGenerateClipTime(self):
    my_optimizer = optimizer.Optimizer(self.codec, self.file_set,
                                       cache_class=self.cache_class,
                                       score_function=ReturnsClipTime)
    my_encoder = encoder.Encoder(my_optimizer.context,
        encoder.OptionValueSet(encoder.OptionSet(), ''))
    # Must use a tricked-out videofile to avoid disk access.
    videofile = DummyVideofile('test_640x480_20.yuv', clip_time=1)
    my_encoding = encoder.Encoding(my_encoder, 123, videofile)
    my_encoding.result = {'psnr':42, 'bitrate':123}
    # If cliptime is not present, this will raise an exception.
    my_optimizer.Score(my_encoding)

  def test_BestUntriedEncodingReturnsSomething(self):
    my_optimizer = self.StdOptimizer()
    first_encoding = my_optimizer.BestEncoding(100, self.videofile)
    first_encoding.Execute().Store()
    other_encoding = my_optimizer.BestUntriedEncoding(100, self.videofile)
    self.assertTrue(other_encoding)
    self.assertNotEqual(first_encoding.encoder.parameters.ToString(),
                        other_encoding.encoder.parameters.ToString())

class TestFileAndRateSet(unittest.TestCase):

  def test_OneFileAddedAndReturned(self):
    the_set = optimizer.FileAndRateSet()
    the_set.AddFilesAndRates(['filename'], [100], 'dirname')
    self.assertEqual([(100, 'dirname/filename')], the_set.AllFilesAndRates())

  def test_NoDirName(self):
    the_set = optimizer.FileAndRateSet()
    the_set.AddFilesAndRates(['filename'], [100])
    self.assertEqual([(100, 'filename')], the_set.AllFilesAndRates())

  def test_OneFileMultipleRates(self):
    the_set = optimizer.FileAndRateSet()
    the_set.AddFilesAndRates(['filename'], [100, 200], 'dirname')
    self.assertEqual(set([(100, 'dirname/filename'),
                          (200, 'dirname/filename')]),
                     set(the_set.AllFilesAndRates()))

  def test_TwoAddCalls(self):
    the_set = optimizer.FileAndRateSet()
    the_set.AddFilesAndRates(['filename'], [100, 200], 'dirname')
    the_set.AddFilesAndRates(['otherfilename'], [200, 300], 'dirname')
    self.assertEqual(set([(100, 'dirname/filename'),
                          (200, 'dirname/filename'),
                          (200, 'dirname/otherfilename'),
                          (300, 'dirname/otherfilename')]),
                     set(the_set.AllFilesAndRates()))

  def test_RatesForFile(self):
    the_set = optimizer.FileAndRateSet()
    the_set.AddFilesAndRates(['filename'], [100, 200])
    the_set.AddFilesAndRates(['otherfilename'], [200, 300])
    self.assertEqual(set([100, 200]),
                     set(the_set.AllRatesForFile('filename')))

if __name__ == '__main__':
  unittest.main()


text:
<?xml version="1.0"?>
<!--

-->
<config>
    <profile>
        <websites>1</websites> <!-- Number of websites to generate -->
        <store_groups>1</store_groups> <!--Number of stores-->
        <store_views>1</store_views> <!-- Number of store views -->
        <simple_products>800</simple_products> <!-- Simple products count -->
        <configurable_products>50</configurable_products> <!--Configurable products count (each configurable has 3 simple products as options, that are not displayed individually in catalog) -->
        <categories>30</categories> <!-- Number of categories to generate -->
        <categories_nesting_level>3</categories_nesting_level> <!-- Nesting level for categories -->
        <catalog_price_rules>10</catalog_price_rules> <!-- Number os catalog price rules -->
        <cart_price_rules>10</cart_price_rules> <!-- Number of cart price rules -->
        <cart_price_rules_floor>2</cart_price_rules_floor> <!-- The price rule condition: minimum products amount in shopping cart for price rule to be applied -->
        <customers>20</customers> <!-- Number of customers to generate -->
        <tax_rates_file>tax_rates.csv</tax_rates_file> <!-- Tax rates file in fixtures directory-->
        <orders>80</orders> <!-- Orders count -->
        <configs> <!-- Config variables and values for change -->
            <config>
                <path>admin/security/use_form_key</path>
                <scope>default</scope>
                <scopeId>0</scopeId>
                <value>0</value>
            </config>
            <config>
                <path>carriers/flatrate/active</path>
                <scope>default</scope>
                <scopeId>0</scopeId>
                <value>1</value>
            </config>
        </configs>
        <indexers> <!-- Indexer mode value (true - Update by Schedule, false - Update on Save) -->
            <indexer>
                <id>catalog_category_product</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>catalog_product_category</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>catalog_product_price</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>catalog_product_attribute</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>cataloginventory_stock</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>catalogrule_rule</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>catalogrule_product</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
            <indexer>
                <id>catalogsearch_fulltext</id>
                <set_scheduled>false</set_scheduled>
            </indexer>
        </indexers>
    </profile>
</config>


text:
<?php

final class DrydockBlueprintViewController extends DrydockBlueprintController {

  private $id;

  public function willProcessRequest(array $data) {
    $this->id = $data['id'];
  }

  public function processRequest() {
    $request = $this->getRequest();
    $viewer = $request->getUser();

    $blueprint = id(new DrydockBlueprintQuery())
      ->setViewer($viewer)
      ->withIDs(array($this->id))
      ->executeOne();
    if (!$blueprint) {
      return new Aphront404Response();
    }

    $title = $blueprint->getBlueprintName();

    $header = id(new PHUIHeaderView())
      ->setHeader($title)
      ->setUser($viewer)
      ->setPolicyObject($blueprint);

    $actions = $this->buildActionListView($blueprint);
    $properties = $this->buildPropertyListView($blueprint, $actions);

    $blueprint_uri = 'blueprint/'.$blueprint->getID().'/';
    $blueprint_uri = $this->getApplicationURI($blueprint_uri);

    $resources = id(new DrydockResourceQuery())
      ->withBlueprintPHIDs(array($blueprint->getPHID()))
      ->setViewer($viewer)
      ->execute();

    $resource_list = $this->buildResourceListView($resources);
    $resource_list->setNoDataString(pht('This blueprint has no resources.'));

    $pager = new AphrontPagerView();
    $pager->setURI(new PhutilURI($blueprint_uri), 'offset');
    $pager->setOffset($request->getInt('offset'));

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->setActionList($actions);
    $crumbs->addTextCrumb(pht('Blueprint %d', $blueprint->getID()));

    $object_box = id(new PHUIObjectBoxView())
      ->setHeader($header)
      ->addPropertyList($properties);

    $xactions = id(new DrydockBlueprintTransactionQuery())
      ->setViewer($viewer)
      ->withObjectPHIDs(array($blueprint->getPHID()))
      ->execute();

    $engine = id(new PhabricatorMarkupEngine())
      ->setViewer($viewer);

    $timeline = id(new PhabricatorApplicationTransactionView())
      ->setUser($viewer)
      ->setObjectPHID($blueprint->getPHID())
      ->setTransactions($xactions)
      ->setMarkupEngine($engine);

    return $this->buildApplicationPage(
      array(
        $crumbs,
        $object_box,
        $resource_list,
        $timeline,
      ),
      array(
        'device'  => true,
        'title'   => $title,
      ));

  }

  private function buildActionListView(DrydockBlueprint $blueprint) {
    $viewer = $this->getRequest()->getUser();

    $view = id(new PhabricatorActionListView())
      ->setUser($viewer)
      ->setObjectURI($this->getRequest()->getRequestURI())
      ->setObject($blueprint);

    $uri = '/blueprint/edit/'.$blueprint->getID().'/';
    $uri = $this->getApplicationURI($uri);

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $blueprint,
      PhabricatorPolicyCapability::CAN_EDIT);

    $view->addAction(
      id(new PhabricatorActionView())
        ->setHref($uri)
        ->setName(pht('Edit Blueprint'))
        ->setIcon('edit')
        ->setWorkflow(!$can_edit)
        ->setDisabled(!$can_edit));

    return $view;
  }

  private function buildPropertyListView(
    DrydockBlueprint $blueprint,
    PhabricatorActionListView $actions) {

    $view = new PHUIPropertyListView();
    $view->setActionList($actions);

    $view->addProperty(
      pht('Type'),
      $blueprint->getImplementation()->getBlueprintName());

    return $view;
  }

}


text:
function [selectedFeatures] = FCBF(featureMatrix,classColumn,threshold)
%function [selectedFeatures] = FCBF(featureMatrix,classColumn,threshold)
%
%Performs feature selection using the FCBF measure by Yu and Liu 2004.
%
%Instead of selecting a fixed number of features it provides a relevancy threshold and selects all
%features which score above that and are not redundant
%
% The license is in the license.txt provided.

numFeatures = size(featureMatrix,2);
classScore = zeros(numFeatures,1);

for i = 1:numFeatures
    classScore(i) = SU(featureMatrix(:,i),classColumn);
end

[classScore indexScore] = sort(classScore,1,'descend');

indexScore = indexScore(classScore > threshold);
classScore = classScore(classScore > threshold);

if ~isempty(indexScore)
    curPosition = 1;
else
    curPosition = 0;
end

while curPosition <= length(indexScore)
    j = curPosition + 1;
    curFeature = indexScore(curPosition);
    while j <= length(indexScore)
        scoreij = SU(featureMatrix(:,curFeature),featureMatrix(:,indexScore(j)));
        if scoreij > classScore(j)
            indexScore(j) = [];
            classScore(j) = [];
        else
            j = j + 1;
        end
    end
    curPosition = curPosition + 1;
end

selectedFeatures = indexScore;

end

function [score] = SU(firstVector,secondVector)
%function [score] = SU(firstVector,secondVector)
%
%calculates SU = 2 * (I(X;Y)/(H(X) + H(Y)))

hX = h(firstVector);
hY = h(secondVector);
iXY = mi(firstVector,secondVector);

score = (2 * iXY) / (hX + hY);
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.view.vertical.VerticalViewPager
        android:id="@+id/verticalViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


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

namespace miataruclientcsharp
{
	public class MiataruLocation
	{
		public string Device { get; set; }
		public string Timestamp { get; set; }
		public string Longitude { get; set; }
		public string Latitude { get; set; }
		public string HorizontalAccuracy { get; set; }
	}

	public class MiataruNoLocation
	{
		public string Device { get; set; }
	}

	public class GetLocationResponse
	{
		public List<MiataruLocation> MiataruLocation { get; set; }
		public List<MiataruNoLocation> MiataruNoLocation { get; set; }
	}
}


text:
using NUnit.Framework;

namespace ServiceStack.OrmLite.MySql.Tests.Expressions
{
    public class RelationalExpressionsTest : ExpressionsTestBase
    {
        [Test]
        public void Can_select_greater_than_expression()
        {
            var expected = new TestType()
            {
                IntColumn = 1,
                BoolColumn = true,
                StringColumn = "test"
            };

            EstablishContext(10, expected);

            var actual = ConnectionString.OpenDbConnection().Select<TestType>(q => q.IntColumn > 1);

            Assert.IsNotNull(actual);
            Assert.AreEqual(10, actual.Count);
            CollectionAssert.DoesNotContain(actual, expected);
        }

        [Test]
        public void Can_select_greater_or_equal_than_expression()
        {
            var expected = new TestType()
            {
                IntColumn = 1,
                BoolColumn = true,
                StringColumn = "test"
            };

            EstablishContext(10, expected);

            var actual = ConnectionString.OpenDbConnection().Select<TestType>(q => q.IntColumn >= 1);

            Assert.IsNotNull(actual);
            Assert.AreEqual(11, actual.Count);
            CollectionAssert.Contains(actual, expected);
        }

        [Test]
        public void Can_select_smaller_than_expression()
        {
            var expected = new TestType()
            {
                IntColumn = 1,
                BoolColumn = true,
                StringColumn = "test"
            };

            EstablishContext(10, expected);

            var actual = ConnectionString.OpenDbConnection().Select<TestType>(q => q.IntColumn < 1);

            Assert.IsNotNull(actual);
            Assert.AreEqual(0, actual.Count);
        }

        [Test]
        public void Can_select_smaller_or_equal_than_expression()
        {
            var expected = new TestType()
            {
                IntColumn = 1,
                BoolColumn = true,
                StringColumn = "test"
            };

            EstablishContext(10, expected);

            var actual = ConnectionString.OpenDbConnection().Select<TestType>(q => q.IntColumn <= 1);

            Assert.IsNotNull(actual);
            Assert.AreEqual(1, actual.Count);
            CollectionAssert.Contains(actual, expected);
        }
    }
}


text:
/*!
 * angular-ui-scroll
 * https://github.com/angular-ui/ui-scroll.git
 * This module is deprecated since 1.6.0 and will be removed in future versions!
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('ui.scroll.jqlite', []);

})();


text:
import re

from getting_started import main

def test_main(cloud_config, capsys):
    main(cloud_config.project)

    out, _ = capsys.readouterr()

    assert re.search(re.compile(
        r'Query Results:.hamlet', re.DOTALL), out)


text:
<?php

App::uses("SOISController", "Controller");

class SalesforceSourcesController extends SOISController {
  // Class name, used by Cake
  public $name = "SalesforceSources";

  public $uses = array("SalesforceSource.SalesforceSource",
                       "OrgIdentitySource");

  /**
   * Salesforce OAuth callback.
   *
   * @since  COmanage Registry v3.1.0
   * @param  integer $id SalesforceSource ID
   */

  public function callback($id) {
    // We have to look in $_GET because what we get back isn't a Cake style named parameter
    // (ie: code=foo, not code:foo)

    try {
      if(empty($_GET['code']) || empty($_GET['state'])) {
        throw new RuntimeException(_txt('er.salesforcesource.callback'));
      }

      $oisid = $this->SalesforceSource->field('org_identity_source_id',
                                              array('SalesforceSource.id' => $id));

      if(!$oisid) {
        throw new InvalidArgumentException(_txt('er.notfound',
                                                array(_txt('ct.salesforce_sources.1', $id))));
      }

      $Backend = $this->OrgIdentitySource->instantiateBackendModel($oisid);

      $response = $Backend->exchangeCode($_GET['code'], base64_decode($_GET['state']));

      // Store the tokens

      $this->SalesforceSource->id = $id;
      $this->SalesforceSource->saveField('access_token', $response->access_token);
      $this->SalesforceSource->saveField('refresh_token', $response->refresh_token);
      // This will be (eg) cs67.salesforce.com
      if(!empty($response->instance_url)) {
        $this->SalesforceSource->saveField('instance_url', $response->instance_url);
      }
      // While we're here, clear the groupable attributes cache
      $this->SalesforceSource->saveField('groupable_attrs', null);

      $this->Flash->set(_txt('pl.salesforcesource.token.ok'), array('key' => 'success'));
    }
    catch(Exception $e) {
      $this->Flash->set($e->getMessage(), array('key' => 'error'));
    }

    $this->redirect(array(
      'plugin'     => 'salesforce_source',
      'controller' => 'salesforce_sources',
      'action'     => 'edit',
      $id
    ));
  }

  /**
   * Perform any followups following a write operation.  Note that if this
   * method fails, it must return a warning or REST response, but that the
   * overall transaction is still considered a success (add/edit is not
   * rolled back).
   * This method is intended to be overridden by model-specific controllers.
   *
   * @since  COmanage Registry v0.1
   * @param  Array Request data
   * @param  Array Current data
   * @param  Array Original request data (unmodified by callbacks)
   * @return boolean true if dependency checks succeed, false otherwise.
   */

  function checkWriteFollowups($reqdata, $curdata = null, $origdata = null) {
    if(!empty($reqdata['SalesforceSource']['serverurl'])
       && (empty($reqdata['SalesforceSource']['refresh_token'])
           || empty($reqdata['SalesforceSource']['access_token']))) {
      // Warn that no oauth token is present

      $this->Flash->set(_txt('pl.salesforcesource.token.missing'), array('key' => 'information'));
    }

    return true;
  }

  /**
   * Authorization for this Controller, called by Auth component
   * - precondition: Session.Auth holds data used for authz decisions
   * - postcondition: $permissions set with calculated permissions
   *
   * @since  COmanage Registry v3.1.0
   * @return Array Permissions
   */

  function isAuthorized() {
    $roles = $this->Role->calculateCMRoles();

    // Construct the permission set for this user, which will also be passed to the view.
    $p = array();

    // Determine what operations this user can perform

    // Accept an OAuth callback?
    $p['callback'] = ($roles['cmadmin'] || $roles['coadmin']);

    // Delete an existing SalesforceSource?
    $p['delete'] = ($roles['cmadmin'] || $roles['coadmin']);

    // Edit an existing SalesforceSource?
    $p['edit'] = ($roles['cmadmin'] || $roles['coadmin']);

    // View all existing SalesforceSources?
    $p['index'] = ($roles['cmadmin'] || $roles['coadmin']);

    // View API limits?
    $p['limits'] = ($roles['cmadmin'] || $roles['coadmin']);

    // View an existing SalesforceSource?
    $p['view'] = ($roles['cmadmin'] || $roles['coadmin']);

    $this->set('permissions', $p);
    return($p[$this->action]);
  }

  /**
   * View SalesforceSource limits.
   *
   * @since  COmanage Registry v3.1.0
   * @param  integer $id SalesforceSource ID
   */

  public function limits($id) {
    // We need the parent ID to instantiate the backend

    try {
      $oisid = $this->SalesforceSource->field('org_identity_source_id', array('SalesforceSource.id' => $id));

      if(!$oisid) {
        throw new InvalidArgumentException(_txt('er.notfound', array(_txt('ct.salesforce_sources.1'), $id)));
      }

      // Obtain limit information
      $Backend = $this->OrgIdentitySource->instantiateBackendModel($oisid);

      $this->set('vv_limits', $Backend->limits());
    }
    catch(Exception $e) {
      $this->Flash->set($e->getMessage(), array('key' => 'error'));
    }
  }
}


text:
define(['thruster/shapes/point2d'], function(Point2d){

	/**
	 * @class
	 * @memberof thruster.shapes
	 */
	var Circle = function(radius){
		/**
		 * Radius of the circle.
		 */
		this.radius = radius;
	};

	/**
	 * Returns the circumerence of this circle.
	 * @returns {Number}
	 */
	Circle.prototype.perimeter = function(){
		return 2 * Math.PI * this.radius;
	};

	/**
	 * Returns the area of this circle.
	 * @returns {Number}
	 */
	Circle.prototype.area = function(){
		return Math.PI * Math.pow(this.radius, 2);
	};

	return Circle;

});


text:
local Vector = require 'libs/vector'
local Entity = require 'entities/entity'
local Ship = require 'entities/ship'
local Bullet = require 'entities/bullet'
local Armor = require 'entities/armor'
local BasicGun = require 'entities/guns/basic-gun'
local PlayerPilot = require 'pilots/player-pilot'
local ReactorEffect = require 'entities/effects/reactor-effect'
local LightPulseEffect = require 'entities/effects/light-pulse-effect'
local PickedUpEffect = require 'entities/effects/picked-up-effect'

-- Classe PlayerShip
local PlayerShip = Ship:subclass('PlayerShip')

-- Image
local shipImage = love.graphics.newImage('assets/images/ship.png')
local laserDotImage = love.graphics.newImage('assets/images/laser-dot.png')

-- Constructeur
function PlayerShip:initialize(x, y, team)
  Ship.initialize(self, x, y, team)
  self.pilot = PlayerPilot:new(self)
  self.image = shipImage

  -- Stats
  self.health = 1000
  self.maxHealth = 1000

  -- Armure
  self.armor = Armor:new(self)
  table.insert(game.entities, self.armor)

  -- Laser
  self.hasLaser = true
  self.laserPulse = 0

  -- Création de l'élément dans le monde physique
  local mx, my, mass, inertia = self.body:getMassData()
  self.body:setMassData(mx, my, mass, inertia)

  self.shape = love.physics.newPolygonShape(16, 0, 0, -12, -16, -16, -16, 16, 0, 12)

  self.fixture = love.physics.newFixture(self.body, self.shape, 1)
  self.fixture:setUserData({entity = self})
  self.fixture:setFriction(1)

  --  Création du réacteur (générateur de particules)
  self.reactor = ReactorEffect:new(self, 0, 0, 0, self.secondaryColor)
  self.reactor.angle = - math.pi
  self.reactor.ps:setPosition(12, 0)

  -- Canons
  self.gun = BasicGun:new(self.pos.x, self.pos.y, self)
end

-- Affichage
function PlayerShip:draw()
  Ship.draw(self)

  -- Canon(s)
  self.gun:draw()

  -- Vaisseau
  self:attach()

  -- Réacteur
  love.graphics.setColor(255, 255, 255, 255)
  self.reactor:draw()

  -- Image du vaisseau
  love.graphics.setColor(self.color:get())
  love.graphics.draw(self.image, self.width / 2, - self.height / 2, math.pi / 2)

  self:detach()

  -- Laser
  if self.hasLaser and self == game.player then

    local lx1, ly1, lx2, ly2 = self.body:getWorldPoints(self.width / 2, 0, syst.width, 0)
    local hitx, hity = false, false

    -- Pour chaque entité visible du jeu
    for e, entity in ipairs(game:getVisibleEntities()) do

      if entity.enabled
        and not entity.toDestroy
        and entity.body
        and entity ~= self
        and not entity.isBullet
        and not entity.isArmor then

        -- Pour chaque fixture de l'entité
        for f, fixture in ipairs(entity.body:getFixtureList()) do
          local xn, yn, fraction = fixture:rayCast(lx1, ly1, lx2, ly2, 1)

          if xn then
            hitx, hity = lx1 + (lx2 - lx1) * fraction, ly1 + (ly2 - ly1) * fraction
            break
          end
        end

        if hitx then break end
      end
    end

    love.graphics.setLineWidth(1)
    love.graphics.setColor(self.secondaryColor:get(192 - 24 * math.cos(self.laserPulse)))
    love.graphics.line(lx1, ly1, hitx or lx2, hity or ly2)

    if hitx then
      love.graphics.draw(laserDotImage, hitx - laserDotImage:getWidth() / 2, hity - laserDotImage:getHeight() / 2)
    end
  end
end

-- Mise à jour
function PlayerShip:update(dt)
  Ship.update(self, dt)

  if self.enabled and not self.toDestroy then
    -- Mise à jour du réacteur (générateur de particules)
    self.reactor:update(dt)

    -- Mise à jour du laser (clignotement)
    self.laserPulse = self.laserPulse + dt * 10

    -- Mise à jour du tir des canons
    self.gun.firing = self.pilot.controls.fire_main
    self.gun:update(dt)
  end
end

return PlayerShip


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts

Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions

    <Extension()>
    Friend Module StringExtensions

        <Extension()>
        Public Function TryReduceAttributeSuffix(
            identifierText As String,
            ByRef withoutSuffix As String) As Boolean

            ' we can't reduce _Attribute to _ because this is not a valid identifier
            Dim halfWidthValueText = SyntaxFacts.MakeHalfWidthIdentifier(identifierText)
            If halfWidthValueText.GetWithoutAttributeSuffix(isCaseSensitive:=False) <> Nothing AndAlso
                Not (halfWidthValueText.Length = 10 AndAlso halfWidthValueText(0) = "_") Then

                withoutSuffix = identifierText.Substring(0, identifierText.Length - 9)
                Return True
            End If

            Return False
        End Function

        <Extension()>
        Public Function EscapeIdentifier(text As String, Optional afterDot As Boolean = False, Optional symbol As ISymbol = Nothing, Optional withinAsyncMethod As Boolean = False) As String
            Dim keywordKind = SyntaxFacts.GetKeywordKind(text)
            Dim needsEscaping = keywordKind <> SyntaxKind.None

            ' REM and New must always be escaped, but there are some conditions where
            ' keywords are not escaped
            If needsEscaping AndAlso
                keywordKind <> SyntaxKind.REMKeyword AndAlso
                keywordKind <> SyntaxKind.NewKeyword Then

                needsEscaping = Not afterDot

                If needsEscaping Then
                    Dim typeSymbol = TryCast(symbol, ITypeSymbol)
                    needsEscaping = typeSymbol Is Nothing OrElse Not IsPredefinedType(typeSymbol)
                End If
            End If

            ' GetKeywordKind won't return SyntaxKind.AwaitKeyword (943836)
            If withinAsyncMethod AndAlso text = "Await" Then
                needsEscaping = True
            End If

            Return If(needsEscaping, "[" & text & "]", text)
        End Function

        <Extension()>
        Public Function ToIdentifierToken(text As String, Optional afterDot As Boolean = False, Optional symbol As ISymbol = Nothing, Optional withinAsyncMethod As Boolean = False) As SyntaxToken
            Contract.ThrowIfNull(text)

            Dim unescaped = text
            Dim wasAlreadyEscaped = False

            If text.Length > 2 AndAlso MakeHalfWidthIdentifier(text.First()) = "[" AndAlso MakeHalfWidthIdentifier(text.Last()) = "]" Then
                unescaped = text.Substring(1, text.Length() - 2)
                wasAlreadyEscaped = True
            End If

            Dim escaped = EscapeIdentifier(text, afterDot, symbol, withinAsyncMethod)
            Dim token = If(escaped.Length > 0 AndAlso escaped(0) = "["c,
                SyntaxFactory.Identifier(escaped, isBracketed:=True, identifierText:=unescaped, typeCharacter:=TypeCharacter.None),
                SyntaxFactory.Identifier(text))

            If Not wasAlreadyEscaped Then
                token = token.WithAdditionalAnnotations(Simplifier.Annotation)
            End If

            Return token
        End Function

        <Extension()>
        Public Function ToModifiedIdentifier(text As String) As ModifiedIdentifierSyntax
            Return SyntaxFactory.ModifiedIdentifier(text.ToIdentifierToken)
        End Function

        <Extension()>
        Public Function ToIdentifierName(text As String) As IdentifierNameSyntax
            Contract.ThrowIfNull(text)
            Return SyntaxFactory.IdentifierName(text.ToIdentifierToken()).WithAdditionalAnnotations(Simplifier.Annotation)
        End Function

        Private Function IsPredefinedType(type As ITypeSymbol) As Boolean
            Select Case type.SpecialType
                Case SpecialType.System_Boolean,
                     SpecialType.System_Byte,
                     SpecialType.System_SByte,
                     SpecialType.System_Int16,
                     SpecialType.System_UInt16,
                     SpecialType.System_Int32,
                     SpecialType.System_UInt32,
                     SpecialType.System_Int64,
                     SpecialType.System_UInt64,
                     SpecialType.System_Single,
                     SpecialType.System_Double,
                     SpecialType.System_Decimal,
                     SpecialType.System_DateTime,
                     SpecialType.System_Char,
                     SpecialType.System_String,
                     SpecialType.System_Object
                    Return True
                Case Else
                    Return False
            End Select
        End Function

    End Module
End Namespace


text:
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="build" name="Java Information Dynamics Toolkit">
	<description>
		Build file for the Java Information Dynamics Toolkit
	</description>

	<!-- set global properties for this build -->
	<property name="version" value="1.2.1"/>
	<property name="mainfilename" value="infodynamics"/>
	<property name="jarplainname" value="${mainfilename}.jar" />
	<property name="jarversiondistnamezip" value="${mainfilename}-jar-${version}.zip" />
	<property name="distname" value="${mainfilename}-dist-${version}" />
	<property name="distnamezip" value="${distname}.zip" />
	<property name="src" location="java/source"/>
	<property name="bin" location="bin"/>
	<property name="unittestsouttoplevel" location="unittests"/>
	<property name="unittestssrc" location="java/unittests"/>
	<property name="unittestsbin" location="${unittestsouttoplevel}/bin"/>
	<property name="reports.tests" location="${unittestsouttoplevel}/reports"/>
	<property name="javadocsdir" location="javadocs"/>
	<property name="versionfile" value="version-${version}.txt"/>

	<path id="project.classpath">
		<pathelement location="bin"/>
	</path>

	<!-- Make required directories -->
	<target name="init" description="Create the compiled code directories">
		<mkdir dir="${bin}"/>
		<mkdir dir="${unittestsbin}"/>
		<mkdir dir="${reports.tests}"/>
	</target>

	<!-- Compile the java toolkit -->
	<target name="compile" depends="init" description="compile the source and unittests">
		<!-- Compile to Java 6 to provide compatibility for users with older JREs.
		     Caveat: The flags here only check the language compatibility, but
		     may still use newer libraries which may cause issues for users with JDK 6.
		     Indeed, one gets the warning: "bootstrap class path not set in conjunction with -source 1.6"
		     To fix this, one would use the bootstrap classpath to point our JDK to an rt.jar
		     for Java 6.
		     At this stage, I'm sure I'm not using new library calls from Java 7, so we can
		     ignore the warning, and I don't want to bother installing Java 6 just to compile
		     like this. I'll endeavour not to use JDK 7 libraries so as not to cause
		     any issues here ... -->
		<javac srcdir="${src}" destdir="${bin}" includeAntRuntime="false" target="1.6" source="1.6"/>
	</target>

	<!-- Jar the toolkit -->
	<target name="jar" depends="compile" description="Create the jar for distribution">
		<!-- Put everything in ${bin} into the infodynamics-${version}.jar file -->
		<jar jarfile="${jarplainname}" basedir="${bin}"/>
	</target>

	<!-- Compile and run the JUnit tests -->
	<target name="junit" depends="compile" description="Run the junit tests and make sure they compile">
		<!-- Compile the junit tests first -->
		<javac destdir="${unittestsbin}" includeAntRuntime="true">
			<!-- Need includeAntRuntime=true if you want to pick up junit.jar and ant-junit.jar in ANT_HOME/lib;
			     Otherwise you will need to set the classpath to include these here. -->
			<src path="${unittestssrc}"/>
			<classpath refid="project.classpath"/>
		</javac>
		<!-- Run the junit tests and make sure they complete ok -->
		<junit printsummary="yes" showoutput="yes" haltonfailure="yes" haltonerror="yes" includeantruntime="true">
			<classpath>
				<path refid="project.classpath"/>
				<pathelement path="${unittestsbin}"/>
			</classpath>
			<formatter type="plain"/>
			<batchtest todir="${reports.tests}"> <!-- Writes full reports with stdout and stderr to ${reports.tests} -->
				<fileset dir="${unittestsbin}">
					<include name="**/*.class"/>
					<exclude name="**/*AbstractTester.class"/>
					<exclude name="**/ActiveInfoStorageCalculatorCorrelationIntegrals.class"/>
					<exclude name="**/ActiveInfoStorageCalculatorKernelDirect.class"/>
				</fileset>
			</batchtest>
		</junit>
	</target>

	<!-- Make javadocs, excluding the classes we've derived from Apache Commons Math -->
	<target name="javadocs" depends="compile" description="Make the javadocs for the toolkit">
		<delete dir="${javadocsdir}"/>
		<javadoc destdir="${javadocsdir}">
			<fileset dir="${src}">
				<include name="**/*.java"/>
				<exclude name="**/commonsmath3/*.java"/>
				<exclude name="**/commonsmath3/**/*.java"/>
			</fileset>
		</javadoc>
		<!-- Change some of the style in the javadocs css for our lists: -->
		<concat destfile="${javadocsdir}/stylesheet.css" append="true">
		.block ul li {list-style:disc; margin-left: 20px;}
		.block ol li {list-style:decimal; margin-left: 40px;}
		.block ol li ol li {list-style:lower-alpha; margin-left: 40px;}
		.block ol li ul li {list-style:disc; margin-left: 40px;}
		.block ol li ul li ol li {list-style:lower-alpha; margin-left: 40px;}
		.block ol li ol li ol li {list-style:lower-roman; margin-left: 40px;}
		.block ul li ol li {list-style:decimal; margin-left: 20px;}
		</concat>
	</target>

	<!-- Clean up -->
	<target name="clean">
		<!-- Delete the compiled code directories -->
		<delete dir="${bin}"/>
		<delete dir="${unittestsbin}"/>
		<delete dir="${reports.tests}"/>
		<delete dir="${unittestsouttoplevel}"/>
		<delete dir="${javadocsdir}"/>
		<delete dir="demos/clojure/target"/>
		<delete file="demos/clojure/pom.xml"/>
		<delete file="demos/clojure/pom.xml.asc"/>
		<delete file="demos/clojure/project.clj"/>
		<delete file="${jarversiondistnamezip}"/>
		<delete file="${distnamezip}"/>
		<delete file="${jarplainname}"/>
		<!-- Don't delete the readme and version files - the user may not have the template to recreate them from -->
	</target>

	<!-- Build the project jar for users -->
	<target name="build" depends="jar" description="user: build the project jar file">
		<echo message="${ant.project.name}: ${ant.file}"/>
	</target>

	<!--
	***********************************

	Developer builds below here

	***********************************
	-->

	<!-- Developer build - creates readme and version files -->
	<target name="readmefiles" description="developer: create the readme and version files from templates">
		<tstamp>
			<format property="TODAY_DATE" pattern="dd/MM/yyyy" locale="en,UK"/>
			<format property="TODAY_YEAR" pattern="yyyy" locale="en,UK"/>
		</tstamp>
		<copy file="readme-template.txt" toFile="readme.txt" failonerror="false" overwrite="true">
			<!-- The template file only exists in SVN - this won't crash ant
			     if users try to run it though because failonerror="false" -->
			<filterset>
				<filter token="YEAR" value="${TODAY_YEAR}"/>
				<filter token="DATE" value="${TODAY_DATE}"/>
				<filter token="VERSION" value="${version}"/>
			</filterset>
		</copy>
		<copy file="version-template.txt" toFile="${versionfile}" failonerror="false">
			<!-- The template file only exists in SVN - this won't crash ant
			     if users try to run it though because failonerror="false" -->
			<filterset>
				<filter token="YEAR" value="${TODAY_YEAR}"/>
				<filter token="DATE" value="${TODAY_DATE}"/>
				<filter token="VERSION" value="${version}"/>
			</filterset>
		</copy>
		<copy file="demos/clojure/deploy/project-template.clj" toFile="demos/clojure/deploy/project.clj" failonerror="false" overwrite="true">
			<!-- The template file only exists in SVN - this won't crash ant
			     if users try to run it though because failonerror="false" -->
			<filterset>
				<filter token="VERSION" value="${version}"/>
			</filterset>
		</copy>
	</target>

	<!-- Developer build - builds everything and makes the jar only distribution file -->
	<target name="jardist" depends="build,readmefiles" description="developer: generate the jar distribution">
		<zip destfile="${jarversiondistnamezip}">
			<fileset file="${jarplainname}"/>
			<fileset file="license-gplv3.txt"/>
			<fileset file="readme.txt"/>
			<fileset file="${versionfile}"/>
			<zipfileset dir="notices" includes="**/*.*,**/*" prefix="notices"/>
		</zip>
	</target>

	<!-- Developer build - builds everything and makes the full distribution file -->
	<target name="dist" depends="jar,junit,javadocs,readmefiles" description="developer: generate the full distribution">
		<echo message="${ant.project.name}: ${ant.file}"/>
		<zip destfile="${distnamezip}">
			<fileset file="build.xml"/>
			<fileset file="${jarplainname}"/>
			<fileset file="license-gplv3.txt"/>
			<fileset file="readme.txt"/>
			<fileset file="InfoDynamicsToolkit.pdf"/>
			<fileset file="${versionfile}"/>
			<zipfileset dir="java" includes="**/*.java" prefix="java"/>
			<zipfileset dir="demos" includes="**/*.*,**/*" excludes="clojure/deploy,clojure/deploy/*.*,python/*.pyc" prefix="demos"/>
			<zipfileset dir="javadocs" includes="**/*.*,**/*" prefix="javadocs"/>
			<zipfileset dir="notices" includes="**/*.*,**/*" prefix="notices"/>
			<zipfileset dir="tutorial" prefix="tutorial"/>
		</zip>
	</target>
</project>


text:
package org.stagemonitor.core.util;

import com.fasterxml.jackson.databind.JsonNode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.xml.bind.DatatypeConverter;

// TODO create HttpRequest POJO
// method, url, headers, outputStreamHandler, responseHandler
// builder methods logErrors(int... excludedStatusCodes)
public class HttpClient {

	private static final long CONNECT_TIMEOUT_SEC = 5;
	private static final long READ_TIMEOUT_SEC = 15;
	private final Logger logger = LoggerFactory.getLogger(getClass());

	public int send(final String method, final String url) {
		return send(method, url, null, null);
	}

	public JsonNode getJson(String url, Map<String, String> headers) {
		headers = new HashMap<String, String>(headers);
		headers.put("Accept", "application/json");
		return send("GET", url, headers, null, new ResponseHandler<JsonNode>() {
			@Override
			public JsonNode handleResponse(InputStream is, Integer statusCode, IOException e) throws IOException {
				return JsonUtils.getMapper().readTree(is);
			}
		});
	}

	public int sendAsJson(final String method, final String url, final Object requestBody) {
		return sendAsJson(method, url, requestBody, new HashMap<String, String>());
	}

	public int sendAsJson(final String method, final String url, final Object requestBody, Map<String, String> headerFields) {
		headerFields = new HashMap<String, String>(headerFields);
		headerFields.put("Content-Type", "application/json");
		return send(method, url, headerFields, new OutputStreamHandler() {
			@Override
			public void withHttpURLConnection(OutputStream os) throws IOException {
				writeRequestBody(requestBody, os);
			}
		});
	}

	public int send(String method, String url, final List<String> requestBodyLines) {

		return send(method, url, null, new OutputStreamHandler() {
			@Override
			public void withHttpURLConnection(OutputStream os) throws IOException {
				for (String line : requestBodyLines) {
					os.write(line.getBytes("UTF-8"));
					os.write('\n');
				}
				os.flush();
			}
		});
	}

	public int send(final String method, final String url, final Map<String, String> headerFields, OutputStreamHandler outputStreamHandler) {
		Integer result = send(method, url, headerFields, outputStreamHandler, new ErrorLoggingResponseHandler(url));
		return result == null ? -1 : result;
	}

	public <T> T send(final String method, final String url, final Map<String, String> headerFields,
					  OutputStreamHandler outputStreamHandler, ResponseHandler<T> responseHandler) {

		HttpURLConnection connection = null;
		InputStream inputStream = null;
		try {
			URL parsedUrl = new URL(url);
			connection = (HttpURLConnection) parsedUrl.openConnection();
			if (parsedUrl.getUserInfo() != null) {
				String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(parsedUrl.getUserInfo().getBytes());
				connection.setRequestProperty("Authorization", basicAuth);
			}
			connection.setDoOutput(true);
			connection.setRequestMethod(method);
			connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(CONNECT_TIMEOUT_SEC));
			connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(READ_TIMEOUT_SEC));
			if (headerFields != null) {
				for (Map.Entry<String, String> header : headerFields.entrySet()) {
					connection.setRequestProperty(header.getKey(), header.getValue());
				}
			}

			if (outputStreamHandler != null) {
				outputStreamHandler.withHttpURLConnection(connection.getOutputStream());
			}

			inputStream = connection.getInputStream();

			return responseHandler.handleResponse(inputStream, connection.getResponseCode(), null);
		} catch (IOException e) {
			if (connection != null) {
				inputStream = connection.getErrorStream();
				try {
					return responseHandler.handleResponse(inputStream, getResponseCodeIfPossible(connection), e);
				} catch (IOException e1) {
					logger.warn("Error sending {} request to url {}: {}", method, url, e.getMessage(), e);
					logger.warn("Error handling error response for {} request to url {}: {}", method, url, e1.getMessage(), e1);
					try {
						logger.trace(new String(IOUtils.readToBytes(inputStream), "UTF-8"));
					} catch (IOException e2) {
						logger.trace("Could not read error stream: {}", e2.getMessage(), e2);
					}
				}
			} else {
				logger.warn("Error sending {} request to url {}: {}", method, url, e.getMessage(), e);
			}

			return null;
		} finally {
			IOUtils.closeQuietly(inputStream);
		}
	}

	private Integer getResponseCodeIfPossible(HttpURLConnection connection) {
		try {
			return connection.getResponseCode();
		} catch (IOException e) {
			// don't handle exception twice
			return null;
		}
	}

	private void writeRequestBody(Object requestBody, OutputStream os) throws IOException {
		if (requestBody != null) {
			if (requestBody instanceof InputStream) {
				IOUtils.copy((InputStream) requestBody, os);
			} else if (requestBody instanceof String) {
				os.write(((String)requestBody).getBytes("UTF-8"));
			} else {
				JsonUtils.writeJsonToOutputStream(requestBody, os);
			}
			os.flush();
		}
	}

	public interface OutputStreamHandler {
		void withHttpURLConnection(OutputStream os) throws IOException;
	}

	public interface ResponseHandler<T> {
		T handleResponse(InputStream is, Integer statusCode, IOException e) throws IOException;
	}

	private static class ErrorLoggingResponseHandler implements ResponseHandler<Integer> {

		private final Logger logger = LoggerFactory.getLogger(getClass());

		private final String url;

		public ErrorLoggingResponseHandler(String url) {
			this.url = url;
		}

		@Override
		public Integer handleResponse(InputStream is, Integer statusCode, IOException e) throws IOException {
			if (statusCode == null) {
				return -1;
			}
			if (statusCode >= 400) {
				logger.warn(url + ": " + statusCode + " " + IOUtils.toString(is));
			} else {
				IOUtils.consumeAndClose(is);
			}
			return statusCode;
		}
	}
}


text:
using System;

namespace KinderChat.Helpers
{
    public class DisposableAction : IDisposable
    {
        private readonly Action action;

        public DisposableAction(Action action)
        {
            this.action = action;
        }

        public void Dispose()
        {
            if (action != null)
                action();
        }
    }
}


text:
package ubic.gemma.web.propertyeditor;

import ubic.gemma.model.genome.biosequence.SequenceType;

import java.beans.PropertyEditorSupport;

/**
 * @author pavlidis
 *
 */
public class SequenceTypePropertyEditor extends PropertyEditorSupport {

    @Override
    public String getAsText() {
        if ( this.getValue() == null ) {
            return "[Not available]";
        }

        SequenceType type = ( SequenceType ) this.getValue();

        if ( type.equals( SequenceType.EST ) ) {
            return "EST";
        } else if ( type.equals( SequenceType.mRNA ) ) {
            return "mRNA";
        } else if ( type.equals( SequenceType.WHOLE_CHROMOSOME ) ) {
            return "Whole Chromosome";
        } else if ( type.equals( SequenceType.DNA ) ) {
            return "DNA";
        } else if ( type.equals( SequenceType.AFFY_COLLAPSED ) ) {
            return "Collapsed Affymetrix Probes";
        } else if ( type.equals( SequenceType.OLIGO ) ) {
            return "Oligo";
        } else if ( type.equals( SequenceType.AFFY_TARGET ) ) {
            return "Affymetrix Target";
        } else if ( type.equals( SequenceType.AFFY_PROBE ) ) {
            return "Affymetrix Probe";
        } else if ( type.equals( SequenceType.REFSEQ ) ) {
            return "RefSeq";
        } else if ( type.equals( SequenceType.BAC ) ) {
            return "BAC";
        } else if ( type.equals( SequenceType.WHOLE_GENOME ) ) {
            return "Whole Genome";
        } else if ( type.equals( SequenceType.OTHER ) ) {
            return "Other";
        } else if ( type.equals( SequenceType.ORF ) ) {
            return "ORF";
        } else {
            return "[Unknown]";
        }

    }

    @Override
    public void setAsText( String text ) throws IllegalArgumentException {
        this.setValue( SequenceType.fromString( text ) );
    }

}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe ActsAsArchive::Migration do

  before(:each) do
    establish_test_db
    Article.create_archive_table
  end

  describe 'method_missing_with_archive' do

    it 'should migrate both tables up' do
      migrate_up
      (@new_article_columns - @old_article_columns).should == [ 'permalink' ]
      (@new_archive_columns - @old_archive_columns).should == [ 'permalink' ]
    end

    it 'should migrate both tables down' do
      migrate_up
      @old_article_columns = @new_article_columns
      @old_archive_columns = @new_archive_columns
      ActiveRecord::Migrator.migrate("#{SPEC}/db/migrate", 0)
      @new_article_columns = columns("articles")
      @new_archive_columns = columns("archived_articles")
      (@old_article_columns - @new_article_columns).should == [ 'permalink' ]
      (@old_archive_columns - @new_archive_columns).should == [ 'permalink' ]
    end

    it "should not touch the archive's deleted_at column" do
      connection.add_column(:articles, :deleted_at, :datetime)
      Article.reset_column_information
      migrate_up("migrate_2")
      (@old_article_columns - @new_article_columns).should == [ 'deleted_at' ]
      (@old_archive_columns - @new_archive_columns).should == []
    end
  end
end


text:
from django.conf.urls import patterns, url

from admins import views

urlpatterns = patterns(
    '',
    # Control panels
    url(r'^admin/overview/$', views.overview, name='admin_overview'),

)


text:
package cli

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestGPG(t *testing.T) {
	t.Parallel()

	if testing.Short() {
		t.Skip("skipping test in short mode.")
	}

	ctx := context.Background()

	var err error
	var g *GPG

	assert.Equal(t, "", g.Binary())

	g, err = New(ctx, Config{})
	require.NoError(t, err)
	assert.NotEqual(t, "", g.Binary())

	_, err = g.ListRecipients(ctx)
	assert.NoError(t, err)

	_, err = g.ListIdentities(ctx)
	assert.NoError(t, err)

	_, err = g.RecipientIDs(ctx, []byte{})
	assert.Error(t, err)

	assert.NoError(t, g.Initialized(ctx))
	assert.Equal(t, "gpg", g.Name())
	assert.Equal(t, "gpg", g.Ext())
	assert.Equal(t, ".gpg-id", g.IDFile())
}


text:
""" Test Django Backend."""
from __future__ import absolute_import
import os

try:
    from django.core.urlresolvers import RegexURLPattern
    from django.test import TestCase
except ImportError:
    import unittest
    raise unittest.SkipTest('Django not found for testing')

from ...backend.django import JSONRPCAPI, api
import json

class TestDjangoBackend(TestCase):
    @classmethod
    def setUpClass(cls):
        os.environ['DJANGO_SETTINGS_MODULE'] = \
            'jsonrpc.tests.test_backend_django.settings'
        super(TestDjangoBackend, cls).setUpClass()

    def test_urls(self):
        self.assertTrue(isinstance(api.urls, list))
        for api_url in api.urls:
            self.assertTrue(isinstance(api_url, RegexURLPattern))

    def test_client(self):
        @api.dispatcher.add_method
        def dummy(request):
            return ""

        json_data = {
            "id": "0",
            "jsonrpc": "2.0",
            "method": "dummy",
        }
        response = self.client.post(
            '',
            json.dumps(json_data),
            content_type='application/json',
        )
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf8'))
        self.assertEqual(data['result'], '')

    def test_positional_args(self):
        @api.dispatcher.add_method
        def positional_args(request, name):
            return name

        json_data = {
            "id": "0",
            "jsonrpc": "2.0",
            "method": "positional_args",
            "params": ["echome!"],
        }
        response = self.client.post(
            '',
            json.dumps(json_data),
            content_type='application/json',
        )
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf8'))
        self.assertEqual(data['result'], json_data['params'][0])

    def test_method_not_allowed(self):
        response = self.client.get(
            '',
            content_type='application/json',
        )
        self.assertEqual(response.status_code, 405, "Should allow only POST")

    def test_invalid_request(self):
        response = self.client.post(
            '',
            '{',
            content_type='application/json',
        )
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf8'))
        self.assertEqual(data['error']['code'], -32700)
        self.assertEqual(data['error']['message'], 'Parse error')

    def test_resource_map(self):
        response = self.client.get('/map')
        self.assertEqual(response.status_code, 200)
        data = response.content.decode('utf8')
        self.assertIn("JSON-RPC map", data)

    def test_method_not_allowed_prefix(self):
        response = self.client.get(
            '/prefix/',
            content_type='application/json',
        )
        self.assertEqual(response.status_code, 405)

    def test_resource_map_prefix(self):
        response = self.client.get('/prefix/map')
        self.assertEqual(response.status_code, 200)

    def test_empty_initial_dispatcher(self):
        class SubDispatcher(type(api.dispatcher)):
            pass

        custom_dispatcher = SubDispatcher()
        custom_api = JSONRPCAPI(custom_dispatcher)
        self.assertEqual(type(custom_api.dispatcher), SubDispatcher)
        self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher))

    def test_batch_request(self):
        @api.dispatcher.add_method
        def upper(request, name):
            return name.upper()

        json_data = [{
            "id": "0",
            "jsonrpc": "2.0",
            "method": "upper",
            "params": ["hello"],
        }, {
            "id": "1",
            "jsonrpc": "2.0",
            "method": "upper",
            "params": ["world"],
        }]
        response = self.client.post(
            '',
            json.dumps(json_data),
            content_type='application/json',
        )
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf8'))
        self.assertEqual(len(data), len(json_data))
        self.assertEqual(data[0]['result'], json_data[0]['params'][0].upper())