text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.hartwig.smsvdrremote"
    android:versionCode="1"
    android:versionName="1.0" >adb uninstall de.hartwig.smsvdrremote

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.WRITE_SMS"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme" android:label="@string/app_name">
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:configChanges="orientation"
             android:noHistory="true">>

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <activity android:name=".RecordActivity" />
         <activity android:name=".SettingActivity" />

         <activity android:name=".RemoteActivity" />
         <activity android:name=".VDRActivity" />
    </application>

</manifest>


text:
"""Support for Acrobat Forms in ReportLab documents

This module is somewhat experimental at this time.

Includes basic support for
    textfields,
    select fields (drop down lists), and
    check buttons.

The public interface consists of functions at the moment.
At some later date these operations may be made into canvas
methods. (comments?)

The ...Absolute(...) functions position the fields with respect
to the absolute canvas coordinate space -- that is, they do not
respect any coordinate transforms in effect for the canvas.

The ...Relative(...) functions position the ONLY THE LOWER LEFT
CORNER of the field using the coordinate transform in effect for
the canvas.  THIS WILL ONLY WORK CORRECTLY FOR TRANSLATED COORDINATES
-- THE SHAPE, SIZE, FONTSIZE, AND ORIENTATION OF THE FIELD WILL NOT BE EFFECTED
BY SCALING, ROTATION, SKEWING OR OTHER NON-TRANSLATION COORDINATE
TRANSFORMS.

Please note that all field names (titles) in a given document must be unique.
Textfields and select fields only support the "base 14" canvas fonts
at this time.

See individual function docstrings below for more information.

The function test1(...) generates a simple test file.

THIS CONTRIBUTION WAS COMMISSIONED BY REPORTLAB USERS
WHO WISH TO REMAIN ANONYMOUS.
"""

### NOTE: MAKE THE STRING FORMATS DYNAMIC IN PATTERNS TO SUPPORT ENCRYPTION XXXX

import string
from reportlab.pdfbase.pdfdoc import LINEEND, PDFString, PDFStream, PDFDictionary, PDFName
from reportlab.lib.colors import obj_R_G_B

#==========================public interfaces

def textFieldAbsolute(canvas, title, x, y, width, height, value="", maxlen=1000000, multiline=0):
    """Place a text field on the current page
        with name title at ABSOLUTE position (x,y) with
        dimensions (width, height), using value as the default value and
        maxlen as the maximum permissible length.  If multiline is set make
        it a multiline field.
    """
    theform = getForm(canvas)
    return theform.textField(canvas, title, x, y, x+width, y+height, value, maxlen, multiline)

def textFieldRelative(canvas, title, xR, yR, width, height, value="", maxlen=1000000, multiline=0):
    "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform"
    (xA, yA) = canvas.absolutePosition(xR,yR)
    return textFieldAbsolute(canvas, title, xA, yA, width, height, value, maxlen, multiline)

def buttonFieldAbsolute(canvas, title, value, x, y):
    """Place a check button field on the current page
        with name title and default value value (one of "Yes" or "Off")
        at ABSOLUTE position (x,y).
    """
    theform = getForm(canvas)
    return theform.buttonField(canvas, title, value, x, y)

def buttonFieldRelative(canvas, title, value, xR, yR):
    "same as buttonFieldAbsolute except the x and y are relative to the canvas coordinate transform"
    (xA, yA) = canvas.absolutePosition(xR,yR)
    return buttonFieldAbsolute(canvas, title, value, xA, yA)

def selectFieldAbsolute(canvas, title, value, options, x, y, width, height):
    """Place a select field (drop down list) on the current page
        with name title and
        with options listed in the sequence options
        default value value (must be one of options)
        at ABSOLUTE position (x,y) with dimensions (width, height)."""
    theform = getForm(canvas)
    theform.selectField(canvas, title, value, options, x, y, x+width, y+height)

def selectFieldRelative(canvas, title, value, options, xR, yR, width, height):
    "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform"
    (xA, yA) = canvas.absolutePosition(xR,yR)
    return selectFieldAbsolute(canvas, title, value, options, xA, yA, width, height)

def test1():
    from reportlab.pdfgen import canvas
    fn = "formtest1.pdf"
    c = canvas.Canvas(fn)
    # first page
    c.setFont("Courier", 10)
    c.drawString(100, 500, "hello world")
    textFieldAbsolute(c, "fieldA", 100, 600, 100, 20, "default value")
    textFieldAbsolute(c, "fieldB", 100, 300, 100, 50, "another default value", multiline=1)
    selectFieldAbsolute(c, "fieldC", "France", ["Canada", "France", "China"], 100, 200, 100, 20)
    c.rect(100, 600, 100, 20)
    buttonFieldAbsolute(c, "field2", "Yes", 100, 700)
    c.rect(100, 700, 20, 20)
    buttonFieldAbsolute(c, "field3", "Off", 100, 800)
    c.rect(100, 800, 20, 20)
    # second page
    c.showPage()
    c.setFont("Helvetica", 7)
    c.translate(50, 20)
    c.drawString(100, 500, "hello world")
    textFieldRelative(c, "fieldA_1", 100, 600, 100, 20, "default value 2")
    c.setStrokeColorRGB(1,0,0)
    c.setFillColorRGB(0,1,0.5)
    textFieldRelative(c, "fieldB_1", 100, 300, 100, 50, "another default value 2", multiline=1)
    selectFieldRelative(c, "fieldC_1", "France 1", ["Canada 0", "France 1", "China 2"], 100, 200, 100, 20)
    c.rect(100, 600, 100, 20)
    buttonFieldRelative(c, "field2_1", "Yes", 100, 700)
    c.rect(100, 700, 20, 20)
    buttonFieldRelative(c, "field3_1", "Off", 100, 800)
    c.rect(100, 800, 20, 20)
    c.save()
    print "wrote", fn

#==========================end of public interfaces

from pdfpattern import PDFPattern

def getForm(canvas):
    "get form from canvas, create the form if needed"
    try:
        return canvas.AcroForm
    except AttributeError:
        theform = canvas.AcroForm = AcroForm()
        # install the form in the document
        d = canvas._doc
        cat = d._catalog
        cat.AcroForm = theform
        return theform

class AcroForm:
    __PDFObject__ = True
    def __init__(self):
        self.fields = []
    def textField(self, canvas, title, xmin, ymin, xmax, ymax, value="", maxlen=1000000, multiline=0):
        # determine the page ref
        doc = canvas._doc
        page = doc.thisPageRef()
        # determine text info
        R, G, B = obj_R_G_B(canvas._fillColorObj)
        #print "rgb", (R,G,B)
        font = canvas. _fontname
        fontsize = canvas. _fontsize
        field = TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen,
                          font, fontsize, R, G, B, multiline)
        self.fields.append(field)
        canvas._addAnnotation(field)
    def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax):
        # determine the page ref
        doc = canvas._doc
        page = doc.thisPageRef()
        # determine text info
        R, G, B = obj_R_G_B(canvas._fillColorObj)
        #print "rgb", (R,G,B)
        font = canvas. _fontname
        fontsize = canvas. _fontsize
        field = SelectField(title, value, options, xmin, ymin, xmax, ymax, page,
              font=font, fontsize=fontsize, R=R, G=G, B=B)
        self.fields.append(field)
        canvas._addAnnotation(field)
    def buttonField(self, canvas, title, value, xmin, ymin):
        # determine the page ref
        doc = canvas._doc
        page = doc.thisPageRef()
        field = ButtonField(title, value, xmin, ymin, page)
        self.fields.append(field)
        canvas._addAnnotation(field)
    def format(self, document):
        from reportlab.pdfbase.pdfdoc import PDFArray
        proxy = PDFPattern(FormPattern, Resources=GLOBALRESOURCES, fields=PDFArray(self.fields))
        return proxy.format(document)

FormPattern = [
'<<', LINEEND,
' /NeedAppearances true ', LINEEND,
' /DA ', PDFString('/Helv 0 Tf 0 g '), LINEEND,
' /DR ', LINEEND,
["Resources"],
' /Fields ', LINEEND,
["fields"],
'>>'
]

def FormFontsDictionary():
    from reportlab.pdfbase.pdfdoc import PDFDictionary
    fontsdictionary = PDFDictionary()
    fontsdictionary.__RefOnly__ = 1
    for (fullname, shortname) in FORMFONTNAMES.items():
        fontsdictionary[shortname] = FormFont(fullname, shortname)
    fontsdictionary["ZaDb"] = ZADB
    return fontsdictionary

def FormResources():
    return PDFPattern(FormResourcesDictionaryPattern,
                      Encoding=ENCODING, Font=GLOBALFONTSDICTIONARY)

ZaDbPattern = [
' <<'
' /BaseFont'
'    /ZapfDingbats'
' /Name'
'    /ZaDb'
' /Subtype'
'    /Type1'
' /Type'
'    /Font'
'>>']

ZADB = PDFPattern(ZaDbPattern)

FormResourcesDictionaryPattern = [
'<<',
' /Encoding ',
["Encoding"], LINEEND,
' /Font ',
["Font"], LINEEND,
'>>'
]

FORMFONTNAMES = {
    "Helvetica": "Helv",
    "Helvetica-Bold": "HeBo",
    'Courier': "Cour",
    'Courier-Bold': "CoBo",
    'Courier-Oblique': "CoOb",
    'Courier-BoldOblique': "CoBO",
    'Helvetica-Oblique': "HeOb",
    'Helvetica-BoldOblique': "HeBO",
    'Times-Roman': "Time",
    'Times-Bold': "TiBo",
    'Times-Italic': "TiIt",
    'Times-BoldItalic': "TiBI",
    }

EncodingPattern = [
'<<',
' /PDFDocEncoding ',
["PDFDocEncoding"], LINEEND,
'>>',
]

PDFDocEncodingPattern = [
'<<'
' /Differences'
'    ['
' 24'
' /breve'
' /caron'
' /circumflex'
' /dotaccent'
' /hungarumlaut'
' /ogonek'
' /ring'
' /tilde'
' 39'
' /quotesingle'
' 96'
' /grave'
' 128'
' /bullet'
' /dagger'
' /daggerdbl'
' /ellipsis'
' /emdash'
' /endash'
' /florin'
' /fraction'
' /guilsinglleft'
' /guilsinglright'
' /minus'
' /perthousand'
' /quotedblbase'
' /quotedblleft'
' /quotedblright'
' /quoteleft'
' /quoteright'
' /quotesinglbase'
' /trademark'
' /fi'
' /fl'
' /Lslash'
' /OE'
' /Scaron'
' /Ydieresis'
' /Zcaron'
' /dotlessi'
' /lslash'
' /oe'
' /scaron'
' /zcaron'
' 160'
' /Euro'
' 164'
' /currency'
' 166'
' /brokenbar'
' 168'
' /dieresis'
' /copyright'
' /ordfeminine'
' 172'
' /logicalnot'
' /.notdef'
' /registered'
' /macron'
' /degree'
' /plusminus'
' /twosuperior'
' /threesuperior'
' /acute'
' /mu'
' 183'
' /periodcentered'
' /cedilla'
' /onesuperior'
' /ordmasculine'
' 188'
' /onequarter'
' /onehalf'
' /threequarters'
' 192'
' /Agrave'
' /Aacute'
' /Acircumflex'
' /Atilde'
' /Adieresis'
' /Aring'
' /AE'
' /Ccedilla'
' /Egrave'
' /Eacute'
' /Ecircumflex'
' /Edieresis'
' /Igrave'
' /Iacute'
' /Icircumflex'
' /Idieresis'
' /Eth'
' /Ntilde'
' /Ograve'
' /Oacute'
' /Ocircumflex'
' /Otilde'
' /Odieresis'
' /multiply'
' /Oslash'
' /Ugrave'
' /Uacute'
' /Ucircumflex'
' /Udieresis'
' /Yacute'
' /Thorn'
' /germandbls'
' /agrave'
' /aacute'
' /acircumflex'
' /atilde'
' /adieresis'
' /aring'
' /ae'
' /ccedilla'
' /egrave'
' /eacute'
' /ecircumflex'
' /edieresis'
' /igrave'
' /iacute'
' /icircumflex'
' /idieresis'
' /eth'
' /ntilde'
' /ograve'
' /oacute'
' /ocircumflex'
' /otilde'
' /odieresis'
' /divide'
' /oslash'
' /ugrave'
' /uacute'
' /ucircumflex'
' /udieresis'
' /yacute'
' /thorn'
' /ydieresis'
'    ]'
' /Type'
' /Encoding'
'>>']

# global constant
PDFDOCENC = PDFPattern(PDFDocEncodingPattern)
# global constant
ENCODING = PDFPattern(EncodingPattern, PDFDocEncoding=PDFDOCENC)

def FormFont(BaseFont, Name):
    from reportlab.pdfbase.pdfdoc import PDFName
    return PDFPattern(FormFontPattern, BaseFont=PDFName(BaseFont), Name=PDFName(Name), Encoding=PDFDOCENC)

FormFontPattern = [
'<<',
' /BaseFont ',
["BaseFont"], LINEEND,
' /Encoding ',
["Encoding"], LINEEND,
' /Name ',
["Name"], LINEEND,
' /Subtype '
' /Type1 '
' /Type '
' /Font '
'>>' ]

# global constants
GLOBALFONTSDICTIONARY = FormFontsDictionary()
GLOBALRESOURCES = FormResources()

def TextField(title, value, xmin, ymin, xmax, ymax, page,
              maxlen=1000000, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627, multiline=0):
    from reportlab.pdfbase.pdfdoc import PDFString, PDFName
    Flags = 0
    if multiline:
        Flags = Flags | (1<<12) # bit 13 is at position 12 :)
    fontname = FORMFONTNAMES[font]
    return PDFPattern(TextFieldPattern,
                      value=PDFString(value), maxlen=maxlen, page=page,
                      title=PDFString(title),
                      xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax,
                      fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B, Flags=Flags)

TextFieldPattern = [
'<<'
' /DA'
' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)'
' /DV ',
["value"], LINEEND,
' /F 4 /FT /Tx'
'/MK << /BC [ 0 0 0 ] >>'
' /MaxLen ',
["maxlen"], LINEEND,
' /P ',
["page"], LINEEND,
' /Rect '
'    [', ["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ]'
'/Subtype /Widget'
' /T ',
["title"], LINEEND,
' /Type'
'    /Annot'
' /V ',
["value"], LINEEND,
' /Ff ',
["Flags"],LINEEND,
'>>']

def SelectField(title, value, options, xmin, ymin, xmax, ymax, page,
              font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627):
    #print "ARGS", (title, value, options, xmin, ymin, xmax, ymax, page, font, fontsize, R, G, B)
    from reportlab.pdfbase.pdfdoc import PDFString, PDFName, PDFArray
    if value not in options:
        raise ValueError, "value %s must be one of options %s" % (repr(value), repr(options))
    fontname = FORMFONTNAMES[font]
    optionstrings = map(PDFString, options)
    optionarray = PDFArray(optionstrings)
    return PDFPattern(SelectFieldPattern,
                      Options=optionarray,
                      Selected=PDFString(value), Page=page,
                      Name=PDFString(title),
                      xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax,
                      fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B)

SelectFieldPattern = [
'<< % a select list',LINEEND,
' /DA ',
' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)',LINEEND,
#'    (/Helv 12 Tf 0 g)',LINEEND,
' /DV ',
["Selected"],LINEEND,
' /F ',
'    4',LINEEND,
' /FT ',
'    /Ch',LINEEND,
' /MK ',
'    <<',
'    /BC',
'        [',
'            0',
'            0',
'            0',
'        ]',
'    /BG',
'        [',
'            1',
'            1',
'            1',
'        ]',
'    >>',LINEEND,
' /Opt ',
["Options"],LINEEND,
' /P ',
["Page"],LINEEND,
'/Rect',
'    [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"],
'    ] ',LINEEND,
'/Subtype',
'    /Widget',LINEEND,
' /T ',
["Name"],LINEEND,
' /Type ',
'    /Annot',
' /V ',
["Selected"],LINEEND,
'>>']

def ButtonField(title, value, xmin, ymin, page):
    if value not in ("Yes", "Off"):
        raise ValueError, "button value must be 'Yes' or 'Off': "+repr(value)
    (dx, dy) = (16.77036, 14.90698)
    return PDFPattern(ButtonFieldPattern,
                      Name=PDFString(title),
                      xmin=xmin, ymin=ymin, xmax=xmin+dx, ymax=ymin+dy,
                      Hide=HIDE,
                      APDOff=APDOFF,
                      APDYes=APDYES,
                      APNYes=APNYES,
                      Value=PDFName(value),
                      Page=page)

ButtonFieldPattern = ['<< ',
'/AA',
'    <<',
'    /D ',
["Hide"], LINEEND,
#'        %(imported.18.0)s',
'    >> ',
'/AP ',
'    <<',
'    /D',
'        <<',
'        /Off ',
#'            %(imported.40.0)s',
["APDOff"], LINEEND,
'        /Yes ',
#'            %(imported.39.0)s',
["APDYes"], LINEEND,
'        >>', LINEEND,
'    /N',
'        << ',
'        /Yes ',
#'            %(imported.38.0)s',
["APNYes"],  LINEEND,
'        >>',
'    >>', LINEEND,
' /AS ',
["Value"], LINEEND,
' /DA ',
PDFString('/ZaDb 0 Tf 0 g'), LINEEND,
'/DV ',
["Value"], LINEEND,
'/F ',
'    4 ',
'/FT ',
'    /Btn ',
'/H ',
'    /T ',
'/MK ',
'    <<',
'    /AC (\\376\\377)',
#PDFString('\376\377'),
'    /CA ',
PDFString('4'),
'    /RC ',
PDFString('\376\377'),
'    >> ',LINEEND,
'/P ',
["Page"], LINEEND,
'/Rect',
'    [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"],
'    ] ',LINEEND,
'/Subtype',
'    /Widget ',
'/T ',
["Name"], LINEEND,
'/Type',
'    /Annot ',
'/V ',
["Value"], LINEEND,
' >>']

HIDE = PDFPattern([
'<< '
'/S '
' /Hide '
'>>'])

def buttonStreamDictionary():
    "everything except the length for the button appearance streams"
    result = PDFDictionary()
    result["SubType"] = "/Form"
    result["BBox"] = "[0 0 16.77036 14.90698]"
    font = PDFDictionary()
    font["ZaDb"] = ZADB
    resources = PDFDictionary()
    resources["ProcSet"] = "[ /PDF /Text ]"
    resources["Font"] = font
    result["Resources"] = resources
    return result

def ButtonStream(content):
    dict = buttonStreamDictionary()
    result = PDFStream(dict, content)
    result.filters = []
    return result

APDOFF = ButtonStream('0.749 g 0 0 16.7704 14.907 re f'+LINEEND)
APDYES = ButtonStream(
'0.749 g 0 0 16.7704 14.907 re f q 1 1 14.7704 12.907 re W '+
'n BT /ZaDb 11.3086 Tf 0 g  1 0 0 1 3.6017 3.3881 Tm (4) Tj ET'+LINEEND)
APNYES = ButtonStream(
'q 1 1 14.7704 12.907 re W n BT /ZaDb 11.3086 Tf 0 g  1 0 0 1 3.6017 3.3881 Tm (4) Tj ET Q'+LINEEND)

#==== script interpretation

if __name__=="__main__":
    test1()

redpajama_set_name: RedPajamaGithub


text:
function[N, N_teeth, z] = assert_enough_points(z, type, varargin)
% assert_enough_points -- Checks for enough points for a shape map
%
% [N, N_teeth, z] = assert_enough_points(z, type, {other, points, appended, to, z})
%
%     Performs checking to ensure that enough points are given to continue with
%     an unzipping algorithm. The input type is a string that can take the
%     following values:
%
%        'geodesic'
%        'slit'
%        'zipper'
%        'zipper_weld'
%        'loewner'

z = z(:);
N = length(z);

switch lower(type)
case 'geodesic'
  assert(N>2, 'Error: the geodesic algorithm requires at least three points');
  N_teeth = N-2;
case 'slit'
  assert(N>2, 'Error: the slit algorithm requires at least three points');
  N_teeth = N-2;
case 'zipper'
  assert(N>3, 'Error: the zipper algorithm requires at least four points');
  assert(mod(N,2)==0, 'Error: the zipper algorithm requires an even number of points');
  N_teeth = (N-2)/2 - 1;
case 'zipper_weld'
  assert(N>2, 'Error: the zipper-weld algorithm requires at least three points');
  N_teeth = (N-2)/2 - 1;
case 'loewner'
  assert(N>2, 'Error: the loewner algorithm requires at least three points');
  N_teeth = N-2;
otherwise
  error(['Unrecognized algorithm specification: ' type]);
end

% The following does z = [z; varargin{1}; varargin{2}; ...]
z = cat(1, z, varargin{:});


text:
var util = require('util');
var playlistdata = require('../lib/services/playlistdata');
var request = require("request")
var firebaseURL;
var _ = require('lodash');
var moment = require('moment');

module.exports = {

	startFetcher: function startFetcher(firebaseURL) {
		this.firebaseURL = firebaseURL;

		playlistdata.init({
			firebaseURL: this.firebaseURL
		});

		var postdata = {
			id: 'nostalgie',
			description: "What a feeling!",
			name: "Radio Nostalgie",
			website: 'http://www.nostalgie.eu',
			icon: 'http://www.nostalgie.eu/content/design/images/_2014/logo2014.gif'
		}
		playlistdata.postChannel(postdata);

		function fetchData() {

			downloadJSON(function(err, data) {
				//console.log("Got data:", data);

				try {

					var unixtimestamp = moment().hour(parseInt(data.tijd0.split('u')[0])).minutes(parseInt(data.tijd0.split('u')[1]));
					var songdata = {
						channelid: 'nostalgie',
						artist: data.artiest0,
						title: data.titel0,
						timestamp: unixtimestamp.toISOString(),
						unixtimestamp: unixtimestamp.unix(),
					};

					playlistdata.postSong(songdata);

					unixtimestamp = moment().hour(parseInt(data.tijd1.split('u')[0])).minutes(parseInt(data.tijd1.split('u')[1]));
					songdata = {
						channelid: 'nostalgie',
						artist: data.artiest1,
						title: data.titel1,
						timestamp: unixtimestamp.toISOString(),
						unixtimestamp: unixtimestamp.unix(),
					};

					playlistdata.postSong(songdata);

					unixtimestamp = moment().hour(parseInt(data.tijd2.split('u')[0])).minutes(parseInt(data.tijd2.split('u')[1]));
					songdata = {
						channelid: 'nostalgie',
						artist: data.artiest2,
						title: data.titel2,
						timestamp: unixtimestamp.toISOString(),
						unixtimestamp: unixtimestamp.unix(),
					};

					playlistdata.postSong(songdata);
				} catch (e) {
					console.error(e);
				}
			});
		}

		function downloadJSON(cb) {
			var when = moment().subtract(5, 'minutes');

			//console.log("Download JSON");
			var url = "http://www.nostalgie.eu/playlist/search/?d=" + when.year() + "-" + when.month() + "-" + when.date() + "&h=" + when.hour() + "&m=" + when.minute();
			request({
				url: url,
				json: true,
				headers: {
					'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36',
					'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
				}
			}, function(error, response, body) {
				//console.log('got HTTP response');
				if (!error && response.statusCode === 200) {
					console.error(error);
					cb(error, body);
				} else {
					cb(error);
				}
			});

		}

		fetchData();

		// fetch the data status every 3 min.
		var checkInterval = setInterval(function() {
			fetchData();
		}, (4 * 60 + Math.random() * 30) * 1000);

	},

	status: function status() {
		return ({
			name: "nostalgie"
		});
	}

};


text:
'''
Colin Gillespie (c.gillespie@ncl.ac.uk)
Last modified: 1/4/05

If want change the shape/colour/etc of a node or arrow
make your changes here
'''
'''
Small changes to format/style and stoichiometry marked as # brett 20050702
Brett G. Olivier (bgoli@users.sourceforge.net)
'''

class EdgeLines:
	'''
	If we want differnt arrow types for the different reaction types
	For example, square 'arrows' for a product
	Just now all the arrows are the same
	'''

	def __init__(self, edge_attribute):
		self.edge_attribute = edge_attribute

	def reactant(self):
		'''See class doc'''
		if self.edge_attribute['arrowtail'] != 'none':
			self.edge_attribute['arrowtail'] = 'normal'
		self.edge_attribute['arrowhead'] = 'none' # brett 20050702
		self.edge_attribute['arrowsize'] = '0.8'  # brett 20050702
		return self.edge_attribute

	def product(self):
		'''See class doc'''
		#if self.edge_attribute['arrowtail'] != 'none':  # brett 20050702
		#	self.edge_attribute['arrowtail'] = 'normal' # brett 20050702
		self.edge_attribute['arrowhead'] = 'normal'

		self.edge_attribute['arrowtail'] = 'none' # brett 20050702
		self.edge_attribute['arrowsize'] = '0.8'  # brett 20050702
		return self.edge_attribute

	def modifier(self):
		'''See class doc'''
		#if self.edge_attribute['arrowtail'] != 'none': # brett 20050702
		#	self.edge_attribute['arrowtail'] = 'normal' # brett 20050702
		self.edge_attribute['arrowhead'] = 'normal'
		self.edge_attribute['arrowtail'] = 'none'               # brett 20050702
		self.edge_attribute['weight'] = 0 						# brett 20050702
		self.edge_attribute['style'] = 'dotted, setlinewidth(2)'# brett 20050702
		self.edge_attribute['arrowsize'] = '0.8'				# brett 20050702
		self.edge_attribute['color'] = 'mediumblue' 			# brett 20050702
		return self.edge_attribute

class DotNodes:
	'''A class used to define the node shapes, colours, fonts, etc.
	So you can change what a species node looks like here.
	For edges, see the EdgeLines class'''

	def	__init__(self, model):
		self.general_node = {'style':'filled', 'fontsize':10, 'fontname':'Arial'}
		self.m = model

	def edgeNode(self, reaction, stoic=0):
		'''See class doc'''
		edge_attribute = {'arrowtail':'none', 'arrowhead':'normal',
			'color':'black', 'fontsize':10, 'fontname':'Arial'}

		if reaction.getReversible() == 1:
			edge_attribute['arrowtail'] = 'normal'

		if reaction.getFast() == 1:
			edge_attribute['color'] = 'red'

		# if stoic != 1:				# brett 20050702
		if stoic > 0.0 and stoic != 1: # brett 20050702: only show non-int, non-unitary stoich.
			edge_attribute['label'] = str(stoic) # brett 20050702

		return EdgeLines(edge_attribute)

	def specieNode(self, i, other_attributes=None):
		'''See class doc'''
		if not other_attributes:
			other_attributes = {}

		label = get_label(self.m.getSpecies(i-1))

		node_attribute = self.general_node
		node_attribute['color'] = 'orange'
		node_attribute['shape'] = 'ellipse'
		node_attribute['label'] = label
		node_attribute['URL'] = "Javascript:species('//sbml:species[%s]')" % str(i)

		#if boundary condition
		if self.m.getSpecies(i-1).getBoundaryCondition():
			node_attribute['color'] = "coral"

		for key, value in other_attributes.items():
			node_attribute[key] = value
		return node_attribute

	def reactionNode(self, i, other_attributes=None):
		'''See class doc'''
		if not other_attributes:
			other_attributes = {}

		label = get_label(self.m.getReaction(i-1))

		node_attribute = self.general_node
		node_attribute['color'] = 'moccasin'
		node_attribute['shape'] = 'rectangle'
		node_attribute['label'] = label
		node_attribute['URL'] = "Javascript:reaction('//sbml:reaction[%s]')" % str(i)

		for key, value in other_attributes.items():
			node_attribute[key] = value
		return node_attribute

	def compartmentNode(self, i, other_attributes=None):
		'''See class doc'''
		if not other_attributes:
			other_attributes = {}

		label = get_label(self.m.getCompartment(i-1))

		node_attribute = self.general_node
		node_attribute['graph_name'] = self.m.getCompartment(i-1).getId()
		node_attribute['label'] = label
		node_attribute['URL'] = "Javascript:compartment(\'//sbml:compartment[%s]\')" \
			% str(i)

		for key, value in other_attributes.items():
			node_attribute[key] = value
		return node_attribute

def get_label(obj):
	'''Just now the visualiser displays id's not names
	Uncomment the lines below to display names'''
#	if len(obj.getName()):
#		return obj.getName()
#	else:
#		return obj.getId()
	return obj.getId()


text:
.. _response_time_distribution:

============================
 Response Time Distribution
============================

The slow query log provides exact information about queries that take a long time to execute. However, sometimes there are a large number of queries that each take a very short amount of time to execute. This feature provides a tool for analyzing that information by counting and displaying the number of queries according to the the length of time they took to execute. The user can define time intervals that divide the range 0 to positive infinity into smaller intervals and then collect the number of commands whose execution times fall into each of those intervals.

Note that in a replication environment, the server will not take into account *any* queries executed by the slave's SQL thread (whether they are slow or not) for the time distribution unless the :variable:`log_slow_slave_statements` variable is set.

The feature isn't implemented in all versions of the server. The variable :variable:`have_response_time_distribution` indicates whether or not it is implemented in the server you are running.

Each interval is described as: ::

(range_base ^ n; range_base ^ (n+1)]

The range_base is some positive number (see Limitations). The interval is defined as the difference between two nearby powers of the range base.

For example, if the range base=10, we have the following intervals: ::

  (0; 10 ^ -6], (10 ^ -6; 10 ^ -5], (10 ^ -5; 10 ^ -4], ..., (10 ^ -1; 10 ^1], (10^1; 10^2]...(10^7; positive infinity]

or ::

  (0; 0.000001], (0.000001; 0.000010], (0.000010; 0.000100], ..., (0.100000; 1.0]; (1.0; 10.0]...(1000000; positive infinity]

For each interval, a count is made of the queries with execution times that fell into that interval.

You can select the range of the intervals by changing the range base. For example, for base range=2 we have the following intervals: ::

  (0; 2 ^ -19], (2 ^ -19; 2 ^ -18], (2 ^ -18; 2 ^ -17], ..., (2 ^ -1; 2 ^1], (2 ^ 1; 2 ^ 2]...(2 ^ 25; positive infinity]

or ::

  (0; 0.000001], (0.000001, 0.000003], ..., (0.25; 0.5], (0.5; 2], (2; 4]...(8388608; positive infinity]

Small numbers look strange (i.e., don't look like powers of 2), because we lose precision on division when the ranges are calculated at runtime. In the resulting table, you look at the high boundary of the range.

For example, you may see: ::

  +----------------+-------+------------+
  |      time      | count |    total   |
  +----------------+-------+------------|
  |       0.000001 |     0 |   0.000000 |
  |       0.000010 |    17 |   0.000094 |
  |       0.000100 |  4301 |   0.236555 |
  |       0.001000 |  1499 |   0.824450 |
  |       0.010000 | 14851 |  81.680502 |
  |       0.100000 |  8066 | 443.635693 |
  |       1.000000 |     0 |   0.000000 |
  |      10.000000 |     0 |   0.000000 |
  |     100.000000 |     1 |  55.937094 |
  |    1000.000000 |     0 |   0.000000 |
  |   10000.000000 |     0 |   0.000000 |
  |  100000.000000 |     0 |   0.000000 |
  | 1000000.000000 |     0 |   0.000000 |
  | TOO LONG QUERY |     0 |   0.000000 |
  +----------------+-------+------------+

This means there were: ::

  * 17 queries with 0.000001 < query execution time < = 0.000010 seconds; total execution time of the 17 queries = 0.000094 seconds

  * 4301 queries with 0.000010 < query execution time < = 0.000100 seconds; total execution time of the 4301 queries = 0.236555 seconds

  * 1499 queries with 0.000100 < query execution time < = 0.001000 seconds; total execution time of the 1499 queries = 0.824450 seconds

  * 14851 queries with 0.001000 < query execution time < = 0.010000 seconds; total execution time of the 14851 queries = 81.680502 seconds

  * 8066 queries with 0.010000 < query execution time < = 0.100000 seconds; total execution time of the 8066 queries = 443.635693 seconds

  * 1 query with 10.000000 < query execution time < = 100.0000 seconds; total execution time of the 1 query = 55.937094 seconds

Usage
=====

SELECT
------

You can get the distribution using the query: ::

  > SELECT * from INFORMATION_SCHEMA.QUERY_RESPONSE_TIME
  time	                 count	 total
  0.000001	         0	 0.000000
  0.000010	         0	 0.000000
  0.000100	         1	 0.000072
  0.001000	         0	 0.000000
  0.010000	         0	 0.000000
  0.100000	         0	 0.000000
  1.000000	         0	 0.000000
  10.000000	         8	 47.268416
  100.000000	         0	 0.000000
  1000.000000	         0	 0.000000
  10000.000000	         0	 0.000000
  100000.000000	         0	 0.000000
  1000000.000000	 0	 0.000000
  TOO LONG QUERY	 0	 0.000000

You can write a complex query like: ::

  SELECT c.count, c.time,
  (SELECT SUM(a.count) FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME as a WHERE a.count != 0) as query_count,
  (SELECT COUNT(*)     FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME as b WHERE b.count != 0) as not_zero_region_count,
  (SELECT COUNT(*)     FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME) as region_count
  FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME as c WHERE c.count > 0;

**Note:** If :variable:`query_response_time_stats` is ON, the execution times for these two ``SELECT`` queries will also be collected.

SHOW
----

Also, you can use this syntax: ::

  > SHOW QUERY_RESPONSE_TIME;
  time	                 count	 total
  0.000001	         0	 0.000000
  0.000010	         0	 0.000000
  0.000100	         1	 0.000072
  0.001000	         0	 0.000000
  0.010000	         0	 0.000000
  0.100000	         0	 0.000000
  1.000000	         0	 0.000000
  10.000000	         8	 47.268416
  100.000000	         0	 0.000000
  1000.000000	         0	 0.000000
  10000.000000	         0	 0.000000
  100000.000000	         0	 0.000000
  1000000.000000	 0	 0.000000
  TOO LONG QUERY	 0	 0.000000

**Note:** The execution time for the SHOW query will also be collected.

FLUSH
-----

Flushing can be done with: ::

  FLUSH QUERY_RESPONSE_TIME;

``FLUSH`` does two things:

  * Clears the collected times from the :table:`QUERY_RESPONSE_TIME` table

  * Reads the value of :variable:`query_response_time_range_base` and uses it to set the range base for the table

**Note:** The execution time for the ``FLUSH`` query will also be collected.

Stored procedures
-----------------

Stored procedure calls count as single query.

Collect time point
------------------

Time is collected after query execution completes (before clearing data structures).

Limitations
===========

  * ``String width for seconds``

    * Value: 7

    * Compile-time variable: ``QUERY_RESPONSE_TIME_STRING_POSITIVE_POWER_LENGTH``

  * ``String width for microseconds``

    * Value: 6

    * Compile-time variable: ``QUERY_RESPONSE_TIME_STRING_NEGATIVE_POWER_LENGTH``

  * Minimum range base

    * Value: 2

    * Compile-time variable: ``QUERY_RESPONSE_TIME_MINIMUM_BASE``

  * Minimum range base

    * Value: 1000

    * Compile-time variable: ``QUERY_RESPONSE_TIME_MAXIMUM_BASE``

  * Minimum time interval

    * Value:  1 microsecond

  * Maximum time interval

    * Value: 9999999 seconds

Version Specific Information
============================

  * :rn:`5.1.49-rel12.0`:
    Full functionality available.

  * :rn:`5.1.53-12.4`:
    Introduced :variable:`have_response_time_distribution`.

System Variables
================

.. variable:: have_response_time_distribution

     :version 5.1.53-12.4: Introduced.
     :scope: Global
     :dyn: No
     :vartype: Boolean
     :default: YES
     :range: YES/NO

Contains the value YES if the server you're running supports this feature; contains NO if the feature is not supported. It is enabled by default.

.. variable::  query_response_time_range_base

     :cli: Yes
     :conf: Yes
     :scope: Global
     :dyn: Yes
     :vartype: Numeric
     :default: 10
     :range: 2-1000

Sets up the logarithm base for the scale.

**Note:** The variable takes effect only after this command has been executed: ::

  FLUSH QUERY_RESPONSE_TIME;

.. variable:: enable_query_response_time_stats

     :version 5.1.49-rel12.0: Introduced.
     :cli: Yes
     :conf: Yes
     :scope: Global
     :dyn: Yes
     :vartype: Boolean
     :default: OFF
     :range: ON/OFF

This variable enables and disables collection of query times if the feature is available in the server that's running. If the value of variable :variable:`have_response_time_distribution` is YES, then you can enable collection of query times by setting this variable to ON using ``SET GLOBAL``.

INFORMATION_SCHEMA Tables
=========================

.. table:: INFORMATION_SCHEMA.QUERY_RESPONSE_TIME

   :column VARCHAR TIME: Interval range in which the query occurred
   :column INT(11) COUNT: Number of queries with execution times that fell into that interval
   :column VARCHAR TOTAL: Total execution time of the queries


text:
{% extends "base.html" %}
{% load staticfiles i18n %}
{% load display_account %}
{% block title %} Account Connections {% endblock title %}

{% block content %}

{% trans "Account Connections" %}

	{% if form.accounts %}

{% trans 'Connected Accounts' %}

	<form method="post" action="{% url 'socialaccount_connections' %}">
	{% csrf_token %}
	<fieldset>
	{% if form.non_field_errors %}

{{ form.non_field_errors }}

	{% endif %}
	{% for base_account in form.accounts %}
	{% with base_account.get_provider_account as account %}

	<input id="id_account_{{ base_account.id }}" type="radio" name="account" value="{{ base_account.id }}" hidden="hidden" />
	<button type="submit" class="btn btn-block btn-social btn-{{account.get_brand.name|lower}} signin-btn signin-btn" onClick="$('#id_account_{{base_account.id}}').prop('checked', 'checked');">
			     Disconnect {{account.get_brand.name}}
			  </button>

	{% endwith %}
	{% endfor %}

	</fieldset>

	</form>

	{% else %}

{% trans 'You currently have no social network accounts connected to this account.' %}

	{% endif %}

{% trans 'Connect More' %}

			{{ form.accounts|display_account|safe }}

{% endblock content %}


text:
require 'test_helper'

class ValidateAcceptanceOfMatcherTest < ActiveSupport::TestCase # :nodoc:

  context "an attribute which must be accepted" do
    setup do
      @model = define_model(:example) do
        validates_acceptance_of :attr
      end.new
    end

    should "require that attribute to be accepted" do
      assert_accepts validate_acceptance_of(:attr), @model
    end

    should "not overwrite the default message with nil" do
      assert_accepts validate_acceptance_of(:attr).with_message(nil), @model
    end
  end

  context "an attribute that does not need to be accepted" do
    setup do
      @model = define_model(:example, :attr => :string).new
    end

    should "not require that attribute to be accepted" do
      assert_rejects validate_acceptance_of(:attr), @model
    end
  end

  context "an attribute which must be accepted with a custom message" do
    setup do
      @model = define_model(:example) do
        validates_acceptance_of :attr, :message => 'custom'
      end.new
    end

    should "require that attribute to be accepted with that message" do
      assert_accepts validate_acceptance_of(:attr).with_message(/custom/),
                     @model
    end
  end

end


text:
/*global define*/
define([
        './Cartesian2',
        './defaultValue',
        './defined',
        './DeveloperError',
        './freezeObject'
    ], function(
        Cartesian2,
        defaultValue,
        defined,
        DeveloperError,
        freezeObject) {
    "use strict";

    /**
     * A 2x2 matrix, indexable as a column-major order array.
     * Constructor parameters are in row-major order for code readability.
     * @alias Matrix2
     * @constructor
     *
     * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
     * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
     * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
     * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
     *
     * @see Matrix2.fromColumnMajorArray
     * @see Matrix2.fromRowMajorArray
     * @see Matrix2.fromScale
     * @see Matrix2.fromUniformScale
     * @see Matrix3
     * @see Matrix4
     */
    var Matrix2 = function(column0Row0, column1Row0, column0Row1, column1Row1) {
        this[0] = defaultValue(column0Row0, 0.0);
        this[1] = defaultValue(column0Row1, 0.0);
        this[2] = defaultValue(column1Row0, 0.0);
        this[3] = defaultValue(column1Row1, 0.0);
    };

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    Matrix2.packedLength = 4;

    /**
     * Stores the provided instance into the provided array.
     *
     * @param {Matrix2} value The value to pack.
     * @param {Number[]} array The array to pack into.
     * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
     */
    Matrix2.pack = function(value, array, startingIndex) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
            throw new DeveloperError('value is required');
        }

        if (!defined(array)) {
            throw new DeveloperError('array is required');
        }
        //>>includeEnd('debug');

        startingIndex = defaultValue(startingIndex, 0);

        array[startingIndex++] = value[0];
        array[startingIndex++] = value[1];
        array[startingIndex++] = value[2];
        array[startingIndex++] = value[3];
    };

    /**
     * Retrieves an instance from a packed array.
     *
     * @param {Number[]} array The packed array.
     * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
     * @param {Matrix2} [result] The object into which to store the result.
     * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
     */
    Matrix2.unpack = function(array, startingIndex, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(array)) {
            throw new DeveloperError('array is required');
        }
        //>>includeEnd('debug');

        startingIndex = defaultValue(startingIndex, 0);

        if (!defined(result)) {
            result = new Matrix2();
        }

        result[0] = array[startingIndex++];
        result[1] = array[startingIndex++];
        result[2] = array[startingIndex++];
        result[3] = array[startingIndex++];
        return result;
    };

    /**
     * Duplicates a Matrix2 instance.
     *
     * @param {Matrix2} matrix The matrix to duplicate.
     * @param {Matrix2} [result] The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided. (Returns undefined if matrix is undefined)
     */
    Matrix2.clone = function(values, result) {
        if (!defined(values)) {
            return undefined;
        }
        if (!defined(result)) {
            return new Matrix2(values[0], values[2],
                               values[1], values[3]);
        }
        result[0] = values[0];
        result[1] = values[1];
        result[2] = values[2];
        result[3] = values[3];
        return result;
    };

    /**
     * Creates a Matrix2 from 4 consecutive elements in an array.
     *
     * @param {Number[]} array The array whose 4 consecutive elements correspond to the positions of the matrix.  Assumes column-major order.
     * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
     * @param {Matrix2} [result] The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
     *
     * @example
     * // Create the Matrix2:
     * // [1.0, 2.0]
     * // [1.0, 2.0]
     *
     * var v = [1.0, 1.0, 2.0, 2.0];
     * var m = Cesium.Matrix2.fromArray(v);
     *
     * // Create same Matrix2 with using an offset into an array
     * var v2 = [0.0, 0.0, 1.0, 1.0, 2.0, 2.0];
     * var m2 = Cesium.Matrix2.fromArray(v2, 2);
     */
    Matrix2.fromArray = function(array, startingIndex, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(array)) {
            throw new DeveloperError('array is required');
        }
        //>>includeEnd('debug');

        startingIndex = defaultValue(startingIndex, 0);

        if (!defined(result)) {
            result = new Matrix2();
        }

        result[0] = array[startingIndex];
        result[1] = array[startingIndex + 1];
        result[2] = array[startingIndex + 2];
        result[3] = array[startingIndex + 3];
        return result;
    };

    /**
     * Creates a Matrix2 instance from a column-major order array.
     *
     * @param {Number[]} values The column-major order array.
     * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
     * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
     */
    Matrix2.fromColumnMajorArray = function(values, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(values)) {
            throw new DeveloperError('values parameter is required');
        }
        //>>includeEnd('debug');

        return Matrix2.clone(values, result);
    };

    /**
     * Creates a Matrix2 instance from a row-major order array.
     * The resulting matrix will be in column-major order.
     *
     * @param {Number[]} values The row-major order array.
     * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
     * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
     */
    Matrix2.fromRowMajorArray = function(values, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(values)) {
            throw new DeveloperError('values is required.');
        }
        //>>includeEnd('debug');

        if (!defined(result)) {
            return new Matrix2(values[0], values[1],
                               values[2], values[3]);
        }
        result[0] = values[0];
        result[1] = values[2];
        result[2] = values[1];
        result[3] = values[3];
        return result;
    };

    /**
     * Computes a Matrix2 instance representing a non-uniform scale.
     *
     * @param {Cartesian2} scale The x and y scale factors.
     * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
     * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
     *
     * @example
     * // Creates
     * //   [7.0, 0.0]
     * //   [0.0, 8.0]
     * var m = Cesium.Matrix2.fromScale(new Cesium.Cartesian2(7.0, 8.0));
     */
    Matrix2.fromScale = function(scale, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(scale)) {
            throw new DeveloperError('scale is required.');
        }
        //>>includeEnd('debug');

        if (!defined(result)) {
            return new Matrix2(
                scale.x, 0.0,
                0.0,     scale.y);
        }

        result[0] = scale.x;
        result[1] = 0.0;
        result[2] = 0.0;
        result[3] = scale.y;
        return result;
    };

    /**
     * Computes a Matrix2 instance representing a uniform scale.
     *
     * @param {Number} scale The uniform scale factor.
     * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
     * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
     *
     * @example
     * // Creates
     * //   [2.0, 0.0]
     * //   [0.0, 2.0]
     * var m = Cesium.Matrix2.fromUniformScale(2.0);
     */
    Matrix2.fromUniformScale = function(scale, result) {
        //>>includeStart('debug', pragmas.debug);
        if (typeof scale !== 'number') {
            throw new DeveloperError('scale is required.');
        }
        //>>includeEnd('debug');

        if (!defined(result)) {
            return new Matrix2(
                scale, 0.0,
                0.0,   scale);
        }

        result[0] = scale;
        result[1] = 0.0;
        result[2] = 0.0;
        result[3] = scale;
        return result;
    };

    /**
     * Creates a rotation matrix.
     *
     * @param {Number} angle The angle, in radians, of the rotation.  Positive angles are counterclockwise.
     * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
     * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
     *
     * @example
     * // Rotate a point 45 degrees counterclockwise.
     * var p = new Cesium.Cartesian2(5, 6);
     * var m = Cesium.Matrix2.fromRotation(Cesium.Math.toRadians(45.0));
     * var rotated = Cesium.Matrix2.multiplyByVector(m, p, new Cesium.Cartesian2());
     */
    Matrix2.fromRotation = function(angle, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(angle)) {
            throw new DeveloperError('angle is required.');
        }
        //>>includeEnd('debug');

        var cosAngle = Math.cos(angle);
        var sinAngle = Math.sin(angle);

        if (!defined(result)) {
            return new Matrix2(
                cosAngle, -sinAngle,
                sinAngle, cosAngle);
        }
        result[0] = cosAngle;
        result[1] = sinAngle;
        result[2] = -sinAngle;
        result[3] = cosAngle;
        return result;
    };

    /**
     * Creates an Array from the provided Matrix2 instance.
     * The array will be in column-major order.
     *
     * @param {Matrix2} matrix The matrix to use..
     * @param {Number[]} [result] The Array onto which to store the result.
     * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
     */
    Matrix2.toArray = function(matrix, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        //>>includeEnd('debug');

        if (!defined(result)) {
            return [matrix[0], matrix[1], matrix[2], matrix[3]];
        }
        result[0] = matrix[0];
        result[1] = matrix[1];
        result[2] = matrix[2];
        result[3] = matrix[3];
        return result;
    };

    /**
     * Computes the array index of the element at the provided row and column.
     *
     * @param {Number} row The zero-based index of the row.
     * @param {Number} column The zero-based index of the column.
     * @returns {Number} The index of the element at the provided row and column.
     *
     * @exception {DeveloperError} row must be 0 or 1.
     * @exception {DeveloperError} column must be 0 or 1.
     *
     * @example
     * var myMatrix = new Cesium.Matrix2();
     * var column1Row0Index = Cesium.Matrix2.getElementIndex(1, 0);
     * var column1Row0 = myMatrix[column1Row0Index]
     * myMatrix[column1Row0Index] = 10.0;
     */
    Matrix2.getElementIndex = function(column, row) {
        //>>includeStart('debug', pragmas.debug);
        if (typeof row !== 'number' || row < 0 || row > 1) {
            throw new DeveloperError('row must be 0 or 1.');
        }
        if (typeof column !== 'number' || column < 0 || column > 1) {
            throw new DeveloperError('column must be 0 or 1.');
        }
        //>>includeEnd('debug');

        return column * 2 + row;
    };

    /**
     * Retrieves a copy of the matrix column at the provided index as a Cartesian2 instance.
     *
     * @param {Matrix2} matrix The matrix to use.
     * @param {Number} index The zero-based index of the column to retrieve.
     * @param {Cartesian2} result The object onto which to store the result.
     * @returns {Cartesian2} The modified result parameter.
     *
     * @exception {DeveloperError} index must be 0 or 1.
     */
    Matrix2.getColumn = function(matrix, index, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required.');
        }
        if (typeof index !== 'number' || index < 0 || index > 1) {
            throw new DeveloperError('index must be 0 or 1.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        var startIndex = index * 2;
        var x = matrix[startIndex];
        var y = matrix[startIndex + 1];

        result.x = x;
        result.y = y;
        return result;
    };

    /**
     * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian2 instance.
     *
     * @param {Matrix2} matrix The matrix to use.
     * @param {Number} index The zero-based index of the column to set.
     * @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified column.
     * @param {Cartesian2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     *
     * @exception {DeveloperError} index must be 0 or 1.
     */
    Matrix2.setColumn = function(matrix, index, cartesian, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(cartesian)) {
            throw new DeveloperError('cartesian is required');
        }
        if (typeof index !== 'number' || index < 0 || index > 1) {
            throw new DeveloperError('index must be 0 or 1.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result = Matrix2.clone(matrix, result);
        var startIndex = index * 2;
        result[startIndex] = cartesian.x;
        result[startIndex + 1] = cartesian.y;
        return result;
    };

    /**
     * Retrieves a copy of the matrix row at the provided index as a Cartesian2 instance.
     *
     * @param {Matrix2} matrix The matrix to use.
     * @param {Number} index The zero-based index of the row to retrieve.
     * @param {Cartesian2} result The object onto which to store the result.
     * @returns {Cartesian2} The modified result parameter.
     *
     * @exception {DeveloperError} index must be 0 or 1.
     */
    Matrix2.getRow = function(matrix, index, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required.');
        }
        if (typeof index !== 'number' || index < 0 || index > 1) {
            throw new DeveloperError('index must be 0 or 1.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        var x = matrix[index];
        var y = matrix[index + 2];

        result.x = x;
        result.y = y;
        return result;
    };

    /**
     * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian2 instance.
     *
     * @param {Matrix2} matrix The matrix to use.
     * @param {Number} index The zero-based index of the row to set.
     * @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified row.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     *
     * @exception {DeveloperError} index must be 0 or 1.
     */
    Matrix2.setRow = function(matrix, index, cartesian, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(cartesian)) {
            throw new DeveloperError('cartesian is required');
        }
        if (typeof index !== 'number' || index < 0 || index > 1) {
            throw new DeveloperError('index must be 0 or 1.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result = Matrix2.clone(matrix, result);
        result[index] = cartesian.x;
        result[index + 2] = cartesian.y;
        return result;
    };

    var scratchColumn = new Cartesian2();

    /**
     * Extracts the non-uniform scale assuming the matrix is an affine transformation.
     *
     * @param {Matrix2} matrix The matrix.
     * @param {Cartesian2} result The object onto which to store the result.
     * @returns {Cartesian2} The modified result parameter.
     */
    Matrix2.getScale = function(matrix, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result.x = Cartesian2.magnitude(Cartesian2.fromElements(matrix[0], matrix[1], scratchColumn));
        result.y = Cartesian2.magnitude(Cartesian2.fromElements(matrix[2], matrix[3], scratchColumn));
        return result;
    };

    var scratchScale = new Cartesian2();

    /**
     * Computes the maximum scale assuming the matrix is an affine transformation.
     * The maximum scale is the maximum length of the column vectors.
     *
     * @param {Matrix2} matrix The matrix.
     * @returns {Number} The maximum scale.
     */
    Matrix2.getMaximumScale = function(matrix) {
        Matrix2.getScale(matrix, scratchScale);
        return Cartesian2.maximumComponent(scratchScale);
    };

    /**
     * Computes the product of two matrices.
     *
     * @param {Matrix2} left The first matrix.
     * @param {Matrix2} right The second matrix.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.multiply = function(left, right, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(left)) {
            throw new DeveloperError('left is required');
        }
        if (!defined(right)) {
            throw new DeveloperError('right is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        var column0Row0 = left[0] * right[0] + left[2] * right[1];
        var column1Row0 = left[0] * right[2] + left[2] * right[3];
        var column0Row1 = left[1] * right[0] + left[3] * right[1];
        var column1Row1 = left[1] * right[2] + left[3] * right[3];

        result[0] = column0Row0;
        result[1] = column0Row1;
        result[2] = column1Row0;
        result[3] = column1Row1;
        return result;
    };

    /**
     * Computes the sum of two matrices.
     *
     * @param {Matrix2} left The first matrix.
     * @param {Matrix2} right The second matrix.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.add = function(left, right, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(left)) {
            throw new DeveloperError('left is required');
        }
        if (!defined(right)) {
            throw new DeveloperError('right is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result[0] = left[0] + right[0];
        result[1] = left[1] + right[1];
        result[2] = left[2] + right[2];
        result[3] = left[3] + right[3];
        return result;
    };

    /**
     * Computes the difference of two matrices.
     *
     * @param {Matrix2} left The first matrix.
     * @param {Matrix2} right The second matrix.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.subtract = function(left, right, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(left)) {
            throw new DeveloperError('left is required');
        }
        if (!defined(right)) {
            throw new DeveloperError('right is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result[0] = left[0] - right[0];
        result[1] = left[1] - right[1];
        result[2] = left[2] - right[2];
        result[3] = left[3] - right[3];
        return result;
    };

    /**
     * Computes the product of a matrix and a column vector.
     *
     * @param {Matrix2} matrix The matrix.
     * @param {Cartesian2} cartesian The column.
     * @param {Cartesian2} result The object onto which to store the result.
     * @returns {Cartesian2} The modified result parameter.
     */
    Matrix2.multiplyByVector = function(matrix, cartesian, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(cartesian)) {
            throw new DeveloperError('cartesian is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        var x = matrix[0] * cartesian.x + matrix[2] * cartesian.y;
        var y = matrix[1] * cartesian.x + matrix[3] * cartesian.y;

        result.x = x;
        result.y = y;
        return result;
    };

    /**
     * Computes the product of a matrix and a scalar.
     *
     * @param {Matrix2} matrix The matrix.
     * @param {Number} scalar The number to multiply by.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.multiplyByScalar = function(matrix, scalar, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (typeof scalar !== 'number') {
            throw new DeveloperError('scalar is required and must be a number');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result[0] = matrix[0] * scalar;
        result[1] = matrix[1] * scalar;
        result[2] = matrix[2] * scalar;
        result[3] = matrix[3] * scalar;
        return result;
    };

    /**
     * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
     *
     * @param {Matrix2} matrix The matrix on the left-hand side.
     * @param {Cartesian2} scale The non-uniform scale on the right-hand side.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     *
     * @see Matrix2.fromScale
     * @see Matrix2.multiplyByUniformScale
     *
     * @example
     * // Instead of Cesium.Matrix2.multiply(m, Cesium.Matrix2.fromScale(scale), m);
     * Cesium.Matrix2.multiplyByScale(m, scale, m);
     */
    Matrix2.multiplyByScale = function(matrix, scale, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(scale)) {
            throw new DeveloperError('scale is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result[0] = matrix[0] * scale.x;
        result[1] = matrix[1] * scale.x;
        result[2] = matrix[2] * scale.y;
        result[3] = matrix[3] * scale.y;
        return result;
    };

    /**
     * Creates a negated copy of the provided matrix.
     *
     * @param {Matrix2} matrix The matrix to negate.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.negate = function(matrix, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result[0] = -matrix[0];
        result[1] = -matrix[1];
        result[2] = -matrix[2];
        result[3] = -matrix[3];
        return result;
    };

    /**
     * Computes the transpose of the provided matrix.
     *
     * @param {Matrix2} matrix The matrix to transpose.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.transpose = function(matrix, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        var column0Row0 = matrix[0];
        var column0Row1 = matrix[2];
        var column1Row0 = matrix[1];
        var column1Row1 = matrix[3];

        result[0] = column0Row0;
        result[1] = column0Row1;
        result[2] = column1Row0;
        result[3] = column1Row1;
        return result;
    };

    /**
     * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
     *
     * @param {Matrix2} matrix The matrix with signed elements.
     * @param {Matrix2} result The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter.
     */
    Matrix2.abs = function(matrix, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(matrix)) {
            throw new DeveloperError('matrix is required');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required');
        }
        //>>includeEnd('debug');

        result[0] = Math.abs(matrix[0]);
        result[1] = Math.abs(matrix[1]);
        result[2] = Math.abs(matrix[2]);
        result[3] = Math.abs(matrix[3]);

        return result;
    };

    /**
     * Compares the provided matrices componentwise and returns
     * <code>true</code> if they are equal, <code>false</code> otherwise.
     *
     * @param {Matrix2} [left] The first matrix.
     * @param {Matrix2} [right] The second matrix.
     * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
     */
    Matrix2.equals = function(left, right) {
        return (left === right) ||
               (defined(left) &&
                defined(right) &&
                left[0] === right[0] &&
                left[1] === right[1] &&
                left[2] === right[2] &&
                left[3] === right[3]);
    };

    /**
     * @private
     */
    Matrix2.equalsArray = function(matrix, array, offset) {
        return matrix[0] === array[offset] &&
               matrix[1] === array[offset + 1] &&
               matrix[2] === array[offset + 2] &&
               matrix[3] === array[offset + 3];
    };

    /**
     * Compares the provided matrices componentwise and returns
     * <code>true</code> if they are within the provided epsilon,
     * <code>false</code> otherwise.
     *
     * @param {Matrix2} [left] The first matrix.
     * @param {Matrix2} [right] The second matrix.
     * @param {Number} epsilon The epsilon to use for equality testing.
     * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
     */
    Matrix2.equalsEpsilon = function(left, right, epsilon) {
        //>>includeStart('debug', pragmas.debug);
        if (typeof epsilon !== 'number') {
            throw new DeveloperError('epsilon must be a number');
        }
        //>>includeEnd('debug');

        return (left === right) ||
                (defined(left) &&
                defined(right) &&
                Math.abs(left[0] - right[0]) <= epsilon &&
                Math.abs(left[1] - right[1]) <= epsilon &&
                Math.abs(left[2] - right[2]) <= epsilon &&
                Math.abs(left[3] - right[3]) <= epsilon);
    };

    /**
     * An immutable Matrix2 instance initialized to the identity matrix.
     *
     * @type {Matrix2}
     * @constant
     */
    Matrix2.IDENTITY = freezeObject(new Matrix2(1.0, 0.0,
                                                0.0, 1.0));

    /**
     * An immutable Matrix2 instance initialized to the zero matrix.
     *
     * @type {Matrix2}
     * @constant
     */
    Matrix2.ZERO = freezeObject(new Matrix2(0.0, 0.0,
                                            0.0, 0.0));

    /**
     * The index into Matrix2 for column 0, row 0.
     *
     * @type {Number}
     * @constant
     *
     * @example
     * var matrix = new Cesium.Matrix2();
     * matrix[Cesium.Matrix2.COLUMN0ROW0] = 5.0; // set column 0, row 0 to 5.0
     */
    Matrix2.COLUMN0ROW0 = 0;

    /**
     * The index into Matrix2 for column 0, row 1.
     *
     * @type {Number}
     * @constant
     *
     * @example
     * var matrix = new Cesium.Matrix2();
     * matrix[Cesium.Matrix2.COLUMN0ROW1] = 5.0; // set column 0, row 1 to 5.0
     */
    Matrix2.COLUMN0ROW1 = 1;

    /**
     * The index into Matrix2 for column 1, row 0.
     *
     * @type {Number}
     * @constant
     *
     * @example
     * var matrix = new Cesium.Matrix2();
     * matrix[Cesium.Matrix2.COLUMN1ROW0] = 5.0; // set column 1, row 0 to 5.0
     */
    Matrix2.COLUMN1ROW0 = 2;

    /**
     * The index into Matrix2 for column 1, row 1.
     *
     * @type {Number}
     * @constant
     *
     * @example
     * var matrix = new Cesium.Matrix2();
     * matrix[Cesium.Matrix2.COLUMN1ROW1] = 5.0; // set column 1, row 1 to 5.0
     */
    Matrix2.COLUMN1ROW1 = 3;

    /**
     * Duplicates the provided Matrix2 instance.
     *
     * @param {Matrix2} [result] The object onto which to store the result.
     * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
     */
    Matrix2.prototype.clone = function(result) {
        return Matrix2.clone(this, result);
    };

    /**
     * Compares this matrix to the provided matrix componentwise and returns
     * <code>true</code> if they are equal, <code>false</code> otherwise.
     *
     * @param {Matrix2} [right] The right hand side matrix.
     * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
     */
    Matrix2.prototype.equals = function(right) {
        return Matrix2.equals(this, right);
    };

    /**
     * Compares this matrix to the provided matrix componentwise and returns
     * <code>true</code> if they are within the provided epsilon,
     * <code>false</code> otherwise.
     *
     * @param {Matrix2} [right] The right hand side matrix.
     * @param {Number} epsilon The epsilon to use for equality testing.
     * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
     */
    Matrix2.prototype.equalsEpsilon = function(right, epsilon) {
        return Matrix2.equalsEpsilon(this, right, epsilon);
    };

    /**
     * Creates a string representing this Matrix with each row being
     * on a separate line and in the format '(column0, column1)'.
     *
     * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1)'.
     */
    Matrix2.prototype.toString = function() {
        return '(' + this[0] + ', ' + this[2] + ')\n' +
               '(' + this[1] + ', ' + this[3] + ')';
    };

    return Matrix2;
});


text:
import io
import locale
import mock
import pytest
from datetime import datetime
from datetime import timedelta
from dallinger import utils, config

class TestSubprocessWrapper(object):
    @pytest.fixture
    def sys(self):
        with mock.patch("dallinger.utils.sys") as sys:
            yield sys

    def test_writing_to_stdout_unaffected_by_default(self):
        def sample(**kwargs):
            assert kwargs["stdin"] is None
            assert kwargs["stdout"] is None

        utils.wrap_subprocess_call(sample)(stdin=None, stdout=None)

    def test_writing_to_stdout_is_diverted_if_broken(self, sys):
        def sample(**kwargs):
            assert kwargs["stdin"] is None
            assert kwargs["stdout"] is not None
            assert kwargs["stdout"] is not sys.stdout

        sys.stdout.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample)(stdin=None, stdout=None)

    def test_writing_to_stdout_is_not_diverted_if_wrapstdout_is_false(self, sys):
        def sample(**kwargs):
            assert kwargs["stdin"] is None
            assert kwargs["stdout"] is None

        sys.stdout.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample, wrap_stdout=False)(stdin=None, stdout=None)

    def test_writing_to_stderr_is_diverted_if_broken(self, sys):
        def sample(**kwargs):
            assert kwargs["stderr"] is not None
            assert kwargs["stderr"] is not sys.stdout

        sys.stderr.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample)(stderr=None)

    def test_reading_from_stdin_is_not_diverted(self, sys):
        def sample(**kwargs):
            assert kwargs["stdin"] is None
            assert kwargs["stdout"] is None

        sys.stdin.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample)(stdin=None, stdout=None)

    def test_arbitrary_outputs_are_not_replaced_even_if_stdout_is_broken(self, sys):
        output = io.StringIO()

        def sample(**kwargs):
            assert kwargs["stdin"] is None
            assert kwargs["stdout"] is output

        sys.stdout.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample)(stdin=None, stdout=output)

    def test_writing_to_broken_stdout_is_output_after_returning(self, sys):
        def sample(**kwargs):
            kwargs["stdout"].write(b"Output")
            # The output isn't written until we return
            sys.stdout.write.assert_not_called()

        sys.stdout.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample)(stdin=None, stdout=None)
        sys.stdout.write.assert_called_once_with(b"Output")

    def test_writing_to_broken_stderr_is_output_after_returning(self, sys):
        def sample(**kwargs):
            kwargs["stderr"].write(b"Output")
            # The output isn't written until we return
            sys.stderr.write.assert_not_called()

        sys.stderr.fileno.side_effect = io.UnsupportedOperation
        utils.wrap_subprocess_call(sample)(stderr=None)
        sys.stderr.write.assert_called_once_with(b"Output")

@pytest.mark.usefixtures("in_tempdir")
class TestGitClient(object):
    @pytest.fixture
    def git(self):
        from dallinger.utils import GitClient

        git = GitClient()
        return git

    def test_client(self, git, stub_config):
        import subprocess

        stub_config.write()
        config = {"user.name": "Test User", "user.email": "test@example.com"}
        git.init(config=config)
        git.add("--all")
        git.commit("Test Repo")
        assert b"Test Repo" in subprocess.check_output(["git", "log"])

    def test_files_with_gitignore(self, git):
        config = {"user.name": "Test User", "user.email": "test@example.com"}
        with open("one.txt", "w") as one:
            one.write("one")
        with open("two.txt", "w") as two:
            two.write("two")
        with open(".gitignore", "w") as ignore:
            ignore.write("two.*")
        git.init(config=config)

        assert set(git.files()) == {".gitignore", "one.txt"}

    def test_both_commited_and_uncommitted_files_shown(self, git):
        config = {"user.name": "Test User", "user.email": "test@example.com"}
        git.init(config=config)

        with open("one.txt", "w") as one:
            one.write("one")
        git.add("--all")

        with open("two.txt", "w") as two:
            two.write("two")

        assert git.files() == {"one.txt", "two.txt"}

    def test_files_handles_nonascii_filenames(self, git):
        config = {"user.name": "Test User", "user.email": "test@example.com"}
        git.init(config=config)
        filename = b"J\xc3\xb8hn D\xc3\xb8\xc3\xa9's \xe2\x80\x93.txt"

        with open(filename, "w") as two:
            two.write("blah")

        assert git.files() == {filename.decode(locale.getpreferredencoding())}

    def test_files_on_non_git_repo(self, git):
        assert git.files() == set()

    def test_includes_details_in_exceptions(self, git):
        with pytest.raises(Exception) as ex_info:
            git.push("foo", "bar")
        assert ex_info.match("[nN]ot a git repository")

    def test_can_use_alternate_output(self, git):
        import tempfile

        git.out = tempfile.NamedTemporaryFile()
        git.encoding = "utf8"
        git.init()
        git.out.seek(0)
        assert b"git init" in git.out.read()

    def test_clone(self, git):
        with mock.patch("dallinger.utils.run_command") as runner:
            tempdir = git.clone("https://some-fake-repo")

        runner.assert_called_once_with(
            ["git", "clone", "https://some-fake-repo", tempdir], mock.ANY
        )

class TestParticipationTime(object):
    @pytest.fixture
    def subject(self):
        from dallinger.utils import ParticipationTime

        return ParticipationTime

    def test_time_translations(self, subject, a, stub_config):
        timeline = subject(a.participant(), datetime.now(), stub_config)
        assert timeline.allowed_hours == stub_config.get("duration")
        assert timeline.allowed_minutes == 60.0
        assert timeline.allowed_seconds == 3600.0

    def test_excess_minutes(self, subject, a, stub_config):
        duration_mins = stub_config.get("duration") * 60
        participant = a.participant()
        five_minutes_over = participant.creation_time + timedelta(
            minutes=duration_mins + 5
        )

        timeline = subject(a.participant(), five_minutes_over, stub_config)

        assert int(round(timeline.excess_minutes)) == 5

    def test_is_overdue_true_if_exceeds_grace_period(self, subject, a, stub_config):
        duration_secs = round(stub_config.get("duration") * 60 * 60)
        participant = a.participant()
        just_over = timedelta(seconds=duration_secs + subject.grace_period_seconds + 1)
        reference_time = participant.creation_time + just_over

        timeline = subject(a.participant(), reference_time, stub_config)

        assert timeline.is_overdue

    def test_is_overdue_false_if_within_grace_period(self, subject, a, stub_config):
        duration_secs = round(stub_config.get("duration") * 60 * 60)
        participant = a.participant()
        just_under = timedelta(seconds=duration_secs + subject.grace_period_seconds - 1)
        reference_time = participant.creation_time + just_under
        timeline = subject(a.participant(), reference_time, stub_config)

        assert not timeline.is_overdue

class TestBaseURL(object):
    @pytest.fixture
    def subject(self):
        from dallinger.utils import get_base_url

        return get_base_url

    @pytest.fixture
    def config(self):
        instance = config.get_config()
        instance.ready = True
        yield instance
        config.config = None

    def test_base_url_uses_flask_if_available(self, subject):
        from dallinger.experiment_server.experiment_server import app

        with app.test_request_context(base_url="https://example.com", path="/launch"):
            assert subject() == "https://example.com"

    def test_base_url_uses_environment(self, subject, config):
        config.set("host", "127.0.0.1")
        config.set("base_port", 5000)
        config.set("num_dynos_web", 1)
        assert subject() == "http://127.0.0.1:5000"

    def test_local_base_url_converts(self, subject, config):
        config.set("host", "0.0.0.0")
        config.set("base_port", 5000)
        config.set("num_dynos_web", 1)
        assert subject() == "http://localhost:5000"

    def test_remote_base_url_always_ssl(self, subject, config):
        config.set("host", "http://dlgr-bogus.herokuapp.com")
        config.set("base_port", 80)
        config.set("num_dynos_web", 1)
        assert subject() == "https://dlgr-bogus.herokuapp.com"

    @pytest.mark.xfail(
        reason="HOST aliasing removed to fix https://github.com/Dallinger/Dallinger/issues/2130"
    )
    def test_os_HOST_environ_used_as_host(self, subject, config):
        with mock.patch("os.environ", {"HOST": "dlgr-bogus-2.herokuapp.com"}):
            config.load_from_environment()
        config.set("base_port", 80)
        config.set("num_dynos_web", 1)
        assert subject() == "https://dlgr-bogus-2.herokuapp.com"

class TestIsolatedWebbrowser(object):
    def test_chrome_isolation(self):
        import webbrowser

        with mock.patch("dallinger.utils.is_command") as is_command:
            is_command.side_effect = lambda s: s == "google-chrome"
            isolated = utils._new_webbrowser_profile()

        assert isinstance(isolated, webbrowser.Chrome)

    def test_firefox_isolation(self):
        import webbrowser

        with mock.patch("dallinger.utils.is_command") as is_command:
            is_command.side_effect = lambda s: s == "firefox"
            isolated = utils._new_webbrowser_profile()

        assert isinstance(isolated, webbrowser.Mozilla)

    def test_fallback_isolation(self):
        import webbrowser

        with mock.patch.multiple(
            "dallinger.utils", is_command=mock.DEFAULT, sys=mock.DEFAULT
        ) as patches:
            patches["is_command"].return_value = False
            patches["sys"].platform = 'anything but "darwin"'
            isolated = utils._new_webbrowser_profile()
        assert isolated == webbrowser


text:
<?php
exec("gpio mode 2 out");
exec("gpio toggle 2");
echo (exec("gpio read 2"));
?>


text:
<?php

namespace Krystal\Paginate;

use RuntimeException;
use LogicException;
use Krystal\Paginate\Style\StyleInterface;

final class Paginator implements PaginatorInterface
{
    /* Defaults */
    const PARAM_PLACEHOLDER = '(:var)';
    const PARAM_QUERY_PARAM = 'page';

    /**
     * Optional pagination style adapter
     *
     * @var \Krystal\Paginate\Style\StyleInterface
     */
    private $style;

    /**
     * Total amount of records
     *
     * @var integer
     */
    private $totalAmount;

    /**
     * Per page count
     *
     * @var integer
     */
    private $itemsPerPage;

    /**
     * Permanent page's URL
     *
     * @var string
     */
    private $url;

    /**
     * Current URI string
     *
     * @var string
     */
    private $uri;

    /**
     * State initialization
     *
     * @param \Krystal\Paginate\Style\StyleInterface $style Optional style adapter
     * @param string $uri Current URI string for dynamic configuration
     * @return void
     */
    public function __construct(StyleInterface $style = null, $uri = null)
    {
        $this->style = $style;
        $this->uri = $uri;
    }

    /**
     * Adjusts URL from URI string to make entire pagination work
     *
     * @param string $uri Current URI string for dynamic configuration
     * @return string|boolean Depending on success
     */
    private static function tweakUrl($uri)
    {
        $parsed = parse_url($uri);

        // If could parse current URI, process the rest
        if (isset($parsed['path'])) {
            // 1. Parse query string
            if (isset($parsed['query'])) {
                parse_str($parsed['query'], $result);
                $query = $result;
            } else {
                $query = array();
            }

            // 2. Append page parameter to current query string
            $params = array_replace_recursive($query, array(self::PARAM_QUERY_PARAM => self::PARAM_PLACEHOLDER));

            // 3. Build current URI appending page parameter
            $url = $parsed['path'] . '?' . http_build_query($params);
            $url = str_replace(rawurlencode(self::PARAM_PLACEHOLDER), self::PARAM_PLACEHOLDER, $url);

            return $url;
        } else {
            // Failed to parse URI
            return false;
        }
    }

    /**
     * Tweaks the service before it can be used
     *
     * @param integer $totalAmount Total amount of records
     * @param integer $itemsPerPage Per page count
     * @param integer $page Current page
     * @return \Krystal\Paginate\Paginator
     */
    public function tweak($totalAmount, $itemsPerPage, $page)
    {
        $this->totalAmount = (int) $totalAmount;
        $this->itemsPerPage = (int) $itemsPerPage;
        $this->setCurrentPage($page);

        // Dynamic tweak by default
        if ($this->uri !== null) {
            $url = self::tweakUrl($this->uri);
            $this->setUrl($url);
        }

        return $this;
    }

    /**
     * Defines a permanent URL
     *
     * @param string $url
     * @return \Krystal\Paginate\Paginator
     */
    public function setUrl($url)
    {
        $this->url = $url;
        return $this;
    }

    /**
     * Returns permanent URL substituting a placeholder with current page number
     *
     * @param integer $page Current page number
     * @throws \RuntimeException If URL isn't defined
     * @throws \LogicException In case the URL string hasn't a placeholder
     * @return string
     */
    public function getUrl($page)
    {
        if (is_null($this->url)) {
            throw new RuntimeException('URL template must be defined');
        }

        if (strpos($this->url, self::PARAM_PLACEHOLDER) !== false) {
            return str_replace(self::PARAM_PLACEHOLDER, $page, $this->url);
        } else {
            // Without placeholder, no substitution is done, therefore pagination links won't work
            throw new LogicException('The URL string must contain at least one placeholder to make pagination links work');
        }
    }

    /**
     * Returns the first page i.e always 1
     *
     * @return integer
     */
    public function getFirstPage()
    {
        return 1;
    }

    /**
     * Returns the last page
     *
     * @return integer
     */
    public function getLastPage()
    {
        $pages = $this->getPageNumbers();
        return (int) array_pop($pages);
    }

    /**
     * Counts the offset
     *
     * @return integer
     */
    public function countOffset()
    {
        return ($this->getCurrentPage() - 1) * $this->getItemsPerPage();
    }

    /**
     * Returns a summary
     *
     * @param string $separator
     * @return string
     */
    public function getSummary($separator = '-')
    {
        if ($this->getTotalAmount() == 0) {
            return (string) 0;
        } else {
            return $this->getStart() . $separator . $this->getEnd();
        }
    }

    /**
     * Returns the start
     *
     * @return integer
     */
    public function getStart()
    {
        return $this->countOffset() + 1;
    }

    /**
     * Returns the end
     *
     * @return integer
     */
    public function getEnd()
    {
        return min($this->getTotalAmount(), $this->getStart() + ($this->getItemsPerPage() - 1));
    }

    /**
     * Checks whether its a current page
     *
     * @param integer $page
     * @return boolean
     */
    public function isCurrentPage($page)
    {
        return $this->getCurrentPage() == $page;
    }

    /**
     * Checks whether there's at least one page before doing pagination
     *
     * @return boolean
     */
    public function hasPages()
    {
        return $this->getPagesCount() > 1;
    }

    /**
     * Checks whether there's a  style adapter
     *
     * @return boolean
     */
    public function hasAdapter()
    {
        return $this->style instanceOf StyleInterface;
    }

    /**
     * Returns total page numbers
     * Style-adapter aware method
     *
     * @return array
     */
    public function getPageNumbers()
    {
        $pages = range(1, $this->getPagesCount());

        // And has an styling adapter
        if ($this->getPagesCount() > 10 && $this->hasAdapter()) {
            return $this->style->getPageNumbers($pages, $this->getCurrentPage());
        } else {
            return $pages;
        }
    }

    /**
     * Checks if next page number is available
     *
     * @return boolean
     */
    public function hasNextPage()
    {
        return $this->getNextPage() - $this->getCurrentPage() == 1;
    }

    /**
     * Checks if previous page number is available
     *
     * @return boolean
     */
    public function hasPreviousPage()
    {
        return $this->getCurrentPage() - $this->getPreviousPage() == 1;
    }

    /**
     * Returns next page number
     *
     * @return integer
     */
    public function getNextPage()
    {
        if ($this->getPagesCount() > $this->getCurrentPage()) {
            return $this->getCurrentPage() + 1;
        } else {
            return $this->getPagesCount();
        }
    }

    /**
     * Returns previous page number
     *
     * @return integer
     */
    public function getPreviousPage()
    {
        if ($this->getCurrentPage() > 1) {
            return $this->getCurrentPage() - 1;
        } else {
            return 1;
        }
    }

    /**
     * Defines current page
     *
     * @param integer|string $currentPage
     * @param boolean $fixRange Whether page range should be fixed if wrong one supplied
     * @return \Krystal\Paginate\Paginator
     */
    private function setCurrentPage($currentPage, $fixRange = true)
    {
        if ($fixRange === true) {
            if (!$this->pageInRange($currentPage)) {
                $currentPage = 1;
            }
        }

        $this->currentPage = (int) $currentPage;
        return $this;
    }

    /**
     * Count total amount of pages
     *
     * @return integer
     */
    private function getPagesCount()
    {
        if ($this->getItemsPerPage() != 0) {
            return (int) abs(ceil($this->getTotalAmount() / $this->getItemsPerPage()));
        } else {
            return 0;
        }
    }

    /**
     * Checks whether page is in range
     *
     * @param integer|string $page
     * @return boolean
     */
    private function pageInRange($page)
    {
        $page = (int) $page;
        return $this->getPagesCount() >= $page;
    }

    /**
     * Returns the URL of the next page
     *
     * @return string
     */
    public function getNextPageUrl()
    {
        return $this->getUrl($this->getNextPage());
    }

    /**
     * Return the URL of the previous page
     *
     * @return string
     */
    public function getPreviousPageUrl()
    {
        return $this->getUrl($this->getPreviousPage());
    }

    /**
     * Returns current page number
     *
     * @return integer
     */
    public function getCurrentPage()
    {
        return $this->currentPage;
    }

    /**
     * Returns defined per page count
     *
     * @return integer
     */
    public function getItemsPerPage()
    {
        return $this->itemsPerPage;
    }

    /**
     * Returns total amount of pages
     *
     * @return integer
     */
    public function getTotalAmount()
    {
        return $this->totalAmount;
    }

    /**
     * Returns current state as array representation
     *
     * @return array
     */
    public function toArray()
    {
        return array(
            'firstPage' => $this->getFirstPage(),
            'lastPage' => $this->getLastPage(),
            'offset' => $this->countOffset(),
            'summary' => $this->getSummary(),
            'hasPages' => $this->hasPages(),
            'hasAdapter' => $this->hasAdapter(),
            'hasNextPage' => $this->hasNextPage(),
            'hasPreviousPage' => $this->hasPreviousPage(),
            'nextPage' => $this->getNextPage(),
            'previousPage' => $this->getPreviousPage(),
            'nextPageUrl' => $this->getNextPageUrl(),
            'previousPageUrl' => $this->getPreviousPageUrl(),
            'currentPage' => $this->getCurrentPage(),
            'perPageCount' => $this->getItemsPerPage(),
            'total' => $this->getTotalAmount(),
            'pageNumbers' => $this->getPageNumbers()
        );
    }

    /**
     * Returns current state as JSON representation
     *
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArray());
    }
}


text:
package com.bwsw.sj.crud.rest.model.service

import com.bwsw.sj.common.si.model.service.ESService
import com.bwsw.sj.common.utils.{RestLiterals, ServiceLiterals}
import com.fasterxml.jackson.annotation.JsonProperty
import scaldi.Injector

class EsServiceApi(name: String,
                   val index: String,
                   provider: String,
                   description: Option[String] = Some(RestLiterals.defaultDescription),
                   @JsonProperty("type") serviceType: Option[String] = Some(ServiceLiterals.elasticsearchType),
                   creationDate: String)
  extends ServiceApi(serviceType.getOrElse(ServiceLiterals.elasticsearchType), name, provider, description, creationDate) {

  override def to()(implicit injector: Injector): ESService = {
    val modelService =
      new ESService(
        name = this.name,
        description = this.description.getOrElse(RestLiterals.defaultDescription),
        provider = this.provider,
        index = this.index,
        serviceType = this.serviceType.getOrElse(ServiceLiterals.elasticsearchType),
        creationDate = this.creationDate
      )

    modelService
  }
}


text:
package objx_test

import (
	"testing"

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

func TestSimpleExample(t *testing.T) {
	// build a map from a JSON object
	o := objx.MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`)

	// Map can be used as a straight map[string]interface{}
	assert.Equal(t, o["name"], "Mat")

	// Get an Value object
	v := o.Get("name")
	require.NotNil(t, v)

	// Test the contained value
	assert.False(t, v.IsInt())
	assert.False(t, v.IsBool())
	assert.True(t, v.IsStr())

	// Get the contained value
	assert.Equal(t, v.Str(), "Mat")

	// Get a default value if the contained value is not of the expected type or does not exist
	assert.Equal(t, 1, v.Int(1))

	// Get a value by using array notation
	assert.Equal(t, "indian", o.Get("foods[0]").Data())

	// Set a value by using array notation
	o.Set("foods[0]", "italian")
	assert.Equal(t, "italian", o.Get("foods[0]").Str())

	// Get a value by using dot notation
	assert.Equal(t, "hobbiton", o.Get("location.county").Str())
}


text:
using UnityEngine;

namespace Assets.Scripts
{
    public class Generator : MonoBehaviour
    {

        public GameObject Obstacle;
        public float RepeatTime = 5.5f;
        private static int score = 0;

        void Start () {
            InvokeRepeating("CreateObstacle", 1f, RepeatTime);
        }

        void OnGUI()
        {
            GUI.color = Color.black;
            GUILayout.Label(" Score: " + score.ToString());
        }

        // Update is called once per frame
        void CreateObstacle() {
            Instantiate(Obstacle);
            score++;
        }
    }
}


text:
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;

namespace WebServiceNamespace
{
    /// <summary>
    /// Summary description for WebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        public WebService()
        {

        }

        [WebMethod]
        public DateTime GetDateTime()
        {
            return DateTime.Now;
        }

        [WebMethod]
        public ComplexType GetComplexOne()
        {
            return ComplexType.GetOne();
        }

        [WebMethod]
        public List<ComplexType> GetComplexList()
        {
            return ComplexType.GetList();
        }
    }
}