text:
% function: spikeTimes

function spikeTime=spikeTimes(V, T, thresh, minISIstep, varargin)
    if ismatrix(V) && ~isvector(V)
        % If we get a matrix, assume voltages of diff neurons
        % (num time steps) x (num neuron)
        [numTime, numNeur] = size(V);
        if numNeur > numTime
            error(['number of neurons > number of time steps; do you ' ...
                   'need to transpose your voltage?'])
        end
        spikeTime = cell(numNeur, 1);
        for neur = 1:numNeur
            % recursion!
            spikeTime{neur} = spikeTimes(V(:, neur), T, thresh, ...
                                         minISIstep, neur);
        end
    else
        % We got a vector, so find the peaks
        s = warning('error', ['signal:findpeaks:' ...
                            'largeMinPeakHeight']);
        warning('error', 'signal:findpeaks:largeMinPeakHeight');
        try
            [spikeV, spikeLoc] = findpeaks(V, ...
                                           'minpeakheight', thresh, ...
                                           'minpeakdistance', ...
                                           minISIstep);
        catch
            fprintf('no spikes found for neuron id %d\n', ...
                    varargin{1});
            spikeLoc = [];
        end
        warning(s);
        % Return the spike times
        spikeTime = T(spikeLoc);
    end


text: {{ app }}<child-component-a></child-component-a><child-component-b></child-component-b>

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function () {
	function pageY(elem) {
		return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
	}

	var buffer = 5; //scroll bar buffer
	function resizeIframe() {
		var height = document.documentElement.clientHeight;
		height -= pageY(document.getElementById('ifm')) + buffer;
		height = (height < 0) ? 0 : height;
		document.getElementById('ifm').style.height = height + 'px';
	}

	document.getElementById('ifm').onload = resizeIframe;
	window.onresize = resizeIframe;
});


text:
#ifndef V0_TSDATA_INL_H
#define V0_TSDATA_INL_H

#include "../tsdata_mime.h"

namespace monsoon {
namespace history {
namespace v0 {

template<typename Fn>
void tsdata_v0::visit(Fn fn) const {
  const auto r = make_xdr_istream(true);
  auto hdr = tsfile_mimeheader(*r); // Decode and discard.
  decode_tsfile_header(*r); // Decode and discard.

  while (!r->at_end())
    std::invoke(fn, decode_time_series(*r));
  r->close();
}

}}} /* namespace monsoon::history::v0 */

#endif /* V0_TSDATA_INL_H */


text:
//LogfileHelpers module
/*
This module contains functions that help filter lists of logfiles.
This module should be imported and used by the LogPuller class to filter log file names.
*/

const async = require('async');

function log_less_than_max(filename, max){
  //@param {String} filename – Valid logfile name.
  //@param {int} max – optional maximum lognum that's acceptable. Reject if log exceeds max
  //@return {bool} – True if this logfile is less than max
  //If only one '.' in log, we definitely want it (it's the first log)
  if (max){
    //Pull the number off the end and compare it
    var log_num = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
    log_num = parseInt(log_num);
    if (!(log_num> max)){
      return true;
    }
  } else {
    return true;
  }
}

function fileListFromDirList(dirList, collect_all_logs, num_logs){
    var file_list = dirList.filter((file)=>{  //returns array with only filenames and optionally filtered by max
      if(!file.attrs.isDirectory()){
        if(collect_all_logs){
          return true;
        } else if (log_less_than_max(file.filename,num_logs)) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    });
    var filtered_list = file_list.map((val)=>{return val.filename}); //map file objects to
    console.log(filtered_list);
    return filtered_list;
}

function asyncFilePull(sftp, file_list, base_path, out_path, isCancelled, progress, callback){

  let count = 0;
  let length = file_list.length;

  async.whilst(
    ()=>{  //test
      return (count < length && !isCancelled());
    },
   (async_cb)=>{  // if test passed.
     let filename = file_list[count];
     count++;
     sftp.fastGet(base_path + `/${filename}`, out_path + `/${filename}`, {concurrency:1}, (err)=>{
       if (err) async_cb(err); // call the final function with an error
       else {
         let percentage = Math.round(count/length*100);
         progress(percentage);
         async_cb(null);
       }
     });
    },
    (err)=>{ // if err we'll get an error; otherwise completed
      if (err){
        console.log("Logpull complete (final callback called) but with error: ");
        console.log(err);
      } else {
        console.log("completed logpull successfully");
        progress(0);
        callback();
      }
    });
}

function generate_date_string(){
    // Returns date string to use for log folders
    var date = new Date();
    let date_string = date.getFullYear() + "_" + (date.getMonth() + 1).toString() + "_" + date.getDate() + "_" + date.getHours() + "_" + date.getMinutes();
    console.log(date_string);
    return date_string;
}

module.exports = {
  log_less_than_max: log_less_than_max,
  fileListFromDirList: fileListFromDirList,
  asyncFilePull: asyncFilePull,
  generate_date_string: generate_date_string
}

if (require.main === module){
  console.log(generate_date_string());
};


text:
FROM %%KOLLA_NAMESPACE%%/%%KOLLA_PREFIX%%glance-base
MAINTAINER Kolla Project (https://launchpad.net/kolla)

EXPOSE 9191

ADD ./start.sh /start.sh
CMD ["/start.sh"]


text:
import {LanguageServiceTestEnv} from './env';
import {Project, ProjectFiles, TestableOptions} from './project';

/**
 * Expect that a list of objects with a `fileName` property matches a set of expected files by only
 * comparing the file names and not any path prefixes.
 *
 * This assertion is independent of the order of either list.
 */
export function assertFileNames(refs: Array<{fileName: string}>, expectedFileNames: string[]) {
  const actualPaths = refs.map(r => r.fileName);
  const actualFileNames = actualPaths.map(p => last(p.split('/')));
  expect(new Set(actualFileNames)).toEqual(new Set(expectedFileNames));
}

export function assertTextSpans(items: Array<{textSpan: string}>, expectedTextSpans: string[]) {
  const actualSpans = items.map(item => item.textSpan);
  expect(new Set(actualSpans)).toEqual(new Set(expectedTextSpans));
}

/**
 * Returns whether the given `ts.Diagnostic` is of a type only produced by the Angular compiler (as
 * opposed to being an upstream TypeScript diagnostic).
 *
 * Template type-checking diagnostics are not "ng-specific" in this sense, since they are plain
 * TypeScript diagnostics that are produced from expressions in the template by way of a TCB.
 */
export function isNgSpecificDiagnostic(diag: ts.Diagnostic): boolean {
  // Angular-specific diagnostics use a negative code space.
  return diag.code < 0;
}

function getFirstClassDeclaration(declaration: string) {
  const matches = declaration.match(/(?:export class )(\w+)(?:\s|\{|<)/);
  if (matches === null || matches.length !== 2) {
    throw new Error(`Did not find exactly one exported class in: ${declaration}`);
  }
  return matches[1].trim();
}

export function createModuleAndProjectWithDeclarations(
    env: LanguageServiceTestEnv, projectName: string, projectFiles: ProjectFiles,
    options: TestableOptions = {}, standaloneFiles: ProjectFiles = {}): Project {
  const externalClasses: string[] = [];
  const externalImports: string[] = [];
  for (const [fileName, fileContents] of Object.entries(projectFiles)) {
    if (!fileName.endsWith('.ts')) {
      continue;
    }
    const className = getFirstClassDeclaration(fileContents);
    externalClasses.push(className);
    externalImports.push(`import {${className}} from './${fileName.replace('.ts', '')}';`);
  }
  const moduleContents = `
        import {NgModule} from '@angular/core';
        import {CommonModule} from '@angular/common';
        ${externalImports.join('\n')}

        @NgModule({
          declarations: [${externalClasses.join(',')}],
          imports: [CommonModule],
        })
        export class AppModule {}
      `;
  projectFiles['app-module.ts'] = moduleContents;
  return env.addProject(projectName, {...projectFiles, ...standaloneFiles}, options);
}

export function humanizeDocumentSpanLike<T extends ts.DocumentSpan>(
    item: T, env: LanguageServiceTestEnv): T&Stringy<ts.DocumentSpan> {
  return {
    ...item,
    textSpan: env.getTextFromTsSpan(item.fileName, item.textSpan),
    contextSpan: item.contextSpan ? env.getTextFromTsSpan(item.fileName, item.contextSpan) :
                                    undefined,
    originalTextSpan: item.originalTextSpan ?
        env.getTextFromTsSpan(item.fileName, item.originalTextSpan) :
        undefined,
    originalContextSpan: item.originalContextSpan ?
        env.getTextFromTsSpan(item.fileName, item.originalContextSpan) :
        undefined,
  };
}
type Stringy<T> = {
  [P in keyof T]: string;
};

export function getText(contents: string, textSpan: ts.TextSpan) {
  return contents.slice(textSpan.start, textSpan.start + textSpan.length);
}

function last<T>(array: T[]): T {
  if (array.length === 0) {
    throw new Error(`last() called on empty array`);
  }
  return array[array.length - 1];
}


text:
namespace MyNamespace
{
  class MyClass
  {
  public:
    int myVar;

    int myFunction() const;
  };
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<additionalHeaders>
    <python_style>
        <firstLine># vim: set encoding=utf-8EOL</firstLine>
        <beforeEachLine># </beforeEachLine>
        <endLine>#EOL</endLine>
        <afterEachLine> </afterEachLine>
        <skipLinePattern>^#!.*$</skipLinePattern>
        <firstLineDetectionPattern>#.*$</firstLineDetectionPattern>
        <lastLineDetectionPattern>#.*$</lastLineDetectionPattern>
        <allowBlankLines>false</allowBlankLines>
        <isMultiline>false</isMultiline>
        <padLines>false</padLines>
    </python_style>
</additionalHeaders>


text:
/**
 * Provides the annotation classes used to annotate ModuleCreator classes denoting which products they belong to.
 * A module creator can be annotated with multiple [product]PluginModuleCreator annotations to link it to multiple products.
 *
 * This package also contains the Dependencies and Dependency annotations as well as a DependencyDescriptor class.
 * These annotations can be used on a ModuleCreator to denote the Maven dependencies (if any) required by the module.
 * The dependencies will be automatically added to the project's pom when the module is generated.
 *
 * @since 3.6
 *
 */
package com.atlassian.plugins.codegen.annotations;


text:
from __future__ import unicode_literals

import time
import warnings
from datetime import datetime, timedelta
from io import BytesIO

from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest, LimitedStream
from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError
from django.test.utils import str_prefix
from django.utils import unittest
from django.utils.http import cookie_date
from django.utils.timezone import utc

class RequestsTests(unittest.TestCase):
    def test_httprequest(self):
        request = HttpRequest()
        self.assertEqual(list(request.GET.keys()), [])
        self.assertEqual(list(request.POST.keys()), [])
        self.assertEqual(list(request.COOKIES.keys()), [])
        self.assertEqual(list(request.META.keys()), [])

    def test_httprequest_repr(self):
        request = HttpRequest()
        request.path = '/somepath/'
        request.GET = {'get-key': 'get-value'}
        request.POST = {'post-key': 'post-value'}
        request.COOKIES = {'post-key': 'post-value'}
        request.META = {'post-key': 'post-value'}
        self.assertEqual(repr(request), str_prefix("<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
        self.assertEqual(build_request_repr(request), repr(request))
        self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
                         str_prefix("<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))

    def test_wsgirequest(self):
        request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': BytesIO(b'')})
        self.assertEqual(list(request.GET.keys()), [])
        self.assertEqual(list(request.POST.keys()), [])
        self.assertEqual(list(request.COOKIES.keys()), [])
        self.assertEqual(set(request.META.keys()), set(['PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input']))
        self.assertEqual(request.META['PATH_INFO'], 'bogus')
        self.assertEqual(request.META['REQUEST_METHOD'], 'bogus')
        self.assertEqual(request.META['SCRIPT_NAME'], '')

    def test_wsgirequest_repr(self):
        request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
        request.GET = {'get-key': 'get-value'}
        request.POST = {'post-key': 'post-value'}
        request.COOKIES = {'post-key': 'post-value'}
        request.META = {'post-key': 'post-value'}
        self.assertEqual(repr(request), str_prefix("<WSGIRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
        self.assertEqual(build_request_repr(request), repr(request))
        self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
                         str_prefix("<WSGIRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))

    def test_parse_cookie(self):
        self.assertEqual(parse_cookie('invalid:key=true'), {})

    def test_httprequest_location(self):
        request = HttpRequest()
        self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"),
            'https://www.example.com/asdf')

        request.get_host = lambda: 'www.example.com'
        request.path = ''
        self.assertEqual(request.build_absolute_uri(location="/path/with:colons"),
            'http://www.example.com/path/with:colons')

    def test_http_get_host(self):
        old_USE_X_FORWARDED_HOST = settings.USE_X_FORWARDED_HOST
        try:
            settings.USE_X_FORWARDED_HOST = False

            # Check if X_FORWARDED_HOST is provided.
            request = HttpRequest()
            request.META = {
                'HTTP_X_FORWARDED_HOST': 'forward.com',
                'HTTP_HOST': 'example.com',
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 80,
            }
            # X_FORWARDED_HOST is ignored.
            self.assertEqual(request.get_host(), 'example.com')

            # Check if X_FORWARDED_HOST isn't provided.
            request = HttpRequest()
            request.META = {
                'HTTP_HOST': 'example.com',
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 80,
            }
            self.assertEqual(request.get_host(), 'example.com')

            # Check if HTTP_HOST isn't provided.
            request = HttpRequest()
            request.META = {
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 80,
            }
            self.assertEqual(request.get_host(), 'internal.com')

            # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
            request = HttpRequest()
            request.META = {
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 8042,
            }
            self.assertEqual(request.get_host(), 'internal.com:8042')

        finally:
            settings.USE_X_FORWARDED_HOST = old_USE_X_FORWARDED_HOST

    def test_http_get_host_with_x_forwarded_host(self):
        old_USE_X_FORWARDED_HOST = settings.USE_X_FORWARDED_HOST
        try:
            settings.USE_X_FORWARDED_HOST = True

            # Check if X_FORWARDED_HOST is provided.
            request = HttpRequest()
            request.META = {
                'HTTP_X_FORWARDED_HOST': 'forward.com',
                'HTTP_HOST': 'example.com',
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 80,
            }
            # X_FORWARDED_HOST is obeyed.
            self.assertEqual(request.get_host(), 'forward.com')

            # Check if X_FORWARDED_HOST isn't provided.
            request = HttpRequest()
            request.META = {
                'HTTP_HOST': 'example.com',
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 80,
            }
            self.assertEqual(request.get_host(), 'example.com')

            # Check if HTTP_HOST isn't provided.
            request = HttpRequest()
            request.META = {
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 80,
            }
            self.assertEqual(request.get_host(), 'internal.com')

            # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
            request = HttpRequest()
            request.META = {
                'SERVER_NAME': 'internal.com',
                'SERVER_PORT': 8042,
            }
            self.assertEqual(request.get_host(), 'internal.com:8042')

        finally:
            settings.USE_X_FORWARDED_HOST = old_USE_X_FORWARDED_HOST

    def test_near_expiration(self):
        "Cookie will expire when an near expiration time is provided"
        response = HttpResponse()
        # There is a timing weakness in this test; The
        # expected result for max-age requires that there be
        # a very slight difference between the evaluated expiration
        # time, and the time evaluated in set_cookie(). If this
        # difference doesn't exist, the cookie time will be
        # 1 second larger. To avoid the problem, put in a quick sleep,
        # which guarantees that there will be a time difference.
        expires = datetime.utcnow() + timedelta(seconds=10)
        time.sleep(0.001)
        response.set_cookie('datetime', expires=expires)
        datetime_cookie = response.cookies['datetime']
        self.assertEqual(datetime_cookie['max-age'], 10)

    def test_aware_expiration(self):
        "Cookie accepts an aware datetime as expiration time"
        response = HttpResponse()
        expires = (datetime.utcnow() + timedelta(seconds=10)).replace(tzinfo=utc)
        time.sleep(0.001)
        response.set_cookie('datetime', expires=expires)
        datetime_cookie = response.cookies['datetime']
        self.assertEqual(datetime_cookie['max-age'], 10)

    def test_far_expiration(self):
        "Cookie will expire when an distant expiration time is provided"
        response = HttpResponse()
        response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
        datetime_cookie = response.cookies['datetime']
        self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT')

    def test_max_age_expiration(self):
        "Cookie will expire if max_age is provided"
        response = HttpResponse()
        response.set_cookie('max_age', max_age=10)
        max_age_cookie = response.cookies['max_age']
        self.assertEqual(max_age_cookie['max-age'], 10)
        self.assertEqual(max_age_cookie['expires'], cookie_date(time.time()+10))

    def test_httponly_cookie(self):
        response = HttpResponse()
        response.set_cookie('example', httponly=True)
        example_cookie = response.cookies['example']
        # A compat cookie may be in use -- check that it has worked
        # both as an output string, and using the cookie attributes
        self.assertTrue('; httponly' in str(example_cookie))
        self.assertTrue(example_cookie['httponly'])

    def test_limited_stream(self):
        # Read all of a limited stream
        stream = LimitedStream(BytesIO(b'test'), 2)
        self.assertEqual(stream.read(), b'te')
        # Reading again returns nothing.
        self.assertEqual(stream.read(), b'')

        # Read a number of characters greater than the stream has to offer
        stream = LimitedStream(BytesIO(b'test'), 2)
        self.assertEqual(stream.read(5), b'te')
        # Reading again returns nothing.
        self.assertEqual(stream.readline(5), b'')

        # Read sequentially from a stream
        stream = LimitedStream(BytesIO(b'12345678'), 8)
        self.assertEqual(stream.read(5), b'12345')
        self.assertEqual(stream.read(5), b'678')
        # Reading again returns nothing.
        self.assertEqual(stream.readline(5), b'')

        # Read lines from a stream
        stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24)
        # Read a full line, unconditionally
        self.assertEqual(stream.readline(), b'1234\n')
        # Read a number of characters less than a line
        self.assertEqual(stream.readline(2), b'56')
        # Read the rest of the partial line
        self.assertEqual(stream.readline(), b'78\n')
        # Read a full line, with a character limit greater than the line length
        self.assertEqual(stream.readline(6), b'abcd\n')
        # Read the next line, deliberately terminated at the line end
        self.assertEqual(stream.readline(4), b'efgh')
        # Read the next line... just the line end
        self.assertEqual(stream.readline(), b'\n')
        # Read everything else.
        self.assertEqual(stream.readline(), b'ijkl')

        # Regression for #15018
        # If a stream contains a newline, but the provided length
        # is less than the number of provided characters, the newline
        # doesn't reset the available character count
        stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
        self.assertEqual(stream.readline(10), b'1234\n')
        self.assertEqual(stream.readline(3), b'abc')
        # Now expire the available characters
        self.assertEqual(stream.readline(3), b'd')
        # Reading again returns nothing.
        self.assertEqual(stream.readline(2), b'')

        # Same test, but with read, not readline.
        stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
        self.assertEqual(stream.read(6), b'1234\na')
        self.assertEqual(stream.read(2), b'bc')
        self.assertEqual(stream.read(2), b'd')
        self.assertEqual(stream.read(2), b'')
        self.assertEqual(stream.read(), b'')

    def test_stream(self):
        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        self.assertEqual(request.read(), b'name=value')

    def test_read_after_value(self):
        """
        Reading from request is allowed after accessing request contents as
        POST or body.
        """
        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        self.assertEqual(request.POST, {'name': ['value']})
        self.assertEqual(request.body, b'name=value')
        self.assertEqual(request.read(), b'name=value')

    def test_value_after_read(self):
        """
        Construction of POST or body is not allowed after reading
        from request.
        """
        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        self.assertEqual(request.read(2), b'na')
        self.assertRaises(Exception, lambda: request.body)
        self.assertEqual(request.POST, {})

    def test_body_after_POST_multipart(self):
        """
        Reading body after parsing multipart is not allowed
        """
        # Because multipart is used for large amounts fo data i.e. file uploads,
        # we don't want the data held in memory twice, and we don't want to
        # silence the error by setting body = '' either.
        payload = "\r\n".join([
                '--boundary',
                'Content-Disposition: form-data; name="name"',
                '',
                'value',
                '--boundary--'
                '']).encode('utf-8')
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        self.assertEqual(request.POST, {'name': ['value']})
        self.assertRaises(Exception, lambda: request.body)

    def test_POST_multipart_with_content_length_zero(self):
        """
        Multipart POST requests with Content-Length >= 0 are valid and need to be handled.
        """
        # According to:
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
        # Every request.POST with Content-Length >= 0 is a valid request,
        # this test ensures that we handle Content-Length == 0.
        payload = "\r\n".join([
                '--boundary',
                'Content-Disposition: form-data; name="name"',
                '',
                'value',
                '--boundary--'
                '']).encode('utf-8')
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
                               'CONTENT_LENGTH': 0,
                               'wsgi.input': BytesIO(payload)})
        self.assertEqual(request.POST, {})

    def test_read_by_lines(self):
        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        self.assertEqual(list(request), [b'name=value'])

    def test_POST_after_body_read(self):
        """
        POST should be populated even if body is read first
        """
        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        raw_data = request.body
        self.assertEqual(request.POST, {'name': ['value']})

    def test_POST_after_body_read_and_stream_read(self):
        """
        POST should be populated even if body is read first, and then
        the stream is read second.
        """
        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        raw_data = request.body
        self.assertEqual(request.read(1), b'n')
        self.assertEqual(request.POST, {'name': ['value']})

    def test_POST_after_body_read_and_stream_read_multipart(self):
        """
        POST should be populated even if body is read first, and then
        the stream is read second. Using multipart/form-data instead of urlencoded.
        """
        payload = "\r\n".join([
                '--boundary',
                'Content-Disposition: form-data; name="name"',
                '',
                'value',
                '--boundary--'
                '']).encode('utf-8')
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': BytesIO(payload)})
        raw_data = request.body
        # Consume enough data to mess up the parsing:
        self.assertEqual(request.read(13), b'--boundary\r\nC')
        self.assertEqual(request.POST, {'name': ['value']})

    def test_raw_post_data_returns_body(self):
        """
        HttpRequest.raw_post_body should be the same as HttpRequest.body
        """
        payload = b'Hello There!'
        request = WSGIRequest({
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': len(payload),
            'wsgi.input': BytesIO(payload)
        })

        with warnings.catch_warnings(record=True):
            self.assertEqual(request.body, request.raw_post_data)

    def test_POST_connection_error(self):
        """
        If wsgi.input.read() raises an exception while trying to read() the
        POST, the exception should be identifiable (not a generic IOError).
        """
        class ExplodingBytesIO(BytesIO):
            def read(self, len=0):
                raise IOError("kaboom!")

        payload = b'name=value'
        request = WSGIRequest({'REQUEST_METHOD': 'POST',
                               'CONTENT_LENGTH': len(payload),
                               'wsgi.input': ExplodingBytesIO(payload)})

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            with self.assertRaises(UnreadablePostError):
                request.raw_post_data
            self.assertEqual(len(w), 1)


text:
#include "tensorflow/compiler/xla/service/hlo_matchers.h"

#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/test.h"

namespace xla {
namespace testing {

bool HloMatcher::MatchAndExplain(
    const HloInstruction* instruction,
    ::testing::MatchResultListener* listener) const {
  // These cases are self-explanatory from the printed value.
  if (!instruction || instruction->opcode() != opcode_) {
    return false;
  }
  // Special case: no operand matchers means don't verify.
  if (operands_.empty()) {
    return true;
  }
  const auto& operands = instruction->operands();
  if (operands.size() != operands_.size()) {
    *listener << "has too "
              << (operands.size() > operands_.size() ? "many" : "few")
              << " operands (got " << operands.size() << ", want "
              << operands_.size() << ")";
    return false;
  }
  for (int index = 0; index < operands.size(); index++) {
    ::testing::StringMatchResultListener inner_listener;
    if (!operands_[index].MatchAndExplain(operands[index], &inner_listener)) {
      if (listener->IsInterested()) {
        *listener << "\noperand " << index << ":\n\t"
                  << operands[index]->ToString()
                  << "\ndoesn't match expected:\n\t";
        operands_[index].DescribeTo(listener->stream());
        string explanation = inner_listener.str();
        if (!explanation.empty()) {
          *listener << ", " << explanation;
        }
      }
      return false;
    }
  }
  return true;
}

void HloMatcher::DescribeTo(::std::ostream* os) const {
  *os << opcode_;
  if (!operands_.empty()) {
    *os << "(";
    for (int i = 0; i < operands_.size(); i++) {
      if (i > 0) {
        *os << ", ";
      }
      operands_[i].DescribeTo(os);
    }
    *os << ")";
  }
}

bool HloParameterMatcher::MatchAndExplain(
    const HloInstruction* instruction,
    ::testing::MatchResultListener* listener) const {
  if (!HloMatcher::MatchAndExplain(instruction, listener)) {
    return false;
  }
  if (instruction->parameter_number() != parameter_number_) {
    *listener << "has wrong parameter number (got "
              << instruction->parameter_number() << ", want "
              << parameter_number_ << ")";
    return false;
  }
  return true;
}

bool HloGetTupleElementMatcher::MatchAndExplain(
    const HloInstruction* instruction,
    ::testing::MatchResultListener* listener) const {
  if (!HloMatcher::MatchAndExplain(instruction, listener)) {
    return false;
  }
  if (instruction->tuple_index() != tuple_index_) {
    *listener << "has wrong tuple index (got " << instruction->tuple_index()
              << ", want " << tuple_index_ << ")";
    return false;
  }
  return true;
}

void HloCustomCallMatcher::DescribeTo(std::ostream* os) const {
  HloMatcher::DescribeTo(os);
  *os << " with call target that ";
  call_target_matcher_.DescribeTo(os);
}

bool HloCustomCallMatcher::MatchAndExplain(
    const HloInstruction* instruction,
    ::testing::MatchResultListener* listener) const {
  if (!HloMatcher::MatchAndExplain(instruction, listener)) {
    return false;
  }
  ::testing::StringMatchResultListener sub_listener;
  bool result = ExplainMatchResult(
      call_target_matcher_, instruction->custom_call_target(), &sub_listener);
  if (sub_listener.str().empty()) {
    sub_listener << " that ";

    std::stringstream desc_stream;
    if (result) {
      call_target_matcher_.DescribeTo(&desc_stream);
    } else {
      call_target_matcher_.DescribeNegationTo(&desc_stream);
    }
    sub_listener << desc_stream.str();
  }
  *listener << "custom-call with call target" << sub_listener.str();
  return result;
}

}  // namespace testing

void PrintTo(const HloInstruction* inst, ::std::ostream* os) {
  *os << (inst ? inst->ToString() : "nullptr");
}

void PrintTo(HloInstruction* inst, ::std::ostream* os) {
  PrintTo(const_cast<const HloInstruction*>(inst), os);
}

}  // namespace xla


text:
package org.apache.cassandra.thrift;

import java.nio.ByteBuffer;
import java.util.*;

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

import org.apache.cassandra.config.*;
import org.apache.cassandra.locator.*;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.MarshalException;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.db.migration.Migration;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.RandomPartitioner;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;

/**
 * This has a lot of building blocks for CassandraServer to call to make sure it has valid input
 * -- ensuring column names conform to the declared comparator, for instance.
 *
 * The methods here mostly try to do just one part of the validation so they can be combined
 * for different needs -- supercolumns vs regular, range slices vs named, batch vs single-column.
 * (ValidateColumnPath is the main exception in that it includes table and CF validation.)
 */
public class ThriftValidation
{
    private static Logger logger = LoggerFactory.getLogger(ThriftValidation.class);

    public static void validateKey(CFMetaData metadata, ByteBuffer key) throws InvalidRequestException
    {
        if (key == null || key.remaining() == 0)
        {
            throw new InvalidRequestException("Key may not be empty");
        }

        // check that key can be handled by FBUtilities.writeShortByteArray
        if (key.remaining() > FBUtilities.MAX_UNSIGNED_SHORT)
        {
            throw new InvalidRequestException("Key length of " + key.remaining() +
                                              " is longer than maximum of " + FBUtilities.MAX_UNSIGNED_SHORT);
        }

        try
        {
            metadata.getKeyValidator().validate(key);
        }
        catch (MarshalException e)
        {
            throw new InvalidRequestException(e.getMessage());
        }
    }

    public static void validateTable(String tablename) throws KeyspaceNotDefinedException
    {
        if (!DatabaseDescriptor.getTables().contains(tablename))
        {
            throw new KeyspaceNotDefinedException("Keyspace " + tablename + " does not exist");
        }
    }

    // Don't check that the table exists, validateTable or validateColumnFamily must be called beforehand.
    public static void validateConsistencyLevel(String table, ConsistencyLevel cl) throws InvalidRequestException
    {
        switch (cl)
        {
            case LOCAL_QUORUM:
            case EACH_QUORUM:
                AbstractReplicationStrategy strategy = Table.open(table).getReplicationStrategy();
                if (!(strategy instanceof NetworkTopologyStrategy))
                    throw new InvalidRequestException("consistency level " + cl + " not compatible with replication strategy (" + strategy.getClass().getName() + ")");
        }
    }

    public static CFMetaData validateColumnFamily(String tablename, String cfName, boolean isCommutativeOp) throws InvalidRequestException
    {
        CFMetaData metadata = validateColumnFamily(tablename, cfName);

        if (isCommutativeOp)
        {
            if (!metadata.getDefaultValidator().isCommutative())
                throw new InvalidRequestException("invalid operation for non commutative columnfamily " + cfName);
        }
        else
        {
            if (metadata.getDefaultValidator().isCommutative())
                throw new InvalidRequestException("invalid operation for commutative columnfamily " + cfName);
        }
        return metadata;
    }

    // To be used when the operation should be authorized whether this is a counter CF or not
    public static CFMetaData validateColumnFamily(String tablename, String cfName) throws InvalidRequestException
    {
        validateTable(tablename);
        if (cfName.isEmpty())
            throw new InvalidRequestException("non-empty columnfamily is required");

        CFMetaData metadata = DatabaseDescriptor.getCFMetaData(tablename, cfName);
        if (metadata == null)
            throw new InvalidRequestException("unconfigured columnfamily " + cfName);

        return metadata;
    }

    /**
     * validates all parts of the path to the column, including the column name
     */
    public static void validateColumnPath(CFMetaData metadata, ColumnPath column_path) throws InvalidRequestException
    {
        if (metadata.cfType == ColumnFamilyType.Standard)
        {
            if (column_path.super_column != null)
            {
                throw new InvalidRequestException("supercolumn parameter is invalid for standard CF " + metadata.cfName);
            }
            if (column_path.column == null)
            {
                throw new InvalidRequestException("column parameter is not optional for standard CF " + metadata.cfName);
            }
        }
        else
        {
            if (column_path.super_column == null)
                throw new InvalidRequestException("supercolumn parameter is not optional for super CF " + metadata.cfName);
        }
        if (column_path.column != null)
        {
            validateColumnNames(metadata, column_path.super_column, Arrays.asList(column_path.column));
        }
        if (column_path.super_column != null)
        {
            validateColumnNames(metadata, (ByteBuffer)null, Arrays.asList(column_path.super_column));
        }
    }

    public static void validateColumnParent(CFMetaData metadata, ColumnParent column_parent) throws InvalidRequestException
    {
        if (metadata.cfType == ColumnFamilyType.Standard)
        {
            if (column_parent.super_column != null)
            {
                throw new InvalidRequestException("columnfamily alone is required for standard CF " + metadata.cfName);
            }
        }

        if (column_parent.super_column != null)
        {
            validateColumnNames(metadata, (ByteBuffer)null, Arrays.asList(column_parent.super_column));
        }
    }

    // column_path_or_parent is a ColumnPath for remove, where the "column" is optional even for a standard CF
    static void validateColumnPathOrParent(CFMetaData metadata, ColumnPath column_path_or_parent) throws InvalidRequestException
    {
        if (metadata.cfType == ColumnFamilyType.Standard)
        {
            if (column_path_or_parent.super_column != null)
            {
                throw new InvalidRequestException("supercolumn may not be specified for standard CF " + metadata.cfName);
            }
        }
        if (metadata.cfType == ColumnFamilyType.Super)
        {
            if (column_path_or_parent.super_column == null && column_path_or_parent.column != null)
            {
                throw new InvalidRequestException("A column cannot be specified without specifying a super column for removal on super CF " + metadata.cfName);
            }
        }
        if (column_path_or_parent.column != null)
        {
            validateColumnNames(metadata, column_path_or_parent.super_column, Arrays.asList(column_path_or_parent.column));
        }
        if (column_path_or_parent.super_column != null)
        {
            validateColumnNames(metadata, (ByteBuffer)null, Arrays.asList(column_path_or_parent.super_column));
        }
    }

    /**
     * Validates the column names but not the parent path or data
     */
    private static void validateColumnNames(CFMetaData metadata, ByteBuffer superColumnName, Iterable<ByteBuffer> column_names)
            throws InvalidRequestException
    {
        if (superColumnName != null)
        {
            if (superColumnName.remaining() > IColumn.MAX_NAME_LENGTH)
                throw new InvalidRequestException("supercolumn name length must not be greater than " + IColumn.MAX_NAME_LENGTH);
            if (superColumnName.remaining() == 0)
                throw new InvalidRequestException("supercolumn name must not be empty");
            if (metadata.cfType == ColumnFamilyType.Standard)
                throw new InvalidRequestException("supercolumn specified to ColumnFamily " + metadata.cfName + " containing normal columns");
        }
        AbstractType comparator = metadata.getComparatorFor(superColumnName);
        for (ByteBuffer name : column_names)
        {
            if (name.remaining() > IColumn.MAX_NAME_LENGTH)
                throw new InvalidRequestException("column name length must not be greater than " + IColumn.MAX_NAME_LENGTH);
            if (name.remaining() == 0)
                throw new InvalidRequestException("column name must not be empty");
            try
            {
                comparator.validate(name);
            }
            catch (MarshalException e)
            {
                throw new InvalidRequestException(e.getMessage());
            }
        }
    }

    public static void validateColumnNames(CFMetaData metadata, ColumnParent column_parent, Iterable<ByteBuffer> column_names) throws InvalidRequestException
    {
        validateColumnNames(metadata, column_parent.super_column, column_names);
    }

    public static void validateRange(CFMetaData metadata, ColumnParent column_parent, SliceRange range) throws InvalidRequestException
    {
        AbstractType comparator = metadata.getComparatorFor(column_parent.super_column);
        try
        {
            comparator.validate(range.start);
            comparator.validate(range.finish);
        }
        catch (MarshalException e)
        {
            throw new InvalidRequestException(e.getMessage());
        }

        if (range.count < 0)
            throw new InvalidRequestException("get_slice requires non-negative count");

        Comparator<ByteBuffer> orderedComparator = range.isReversed() ? comparator.reverseComparator : comparator;
        if (range.start.remaining() > 0
            && range.finish.remaining() > 0
            && orderedComparator.compare(range.start, range.finish) > 0)
        {
            throw new InvalidRequestException("range finish must come after start in the order of traversal");
        }
    }

    public static void validateColumnOrSuperColumn(CFMetaData metadata, ColumnOrSuperColumn cosc)
            throws InvalidRequestException
    {
        boolean isCommutative = metadata.getDefaultValidator().isCommutative();

        int nulls = 0;
        if (cosc.column == null) nulls++;
        if (cosc.super_column == null) nulls++;
        if (cosc.counter_column == null) nulls++;
        if (cosc.counter_super_column == null) nulls++;

        if (nulls != 3)
            throw new InvalidRequestException("ColumnOrSuperColumn must have one (and only one) of column, super_column, counter and counter_super_column");

        if (cosc.column != null)
        {
            if (isCommutative)
                throw new InvalidRequestException("invalid operation for commutative columnfamily " + metadata.cfName);

            validateTtl(cosc.column);
            validateColumnPath(metadata, new ColumnPath(metadata.cfName).setSuper_column((ByteBuffer)null).setColumn(cosc.column.name));
            validateColumnData(metadata, cosc.column, false);
        }

        if (cosc.super_column != null)
        {
            if (isCommutative)
                throw new InvalidRequestException("invalid operation for commutative columnfamily " + metadata.cfName);

            for (Column c : cosc.super_column.columns)
            {
                validateColumnPath(metadata, new ColumnPath(metadata.cfName).setSuper_column(cosc.super_column.name).setColumn(c.name));
                validateColumnData(metadata, c, true);
            }
        }

        if (cosc.counter_column != null)
        {
            if (!isCommutative)
                throw new InvalidRequestException("invalid operation for non commutative columnfamily " + metadata.cfName);

            validateColumnPath(metadata, new ColumnPath(metadata.cfName).setSuper_column((ByteBuffer)null).setColumn(cosc.counter_column.name));
        }

        if (cosc.counter_super_column != null)
        {
            if (!isCommutative)
                throw new InvalidRequestException("invalid operation for non commutative columnfamily " + metadata.cfName);

            for (CounterColumn c : cosc.counter_super_column.columns)
                validateColumnPath(metadata, new ColumnPath(metadata.cfName).setSuper_column(cosc.counter_super_column.name).setColumn(c.name));
        }
    }

    private static void validateTtl(Column column) throws InvalidRequestException
    {
        if (column.isSetTtl() && column.ttl <= 0)
        {
            throw new InvalidRequestException("ttl must be positive");
        }
        // if it's not set, then it should be zero -- here we are just checking to make sure Thrift doesn't change that contract with us.
        assert column.isSetTtl() || column.ttl == 0;
    }

    public static void validateMutation(CFMetaData metadata, Mutation mut)
            throws InvalidRequestException
    {
        ColumnOrSuperColumn cosc = mut.column_or_supercolumn;
        Deletion del = mut.deletion;

        int nulls = 0;
        if (cosc == null) nulls++;
        if (del == null) nulls++;

        if (nulls != 1)
        {
            throw new InvalidRequestException("mutation must have one and only one of column_or_supercolumn or deletion");
        }

        if (cosc != null)
        {
            validateColumnOrSuperColumn(metadata, cosc);
        }
        else
        {
            validateDeletion(metadata, del);
        }
    }

    public static void validateDeletion(CFMetaData metadata, Deletion del) throws InvalidRequestException
    {

        if (del.super_column != null)
            validateColumnNames(metadata, (ByteBuffer)null, Arrays.asList(del.super_column));

        if (del.predicate != null)
        {
            validateSlicePredicate(metadata, del.super_column, del.predicate);
            if (del.predicate.slice_range != null)
                throw new InvalidRequestException("Deletion does not yet support SliceRange predicates.");
        }

        if (metadata.cfType == ColumnFamilyType.Standard && del.super_column != null)
        {
            String msg = String.format("Deletion of super columns is not possible on a standard ColumnFamily (KeySpace=%s ColumnFamily=%s Deletion=%s)", metadata.ksName, metadata.cfName, del);
            throw new InvalidRequestException(msg);
        }

        if (metadata.getDefaultValidator().isCommutative())
        {
            // forcing server timestamp even if a timestamp was set for coherence with other counter operation
            del.timestamp = System.currentTimeMillis();
        }
        else if (!del.isSetTimestamp())
        {
            throw new InvalidRequestException("Deletion timestamp is not optional for non commutative column family " + metadata.cfName);
        }
    }

    public static void validateSlicePredicate(CFMetaData metadata, ByteBuffer scName, SlicePredicate predicate) throws InvalidRequestException
    {
        if (predicate.column_names == null && predicate.slice_range == null)
            throw new InvalidRequestException("A SlicePredicate must be given a list of Columns, a SliceRange, or both");

        if (predicate.slice_range != null)
            validateRange(metadata, new ColumnParent(metadata.cfName).setSuper_column(scName), predicate.slice_range);

        if (predicate.column_names != null)
            validateColumnNames(metadata, scName, predicate.column_names);
    }

    /**
     * Validates the data part of the column (everything in the Column object but the name, which is assumed to be valid)
     */
    public static void validateColumnData(CFMetaData metadata, Column column, boolean isSubColumn) throws InvalidRequestException
    {
        validateTtl(column);
        if (!column.isSetValue())
            throw new InvalidRequestException("Column value is required");
        if (!column.isSetTimestamp())
            throw new InvalidRequestException("Column timestamp is required");

        ColumnDefinition columnDef = metadata.getColumnDefinition(column.name);
        try
        {
            AbstractType validator = metadata.getValueValidator(columnDef);
            if (validator != null)
                validator.validate(column.value);
        }
        catch (MarshalException me)
        {
            if (logger.isDebugEnabled())
                logger.debug("rejecting invalid value " + ByteBufferUtil.bytesToHex(summarize(column.value)));
            throw new InvalidRequestException(String.format("(%s) [%s][%s][%s] failed validation",
                                                            me.getMessage(),
                                                            metadata.ksName,
                                                            metadata.cfName,
                                                            (isSubColumn ? metadata.subcolumnComparator : metadata.comparator).getString(column.name)));
        }

        // Indexed column values cannot be larger than 64K.  See CASSANDRA-3057 for more details
        if (columnDef != null && columnDef.getIndexType() != null && column.value.remaining() > FBUtilities.MAX_UNSIGNED_SHORT)
            throw new InvalidRequestException(String.format("Can't index column value of size %d for index %s in CF %s of KS %s",
                                                            column.value.remaining(),
                                                            columnDef.getIndexName(),
                                                            metadata.cfName,
                                                            metadata.ksName));
    }

    /**
     * Return, at most, the first 64K of the buffer. This avoids very large column values being
     * logged in their entirety.
     */
    private static ByteBuffer summarize(ByteBuffer buffer)
    {
        int MAX = Short.MAX_VALUE;
        if (buffer.remaining() <= MAX)
            return buffer;
        return (ByteBuffer) buffer.slice().limit(buffer.position() + MAX);
    }

    public static void validatePredicate(CFMetaData metadata, ColumnParent column_parent, SlicePredicate predicate)
            throws InvalidRequestException
    {
        if (predicate.column_names == null && predicate.slice_range == null)
            throw new InvalidRequestException("predicate column_names and slice_range may not both be null");
        if (predicate.column_names != null && predicate.slice_range != null)
            throw new InvalidRequestException("predicate column_names and slice_range may not both be present");

        if (predicate.getSlice_range() != null)
            validateRange(metadata, column_parent, predicate.slice_range);
        else
            validateColumnNames(metadata, column_parent, predicate.column_names);
    }

    public static void validateKeyRange(KeyRange range) throws InvalidRequestException
    {
        if ((range.start_key == null) != (range.end_key == null))
        {
            throw new InvalidRequestException("start key and end key must either both be non-null, or both be null");
        }
        if ((range.start_token == null) != (range.end_token == null))
        {
            throw new InvalidRequestException("start token and end token must either both be non-null, or both be null");
        }
        if ((range.start_key == null) == (range.start_token == null))
        {
            throw new InvalidRequestException("exactly one of {start key, end key} or {start token, end token} must be specified");
        }

        if (range.start_key != null)
        {
            IPartitioner p = StorageService.getPartitioner();
            Token startToken = p.getToken(range.start_key);
            Token endToken = p.getToken(range.end_key);
            if (startToken.compareTo(endToken) > 0 && !endToken.equals(p.getMinimumToken()))
            {
                if (p instanceof RandomPartitioner)
                    throw new InvalidRequestException("start key's md5 sorts after end key's md5.  this is not allowed; you probably should not specify end key at all, under RandomPartitioner");
                else
                    throw new InvalidRequestException("start key must sort before (or equal to) finish key in your partitioner!");
            }
        }

        if (range.count <= 0)
        {
            throw new InvalidRequestException("maxRows must be positive");
        }
    }

    public static void validateIndexClauses(CFMetaData metadata, IndexClause index_clause)
    throws InvalidRequestException
    {
        if (index_clause.expressions.isEmpty())
            throw new InvalidRequestException("index clause list may not be empty");
        Set<ByteBuffer> indexedColumns = Table.open(metadata.ksName).getColumnFamilyStore(metadata.cfName).getIndexedColumns();
        AbstractType nameValidator =  ColumnFamily.getComparatorFor(metadata.ksName, metadata.cfName, null);

        boolean isIndexed = false;
        for (IndexExpression expression : index_clause.expressions)
        {
            try
            {
                nameValidator.validate(expression.column_name);
            }
            catch (MarshalException me)
            {
                throw new InvalidRequestException(String.format("[%s]=[%s] failed name validation (%s)",
                                                                ByteBufferUtil.bytesToHex(expression.column_name),
                                                                ByteBufferUtil.bytesToHex(expression.value),
                                                                me.getMessage()));
            }

            AbstractType valueValidator = DatabaseDescriptor.getValueValidator(metadata.ksName, metadata.cfName, expression.column_name);
            try
            {
                valueValidator.validate(expression.value);
            }
            catch (MarshalException me)
            {
                throw new InvalidRequestException(String.format("[%s]=[%s] failed value validation (%s)",
                                                                ByteBufferUtil.bytesToHex(expression.column_name),
                                                                ByteBufferUtil.bytesToHex(expression.value),
                                                                me.getMessage()));
            }

            isIndexed |= expression.op.equals(IndexOperator.EQ) && indexedColumns.contains(expression.column_name);
        }

        if (!isIndexed)
            throw new InvalidRequestException("No indexed columns present in index clause with operator EQ");
    }

    public static void validateCfDef(CfDef cf_def, CFMetaData old) throws InvalidRequestException
    {
        try
        {
            if (cf_def.key_alias != null)
            {
                if (!cf_def.key_alias.hasRemaining())
                    throw new InvalidRequestException("key_alias may not be empty");
                try
                {
                    // it's hard to use a key in a select statement if we can't type it.
                    // for now let's keep it simple and require ascii.
                    AsciiType.instance.validate(cf_def.key_alias);
                }
                catch (MarshalException e)
                {
                    throw new InvalidRequestException("Key aliases must be ascii");
                }
            }

            ColumnFamilyType cfType = ColumnFamilyType.create(cf_def.column_type);
            if (cfType == null)
                throw new InvalidRequestException("invalid column type " + cf_def.column_type);

            TypeParser.parse(cf_def.key_validation_class);
            TypeParser.parse(cf_def.comparator_type);
            TypeParser.parse(cf_def.subcomparator_type);
            TypeParser.parse(cf_def.default_validation_class);
            if (cfType != ColumnFamilyType.Super && cf_def.subcomparator_type != null)
                throw new InvalidRequestException("subcomparator_type is invalid for standard columns");

            if (cf_def.column_metadata == null)
                return;

            AbstractType comparator = cfType == ColumnFamilyType.Standard
                                    ? TypeParser.parse(cf_def.comparator_type)
                                    : TypeParser.parse(cf_def.subcomparator_type);

            if (cf_def.key_alias != null)
            {
                // check if any of the columns has name equal to the cf.key_alias
                for (ColumnDef columnDef : cf_def.column_metadata)
                {
                    if (cf_def.key_alias.equals(columnDef.name))
                        throw new InvalidRequestException("Invalid column name: "
                                                          + AsciiType.instance.compose(cf_def.key_alias)
                                                          + ", because it equals to the key_alias.");
                }
            }

            // initialize a set of names NOT in the CF under consideration
            Set<String> indexNames = new HashSet<String>();
            for (ColumnFamilyStore cfs : ColumnFamilyStore.all())
            {
                if (!cfs.getColumnFamilyName().equals(cf_def.name))
                    for (ColumnDefinition cd : cfs.metadata.getColumn_metadata().values())
                        indexNames.add(cd.getIndexName());
            }

            for (ColumnDef c : cf_def.column_metadata)
            {
                TypeParser.parse(c.validation_class);

                try
                {
                    comparator.validate(c.name);
                }
                catch (MarshalException e)
                {
                    throw new InvalidRequestException(String.format("Column name %s is not valid for comparator %s",
                                                                    ByteBufferUtil.bytesToHex(c.name), cf_def.comparator_type));
                }

                if (c.index_type == null)
                {
                    if (c.index_name != null)
                        throw new ConfigurationException("index_name cannot be set without index_type");
                }
                else
                {
                    if (cfType == ColumnFamilyType.Super)
                        throw new InvalidRequestException("Secondary indexes are not supported on supercolumns");
                    assert c.index_name != null; // should have a default set by now if none was provided
                    if (!Migration.isLegalName(c.index_name))
                        throw new InvalidRequestException("Illegal index name " + c.index_name);
                    // check index names against this CF _and_ globally
                    if (indexNames.contains(c.index_name))
                        throw new InvalidRequestException("Duplicate index name " + c.index_name);
                    indexNames.add(c.index_name);

                    ColumnDefinition oldCd = old == null ? null : old.getColumnDefinition(c.name);
                    if (oldCd != null && oldCd.getIndexType() != null)
                    {
                        assert oldCd.getIndexName() != null;
                        if (!oldCd.getIndexName().equals(c.index_name))
                            throw new InvalidRequestException("Cannot modify index name");
                    }
                }
            }
            validateMinMaxCompactionThresholds(cf_def);
            validateMemtableSettings(cf_def);
        }
        catch (ConfigurationException e)
        {
            throw new InvalidRequestException(e.getMessage());
        }
    }

    public static void validateCommutativeForWrite(CFMetaData metadata, ConsistencyLevel consistency) throws InvalidRequestException
    {
        if (consistency == ConsistencyLevel.ANY)
        {
            throw new InvalidRequestException("Consistency level ANY is not yet supported for counter columnfamily " + metadata.cfName);
        }
        else if (!metadata.getReplicateOnWrite() && consistency != ConsistencyLevel.ONE)
        {
            throw new InvalidRequestException("cannot achieve CL > CL.ONE without replicate_on_write on columnfamily " + metadata.cfName);
        }
    }

    public static void validateKsDef(KsDef ks_def) throws ConfigurationException
    {
        // Attempt to instantiate the ARS, which will throw a ConfigException if
        //  the strategy_options aren't fully formed or if the ARS Classname is invalid.
        Map<String, String> options = KSMetaData.forwardsCompatibleOptions(ks_def);
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();
        IEndpointSnitch eps = DatabaseDescriptor.getEndpointSnitch();
        Class<? extends AbstractReplicationStrategy> cls = AbstractReplicationStrategy.getClass(ks_def.strategy_class);

        if (cls.equals(LocalStrategy.class))
            throw new ConfigurationException("Unable to use given strategy class: LocalStrategy is reserved for internal use.");

        AbstractReplicationStrategy.createReplicationStrategy(ks_def.name, cls, tmd, eps, options);
    }

    public static void validateMinMaxCompactionThresholds(org.apache.cassandra.thrift.CfDef cf_def) throws ConfigurationException
    {
        if (cf_def.isSetMin_compaction_threshold() && cf_def.isSetMax_compaction_threshold())
        {
            if ((cf_def.min_compaction_threshold > cf_def.max_compaction_threshold)
                && cf_def.max_compaction_threshold != 0)
            {
                throw new ConfigurationException("min_compaction_threshold cannot be greater than max_compaction_threshold");
            }
        }
        else if (cf_def.isSetMin_compaction_threshold())
        {
            if (cf_def.min_compaction_threshold > CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD)
            {
                throw new ConfigurationException(String.format("min_compaction_threshold cannot be greather than max_compaction_threshold (default %d)",
                                                               CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD));
            }
        }
        else if (cf_def.isSetMax_compaction_threshold())
        {
            if (cf_def.max_compaction_threshold < CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD && cf_def.max_compaction_threshold != 0)
            {
                throw new ConfigurationException("max_compaction_threshold cannot be less than min_compaction_threshold");
            }
        }
        else
        {
            //Defaults are valid.
        }
    }

    public static void validateMemtableSettings(org.apache.cassandra.thrift.CfDef cf_def) throws ConfigurationException
    {
        if (cf_def.isSetMemtable_flush_after_mins())
            DatabaseDescriptor.validateMemtableFlushPeriod(cf_def.memtable_flush_after_mins);
        if (cf_def.isSetMemtable_throughput_in_mb())
            DatabaseDescriptor.validateMemtableThroughput(cf_def.memtable_throughput_in_mb);
        if (cf_def.isSetMemtable_operations_in_millions())
            DatabaseDescriptor.validateMemtableOperations(cf_def.memtable_operations_in_millions);
    }

    public static void validateKeyspaceNotYetExisting(String newKsName) throws InvalidRequestException
    {
        // keyspace names must be unique case-insensitively because the keyspace name becomes the directory
        // where we store CF sstables.  Names that differ only in case would thus cause problems on
        // case-insensitive filesystems (NTFS, most installations of HFS+).
        for (String ksName : DatabaseDescriptor.getTables())
        {
            if (ksName.equalsIgnoreCase(newKsName))
                throw new InvalidRequestException("Keyspace names must be case-insensitively unique");
        }
    }
}


text:
module MailAccountAdmin
  class EmailAccount < ActiveRecord::Base
    include BaseJump::Expirable

    scope :sendable, -> { where(outgoing_server_enabled: true) }

    attr_encrypted :username, :key => :username_encryption_key
    attr_encrypted :outgoing_username, :key => :username_encryption_key

    attr_encrypted :password, :key => :password_encryption_key
    attr_encrypted :outgoing_password, :key => :password_encryption_key

    expirable_on :lower => :available_from, :upper => :available_until

    def username_encryption_key
      Digest::SHA512.hexdigest(Digest::SHA512.hexdigest(encryption_key_base)).reverse
    end
    def password_encryption_key
      Digest::SHA512.hexdigest(Digest::SHA512.hexdigest(encryption_key_base).reverse)
    end

    def to_action_mailer
      raise "This mail account has not been activated for sending. To do so, mark outgoing_server_enabled as true." unless !!outgoing_server_enabled

      hash = {}
      hash[:address] = first_non_blank(outgoing_server, incoming_server)
      hash[:port] = outgoing_port if outgoing_port
      hash[:domain] = helo_domain unless helo_domain.blank?
      hash[:user_name] = first_non_blank(self.outgoing_username, self.username)
      hash[:password] = first_non_blank(self.outgoing_password, self.password)

      hash[:authentication] = first_non_blank(authentication, 'plain').to_s
      hash[:openssl_verify_mode] = 'none' unless !!verify_ssl_certificate
      hash[:enable_starttls_auto] = !!enable_starttls_auto

      hash
    end

    private

    def encryption_key_base
      Rails.application.config.secret_key_base.to_s.reverse
    end
    def first_non_blank(*items)
      items.select { |s| !s.blank? }.first
    end

  end
end


text:
package com.davidsoergel.dsutils;

import org.apache.log4j.Logger;

/**
 * @version $Id$
 */
public class PluginException extends ChainedException
	{
	// ------------------------------ FIELDS ------------------------------

	private static final Logger logger = Logger.getLogger(PluginException.class);

	// --------------------------- CONSTRUCTORS ---------------------------

	public PluginException(String s)
		{
		super(s);
		}

	public PluginException(Throwable t)
		{
		super(t);
		}
	}


text:
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on July 13, 2011 04:51:58 PM America/New_York */

@font-face {
    font-family: 'GentiumBasicRegular';
    src: url('/gentium/GenBasR-webfont.eot');
    src: url('/gentium/GenBasR-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBasR-webfont.woff') format('woff'),
         url('/gentium/GenBasR-webfont.ttf') format('truetype'),
         url('/gentium/GenBasR-webfont.svg#GentiumBasicRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBasicItalic';
    src: url('/gentium/GenBasI-webfont.eot');
    src: url('/gentium/GenBasI-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBasI-webfont.woff') format('woff'),
         url('/gentium/GenBasI-webfont.ttf') format('truetype'),
         url('/gentium/GenBasI-webfont.svg#GentiumBasicItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBasicBold';
    src: url('/gentium/GenBasB-webfont.eot');
    src: url('/gentium/GenBasB-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBasB-webfont.woff') format('woff'),
         url('/gentium/GenBasB-webfont.ttf') format('truetype'),
         url('/gentium/GenBasB-webfont.svg#GentiumBasicBold') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBasicBoldItalic';
    src: url('/gentium/GenBasBI-webfont.eot');
    src: url('/gentium/GenBasBI-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBasBI-webfont.woff') format('woff'),
         url('/gentium/GenBasBI-webfont.ttf') format('truetype'),
         url('/gentium/GenBasBI-webfont.svg#GentiumBasicBoldItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBookBasicRegular';
    src: url('/gentium/GenBkBasR-webfont.eot');
    src: url('/gentium/GenBkBasR-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBkBasR-webfont.woff') format('woff'),
         url('/gentium/GenBkBasR-webfont.ttf') format('truetype'),
         url('/gentium/GenBkBasR-webfont.svg#GentiumBookBasicRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBookBasicItalic';
    src: url('/gentium/GenBkBasI-webfont.eot');
    src: url('/gentium/GenBkBasI-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBkBasI-webfont.woff') format('woff'),
         url('/gentium/GenBkBasI-webfont.ttf') format('truetype'),
         url('/gentium/GenBkBasI-webfont.svg#GentiumBookBasicItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBookBasicBold';
    src: url('/gentium/GenBkBasB-webfont.eot');
    src: url('/gentium/GenBkBasB-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBkBasB-webfont.woff') format('woff'),
         url('/gentium/GenBkBasB-webfont.ttf') format('truetype'),
         url('/gentium/GenBkBasB-webfont.svg#GentiumBookBasicBold') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'GentiumBookBasicBoldItalic';
    src: url('/gentium/GenBkBasBI-webfont.eot');
    src: url('/gentium/GenBkBasBI-webfont.eot?#iefix') format('embedded-opentype'),
         url('/gentium/GenBkBasBI-webfont.woff') format('woff'),
         url('/gentium/GenBkBasBI-webfont.ttf') format('truetype'),
         url('/gentium/GenBkBasBI-webfont.svg#GentiumBookBasicBoldItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}


text:
package jmx.test;

public interface HelloMBean {

	public void sayHello();

	public int add(int x, int y);

	// attributes

	// a read-only attribute called Name of type String
	public String getName();

	// a read-write attribute called CacheSize of type int
	public int getCacheSize();

	public void setCacheSize(int size);
}


text:
package com.google.appengine.api.datastore;

import java.util.Iterator;

/**
 * {@link Iterator} implementation that respects the provided offset and limit.
 *
 */
class SlicingIterator<T> extends AbstractIterator<T> {

  private final Iterator<T> delegate;
  // we'll decrement this as we consume results
  private int remainingOffset;
  private final Integer limit;
  private Integer numEntitiesReturned = 0;

  /**
   * @param delegate The {@link Iterator} that we're slicing.
   * @param offset The number of results to consume before we actually return any data. Can be null.
   * @param limit The maximum number of results we'll return. Can be null.
   */
  SlicingIterator(Iterator<T> delegate, Integer offset, Integer limit) {
    this.remainingOffset = offset == null ? 0 : offset;
    this.limit = limit;
    this.delegate = delegate;
  }

  @Override
  protected T computeNext() {
    if (numEntitiesReturned.equals(limit)) {
      endOfData();
    }
    T next = null;
    // Keep consuming as long as there is more data and remainingOffset isn't
    // negative
    while (delegate.hasNext() && remainingOffset-- >= 0) {
      next = delegate.next();
    }

    if (remainingOffset >= 0 || next == null) {
      // Either we didn't exhaust the offset or we did
      // exhaust the offset and we ran out of data.  Either way, we're done.
      endOfData();
    } else {
      // reset to 0 to ensure we consume exactly one entity the next time through
      remainingOffset = 0;
      numEntitiesReturned++;
    }
    return next;
  }
}


text:
export interface AddItemResponse {
    message: string;
    id?: number;
}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../効/index.html">
<meta http-equiv=refresh content="0; url='../効/index.html'">

Redirecting...

Click here if you are not redirected.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator.annotations;

import com.facebook.presto.spi.function.InvocationConvention;
import com.facebook.presto.spi.function.OperatorType;
import com.facebook.presto.spi.type.TypeSignature;

import java.util.List;
import java.util.Optional;

import static com.facebook.presto.metadata.Signature.internalOperator;
import static java.util.Objects.requireNonNull;

public final class OperatorImplementationDependency
        extends ScalarImplementationDependency
{
    private final OperatorType operator;

    public OperatorImplementationDependency(OperatorType operator, TypeSignature returnType, List<TypeSignature> argumentTypes, Optional<InvocationConvention> invocationConvention)
    {
        super(internalOperator(operator, returnType, argumentTypes), invocationConvention);
        this.operator = requireNonNull(operator, "operator is null");
    }

    public OperatorType getOperator()
    {
        return operator;
    }
}


text:
package util

import (
	"testing"

	buildapi "github.com/openshift/origin/pkg/build/api"
	kapi "k8s.io/kubernetes/pkg/api"
)

func TestGetBuildPodName(t *testing.T) {
	if expected, actual := "mybuild-build", GetBuildPodName(&buildapi.Build{ObjectMeta: kapi.ObjectMeta{Name: "mybuild"}}); expected != actual {
		t.Errorf("Expected %s, got %s", expected, actual)
	}
}

func TestGetBuildLabel(t *testing.T) {
	type getBuildLabelTest struct {
		labels         map[string]string
		expectedValue  string
		expectedExists bool
	}

	tests := []getBuildLabelTest{
		{
			// 0 - new label
			labels:         map[string]string{buildapi.BuildLabel: "value"},
			expectedValue:  "value",
			expectedExists: true,
		},
		{
			// 1 - deprecated label
			labels:         map[string]string{buildapi.DeprecatedBuildLabel: "value"},
			expectedValue:  "value",
			expectedExists: true,
		},
		{
			// 2 - deprecated label
			labels:         map[string]string{},
			expectedValue:  "",
			expectedExists: false,
		},
	}
	for i, tc := range tests {
		value, exists := GetBuildLabel(&kapi.Pod{ObjectMeta: kapi.ObjectMeta{Labels: tc.labels}})
		if value != tc.expectedValue {
			t.Errorf("(%d) unexpected value, expected %s, got %s", i, tc.expectedValue, value)
		}
		if exists != tc.expectedExists {
			t.Errorf("(%d) unexpected exists flag, expected %v, got %v", i, tc.expectedExists, exists)
		}
	}
}


text:
/*
 * Grafeas API
 *
 * An API to insert and retrieve annotations on cloud artifacts.
 *
 * API version: v1alpha1
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package grafeas

// VulnerabilityType provides metadata about a security vulnerability.
type ApiVulnerabilityType struct {
	// The CVSS score for this Vulnerability.
	CvssScore float32 `json:"cvss_score,omitempty"`
	Severity *VulnerabilityTypeSeverity `json:"severity,omitempty"`
	// All information about the package to specifically identify this vulnerability. One entry per (version range and cpe_uri) the package vulnerability has manifested in.
	Details []VulnerabilityTypeDetail `json:"details,omitempty"`
}


text:
module **browser.webworker**
----------------------------

Le module **webworker** fournit une intégration basique entre Brython et les
[WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).

Il permet d'exécuter un script Python dans un "travailleur" (web worker) de
façon relativement simple. Deux classes sont fournies : `Worker` et
`RPCWorker`.

## Classe Worker

Cette classe permet d'exécuter un script dans le travailleur et de communiquer
avec lui par envoi de messages.

Pour démarrer le travailleur, on crée une instance de la classe `WorkerParent`.
Le constructeur prend comme arguments l'url du script à exécuter (absolue ou
relative au répertoire du code source Brython), les arguments passés au script
(disponibles par `sys.argv` dans le script) et le contenu de `os.environ` pour
le script.

```python
from browser import webworker as ww
w = ww.WorkerParent('web_workers/test_worker.py', [1, 2, 3], {"test": "Ahoj"})
```

La communication avec le travailleur s'effectue par envoi de messages,
représentés par la classe `Message`. Notez qu'alors qu'il faut attendre un
certain temps avant que le travailleur soit prêt (ce qui se traduit par un
statut `w.status` égal à `S_RUNNING`), on peut commencer à lui envoyer des
messages immédiatement (ils sont mis dans une file d'attente et envoyés quand
le travailleur est prêt).

```python
m = ww.Message('ping', "salut")
r = w.post_message(m, want_reply=True)
```

L'envoi du message est fait par la méthode `WorkerCommon.post_message`, qui
prend comme paramètres le message (instance de la classe `Message`) et
`want_reply` qui indique si on veut attendre une réponse au message. Le
résultat est une instance de `asyncio.Future` qui sera résolue quand la
réponse arrivera.

On peut ajouter un paramètre `timeout`, le temps (en secondes) après lequel
le _future_ échoue si on n'a pas reçu de réponse.

Si on veut ignorer la réponse, ou qu'on n'en attend pas, on peut omettre les
deux paramètres et faire seulement

```python
w.post_message(ww.Message('quit', None))
```

Implémenter le travailleur est très simple. On définit d'abord les méthodes qui
vont traiter les différents messages:

```python
from browser.webworker import current_worker, Message
from browser import console

from sys import argv
from os import environ

def pong(self, message, **_):
    print('Le Web worker a reçu le message (',message.id,')', message.name,
        message.data)
    current_worker.post_reply(message, Message('pong', message.data))

def quit(self, *args, **kwargs):
    current_worker.terminate()

```

Remarquez l'utilisation de `current_worker.post_reply` au lieu de
`current_worker.post_message` pour indiquer que le message est une réponse au
message reçu.

Ensuite il faut associer ces méthodes aux messages correspondants. Ceci est
fait par la méthode `WorkerCommon.bind_message`. Son premier argument est le
nom du message et le second est la méthode à appeler quand le message
arrive.

```
current_worker.bind_message('ping', pong)
current_worker.bind_message('quit', quit)
```

Enfin il faut dire au parent qu'on est prêt à accepter des message. Pour cela
on utilise la méthode `current_worker.exec`.

```python
print("Début du worker de test avec les arguments:", argv,
    "et l'environnement", environ)
current_worker.exec()
```

`current_worker` est une instance de la classe `WorkerChild` est n'est
disponible que dans le travailleur.

## Classe RPCWorker

Les classes `WorkerParent` et `WorkerChild` qui représentent les deux côtés
de la connection sont très simples et peuvent être utilisés pour construire
des travailleurs plus utiles. Par exemple les classes `RPCWorkerParent` et
`RPCWorkerChild` qui sont utiles dans un scénario où nous voudrions
exécuter des méthodes Python dans un travailleur comme si elles étaient
dans le fil d'exécution principal.

Un programme pourrait typiquement se présenter ainsi:

```python
from browser import webworker as ww
from asyncio import coroutine

@coroutine
def main(w):
    # Attente du démarrage du travailleur
    yield w.wait_for_status(ww.S_RUNNING)

    # Appel de la méthode distante "add"
    a = yield w.add(10,20)
    assert a == 30

    # Appel de la méthode distante "log"
    yield w.log("Message de sortie")

    # Destruction du travailleur
    w.terminate()

# Création d'une nouvelle instance de travailleur
w = ww.RPCWorkerParent('web_workers/test_rpc.py', [1, 2, 3],
    {"USER":"personne"})

# Exécute la méthode principale
main(w)
```

La différence avec l'exemple `WorkerParent` est qu'il faut maintenant
réellement attendre que le travailleur ait démarré (jusque là nous ne savons
pas quelles méthodes il expose). Il faut donc tout envelopper dans une
coroutine `main` (`async def` dans les versions récentes de Python), où nous
pouvons attendre que le travailleur soit prêt par un `yield from` (`await`)
depuis la méthode `WorkerCommon.wait_for_status`.

On appelle ensuite la méthode `add`, qui doit être définie dans le
travailleur, où elle est exécutée. La méthode retourne une instance de
`asyncio.Future` qui représente la valeur de retour de l'appel de méthode. Le
`yield` dans la coroutine met en pause sont exécution jusqu'à ce qu'il soit
disponible. On appelle ensuite la méthode `log` et pour finir on clôt le
travail par la méthode `WorkerCommon.terminate`.

L'implémentation de la partie travailleur est très proche du cas précédent. La
principale différence est qu'à la place de `WorkerCommon.bind_message` on
utilise la méthode `RPCWorkerChild.register_method`:

```python
from browser.webworker import current_worker, Message
from browser import console

from sys import argv
from os import environ

def add(x, y):
    """Additionne deux nombres"""
    return x+y

def log(*args):
    print(*args)

# Enregistre les méthodes `add` et `log`.
current_worker.register_method(add)
current_worker.register_method(log)

# Dit au parent qu'on est prêt
print("Lancement du travailleur RPC de test avec les arguments:", argv,
    "et l'environment", environ)
current_worker.exec()
```

## Création de nouvelles classes `Worker`

Chaque nouveau type de travailleur nécessite deux classes, Parent et Enfant,
pour représenter le travailleur dans le fil d'exécution principal et dans le
thread du travailleur. Elles sont reliées à travers l'attribut `CHILD_CLASS`
de la classe Parent. Il doit d'agir d'une chaine de caractères qui peut être
utilisé pour importer la classe Enfant dans le travailleur (par exemple
pour la classe `RPCWorkerParent` l'attribut vaut
`"browser.webworker.RPCWorkerChild"`).

Le module se charge ensuite d'instancier la classe Enfant dans le travailleur
et de le stocker dans `webworker.current_worker`.


text:
  Argentières est
       un village
       localisé dans le département de Seine-et-Marne en Île-de-France. Elle comptait 355 habitants en 2008.

Le nombre d'habitations, à Argentières, se décomposait en 2011 en un appartements et 151 maisons soit
 un marché plutôt équilibré.

Si vous pensez emmenager à Argentières, vous pourrez aisément trouver une maison à acheter.

À coté de Argentières sont localisées les communes de
Guignes localisée à 5 km, 2 969 habitants,
Mormant localisée à 5 km, 4 338 habitants,
Fontenay-Trésigny à 5 km, 4 967 habitants,
Aubepierre-Ozouer-le-Repos à 2 km, 891 habitants,
Verneuil-l'Étang localisée à 2 km, 3 069 habitants,
Beauvoir située à 1 km, 198 habitants,
 entre autres. De plus, Argentières est située à seulement 19 km de Melun.


text:
var LineByLineReader = require('line-by-line');
var fs = require('fs');
var cli = require('cli');

var commentBuff = {};
var previousLine = '';
var stdout = [];

module.exports = {
    processFiles: function() {
        cli.args.forEach(function(src) {
            processFile(src);
        });
    }
};

/**
 * Read a file and add full class name
 * @param {string} src
 */
function processFile(src) {
    commentBuff = {};
    previousLine = '';
    stdout = [];

    var lr = new LineByLineReader(src);

    lr.on('line', function(line) {
        stdout.push(processLine(line));
        previousLine = line;
    });

    lr.on('end', function() {
        fs.writeFile(src, stdout.join('\n') + '\n');
    });

    lr.on('error', function(err) {
        throw err;
    });
}

/**
 * Extract the needed info for class line
 * @param {string} line
 * @returns {string}
 */
function processLine(line) {
    var isClassLine = /^\s*[\.&][^\s]+/gi.test(line);

    if (!isClassLine) {
        return line;
    }

    checkPreviousLine();

    var spaces = /^\s+/gi.exec(line);
    var level = spaces ? spaces[0].length : 0;
    var name = line.trim();

    // Sub classes need to have a different format
    if (level === 0 || name.charAt(0) !== '.') {
        name = name.replace(/[\.&\s{]/gi, '');
    } else {
        name = ' ' + name.replace(/[\.\s{]/gi, '');
    }

    commentBuff[level] = name;

    return buildComment(level) + '\n' + line;
}

/**
 * Return the complete class name comment
 * @param {number} level
 * @returns {string}
 */
function buildComment(level) {
    var comment = '\/\/ ';

    for (var i = 0; i <= level; i++) {
        comment = ' ' + comment;

        if (commentBuff[i]) {
            comment += commentBuff[i];
        }
    }

    return comment.substr(1);
}

/**
 * If the previous line is already a comment, we remove it
 */
function checkPreviousLine() {
    if (/^\s*[\/\/]/gi.test(previousLine)) {
        stdout.splice(-1);
    }
}


text:
  white-space: nowrap;
  font-size: smaller;
  padding: 4px 8px;
}


text:
import Ember from 'ember';

export default Ember.ArrayController.extend({
    itemController: 'item',
    isProcessing: false,
    actions: {
        voidAuthorization: function(model) {
            this.setProperties({
                isProcessing: true //Set isProcessing true to disable form button
            });

            var self = this;
            var aid = model.get('id');
            var onSuccess = function (model) {
                Ember.Logger.debug("Success!");
                Ember.Logger.debug('  void success results = ' + JSON.stringify(model));

                //after success update authorization status.
                var authorization = self.store.getById('authorization', aid);
                authorization.set('status', model.get('status'));
                self.setProperties({
                    isProcessing: false
                });
                //self.transitionToRoute('index');
            };
            var onFail = function (model) {
                retry(function () {
                    Ember.Logger.debug("Retry invoked!");
                    return model.save();
                }, 3); //NOTE: Retry could be bumped up to 3 or 5 times.
            };
            var retry = function (callback, nTimes) {
                try {
                    return callback();
                } catch (reason) {
                    if (nTimes-- > 0) {
                        return retry(callback, nTimes);
                    }
                    self.setProperties({
                        isProcessing: false
                    });
                    throw reason;
                }
            };
            var voidAuthorization = this.store.createRecord('void', {
                authorizationId: model.get('authorizationId'),
                total: model.get('total'),
                currency: model.get('currency'),
                isFinalCapture: true
            });
            voidAuthorization.save().then(onSuccess, onFail);
        },
        capture: function (model) {
            this.setProperties({
                isProcessing: true //Set isProcessing true to disable form button
            });

            var self = this;
            var aid = model.get('id');
            var onSuccess = function (model) {
                Ember.Logger.debug("Success!");
                Ember.Logger.debug('  capture success results = ' + JSON.stringify(model));

                //after success update authorization status.
                var authorization = self.store.getById('authorization', aid);
                authorization.set('status', model.get('status'));
                self.setProperties({
                    isProcessing: false
                });
                //self.transitionToRoute('index');
            };
            var onFail = function (model) {
                retry(function () {
                    Ember.Logger.debug("Retry invoked!");
                    return model.save();
                }, 3); //NOTE: Retry could be bumped up to 3 or 5 times.
            };
            var retry = function (callback, nTimes) {
                try {
                    return callback();
                } catch (reason) {
                    if (nTimes-- > 0) {
                        return retry(callback, nTimes);
                    }
                    self.setProperties({
                        isProcessing: false
                    });
                    throw reason;
                }
            };
            var capture = this.store.createRecord('capture', {
                authorizationId: model.get('authorizationId'),
                total: model.get('total'),
                currency: model.get('currency'),
                isFinalCapture: true
            });
            capture.save().then(onSuccess, onFail);
        }
    }
});


text:
import { Component, ViewChild } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { ModalController, NavController, NavParams } from 'ionic-angular';
import * as _ from 'lodash';
import { Logger } from '../../../../providers/logger/logger';

// providers
import { CoinbaseProvider } from '../../../../providers/coinbase/coinbase';
import { OnGoingProcessProvider } from '../../../../providers/on-going-process/on-going-process';
import { PlatformProvider } from '../../../../providers/platform/platform';
import { PopupProvider } from '../../../../providers/popup/popup';
import { ProfileProvider } from '../../../../providers/profile/profile';
import { WalletProvider } from '../../../../providers/wallet/wallet';

// pages
import { FinishModalPage } from '../../../finish/finish';
import { CoinbaseAccountPage } from '../../coinbase/coinbase-account/coinbase-account';

@Component({
  selector: 'page-coinbase-withdraw',
  templateUrl: 'coinbase-withdraw.html'
})
export class CoinbaseWithdrawPage {
  @ViewChild('slideButton')
  slideButton;

  private accountId: string;

  public hideSlideButton: boolean;
  public data: object = {};
  public amount: string;
  public currency: string;
  public description: string;
  public destinationTag: number;

  public wallet;
  public address: string;

  public buttonText: string;

  // Platform info
  public isCordova: boolean;

  constructor(
    private logger: Logger,
    private coinbaseProvider: CoinbaseProvider,
    private popupProvider: PopupProvider,
    private navCtrl: NavController,
    private onGoingProcessProvider: OnGoingProcessProvider,
    private navParams: NavParams,
    private profileProvider: ProfileProvider,
    private modalCtrl: ModalController,
    private platformProvider: PlatformProvider,
    private translate: TranslateService,
    private walletProvider: WalletProvider
  ) {
    this.isCordova = this.platformProvider.isCordova;
    this.hideSlideButton = false;

    this.amount = this.navParams.data.amount;
    this.currency = this.navParams.data.currency;
    this.description = this.navParams.data.description;

    this.accountId = this.navParams.data.id;
    this.coinbaseProvider.getAccount(this.accountId, this.data);

    this.wallet = this.profileProvider.getWallet(
      this.navParams.data.toWalletId
    );

    this.buttonText = this.isCordova
      ? this.translate.instant('Slide to withdraw')
      : this.translate.instant('Click to withdraw');
  }

  ionViewDidLoad() {
    this.logger.info('Loaded: CoinbaseWithdrawPage');
    this.navCtrl.swipeBackEnabled = false;
    if (this.isCordova) {
      window.addEventListener('keyboardWillShow', () => {
        this.hideSlideButton = true;
      });

      window.addEventListener('keyboardWillHide', () => {
        this.hideSlideButton = false;
      });
    }
  }

  ionViewWillLeave() {
    this.navCtrl.swipeBackEnabled = true;
  }

  ionViewWillEnter() {
    if (_.isEmpty(this.wallet)) {
      this.showErrorAndBack(this.translate.instant('No wallet found'));
      return;
    }

    this.walletProvider.getAddress(this.wallet, false).then(address => {
      this.address = address;
    });
  }

  private showErrorAndBack(err): void {
    if (this.isCordova) this.slideButton.isConfirmed(false);
    this.logger.error(err);
    err = err.errors ? err.errors[0].message : err;
    this.popupProvider
      .ionicAlert(this.translate.instant('Error'), err)
      .then(() => {
        this.navCtrl.pop();
      });
  }

  public showError(err): void {
    if (this.isCordova) this.slideButton.isConfirmed(false);
    this.logger.error(err);
    err = err.errors ? err.errors[0].message : err;
    this.popupProvider.ionicAlert(this.translate.instant('Error'), err);
  }

  public approve(): void {
    const tx = {
      to: this.address,
      amount: this.amount,
      currency: this.currency,
      description: this.description,
      destination_tag: this.destinationTag
    };
    this._sendTransaction(tx);
  }

  private _sendTransaction(tx, code?): void {
    this.onGoingProcessProvider.set('sendingTx');
    this.coinbaseProvider
      .sendTransaction(this.accountId, tx, code)
      .then(data => {
        this.onGoingProcessProvider.clear();
        this.logger.info(data.data);
        this.coinbaseProvider.logEvent({
          method: 'withdraw',
          amount: tx.amount,
          currency: tx.currency
        });
        this.openFinishModal();
      })
      .catch(e => {
        this.onGoingProcessProvider.clear();
        if (e == '2fa') {
          const message = this.translate.instant('Enter 2-step verification');
          const opts = {
            type: 'number',
            enableBackdropDismiss: false
          };
          this.popupProvider.ionicPrompt(null, message, opts).then(res => {
            if (res === null) {
              this.showErrorAndBack(
                this.translate.instant('Missing 2-step verification')
              );
              return;
            }
            this._sendTransaction(tx, res);
          });
        } else {
          this.showErrorAndBack(e);
        }
      });
  }

  public openFinishModal() {
    const finishText = this.translate.instant('Withdraw success');
    const finishComment = this.translate.instant(
      'It could take a while to confirm transaction'
    );
    const modal = this.modalCtrl.create(
      FinishModalPage,
      { finishText, finishComment },
      { showBackdrop: true, enableBackdropDismiss: false }
    );
    modal.present();
    modal.onDidDismiss(_ => {
      this.navCtrl.popToRoot({ animate: false }).then(_ => {
        this.navCtrl.parent.select(1);
        this.navCtrl.push(
          CoinbaseAccountPage,
          {
            id: this.accountId
          },
          { animate: false }
        );
      });
    });
  }
}