text:
angular.module('ruthaAuth')
.controller('LoginController', function($scope, $log) {
    $log.info('Login controller');
});

redpajama_set_name: RedPajamaGithub


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/mainLayout"
    android:gravity="center">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <fr.bouyguestelecom.sample.SubtitleLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:id="@+id/subtitle_Layout"/>

    <LinearLayout
        android:layout_alignParentTop="@+id/videoView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/mainLinearLayout"
        android:layout_alignParentBottom="true" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btnPlayCanalPlusSD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayCanalPlusSD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayCanalPlusHD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayCanalPlusHD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayCanalCinemaSD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayCanalCinemaSD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayCanalCinemaHD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayCanalCinemaHD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayTF1HD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayTF1HD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayM6HD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayM6HD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayDorcelHD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayDorcelHD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>
            <Button
                android:id="@+id/btnPlayXXLHD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayXXLHD"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btnGetProfileRtp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetProfileRtp"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnPlayRtp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayRtp"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnPlayHls"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayHls"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnPlayVod"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayVod"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnPlayMedia"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayMedia"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnSeek"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnSeek"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnStop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnStop"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnMoveResize"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnMoveResize"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnResize"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnResize"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnMove"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnMove"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnPlayRtpAdult"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayRtpAdult"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnPlayRtpNoRights"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnPlayRtpNoRights"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnUnlockMorality"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnUnlockMorality"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnGetAvailableSubtitles"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetAvailableSubtitles"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnGetCurrentSubtitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetCurrentSubtitle"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnSetCurrentSubtitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnSetCurrentSubtitle"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnShowSubtitles"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnShowSubtitles"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btnGetSpeed"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetSpeed"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <!--<Button
                android:id="@+id/btnSetSpeed"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnSetSpeed"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>-->

            <Button
                android:id="@+id/btnGetCurrentPosition"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetCurrentPosition"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnGetDuration"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetDuration"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnGetUniverse"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetUniverse"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnSetUniverse"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnSetUniverse"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnGetPlaneSize"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetPanelSize"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btnGetState"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetState"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnGetAvailableLanguages"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetAvailableLanguages"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnGetCurrentLanguage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnGetCurrentLanguage"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

            <Button
                android:id="@+id/btnSetCurrentLanguage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btnSetCurrentLanguage"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/editPlayIp"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:hint="@string/editPlayIp" />

            <Button
                android:id="@+id/btnPlayIp"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/btnPlayIp"
                android:background="@drawable/item_selector"
                android:layout_margin="2dp"
                android:padding="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center" >

            <TextView
                android:id="@+id/txtInfo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="@string/txtInfo" />

            <TextView
                android:id="@+id/txtCallbackState"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="@string/txtCallbackState" />

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>


text:
import os
import socket
import logging
import commands

from consts import CHUNKSIZE, CUTOCS_READ, CSTOCU_READ_DATA, CSTOCU_READ_STATUS
from utils import uint64, pack, unpack

logger = logging.getLogger(__name__)

mfsdirs = []
def _scan():
    cmd = """ps -eo cmd| grep mfschunkserver | grep -v grep |
    head -1 | cut -d ' ' -f1 | xargs dirname | sed 's#sbin##g'"""
    mfs_prefix = commands.getoutput(cmd)
    mfs_cfg = '%s/etc/mfshdd.cfg' % mfs_prefix
    mfs_cfg_list = (mfs_cfg, '/etc/mfs/mfshdd.cfg',
    '/etc/mfshdd.cfg', '/usr/local/etc/mfshdd.cfg')
    for conf in mfs_cfg_list:
        if not os.path.exists(conf):
            continue
        f = open(conf)
        for line in f:
            if line.startswith('#') or line.startswith('*'):
                continue
            fields = line.split()
            if fields:
                path = fields[0]
                if os.path.exists(path):
                    mfsdirs.append(path)
        f.close()
_scan()

CHUNKHDRSIZE = 1024 * 5

def read_chunk_from_local(chunkid, version, size, offset=0):
    if offset + size > CHUNKSIZE:
        raise ValueError("size too large %s > %s" %
            (size, CHUNKSIZE-offset))

    from dpark.accumulator import LocalReadBytes
    name = '%02X/chunk_%016X_%08X.mfs' % (chunkid & 0xFF, chunkid, version)
    for d in mfsdirs:
        p = os.path.join(d, name)
        if os.path.exists(p):
            if os.path.getsize(p) < CHUNKHDRSIZE + offset + size:
                logger.error('%s is not completed: %d < %d', name,
                        os.path.getsize(p), CHUNKHDRSIZE + offset + size)
                return
                #raise ValueError("size too large")
            f = open(p)
            f.seek(CHUNKHDRSIZE + offset)
            while size > 0:
                to_read = min(size, 640*1024)
                data = f.read(to_read)
                if not data:
                    return
                LocalReadBytes.add(len(data))
                yield data
                size -= len(data)
            f.close()
            return
    else:
        logger.warning("%s was not found", name)

def read_chunk(host, port, chunkid, version, size, offset=0):
    if offset + size > CHUNKSIZE:
        raise ValueError("size too large %s > %s" %
            (size, CHUNKSIZE-offset))

    from dpark.accumulator import RemoteReadBytes

    conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn.settimeout(10)
    conn.connect((host, port))

    msg = pack(CUTOCS_READ, uint64(chunkid), version, offset, size)
    n = conn.send(msg)
    while n < len(msg):
        if not n:
            raise IOError("write failed")
        msg = msg[n:]
        n = conn.send(msg)

    def recv(n):
        d = conn.recv(n)
        while len(d) < n:
            nd = conn.recv(n-len(d))
            if not nd:
                raise IOError("not enough data")
            d += nd
        return d

    while size > 0:
        cmd, l = unpack("II", recv(8))

        if cmd == CSTOCU_READ_STATUS:
            if l != 9:
                raise Exception("readblock: READ_STATUS incorrect message size")
            cid, code = unpack("QB", recv(l))
            if cid != chunkid:
                raise Exception("readblock; READ_STATUS incorrect chunkid")
            conn.close()
            return

        elif cmd == CSTOCU_READ_DATA:
            if l < 20 :
                raise Exception("readblock; READ_DATA incorrect message size")
            cid, bid, boff, bsize, crc = unpack("QHHII", recv(20))
            if cid != chunkid:
                raise Exception("readblock; READ_STATUS incorrect chunkid")
            if l != 20 + bsize:
                raise Exception("readblock; READ_DATA incorrect message size ")
            if bsize == 0 : # FIXME
                raise Exception("readblock; empty block")
                #yield ""
                #continue
            if bid != offset >> 16:
                raise Exception("readblock; READ_DATA incorrect block number")
            if boff != offset & 0xFFFF:
                raise Exception("readblock; READ_DATA incorrect block offset")
            breq = 65536 - boff
            if size < breq:
                breq = size
            if bsize != breq:
                raise Exception("readblock; READ_DATA incorrect block size")

            while breq > 0:
                data = conn.recv(breq)
                if not data:
                    #print chunkid, version, offset, size, bsize, breq
                    raise IOError("unexpected ending: need %d" % breq)
                RemoteReadBytes.add(len(data))
                yield data
                breq -= len(data)

            offset += bsize
            size -= bsize
        else:
            raise Exception("readblock; unknown message: %s" % cmd)
    conn.close()

def test():
    d = list(read_chunk('192.168.11.3', 9422, 6544760, 1, 6, 0))
    print len(d), sum(len(s) for s in d)
    d = list(read_chunk('192.168.11.3', 9422, 6544936, 1, 46039893, 0))
    print len(d), sum(len(s) for s in d)

if __name__ == '__main__':
    test()


text:
(function () {

    angular.module('vorbs.services')
        .factory('BookingsService', BookingsService);

    BookingsService.$inject = ['$resource', 'dateFilter'];

    function BookingsService($resource, dateFilter) {

        function formatDate(dateTime) {
            return dateFilter(dateTime, 'dd/MM/yyyy');
        }

        function formatTime(dateTime) {
            return dateFilter(dateTime, 'H:mm');
        }

        function formatBooking(booking) {

            booking.start = {
                date: formatDate(booking.startDate),
                time: formatTime(booking.startDate)
            };

            booking.end = {
                date: formatDate(booking.endDate),
                time: formatTime(booking.endDate)
            };

            return booking;
        }

        return $resource('/api/bookings', {}, {
            search: {
                method: 'GET',
                isArray: true,
                interceptor: {
                    response: function (resp) {

                        var data = resp.data;

                        if (data) {
                            angular.forEach(data, function (value) {
                                value = formatBooking(value);
                            });
                        }

                        return data;
                    }
                },
                url: '/api/bookings/search'
            },
            getByID: {
                method: 'GET',
                params: {
                    bookingId: '@bookingId'
                },
                interceptor: {
                    response: function (resp) {
                        var data = resp.data;
                        if (data) data = formatBooking(data);
                        return data;
                    }
                },
                url: '/api/bookings/:bookingId'
            },
            getByPeriod: {
                method: 'GET',
                isArray: true,
                params: {
                    startDate: '@startDate',
                    period: '@period'
                },
                interceptor: {
                    response: function (resp) {

                        var data = resp.data;

                        if (data) {
                            angular.forEach(data, function (value) {
                                value = formatBooking(value);
                            });
                        }

                        return data;
                    }
                },
                url: '/api/bookings/:startDate/:period'
            },
            update: {
                method: 'PUT',
                params: {
                    existingId: '@existingId',
                    recurrence: '@recurrence'
                },
                url: '/api/bookings/:existingId/:recurrence'
            },
            remove: {
                method: 'DELETE',
                params: {
                    bookingId: '@bookingId',
                    recurrence: '@recurrence'
                },
                url: '/api/bookings/:bookingId/:recurrence'
            }
        });
    }

})();


text:
/* @flow */

import { ZalgoPromise } from 'zalgo-promise/src';
import { getDomain } from 'cross-domain-utils/src';

import { config } from '../config';

export function isPayPalDomain() : boolean {
    return Boolean(`${ window.location.protocol }//${ window.location.host }`.match(config.paypal_domain_regex)) || window.mockDomain === 'mock://www.paypal.com';
}

// eslint-disable-next-line flowtype/no-weak-types
export function memoize<R>(method : (...args : Array<any>) => R, options : { time? : number } = {}) : ((...args : Array<any>) => R) {

    let cache : { [key : string] : R } = {};

    // eslint-disable-next-line no-unused-vars, flowtype/no-weak-types
    return function memoizedFunction(...args : Array<any>) : R {

        let key : string;

        try {
            key = JSON.stringify(arguments);
        } catch (err) {
            throw new Error(`Arguments not serializable -- can not be used to memoize`);
        }

        if (cache.hasOwnProperty(key)) {
            return cache[key];
        }

        cache[key] = method.apply(this, arguments);

        if (options.time) {
            setTimeout(() => {
                delete cache[key];
            }, options.time);
        }

        return cache[key];
    };
}

// eslint-disable-next-line no-unused-vars
export function noop(...args : Array<mixed>) {
    // pass
}

export function once(method : Function) : Function {
    let called = false;

    return function onceFunction() : mixed {
        if (!called) {
            called = true;
            return method.apply(this, arguments);
        }
    };
}

export function uniqueID() : string {

    let chars = '0123456789abcdef';

    return 'xxxxxxxxxx'.replace(/./g, () => {
        return chars.charAt(Math.floor(Math.random() * chars.length));
    });
}

export function hashStr(str : string) : number {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);
    }
    return Math.floor(Math.pow(Math.sqrt(hash), 5));
}

export function strHashStr(str : string) : string {
    let hash = '';

    for (let i = 0; i < str.length; i++) {
        let total = (str[i].charCodeAt(0) * i);

        if (str[i + 1]) {
            total += (str[i + 1].charCodeAt(0) * (i - 1));
        }

        hash += String.fromCharCode(97 + (Math.abs(total) % 26));
    }

    return hash;
}

export function match(str : string, pattern : RegExp) : ?string {
    let regmatch = str.match(pattern);
    if (regmatch) {
        return regmatch[1];
    }
}

export function safeJSON(item : mixed) : string {
    return JSON.stringify(item, (key, val) => {

        if (typeof val === 'function') {
            return `<${ typeof val }>`;
        }

        try {
            JSON.stringify(val);
        } catch (err) {
            return `<${ typeof val }>`;
        }

        return val;
    });
}

type Listener = {
    listen : (method : Function) => {
        cancel : () => void
    },
    once : (method : Function) => void,
    trigger : (...args : Array<mixed>) => void
};

export function eventEmitter() : Listener {

    let listeners = [];

    return {
        listen(method : Function) : { cancel : () => void } {
            listeners.push(method);

            return {
                cancel() {
                    listeners.splice(listeners.indexOf(method), 1);
                }
            };
        },

        once(method : Function) {
            let listener = this.listen(function onceListener() {
                method.apply(null, arguments);
                listener.cancel();
            });
        },

        trigger(...args : Array<mixed>) {
            for (let listener of listeners) {
                listener(...args);
            }
        }
    };
}

export function onKey(obj : Object, key : string, callback : Function) {

    if (!obj) {
        return;
    }

    let value = obj[key];

    if (value) {
        value = callback(value) || value;
    }

    try {

        delete obj[key];

        Object.defineProperty(obj, key, {

            configurable: true,

            set(item) {
                value = item;

                if (value) {
                    value = callback(value) || value;
                }
            },

            get() : mixed {
                return value;
            }
        });

    } catch (err) {
        // pass
    }
}

export function awaitKey<T: mixed>(obj : Object, key : string) : ZalgoPromise<T> {
    return new ZalgoPromise(resolve => {
        return onKey(obj, key, resolve);
    });
}

export function stringifyError(err : mixed) : string {

    if (!err) {
        return `<unknown error: ${ Object.prototype.toString.call(err) }>`;
    }

    if (err instanceof Error) {
        return err.stack;
    }

    if (typeof err.toString === 'function') {
        return err.toString();
    }

    return Object.prototype.toString.call(err);
}

export function stringifyErrorMessage(err : mixed) : string {

    let defaultMessage = `<unknown error: ${ Object.prototype.toString.call(err) }>`;

    if (!err) {
        return defaultMessage;
    }

    if (err instanceof Error) {
        return err.message || defaultMessage;
    }

    if (typeof err.message === 'string') {
        return err.message || defaultMessage;
    }

    return defaultMessage;
}

export let isLocalStorageEnabled = memoize(() : boolean => {
    try {
        if (window.localStorage) {
            let value = Math.random().toString();
            window.localStorage.setItem('__test__localStorage__', value);
            let result = window.localStorage.getItem('__test__localStorage__');
            window.localStorage.removeItem('__test__localStorage__');
            if (value === result) {
                return true;
            }
        }
    } catch (err) {
        // pass
    }
    return false;
});

export function getDomainSetting<T : mixed>(name : string, def : ?T) : ?T {

    let domain = window.xchild
        ? window.xchild.getParentDomain()
        : getDomain();

    if (config.domain_settings) {
        let hash = strHashStr(domain);
        let settings = config.domain_settings[hash];

        if (settings) {
            return settings[name];
        }
    }

    return def;
}

export function patchMethod(obj : Object, name : string, handler : Function) {
    let original = obj[name];

    obj[name] = function patchedMethod() : mixed {
        return handler({
            context:      this,
            args:         arguments,
            original,
            callOriginal: () => original.apply(this, arguments)
        });
    };
}

export function extend<T : Object | Function>(obj : T, source : Object) : T {
    if (!source) {
        return obj;
    }

    for (let key in source) {
        if (source.hasOwnProperty(key)) {
            obj[key] = source[key];
        }
    }

    return obj;
}

export function hasValue<T : mixed>(obj : { [string] : T }, value : T) : boolean {
    for (let key in obj) {
        if (obj.hasOwnProperty(key) && obj[key] === value) {
            return true;
        }
    }
    return false;
}

export function contains<T>(arr : Array<T>, value : T) : boolean {
    return arr.indexOf(value) !== -1;
}

export function sortBy<T>(arr : Array<T>, order : Array<T>) : Array<T> {
    return arr.sort((a : T, b : T) => {
        return order.indexOf(a) - order.indexOf(b);
    });
}

export function reverseMap(obj : { [string] : string }) : { [string] : string } {
    let result = {};
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            result[obj[key]] = key;
        }
    }
    return result;
}

export function arrayRemove<T>(arr : Array<T>, item : T) {
    arr.splice(arr.indexOf(item), 1);
}


text:
package net.stuxcrystal.simpledev.commands.commands.contrib.annotations.autoparse;

import java.lang.annotation.*;

/**
 * Tells the command how to parse the argument.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Argument {

    /**
     * The value index.
     * @return The value index.
     */
    int value();

    /**
     * The stop index. (List only)
     * @return The maximal index of the argument.
     */
    int stop() default Integer.MAX_VALUE;

    /**
     * The step for the argument slice. (List only)
     * @return The argument slice.
     */
    int step() default 1;

    /**
     * Contains the default value. (Non-Array only)
     * @return The default value.
     */
    String defaultValue() default "§";

    /**
     * The type of the annotation (used when the type of the argument cannot be determined from the parameter type)
     * @return The type of the annotation.
     */
    Class<?> type() default void.class;
}


text:
require_relative "../../lib/signup/signup_processor"

describe SignupProcessor do
  subject do
    SignupProcessor.new(organization, contact_person, billing, purchase)
  end

  let(:organization_name) { "Mr Test" }

  let(:organization_type) {}

  let(:size) { "10-50" }

  let(:organization) do
    {
      "name"           => organization_name,
      "company_number" => "123456",
      "size"           => size,
      "sector"         => "Education",
      "origin"         => "odi-leeds",
      "type"           => organization_type
    }
  end

  let(:contact_person) do
    {
      "name"                           => "Contact person",
      "email"                          => "contact@person.com",
      "twitter"                        => "@twitter",
      "dob"                            => "DOB",
      "university_email"               => "uni-email@example.com",
      "university_address_country"     => "Uni address country",
      "university_country"             => "Uni country",
      "university_name"                => "Uni name",
      "university_name_other"          => "Uni name other",
      "university_course_name"         => "Uni course name",
      "university_qualification"       => "Uni qualification",
      "university_qualification_other" => "Uni qualification other",
      "university_course_start_date"   => "Uni course start date",
      "university_course_end_date"     => "Uni course end date"
    }
  end

  let(:billing) do
    {
      "name" => "Billing person",
      "email" => "test@example.com",
      "telephone" => "01234 567890",
      "address" => {
        "street_address"   => "1 Some Street",
        "address_locality" => "Some town",
        "address_region"   => "Some region",
        "address_country"  => "Some country",
        "postal_code"      => "Some postcode"
      },
      "coupon" => "COUPON"
    }
  end

  let(:category) { "individual" }

  let(:purchase) do
    {
      "offer_category"           => category,
      "membership_id"            => 123456,
      "payment_method"           => "credit_card",
      "payment_freq"             => "annual",
      "payment_ref"              => "012345",
      "discount"                 => 50.0,
      "purchase_order_reference" => "PO1234"
    }
  end

  describe "#perform" do
    let(:expected_organization_details_name) { "Mr Test" }

    let(:expected_organization_details) do
      {
        "name"            => expected_organization_details_name,
        "contact_name"    => "Contact person",
        "company_number"  => "123456",
        "email"           => "test@example.com"
      }
    end

    let(:expected_membership_details) do
      {
        "product_name"                   => "individual",
        "supporter_level"                => "Individual",
        "id"                             => "123456",
        "join_date"                      => Date.today.to_s, # Not ideal, but no times so should ok?
        "contact_email"                  => "contact@person.com",
        "twitter"                        => "@twitter",
        "size"                           => "10-50",
        "sector"                         => "Education",
        "origin"                         => "odi-leeds",
        "coupon"                         => "COUPON",
        "dob"                            => "DOB",
        "university_email"               => "uni-email@example.com",
        "university_address_country"     => "Uni address country",
        "university_country"             => "Uni country",
        "university_name"                => "Uni name",
        "university_name_other"          => "Uni name other",
        "university_course_name"         => "Uni course name",
        "university_qualification"       => "Uni qualification",
        "university_qualification_other" => "Uni qualification other",
        "university_course_start_date"   => "Uni course start date",
        "university_course_end_date"     => "Uni course end date"
      }
    end

    let(:expected_invoice_to_name) { "Mr Test" }

    let(:expected_invoice_to) do
      {
        "name" => expected_invoice_to_name,
        "contact_point" => {
          "name"      => "Billing person",
          "email"     => "test@example.com",
          "telephone" => "01234 567890"
        },
        "address" => {
          "street_address"   => "1 Some Street",
          "address_locality" => "Some town",
          "address_region"   => "Some region",
          "address_country"  => "Some country",
          "postal_code"      => "Some postcode"
        }
      }
    end

    let(:expected_invoice_line_item_description) do
      "ODI Individual supporter (123456) [Individual] (annual card payment)"
    end

    let(:expected_invoice_details) do
      {
        "payment_method" => "credit_card",
        "payment_ref" => "012345",
        "line_items" => [
          {
            "quantity"      => 1,
            "base_price"    => 90,
            "discount_rate" => 50.0,
            "description"   => expected_invoice_line_item_description
          }
        ],
        "repeat"                   => "annual",
        "purchase_order_reference" => "PO1234",
        "sector"                   => "Education",
        "line_amount_types"        => "Inclusive"
      }
    end

    it "should save the signup details to the CRM" do
      expect(SendSignupToCapsule).to receive(:perform).with(
        expected_organization_details, expected_membership_details
      ).once

      expect(Resque).to receive(:enqueue).with(
        Invoicer, expected_invoice_to, expected_invoice_details
      ).once

      subject.perform
    end

    context "organization name is empty" do
      let(:organization_name) { nil }

      let(:expected_organization_details_name) { "Contact person" }
      let(:expected_invoice_to_name) { "Contact person" }

      it "should save the signup details to the CRM" do
        expect(SendSignupToCapsule).to receive(:perform).with(
          expected_organization_details, expected_membership_details
        ).once

        expect(Resque).to receive(:enqueue).with(
          Invoicer, expected_invoice_to, expected_invoice_details
        ).once

        subject.perform
      end
    end

    context "organization type is empty" do
      let(:organization_type) { "non_commercial" }

      let(:expected_invoice_line_item_description) do
        "ODI Individual supporter (123456) [Non Commercial] (annual card payment)"
      end

      it "should save the signup details to the CRM" do
        expect(SendSignupToCapsule).to receive(:perform).with(
          expected_organization_details, expected_membership_details
        ).once

        expect(Resque).to receive(:enqueue).with(
          Invoicer, expected_invoice_to, expected_invoice_details
        ).once

        subject.perform
      end
    end

    context "individual signing up with flexible pricing" do
      let(:category) { 'individual' }

      let(:expected_invoice_line_item_description) do
        "ODI Individual supporter (123456) [Individual] (annual card payment)"
      end

      let(:purchase) do
        {
          "offer_category"           => category,
          "membership_id"            => 123456,
          "payment_method"           => "credit_card",
          "payment_freq"             => "annual",
          "payment_ref"              => "012345",
          "discount"                 => 0,
          "purchase_order_reference" => "PO1234",
          "amount_paid"              => 5
        }
      end

      let(:expected_invoice_details) do
        {
          "payment_method" => "credit_card",
          "payment_ref" => "012345",
          "line_items" => [
            {
              "quantity"      => 1,
              "base_price"    => 5,
              "discount_rate" => 0,
              "description"   => expected_invoice_line_item_description
            }
          ],
          "repeat"                   => "annual",
          "purchase_order_reference" => "PO1234",
          "sector"                   => "Education",
          "line_amount_types"        => "Inclusive"
        }
      end

      it "should save the signup details to the CRM" do
        expect(SendSignupToCapsule).to receive(:perform).with(
          expected_organization_details, expected_membership_details
        ).once

        expect(Resque).to receive(:enqueue).with(
          Invoicer, expected_invoice_to, expected_invoice_details
        ).once

        subject.perform
      end
    end
  end

  describe "#membership_type" do
    let(:size) { }
    let(:type) { }
    let(:category) { }

    context "individual" do
      let(:category) { "individual" }

      it "returns the details for individual supporters" do
        expect(subject.membership_type).to eq({
          price:       90,
          description: "Individual supporter",
          type:        "Individual"
        })
      end

      it "tells Xero to raise an invoice inclusive of VAT" do
        expect(subject.line_amount_types).to eq('Inclusive')
      end
    end

    context "corporate supporter" do
      let(:category) { "corporate" }

      it "returns the details for corporate supporters" do
        expect(subject.membership_type).to eq({
          price:       2200,
          description: "Corporate Supporter",
          type:        "Corporate supporter"
        })
      end

      it "tells Xero to raise an invoice inclusive of VAT" do
        expect(subject.line_amount_types).to eq('Exclusive')
      end
    end

    context "non-commercial supporter" do
      let(:organization_type) { "non_commercial" }

      it "returns the details for supporters" do
        expect(subject.membership_type).to eq({
          price:       720,
          description: "Supporter",
          type:        "Supporter"
        })
      end
    end

    context "supporter with valid organisation size" do
      let(:size) { "10-50" }

      it "returns the details for supporters" do
        expect(subject.membership_type).to eq({
          price:       720,
          description: "Supporter",
          type:        "Supporter"
        })
      end
    end
  end

  describe "#invoice_description" do
    let(:membership_id) { "12345" }
    let(:description) { "Individual supporter" }
    let(:type) { "individual" }
    let(:frequency) { "annual" }
    let(:method) { "credit_card" }

    it "returns the correct description" do
      expect(subject.invoice_description(membership_id, description, type, method, frequency)).to eq(
        "ODI Individual supporter (12345) [Individual] (annual card payment)"
      )
    end
  end

  describe "#format_payment_method" do
    context "payment method is credit card" do
      let(:payment_method) { "credit_card" }

      it "returns 'card'" do
        expect(subject.format_payment_method(payment_method)).to eq("card")
      end
    end

    context "payment method is direct debit" do
      let(:payment_method) { "direct_debit" }

      it "returns 'direct_debit'" do
        expect(subject.format_payment_method(payment_method)).to eq("dd")
      end
    end

    context "payment method is something else" do
      let(:payment_method) { "invoice" }

      it "returns what was passed in" do
        expect(subject.format_payment_method(payment_method)).to eq("invoice")
      end
    end
  end
end


text:
.. _int: https://docs.python.org/2/library/stdtypes.html

.. _str: https://docs.python.org/2/library/stdtypes.html

.. _bool: https://docs.python.org/2/library/stdtypes.html

.. _vmodl.DynamicData: ../../../vmodl/DynamicData.rst

vim.host.AutoStartManager.SystemDefaults
========================================
  Defines the system default auto-start/auto-stop values.
:extends: vmodl.DynamicData_

Attributes:
    enabled (`bool`_, optional):

       Indicates whether or not auto-start manager is enabled.
    startDelay (`int`_, optional):

       System-default autoStart delay in seconds. The default is 120 seconds.
    stopDelay (`int`_, optional):

       System-default autoStop delay in seconds. The default is 120 seconds.
    waitForHeartbeat (`bool`_, optional):

       System-default waitForHeartbeat setting.
    stopAction (`str`_, optional):

       System-default power-off action. Used if the stopAction string in the AutoPowerInfo object for a particular machine is set to systemDefault. If stopAction and startAction for a virtual machine are both set to none, that virtual machine is removed from the AutoStart sequence.


text:
<?php
use Oasis\Mlib\Utils\Exceptions\InvalidDataTypeException;
use Oasis\Mlib\Utils\Validators\BooleanValidator;

/**
 * Created by PhpStorm.
 * User: minhao
 * Date: 2016-09-02
 * Time: 15:59
 */
class BooleanValidatorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getInvalidInputInStrictMode
     *
     * @param $target
     */
    public function testStrictModeInvalidInput($target)
    {
        $validator = new BooleanValidator(true);

        $this->expectException(InvalidDataTypeException::class);
        $this->assertTrue(is_bool($validator->validate($target)));
    }

    /**
     * @dataProvider getValidInputInStrictMode
     *
     * @param $target
     */
    public function testStrictModeValid($target)
    {
        $validator = new BooleanValidator(true);

        $this->assertTrue(is_bool($validator->validate($target)));
    }

    /**
     * @dataProvider getInvalidInputInNonStrictMode
     *
     * @param $target
     */
    public function testNonStrictModeInvalidInput($target)
    {
        $validator = new BooleanValidator(false);

        $this->expectException(InvalidDataTypeException::class);
        $this->assertTrue(is_bool($validator->validate($target)));
    }

    /**
     * @dataProvider getValidInputInNonStrictMode
     *
     * @param $target
     */
    public function testNonStrictModeValid($target)
    {
        $validator = new BooleanValidator(false);

        $this->assertTrue(is_bool($validator->validate($target)));
    }

    public function getInvalidInputInStrictMode()
    {
        return [
            [''],
            ['on'],
            ['1'],
            ['0.0'],
            [1],
            [0],
            [1.0],
            [0.0],
            [null],
            [new stdClass()],
            [[]],
            [[123]],
        ];
    }

    public function getInvalidInputInNonStrictMode()
    {
        return [
            ['1.0'],
            ['0.0'],
            [new stdClass()],
            [[]],
            [[123]],
            [null],
        ];
    }

    public function getValidInputInNonStrictMode()
    {
        return [
            [true],
            [false],
            ['on'],
            ['On'],
            ['ON'],
            ['off'],
            ['yes'],
            ['no'],
            ['true'],
            ['false'],
            [''],
            [1],
            [0],
            [1.0],
            [0.0],
        ];
    }

    public function getValidInputInStrictMode()
    {
        return [
            [true],
            [false],
        ];
    }
}


text:
package apple.corefoundation;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.dispatch.*;
import apple.foundation.*;

/*<javadoc>*/
/*</javadoc>*/
@Mapping("CFBundleRef") @Library("CoreFoundation/CoreFoundation.h")
public class CFBundle
    extends CFType
     {

    protected CFBundle() {}

    @GlobalFunction("CFBundleGetMainBundle")
    public static native CFBundle getMainBundle();
    @GlobalFunction("CFBundleGetBundleWithIdentifier")
    public static native CFBundle getBundleWithIdentifier(CFString bundleID);
    @GlobalFunction("CFBundleGetAllBundles")
    public static native CFArray getAllBundles();
    @GlobalFunction("CFBundleGetTypeID")
    public static native @MachineSizedUInt long getClassTypeID();
    @GlobalFunction("CFBundleCreate")
    public static native CFBundle create(CFAllocator allocator, CFURL bundleURL);
    @GlobalFunction("CFBundleCreateBundlesFromDirectory")
    public static native CFArray createBundlesFromDirectory(CFAllocator allocator, CFURL directoryURL, CFString bundleType);
    @GlobalFunction("CFBundleCopyBundleURL")
    public static native CFURL copyBundleURL(CFBundle bundle);
    @GlobalFunction("CFBundleGetValueForInfoDictionaryKey")
    public static native CFType getValueForInfoDictionaryKey(CFBundle bundle, CFString key);
    @GlobalFunction("CFBundleGetInfoDictionary")
    public static native CFDictionary getInfoDictionary(CFBundle bundle);
    @GlobalFunction("CFBundleGetLocalInfoDictionary")
    public static native CFDictionary getLocalInfoDictionary(CFBundle bundle);
    @GlobalFunction("CFBundleGetPackageInfo")
    public static native void getPackageInfo(CFBundle bundle, Todo packageType, Todo packageCreator);
    @GlobalFunction("CFBundleGetIdentifier")
    public static native CFString getIdentifier(CFBundle bundle);
    @GlobalFunction("CFBundleGetVersionNumber")
    public static native int getVersionNumber(CFBundle bundle);
    @GlobalFunction("CFBundleGetDevelopmentRegion")
    public static native CFString getDevelopmentRegion(CFBundle bundle);
    @GlobalFunction("CFBundleCopySupportFilesDirectoryURL")
    public static native CFURL copySupportFilesDirectoryURL(CFBundle bundle);
    @GlobalFunction("CFBundleCopyResourcesDirectoryURL")
    public static native CFURL copyResourcesDirectoryURL(CFBundle bundle);
    @GlobalFunction("CFBundleCopyPrivateFrameworksURL")
    public static native CFURL copyPrivateFrameworksURL(CFBundle bundle);
    @GlobalFunction("CFBundleCopySharedFrameworksURL")
    public static native CFURL copySharedFrameworksURL(CFBundle bundle);
    @GlobalFunction("CFBundleCopySharedSupportURL")
    public static native CFURL copySharedSupportURL(CFBundle bundle);
    @GlobalFunction("CFBundleCopyBuiltInPlugInsURL")
    public static native CFURL copyBuiltInPlugInsURL(CFBundle bundle);
    @GlobalFunction("CFBundleCopyInfoDictionaryInDirectory")
    public static native CFDictionary copyInfoDictionaryInDirectory(CFURL bundleURL);
    @GlobalFunction("CFBundleGetPackageInfoInDirectory")
    public static native boolean getPackageInfoInDirectory(CFURL url, Todo packageType, Todo packageCreator);
    @GlobalFunction("CFBundleCopyResourceURL")
    public static native CFURL copyResourceURL(CFBundle bundle, CFString resourceName, CFString resourceType, CFString subDirName);
    @GlobalFunction("CFBundleCopyResourceURLsOfType")
    public static native CFArray copyResourceURLsOfType(CFBundle bundle, CFString resourceType, CFString subDirName);
    @GlobalFunction("CFBundleCopyLocalizedString")
    public static native CFString copyLocalizedString(CFBundle bundle, CFString key, CFString value, CFString tableName);
    @GlobalFunction("CFBundleCopyResourceURLInDirectory")
    public static native CFURL copyResourceURLInDirectory(CFURL bundleURL, CFString resourceName, CFString resourceType, CFString subDirName);
    @GlobalFunction("CFBundleCopyResourceURLsOfTypeInDirectory")
    public static native CFArray copyResourceURLsOfTypeInDirectory(CFURL bundleURL, CFString resourceType, CFString subDirName);
    @GlobalFunction("CFBundleCopyBundleLocalizations")
    public static native CFArray copyBundleLocalizations(CFBundle bundle);
    @GlobalFunction("CFBundleCopyPreferredLocalizationsFromArray")
    public static native CFArray copyPreferredLocalizationsFromArray(CFArray locArray);
    @GlobalFunction("CFBundleCopyLocalizationsForPreferences")
    public static native CFArray copyLocalizationsForPreferences(CFArray locArray, CFArray prefArray);
    @GlobalFunction("CFBundleCopyResourceURLForLocalization")
    public static native CFURL copyResourceURLForLocalization(CFBundle bundle, CFString resourceName, CFString resourceType, CFString subDirName, CFString localizationName);
    @GlobalFunction("CFBundleCopyResourceURLsOfTypeForLocalization")
    public static native CFArray copyResourceURLsOfTypeForLocalization(CFBundle bundle, CFString resourceType, CFString subDirName, CFString localizationName);
    @GlobalFunction("CFBundleCopyInfoDictionaryForURL")
    public static native CFDictionary copyInfoDictionaryForURL(CFURL url);
    @GlobalFunction("CFBundleCopyLocalizationsForURL")
    public static native CFArray copyLocalizationsForURL(CFURL url);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFBundleCopyExecutableArchitecturesForURL")
    public static native CFArray copyExecutableArchitecturesForURL(CFURL url);
    @GlobalFunction("CFBundleCopyExecutableURL")
    public static native CFURL copyExecutableURL(CFBundle bundle);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFBundleCopyExecutableArchitectures")
    public static native CFArray copyExecutableArchitectures(CFBundle bundle);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFBundlePreflightExecutable")
    public static native boolean preflightExecutable(CFBundle bundle, Todo error);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFBundleLoadExecutableAndReturnError")
    public static native boolean loadExecutableAndReturnError(CFBundle bundle, Todo error);
    @GlobalFunction("CFBundleLoadExecutable")
    public static native boolean loadExecutable(CFBundle bundle);
    @GlobalFunction("CFBundleIsExecutableLoaded")
    public static native boolean isExecutableLoaded(CFBundle bundle);
    @GlobalFunction("CFBundleUnloadExecutable")
    public static native void unloadExecutable(CFBundle bundle);
    @GlobalFunction("CFBundleGetFunctionPointerForName")
    public static native Todo getFunctionPointerForName(CFBundle bundle, CFString functionName);
    @GlobalFunction("CFBundleGetFunctionPointersForNames")
    public static native void getFunctionPointersForNames(CFBundle bundle, CFArray functionNames, Todo ftbl);
    @GlobalFunction("CFBundleGetDataPointerForName")
    public static native Todo getDataPointerForName(CFBundle bundle, CFString symbolName);
    @GlobalFunction("CFBundleGetDataPointersForNames")
    public static native void getDataPointersForNames(CFBundle bundle, CFArray symbolNames, Todo stbl);
    @GlobalFunction("CFBundleCopyAuxiliaryExecutableURL")
    public static native CFURL copyAuxiliaryExecutableURL(CFBundle bundle, CFString executableName);
    @GlobalFunction("CFBundleGetPlugIn")
    public static native CFPlugIn getPlugIn(CFBundle bundle);
    @GlobalFunction("CFBundleOpenBundleResourceMap")
    public static native short openBundleResourceMap(CFBundle bundle);
    @GlobalFunction("CFBundleOpenBundleResourceFiles")
    public static native int openBundleResourceFiles(CFBundle bundle, Todo refNum, Todo localizedRefNum);
    @GlobalFunction("CFBundleCloseBundleResourceMap")
    public static native void closeBundleResourceMap(CFBundle bundle, short refNum);

}


text:
const fs = require('fs');
const path = require('path');

const copy = (from, to) => {
  let rs = null;
  let ws = null;

  try {
    rs = fs.createReadStream(from);
  } catch (err) {
    console.error(err);
    return;
  }

  try {
    ws = fs.createWriteStream(to);
  } catch (err) {
    console.error(err);
    return;
  }

  return rs.pipe(ws);
};

module.exports = copy;


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [0.6.5] -

### Added
- Added expiration time to request logs

### Changed
- Changed admin filters on list pages to use marble form. Added deprecation notice for older filters

### Fixed
- Fixed problem with admin sidebar when collapsed

## [0.6.4] -
### Changed
- Upgraded all task to the correct format

### Removed
- Remove storybooks

## [0.6.3] -
### Added
- Added task as Queue and as Background job
- Added Marble Form component, review docs [here](https://www.notion.so/marbleform/Marble-form-06ab3c3054644dacb754ab9164d594df)

## [0.6.2] -

### Added
- Added form builder on developer tools

### Changed
- Improve csv exports using `json2csv` with loader and optional filename
- Migrate all forms to use Marble Form

### Fixed
- Fix list formatters on users, groups, roles and organizations
- Reset password and invite users now use User tokens

## [0.6.1] - 2018-05-06

### Added
- Added seed data task
- Improve formatter on base table columns to allow `user.name` as property
- Added title change on header on PageComponent enter
- Added title support from env vars on server and react
- Query params to make filter functionality easier on list routers
- Added csv exports to ListPageComponents when `exportFormatter` function is present
- Added breadcrumbs component to lib
- Added breadcrumbs functionality to PageComponent
- Added pathname to request logs

### Changed
- Updated Role, Organization and Group list pages to use ListPageComponent
- Updated Role, Organization and Group detials page to use PageComponent
- Improve request logs page with more filters and reload button

### Fixed
- Mongoose models need `usePushEach: true` on all models with array attributes to prevent `Unknown modifier: $pushAll` error
- Fix table totals reduce function

## [0.6.0] - 2018-03-19
### Added
- Page component
- List page component with custom headers and support for selectable

### Changed
- Change name on branched-paginadedTable to branched-paginaded-table
- Changed user details, user list and user deleted list to use Page component and List page component
- Added selectable prop to branched-paginaded-table with onSelectChange to listen for changes

### Fixed
- Fix bug on page change within the same page component. Didn't do a reload.


text:
import numpy as np

class EpsilonAgent:
	"""
	Decorator Agent which implements an epsilon-greedy policy.  Uses a second agent to produce non-random actions
	"""

	def __init__(self, agent, counter, initial_exploration=1.0, final_exploration=0.1, initial_frame=0, final_frame=1000000):
		"""
		"""

		self.epsilon = initial_exploration
		self.eps_init = initial_exploration
		self.eps_final = final_exploration

		self.counter = counter
		self.initial_frame = initial_frame
		self.final_frame = final_frame

		self.base_agent = agent
		self.num_actions = agent.num_actions

	def start_episode(self):
		"""
		"""

		self.base_agent.start_episode()

	def observe(self, state):
		"""
		Receive an observation
		"""

		self.base_agent.observe(state)

	def act(self):
		"""
		"""

		# The base agent may require acting for internal purposes, so allow the agent ot act
		action, Q = self.base_agent.act()

		# Determine if epsilon is the initial or final value, or some transition value inbetween
		if self.counter.count < self.initial_frame:
			self.epsilon = self.eps_init
		elif self.counter.count < self.final_frame:
			self.epsilon = self.eps_init + (self.eps_final - self.eps_init)*(float(self.counter.count - self.initial_frame)/self.final_frame)
		else:
			self.epsilon = self.eps_final

		# Should the agent perform a random action?
		if np.random.random() < self.epsilon:
			action = np.random.randint(self.num_actions)

		return action, Q

	def learn(self, action, reward, is_terminal):
		"""
		Learn from the action taken (maybe due to environmental influence, etc), provided reward and next state
		"""

		self.base_agent.learn(action, reward, is_terminal)


text:
namespace tigl
{
class CTiglUIDManager;
class CTiglUIDObject;
class CCPACSProfileBasedStructuralElement;

namespace generated
{
    // This class is used in:
    // CPACSProfileBasedStructuralElement

    /// @brief materialDefinitionForProfileBasedPointType
    ///
    /// MaterialDefinitionForProfileBased type, containing a
    /// material definition (Reference to material and thickness) for
    /// profile based objects, addition point reinforcements
    ///
    class CPACSMaterialDefinitionForProfileBasedPoint : public ITiglUIDRefObject
    {
    public:
        TIGL_EXPORT CPACSMaterialDefinitionForProfileBasedPoint(CCPACSProfileBasedStructuralElement* parent, CTiglUIDManager* uidMgr);

        TIGL_EXPORT virtual ~CPACSMaterialDefinitionForProfileBasedPoint();

        TIGL_EXPORT CCPACSProfileBasedStructuralElement* GetParent();

        TIGL_EXPORT const CCPACSProfileBasedStructuralElement* GetParent() const;

        TIGL_EXPORT virtual CTiglUIDObject* GetNextUIDParent();
        TIGL_EXPORT virtual const CTiglUIDObject* GetNextUIDParent() const;

        TIGL_EXPORT CTiglUIDManager& GetUIDManager();
        TIGL_EXPORT const CTiglUIDManager& GetUIDManager() const;

        TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath);
        TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const;

        TIGL_EXPORT virtual const boost::optional<std::string>& GetPointUID() const;
        TIGL_EXPORT virtual void SetPointUID(const boost::optional<std::string>& value);

        TIGL_EXPORT virtual const std::string& GetMaterialUID() const;
        TIGL_EXPORT virtual void SetMaterialUID(const std::string& value);

        TIGL_EXPORT virtual const double& GetCrossSectionArea() const;
        TIGL_EXPORT virtual void SetCrossSectionArea(const double& value);

        TIGL_EXPORT virtual const boost::optional<double>& GetOptionalAux1() const;
        TIGL_EXPORT virtual void SetOptionalAux1(const boost::optional<double>& value);

        TIGL_EXPORT virtual const boost::optional<double>& GetOptionalAux2() const;
        TIGL_EXPORT virtual void SetOptionalAux2(const boost::optional<double>& value);

    protected:
        CCPACSProfileBasedStructuralElement* m_parent;

        CTiglUIDManager* m_uidMgr;

        /// uID of the profile point to which the
        /// additional stiffness shall be applied.
        boost::optional<std::string> m_pointUID;

        /// uID of a material definition.
        std::string                  m_materialUID;

        /// cross sectional area of additional long.
        /// stiffener at strctural element point
        double                       m_crossSectionArea;

        /// optional auxiliary parameter for special use
        /// (no physical meaning)
        boost::optional<double>      m_optionalAux1;

        /// optional auxiliary parameter for special use
        /// (no physical meaning)
        boost::optional<double>      m_optionalAux2;

    private:
        TIGL_EXPORT const CTiglUIDObject* GetNextUIDObject() const final;
        TIGL_EXPORT void NotifyUIDChange(const std::string& oldUid, const std::string& newUid) final;

        CPACSMaterialDefinitionForProfileBasedPoint(const CPACSMaterialDefinitionForProfileBasedPoint&) = delete;
        CPACSMaterialDefinitionForProfileBasedPoint& operator=(const CPACSMaterialDefinitionForProfileBasedPoint&) = delete;

        CPACSMaterialDefinitionForProfileBasedPoint(CPACSMaterialDefinitionForProfileBasedPoint&&) = delete;
        CPACSMaterialDefinitionForProfileBasedPoint& operator=(CPACSMaterialDefinitionForProfileBasedPoint&&) = delete;
    };
} // namespace generated

// Aliases in tigl namespace
using CCPACSMaterialDefinitionForProfileBasedPoint = generated::CPACSMaterialDefinitionForProfileBasedPoint;
} // namespace tigl


text:
class TestRouter(object):

    def db_for_read(self, model, **hints):
        """Read from diff_keys."""
        if model._meta.app_label == 'diff_keys':
            return 'diff_keys'
        return 'default'

    def db_for_write(self, model, **hints):
        """Write to diff_keys."""
        if model._meta.app_label == 'diff_keys':
            return 'diff_keys'
        return 'default'


text:
package org.apache.sentry.provider.db;

import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.sentry.core.common.ActiveRoleSet;
import org.apache.sentry.core.common.Authorizable;
import org.apache.sentry.core.common.SentryConfigurationException;
import org.apache.sentry.provider.common.ProviderBackend;
import org.apache.sentry.provider.common.ProviderBackendContext;
import org.apache.sentry.provider.db.service.thrift.SentryPolicyServiceClient;
import org.apache.sentry.service.thrift.SentryServiceClientFactory;
import org.apache.sentry.service.thrift.ServiceConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableSet;

public class SimpleDBProviderBackend implements ProviderBackend {

  private static final Logger LOGGER = LoggerFactory
      .getLogger(SimpleDBProviderBackend.class);

  private Configuration conf;
  private int retryCount;
  private int retryIntervalSec;

  public SimpleDBProviderBackend(Configuration conf, String resourcePath) throws Exception { //NOPMD
    // DB Provider doesn't use policy file path
    this(conf);
  }

  public SimpleDBProviderBackend(Configuration conf) throws Exception {
    this.conf = conf;
    this.retryCount = conf.getInt(ServiceConstants.ClientConfig.RETRY_COUNT_CONF, ServiceConstants.ClientConfig.RETRY_COUNT_DEFAULT);
    this.retryIntervalSec = conf.getInt(ServiceConstants.ClientConfig.RETRY_INTERVAL_SEC_CONF, ServiceConstants.ClientConfig.RETRY_INTERVAL_SEC_DEFAULT);
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public void initialize(ProviderBackendContext context) {
    //Noop
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public ImmutableSet<String> getPrivileges(Set<String> groups, ActiveRoleSet roleSet, Authorizable... authorizableHierarchy) {
    int retries = Math.max(retryCount + 1, 1); // if customer configs retryCount as Integer.MAX_VALUE, try only once
    while (retries > 0) {
      retries--;
      SentryPolicyServiceClient policyServiceClient = null;
      try {
        policyServiceClient = SentryServiceClientFactory.create(conf);
        return ImmutableSet.copyOf(policyServiceClient.listPrivilegesForProvider(groups, roleSet, authorizableHierarchy));
      } catch (Exception e) {
        //TODO: differentiate transient errors and permanent errors
        String msg = "Unable to obtain privileges from server: " + e.getMessage() + ".";
        if (retries > 0) {
          LOGGER.warn(msg +  " Will retry for " + retries + " time(s)");
        } else {
          LOGGER.error(msg, e);
        }
        if (retries > 0) {
          try {
            Thread.sleep(retryIntervalSec * 1000);
          } catch (InterruptedException e1) {
            LOGGER.info("Sleeping is interrupted.", e1);
          }
        }
      } finally {
        if(policyServiceClient != null) {
          policyServiceClient.close();
        }
      }
    }

    return ImmutableSet.of();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public ImmutableSet<String> getRoles(Set<String> groups, ActiveRoleSet roleSet) {
    throw new UnsupportedOperationException("Not yet implemented.");
  }

  @Override
  public void close() {
    //Noop
  }

  /**
   * SimpleDBProviderBackend does not implement validatePolicy()
   */
  @Override
  public void validatePolicy(boolean strictValidation) throws SentryConfigurationException {
  //Noop
  }
}


text:
package commbank.coppersmith

import commbank.coppersmith.util.Timestamp
import org.joda.time.DateTime
import org.scalacheck.Prop.forAll
import org.scalacheck.Gen

import org.specs2.{ScalaCheck, Specification}
import org.specs2.matcher.Matcher

import scalaz.NonEmptyList
import scalaz.scalacheck.ScalazArbitrary.NonEmptyListArbitrary
import scalaz.syntax.std.boolean.ToBooleanOpsFromBoolean
import scalaz.syntax.std.list.ToListOpsFromList

import Feature._, Value._, Type._
import FeatureBuilderSource.fromFS
import Arbitraries._
import commbank.coppersmith.test.thrift.{Account, Customer}

object SelectFeatureSetSpec extends Specification with ScalaCheck { def is = s2"""
  SelectFeatureSet - Test an example set of features based on selecting fields
  ===========
  An example feature set
    must generate expected metadata       $generateMetadata
    must generate expected feature values $generateFeatureValues
"""

  object CustomerFeatureSet extends AbstractFeatureSet[Customer] {
    val namespace           = "test.namespace"
    def entity(c: Customer) = c.id
    def time(c: Customer, ctx: FeatureContext)   = c.time

    val source  = From[Customer]()
    val builder = source.featureSetBuilder(namespace, entity)
    val select  = builder

    type CF = Feature[Customer, Value]
    val age:       CF = select(_.age)                       .asFeature(Ordinal,    "age",       "Age")
    val tallAge:   CF = select(_.age).where(_.height > 2.0) .asFeature(Continuous, "tallAge",   "Tall Age")
    val oldHeight: CF = select(_.height).where(_.age > 65)  .asFeature(Continuous, "oldHeight", "Old Height")
    val time:      CF = select(c => Timestamp(c.time, None)).asFeature(Instant,    "time",      "Time")

    val credit:    CF = builder.map(c => (c, c.credit)).collect {
                          case (c, Some(score)) => (c, score)
                        }.select(_._2).asFeature(Continuous, "credit", "Credit Score")

    val altCredit: CF = builder.map(_.credit).collect {
                          case Some(score) => score
                        }.asFeature(Continuous, "altCredit", "Alternate Impl")

    val youngIsVerified: CF =
      select(_.isVerified).where(_.age < 40).asFeature(Nominal, "youngIsVerified", "Young isVerified")

    def features = List(age, tallAge, oldHeight, time, credit, altCredit, youngIsVerified)
  }

  def generateMetadata = {
    val metadata = CustomerFeatureSet.metadata
    import CustomerFeatureSet.namespace

    metadata must_== List(
      Metadata[Customer, Integral]     (namespace, "age",             "Age",              Ordinal),
      Metadata[Customer, Integral]     (namespace, "tallAge",         "Tall Age",         Continuous),
      Metadata[Customer, FloatingPoint](namespace, "oldHeight",       "Old Height",       Continuous),
      Metadata[Customer, Time]         (namespace, "time",            "Time",             Instant),
      Metadata[Customer, FloatingPoint](namespace, "credit",          "Credit Score",     Continuous),
      Metadata[Customer, FloatingPoint](namespace, "altCredit",       "Alternate Impl",   Continuous),
      Metadata[Customer, Bool]         (namespace, "youngIsVerified", "Young isVerified", Nominal)
    )
  }

  def generateFeatureValues = forAll { (c: Customer) => {
    val featureValues = CustomerFeatureSet.generate(c)

    val expectTallAge    = c.height > 2.0
    val expectOldHeight  = c.age > 65
    val expectCredit     = c.credit.isDefined
    val expectIsVerified = c.age < 40

    featureValues must_== List(
                         Some(FeatureValue[Integral]     (c.id, "age",             c.age)),
      expectTallAge.option(   FeatureValue[Integral]     (c.id, "tallAge",         c.age)),
      expectOldHeight.option( FeatureValue[FloatingPoint](c.id, "oldHeight",       c.height)),
                         Some(FeatureValue[Time]         (c.id, "time",            Timestamp(c.time, None))),
      expectCredit.option(    FeatureValue[FloatingPoint](c.id, "credit",          c.credit)),
      expectCredit.option(    FeatureValue[FloatingPoint](c.id, "altCredit",       c.credit)),
      expectIsVerified.option(FeatureValue[Bool]         (c.id, "youngIsVerified", c.isVerified))
    ).flatten
  }}
}

object AggregationFeatureSetSpec extends Specification with ScalaCheck { def is = s2"""
  AggregationFeatureSet - Test an example set of features based on aggregating records
  ===========
  An example feature set
    must generate expected metadata       $generateMetadata
    must generate expected feature values $generateFeatureValues
  The avg aggregator
    must generate expected values         $generateAvgValues
"""

  object CustomerFeatureSet extends AggregationFeatureSet[Customer] {
    val namespace           = "test.namespace"
    def entity(c: Customer) = c.id
    def time(c: Customer, ctx: FeatureContext)   = ctx.generationTime.getMillis

    val source  = From[Customer]()
    val builder = source.featureSetBuilder(namespace, entity)
    val select: FeatureSetBuilder[Customer, Customer]  = builder

    type CAF = AggregationFeature[Customer, Customer, _, Value]

    def bigD(f: Customer => Double): (Customer => BigDecimal) = c => BigDecimal(f(c))

    val sizeF:    CAF = select(size)                      .asFeature(Discrete,   "size",    "Agg feature")
    val bigSizeF: CAF = select(size).having(_ > 5)        .asFeature(Discrete,   "sizeB",   "Agg feature")
    val countF:   CAF = select(count(where = _.age >= 18)).asFeature(Continuous, "count",   "Agg feature")
    val sumF:     CAF = select(sum(_.height))             .asFeature(Continuous, "sum",     "Agg feature")
    val maxF:     CAF = select(max(_.age))                .asFeature(Continuous, "max",     "Agg feature")
    val minF:     CAF = select(min(_.height))             .asFeature(Continuous, "min",     "Agg feature")
    val maxByF:   CAF = select(maxBy(_.id)(_.height))     .asFeature(Continuous, "maxBy",   "Agg feature")
    val minByF:   CAF = select(minBy(_.id)(_.age))        .asFeature(Continuous, "minBy",   "Agg feature")
    val avgF:     CAF = select(avg(_.age.toDouble))       .asFeature(Continuous, "avg",     "Agg feature")
    val sumBigDF: CAF = select(sum(bigD(_.height)))       .asFeature(Continuous, "sumBigD", "Agg feature")
    val maxBigDF: CAF = select(max(bigD(_.age)))          .asFeature(Continuous, "maxBigD", "Agg feature")
    val avgBigDF: CAF = select(avgBigDec(_.age))          .asFeature(Continuous, "avgBigD", "Agg feature")
    val ucbF:     CAF = select(uniqueCountBy(_.age % 10)) .asFeature(Continuous, "ucb",     "Agg feature")
    // Ensure that generated value is deterministic (based on order of value) when discriminators are equal
    val maxVByF:  CAF = select(maxBy(_ => "")(_.height))  .asFeature(Continuous, "maxVBy",  "Agg feature")
    val minVByF:  CAF = select(minBy(_ => "")(_.age))     .asFeature(Continuous, "minVBy",  "Agg feature")

    import com.twitter.algebird.Aggregator

    val collectF: AggregationFeature[Customer, Double, _, Value] =
      builder.map(c => (c, c.credit)).collect {
        case (c, Some(credit)) => credit
      }.select(Aggregator.min[Double]).asFeature(Continuous, "collect", "Agg feature")

    def aggregationFeatures = List(
      sizeF,
      bigSizeF,
      countF,
      sumF,
      maxF,
      minF,
      maxByF,
      minByF,
      avgF,
      sumBigDF,
      maxBigDF,
      avgBigDF,
      ucbF,
      collectF,
      maxVByF,
      minVByF
    )
  }

  def generateMetadata = {
    val metadata = CustomerFeatureSet.metadata
    import CustomerFeatureSet.namespace

    metadata must_== List(
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "size",    "Agg feature", Discrete),
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "sizeB",   "Agg feature", Discrete),
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "count",   "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), FloatingPoint](namespace, "sum",     "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "max",     "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), FloatingPoint](namespace, "min",     "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), FloatingPoint](namespace, "maxBy",   "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "minBy",   "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), FloatingPoint](namespace, "avg",     "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Decimal]      (namespace, "sumBigD", "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Decimal]      (namespace, "maxBigD", "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Decimal]      (namespace, "avgBigD", "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "ucb",     "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), FloatingPoint](namespace, "collect", "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), FloatingPoint](namespace, "maxVBy",  "Agg feature", Continuous),
      Metadata[(EntityId, Iterable[Customer]), Integral]     (namespace, "minVBy",  "Agg feature", Continuous)
    )
  }

  def generateFeatureValues = forAll { (cs: NonEmptyList[Customer], dateTime: DateTime) => {
    val featureValues = CustomerFeatureSet.generate((cs.head.id, cs.list))

    val eavtValues = featureValues.map { fv => fv.asEavt(dateTime.getMillis) }.toList

    val c           = cs.head
    val heights     = cs.map(_.height).list
    val ages        = cs.map(_.age).list
    val groupedAges = cs.map(_.age).list.groupBy(_ % 10)
    val credit      = cs.map(_.credit).list.collect { case Some(c) => c }.toNel.map(_.list.min)
    val time        = dateTime.getMillis
    val maxCById    = cs.list.maxBy(c => (c.id, c.height))
    val minCById    = cs.list.minBy(c => (c.id, c.age))
    val expectBig   = cs.size > 5

    val expected = List(
                  Some((c.id, "size",    cs.size:                            Integral,      time)),
      expectBig.option((c.id, "sizeB",   cs.size:                            Integral,      time)),
                  Some((c.id, "count",   ages.filter(_ >= 18).size:          Integral,      time)),
                  Some((c.id, "sum",     heights.sum:                        FloatingPoint, time)),
                  Some((c.id, "max",     ages.max:                           Integral,      time)),
                  Some((c.id, "min",     heights.min:                        FloatingPoint, time)),
                  Some((c.id, "maxBy",   maxCById.height:                    FloatingPoint, time)),
                  Some((c.id, "minBy",   minCById.age:                       Integral,      time)),
                  Some((c.id, "avg",     (ages.sum.toDouble / ages.size):    FloatingPoint, time)),
                  Some((c.id, "sumBigD", heights.map(BigDecimal(_)).sum:     Decimal,       time)),
                  Some((c.id, "maxBigD", ages.map(BigDecimal(_)).max:        Decimal,       time)),
                  Some((c.id, "avgBigD", (ages.sum / BigDecimal(ages.size)): Decimal,       time)),
                  Some((c.id, "ucb",     groupedAges.size:                   Integral,      time)),
      credit.map(d =>  (c.id, "collect", d:                                  FloatingPoint, time)),
                  Some((c.id, "maxVBy",  heights.max:                        FloatingPoint, time)),
                  Some((c.id, "minVBy",  ages.min:                           Integral,      time))
    ).flatten

    eavtValues.toList must matchEavts(expected)
  }}

  def matchEavts(expected: List[(EntityId, Name, Value, FeatureTime)])
      : Matcher[List[(EntityId, Name, Value, FeatureTime)]] =
    expected.contain(_.zip(===, ===, matchValue, ===))

  def matchValue(expected: Value): Matcher[Value] = expected match {
    case Integral(_) | Str(_) | FloatingPoint(None) | Decimal(None) | Bool(_) | Date(_) | Time(_) => be_===(expected)
    case FloatingPoint(Some(expectedDouble)) =>
      beCloseTo(expectedDouble +/- 0.000000000001) ^^ (
        (v: Value) => v match {
          case FloatingPoint(Some(actualDouble)) => actualDouble
          case _ => Double.NaN
        }
      )
    case Decimal(Some(expectedBigDecimal)) =>
      beCloseTo(expectedBigDecimal +/- BigDecimal("0.0000000000000000001")) ^^ (
        (v: Value) => v match {
          case Decimal(Some(actualBigDecimal)) => actualBigDecimal
          case _ => null
        }
      )
  }

  object AverageFeatureSet extends AggregationFeatureSet[Account] {
    val namespace                               = "test.namespace"
    def entity(a: Account)                      = a.id
    def time(a: Account, ctx: FeatureContext)   = ctx.generationTime.getMillis

    val source  = From[Account]()
    val builder = source.featureSetBuilder(namespace, entity)
    val select: FeatureSetBuilder[Account, Account] = builder

    type CAF      = AggregationFeature[Account, Account, _, Value]
    val avgF: CAF = select(avgBigDec(c => BigDecimal(c.balanceBigDecimal)))
      .asFeature(Continuous, "avg", "Agg feature")

    def aggregationFeatures = List(avgF)
  }

  def generateAvgValues = {
    testAverage(NonEmptyList("1000000000000.02", "0.02"), BigDecimal("500000000000.02"))
    testAverage(NonEmptyList("1200000000000.01", "1200000000000.03", "0.02"), BigDecimal("800000000000.02"))
  }

  def testAverage(vals: NonEmptyList[String], expected: BigDecimal) = {
    val as   = vals.map(v => Gen.resultOf(Account.apply _).sample.get.copy(balanceBigDecimal = v))
    val time = DateTime.now.getMillis

    val featureValues = AverageFeatureSet.generate((as.head.id, as.list))

    val eavtValues = featureValues.map { fv => fv.asEavt(time) }.toList

    eavtValues.toList must matchEavts(List((as.head.id, "avg", expected: Decimal, time)))
  }
}


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

// Package stsclient is for oauth token exchange integration.
package stsclient

import (
	"bytes"
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"istio.io/istio/security/pkg/nodeagent/plugin"
	"istio.io/pkg/env"
	"istio.io/pkg/log"
)

var (
	// GKEClusterURL is the URL to send requests to the token exchange service.
	GKEClusterURL = env.RegisterStringVar("GKE_CLUSTER_URL", "", "The url of GKE cluster").Get()
	// SecureTokenEndpoint is the Endpoint the STS client calls to.
	SecureTokenEndpoint = "https://securetoken.googleapis.com/v1/identitybindingtoken"
	stsClientLog        = log.RegisterScope("stsclient", "STS client debugging", 0)
)

const (
	httpTimeOutInSec = 5
	contentType      = "application/json"
	scope            = "https://www.googleapis.com/auth/cloud-platform"
)

type federatedTokenResponse struct {
	AccessToken     string `json:"access_token"`
	IssuedTokenType string `json:"issued_token_type"`
	TokenType       string `json:"token_type"`
	ExpiresIn       int64  `json:"expires_in"` // Expiration time in seconds
}

// Plugin for google securetoken api interaction.
type Plugin struct {
	hTTPClient *http.Client
}

// NewPlugin returns an instance of secure token service client plugin
func NewPlugin() plugin.Plugin {
	caCertPool, err := x509.SystemCertPool()
	if err != nil {
		stsClientLog.Errorf("Failed to get SystemCertPool: %v", err)
		return nil
	}
	return Plugin{
		hTTPClient: &http.Client{
			Timeout: httpTimeOutInSec * time.Second,
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					RootCAs: caCertPool,
				},
			},
		},
	}
}

// ExchangeToken exchange oauth access token from trusted domain and k8s sa jwt.
func (p Plugin) ExchangeToken(ctx context.Context, trustDomain, k8sSAjwt string) (
	string /*access token*/, time.Time /*expireTime*/, int /*httpRespCode*/, error) {
	aud := constructAudience(trustDomain)
	var jsonStr = constructFederatedTokenRequest(aud, k8sSAjwt)
	req, _ := http.NewRequest("POST", SecureTokenEndpoint, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", contentType)

	resp, err := p.hTTPClient.Do(req)
	errMsg := "failed to call token exchange service. "
	if err != nil || resp == nil {
		statusCode := http.StatusServiceUnavailable
		// If resp is not null, return the actually status code returned from the token service.
		// If resp is null, return a service unavailable status and try again.
		if resp != nil {
			statusCode = resp.StatusCode
			errMsg += fmt.Sprintf("HTTP status: %s. Error: %v", resp.Status, err)
		} else {
			errMsg += fmt.Sprintf("HTTP response empty. Error: %v", err)
		}
		return "", time.Now(), statusCode, errors.New(errMsg)
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	respData := &federatedTokenResponse{}
	if err := json.Unmarshal(body, respData); err != nil {
		return "", time.Now(), resp.StatusCode, fmt.Errorf(
			"failed to unmarshal response data. HTTP status: %s. Error: %v. Body size: %d", resp.Status, err, len(body))
	}

	if respData.AccessToken == "" {
		return "", time.Now(), resp.StatusCode, fmt.Errorf(
			"exchanged empty token. HTTP status: %s. Response: %v", resp.Status, string(body))
	}

	return respData.AccessToken, time.Now().Add(time.Second * time.Duration(respData.ExpiresIn)), resp.StatusCode, nil
}

func constructAudience(trustDomain string) string {
	if GKEClusterURL == "" {
		return trustDomain
	}

	return fmt.Sprintf("identitynamespace:%s:%s", trustDomain, GKEClusterURL)
}

func constructFederatedTokenRequest(aud, jwt string) []byte {
	values := map[string]string{
		"audience":           aud,
		"grantType":          "urn:ietf:params:oauth:grant-type:token-exchange",
		"requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
		"subjectTokenType":   "urn:ietf:params:oauth:token-type:jwt",
		"subjectToken":       jwt,
		"scope":              scope,
	}
	jsonValue, _ := json.Marshal(values)
	return jsonValue
}


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['stableinterface'],
                    'supported_by': 'core'}

DOCUMENTATION = '''
---
module: seboolean
short_description: Toggles SELinux booleans
description:
     - Toggles SELinux booleans.
version_added: "0.7"
options:
  name:
    description:
      - Name of the boolean to configure.
    required: true
  persistent:
    description:
      - Set to C(yes) if the boolean setting should survive a reboot.
    type: bool
    default: 'no'
  state:
    description:
      - Desired boolean value
    type: bool
    required: true
  ignore_selinux_state:
    description:
    - Useful for scenarios (chrooted environment) that you can't get the real SELinux state.
    type: bool
    default: false
    version_added: '2.8'
notes:
   - Not tested on any Debian based system.
requirements:
- libselinux-python
- libsemanage-python
author:
- Stephen Fromm (@sfromm)
'''

EXAMPLES = '''
- name: Set httpd_can_network_connect flag on and keep it persistent across reboots
  seboolean:
    name: httpd_can_network_connect
    state: yes
    persistent: yes
'''

import os
import traceback

SELINUX_IMP_ERR = None
try:
    import selinux
    HAVE_SELINUX = True
except ImportError:
    SELINUX_IMP_ERR = traceback.format_exc()
    HAVE_SELINUX = False

SEMANAGE_IMP_ERR = None
try:
    import semanage
    HAVE_SEMANAGE = True
except ImportError:
    SEMANAGE_IMP_ERR = traceback.format_exc()
    HAVE_SEMANAGE = False

from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import binary_type
from ansible.module_utils._text import to_bytes, to_text

def get_runtime_status(ignore_selinux_state=False):
    return True if ignore_selinux_state is True else selinux.is_selinux_enabled()

def has_boolean_value(module, name):
    bools = []
    try:
        rc, bools = selinux.security_get_boolean_names()
    except OSError:
        module.fail_json(msg="Failed to get list of boolean names")
    # work around for selinux who changed its API, see
    # https://github.com/ansible/ansible/issues/25651
    if len(bools) > 0:
        if isinstance(bools[0], binary_type):
            name = to_bytes(name)
    if name in bools:
        return True
    else:
        return False

def get_boolean_value(module, name):
    state = 0
    try:
        state = selinux.security_get_boolean_active(name)
    except OSError:
        module.fail_json(msg="Failed to determine current state for boolean %s" % name)
    if state == 1:
        return True
    else:
        return False

def semanage_get_handle(module):
    handle = semanage.semanage_handle_create()
    if not handle:
        module.fail_json(msg="Failed to create semanage library handle")

    managed = semanage.semanage_is_managed(handle)
    if managed <= 0:
        semanage.semanage_handle_destroy(handle)
    if managed < 0:
        module.fail_json(msg="Failed to determine whether policy is manage")
    if managed == 0:
        if os.getuid() == 0:
            module.fail_json(msg="Cannot set persistent booleans without managed policy")
        else:
            module.fail_json(msg="Cannot set persistent booleans; please try as root")

    if semanage.semanage_connect(handle) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to connect to semanage")

    return handle

def semanage_begin_transaction(module, handle):
    if semanage.semanage_begin_transaction(handle) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to begin semanage transaction")

def semanage_set_boolean_value(module, handle, name, value):
    rc, t_b = semanage.semanage_bool_create(handle)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to create seboolean with semanage")

    if semanage.semanage_bool_set_name(handle, t_b, name) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to set seboolean name with semanage")

    rc, boolkey = semanage.semanage_bool_key_extract(handle, t_b)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to extract boolean key with semanage")

    rc, exists = semanage.semanage_bool_exists(handle, boolkey)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to check if boolean is defined")
    if not exists:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="SELinux boolean %s is not defined in persistent policy" % name)

    rc, sebool = semanage.semanage_bool_query(handle, boolkey)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to query boolean in persistent policy")

    semanage.semanage_bool_set_value(sebool, value)

    if semanage.semanage_bool_modify_local(handle, boolkey, sebool) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to modify boolean key with semanage")

    if semanage.semanage_bool_set_active(handle, boolkey, sebool) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to set boolean key active with semanage")

    semanage.semanage_bool_key_free(boolkey)
    semanage.semanage_bool_free(t_b)
    semanage.semanage_bool_free(sebool)

def semanage_get_boolean_value(module, handle, name):
    rc, t_b = semanage.semanage_bool_create(handle)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to create seboolean with semanage")

    if semanage.semanage_bool_set_name(handle, t_b, name) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to set seboolean name with semanage")

    rc, boolkey = semanage.semanage_bool_key_extract(handle, t_b)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to extract boolean key with semanage")

    rc, exists = semanage.semanage_bool_exists(handle, boolkey)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to check if boolean is defined")
    if not exists:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="SELinux boolean %s is not defined in persistent policy" % name)

    rc, sebool = semanage.semanage_bool_query(handle, boolkey)
    if rc < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to query boolean in persistent policy")

    value = semanage.semanage_bool_get_value(sebool)

    semanage.semanage_bool_key_free(boolkey)
    semanage.semanage_bool_free(t_b)
    semanage.semanage_bool_free(sebool)

    return value

def semanage_commit(module, handle, load=0):
    semanage.semanage_set_reload(handle, load)
    if semanage.semanage_commit(handle) < 0:
        semanage.semanage_handle_destroy(handle)
        module.fail_json(msg="Failed to commit changes to semanage")

def semanage_destroy_handle(module, handle):
    rc = semanage.semanage_disconnect(handle)
    semanage.semanage_handle_destroy(handle)
    if rc < 0:
        module.fail_json(msg="Failed to disconnect from semanage")

# The following method implements what setsebool.c does to change
# a boolean and make it persist after reboot..
def semanage_boolean_value(module, name, state):
    value = 0
    changed = False
    if state:
        value = 1
    try:
        handle = semanage_get_handle(module)
        semanage_begin_transaction(module, handle)
        cur_value = semanage_get_boolean_value(module, handle, name)
        if cur_value != value:
            changed = True
            if not module.check_mode:
                semanage_set_boolean_value(module, handle, name, value)
                semanage_commit(module, handle)
        semanage_destroy_handle(module, handle)
    except Exception as e:
        module.fail_json(msg=u"Failed to manage policy for boolean %s: %s" % (name, to_text(e)))
    return changed

def set_boolean_value(module, name, state):
    rc = 0
    value = 0
    if state:
        value = 1
    try:
        rc = selinux.security_set_boolean(name, value)
    except OSError:
        module.fail_json(msg="Failed to set boolean %s to %s" % (name, value))
    if rc == 0:
        return True
    else:
        return False

def main():
    module = AnsibleModule(
        argument_spec=dict(
            ignore_selinux_state=dict(type='bool', default=False),
            name=dict(type='str', required=True),
            persistent=dict(type='bool', default=False),
            state=dict(type='bool', required=True),
        ),
        supports_check_mode=True,
    )

    if not HAVE_SELINUX:
        module.fail_json(msg=missing_required_lib('libselinux-python'), exception=SELINUX_IMP_ERR)

    if not HAVE_SEMANAGE:
        module.fail_json(msg=missing_required_lib('libsemanage-python'), exception=SEMANAGE_IMP_ERR)

    ignore_selinux_state = module.params['ignore_selinux_state']

    if not get_runtime_status(ignore_selinux_state):
        module.fail_json(msg="SELinux is disabled on this host.")

    name = module.params['name']
    persistent = module.params['persistent']
    state = module.params['state']

    result = dict(
        name=name,
        persistent=persistent,
        state=state
    )
    changed = False

    if hasattr(selinux, 'selinux_boolean_sub'):
        # selinux_boolean_sub allows sites to rename a boolean and alias the old name
        # Feature only available in selinux library since 2012.
        name = selinux.selinux_boolean_sub(name)

    if not has_boolean_value(module, name):
        module.fail_json(msg="SELinux boolean %s does not exist." % name)

    if persistent:
        changed = semanage_boolean_value(module, name, state)
    else:
        cur_value = get_boolean_value(module, name)
        if cur_value != state:
            changed = True
            if not module.check_mode:
                changed = set_boolean_value(module, name, state)
                if not changed:
                    module.fail_json(msg="Failed to set boolean %s to %s" % (name, state))
                try:
                    selinux.security_commit_booleans()
                except Exception:
                    module.fail_json(msg="Failed to commit pending boolean %s value" % name)

    result['changed'] = changed

    module.exit_json(**result)

if __name__ == '__main__':
    main()