text:
import {
    assert,
    range,
    setImmediate,
    $switch,
    ThrottleTime,
    freezed,
    tortologyDict,
    UndoRedoStack,
    gaussBlur,
    Vector,
    } from './mods/utils.js'

import {
    draw,
    } from './mods/draw.js'

import {CanvasTransform} from './mods/canvastransform.js'
import {ANColorPicker} from './lib/ancp.js'

function main(){

    const State = freezed({
        imgview: null,
        img: null,
        urs: null,
        ancp: null,
        origValueMatrix: null,
        canvasTransform: null,
        canvasTransformOps: null,

        tempcnv: null,
    })

    const DrawMode = tortologyDict(`
        Regular
        experimental_Mochi
        experimental_A
        experimental_A0
        experimental_Crease
        experimental_Erode
        `)

    const app = new Vue({
        el: '#vue-root',
        data: {
            appinited:false,
            width: 0,
            height: 0,

            DrawMode: DrawMode,
            drawmode: DrawMode.Regular,
            useOpacity: false,
            sizeOnTime: false,
            brushsize: 40,
            useconststep: true,
            ignoreVelocity: false,
            drawmassCoef: 0,
            useinterp: true,
            interpLimitSize: 10,
            // interpLimitSize: 300,
            useLittleExtendedRegion: true,

            ///
            readyToPanCanvas: false,

            ///
            brushcolor: new Color(0,0,0),
            brushcolor2: new Color(255,255,255),

            /// UI
            showHelp: true,
            openImagesVisible: false,
            openImagesPinned: false,
            canvasInitializing: false,
            colorPickerVisible: false,
            colorPickerPinned: true,
        },
        computed:{
            frontColorStyle(){
                return `rgb(${this.brushcolor.r},${this.brushcolor.g},${this.brushcolor.b})`
            },
            backColorStyle(){
                return `rgb(${this.brushcolor2.r},${this.brushcolor2.g},${this.brushcolor2.b})`
            },
            ui_showuni(){
                const DrawMode = this.DrawMode
                return [DrawMode.experimental_A
                       ,DrawMode.experimental_A0
                       ,DrawMode.experimental_Crease].includes(this.drawmode)
            },
            ui_show_useLittleExtendedRegion(){
                const DrawMode = this.DrawMode
                return [DrawMode.Regular].includes(this.drawmode)
            },
        },

        methods: {
            p(...args){console.log(args)},

            pinvis(name){
                assert(name+'Visible' in this)
                assert(name+'Pinned' in this)
                // return (this[name+'Visible'] || this[name+'Pinned']) ? 'show' : 'hide'
                return (this[name+'Visible'] || this[name+'Pinned']) ? '' : 'hide'
            },

            status(msg){
                this.$refs.status.textContent = msg
            },

            onFileChange(e){
                this.status('loading...')

                setImmediate(_=>{
                    this._filechange(e.target.files[0])
                })
            },

            onPaste(e){
                this._getPastedImageFile(e, file=>{
                    e.target.blur()
                    this._filechange(file)
                })
            },
            _filechange(file){
                loadImageFile(file, e=>{
                    this.status('')
                    const {name, img} = e
                    this.initCanvas({name, img})
                })
            },

            onFileChange_Fill(e){
                this._filechange_Fill(e.target.files[0])
            },
            onPaste_Fill(e){
                this._getPastedImageFile(e, file=>{
                    e.target.blur()
                    this._filechange_Fill(file)
                })
            },
            _filechange_Fill(file){
                loadImageFile(file, e=>{
                    const {name, img} = e

                    const cnv = this.$refs.maincanvas
                    const ctx = cnv.getContext('2d')
                    clearCanvas(cnv, 'rgba(255,255,255,1.0)')
                    ctx.drawImage(img,0,0)
                    State.tempcnv.getContext('2d').drawImage(cnv,0,0)
                    State.urs.forget() /// temp
                })
            },

            _getPastedImageFile(e, callback){
                if(document.activeElement !== e.target)
                    return
                e.preventDefault()

                const cd = e.clipboardData
                if (!(cd || cd.types || cd.types.length === 1 || cd.types[0] === 'Files'))
                    return

                const imageFile = e.clipboardData.items[0].getAsFile()
                if(!imageFile)
                    return

                callback(imageFile)
            },
            onPasteKeydown(e){
                if(!(e.ctrlKey && e.code==='KeyV'))
                    e.preventDefault()
            },

            initCanvas({name, img}){
                this.canvasInitializing = true

                // console.log('initCanvas', name, img)
                this.width = img.naturalWidth
                this.height = img.naturalHeight

                setImmediate(_=>{
                    if(State.img)
                        revokeImgs([State.img])

                    const W = this.width
                    const H = this.height
                    const cnv = this.$refs.maincanvas
                    const ctx = cnv.getContext('2d')

                    if(false)
                        /// use alpha
                        clearCanvas(cnv)
                    else {
                        /// non-alpha
                        clearCanvas(cnv, 'rgba(255,255,255,1.0)')
                    }

                    ///
                    const ctx2 = this.$refs.origimgpreviewcanvas.getContext('2d')
                    ctx2.drawImage(img, 0,0)

                    ///
                    const origview = ctx2.getImageData(0,0,W,H).data /// Uint8ClampedArray
                    State.img = img

                    const tempcnv = document.createElement('canvas')
                    tempcnv.width = W
                    tempcnv.height = H
                    tempcnv.getContext('2d').drawImage(cnv,0,0)
                    State.tempcnv = tempcnv

                    /// origValueMatrix[y][x]
                    void function(){

                        const ab = new ArrayBuffer(W*H)
                        const abDest = new ArrayBuffer(W*H)
                        const view = new Uint8ClampedArray(ab)
                        const viewDest = new Uint8ClampedArray(abDest)
                        var i=0
                        var j=0
                        for(const y of range(H))
                            for(const x of range(W)) {
                                // view[i] = origview[j]
                                view[i] = Math.round(0.2989*origview[j] + 0.5870*origview[j+1] + 0.1140*origview[j+2])
                                i++
                                j+=4
                            }
                        // gaussBlur(abDest, ab, W, H, 5)
                        gaussBlur(abDest, ab, W, H, 1)

                        State.origValueMatrix = []
                        var i=0
                        for(const y of range(H)) {
                            const a = []
                            for(const x of range(W)) {
                                a.push(viewDest[i++])
                            }
                            // State.origValueMatrix[y] = a
                            State.origValueMatrix[y] = new Uint8ClampedArray(a)
                        }
                    }()

                    void function(){
                        /// centering
                        const ct = State.canvasTransform
                        ct.resetTransform2()
                        const center = new Vector( window.pageXOffset + document.body.clientWidth/2
                                                 , window.pageYOffset + document.body.clientHeight/2 )
                        ct.translate(center.sub(new Vector(W/2, H/2)))
                        ct.update()
                    }()

                    State.urs.forget()

                    this.canvasInitializing = false
                })
            },
            onMousedown(e){
                const cnv = this.$refs.maincanvas
                const container = this.$refs.cnvcontainer

                // if(e.target === cnv) {
                if([cnv,container,document.body].includes(e.target)) {
                    e.preventDefault()
                    document.activeElement.blur()

                    void (()=>{
                        /// prevent context menu on right click
                        if(e.ctrlKey || e.altKey)
                            return

                        const f = e=>e.preventDefault()
                        const up = e=>{
                            e.preventDefault()
                            document.removeEventListener('mouseup', up)
                            setImmediate(_=>{
                                document.removeEventListener('contextmenu', f)
                            })

                        }
                        document.addEventListener('contextmenu', f)
                        document.addEventListener('mouseup', up)
                    })()

                    if(this.readyToPanCanvas) {
                        State.canvasTransformOps.startPan()
                    } else if(e.altKey) {
                        const {x,y} = State.canvasTransform.mousePositionOnCanvas()
                        changeBrushSize(this, this.$refs.uicanvas, State.canvasTransform, x,y)
                    } else if(e.ctrlKey || e.button === 2 || e.button === 1) {
                        const {x,y} = State.canvasTransform.mousePositionOnCanvas()
                        const c = pickColor(cnv, x, y)
                        this.brushcolor.r = c.r
                        this.brushcolor.g = c.g
                        this.brushcolor.b = c.b
                        State.ancp.setColor(c.r, c.g, c.b)
                    } else {
                        draw(this, State.canvasTransform, State)
                    }

                    return false

                }

            },
        },

        mounted() {
            document.addEventListener('mousedown', e=>{
                this.onMousedown(e)
            })

            // window.addEventListener('keypress', e=>console.log(e))

            const keymap = {
                F1:{down:e=>{}}, /// prevent
                Enter: {down:e=>{
                    const cnv = this.$refs.maincanvas
                    const ctx = cnv.getContext('2d')
                    // ctx.clearRect(0,0,this.width,this.height)
                    ctx.fillStyle = 'rgba(255,255,255,1.0)'
                    ctx.fillRect(0,0,this.width,this.height)
                    State.tempcnv.getContext('2d').drawImage(cnv,0,0)
                }},
                'C:KeyZ': {down:e=> State.urs.undo()},
                'C:KeyY': {down:e=> State.urs.redo()},
                KeyQ: {down:e=> this.useOpacity = !this.useOpacity},
                KeyX: {down:e=> [this.brushcolor, this.brushcolor2] = [this.brushcolor2, this.brushcolor] },
                Digit1: {down:e=>this.drawmassCoef-=1},
                Digit2: {down:e=>this.drawmassCoef+=1},
                KeyH: {down:e=>this.showHelp = !this.showHelp},

                KeyC: {down:e=>this.ignoreVelocity=true, up:e=>this.ignoreVelocity=false},
                Space: {down:e=>this.readyToPanCanvas=true, up:e=>this.readyToPanCanvas=false},

                /// canvas transform
                KeyF: {down:e=>State.canvasTransformOps.flip()},
                Delete: {down:e=>State.canvasTransformOps.rotate(-RotPref.angle), repeat:true},
                End: {down:e=>State.canvasTransformOps.rotate(RotPref.angle), repeat:true},
                F2:       {down:e=> State.canvasTransformOps.zoom(1/ZoomPref.step), repeat:true},
                PageDown: {down:e=> State.canvasTransformOps.zoom(1/ZoomPref.step), repeat:true},
                F3:     {down:e=> State.canvasTransformOps.zoom(ZoomPref.step), repeat:true},
                PageUp: {down:e=> State.canvasTransformOps.zoom(ZoomPref.step), repeat:true},
                F4:   {down:e=> State.canvasTransformOps.resetTransform()},
                Home: {down:e=> State.canvasTransformOps.resetTransform()},
                Insert: {down:e=> State.canvasTransformOps.resetRotation()},
            }
            const downstate = {}
            window.addEventListener('keydown', e=>{
                if(/^(Alt|Control|Shift)/.test(e.code))
                    return

                const n0 = downstate[e.code]
                if(n0) {
                    e.preventDefault()
                    const o = keymap[n0]
                    if(o && o.repeat && o.down)
                        o.down(e)
                } else {
                    const n = (e.altKey?'A:':'')+(e.ctrlKey?'C:':'')+(e.shiftKey?'S:':'')+e.code
                    const o = keymap[n]
                    if(o) {
                        e.preventDefault()
                        if(o.down)
                            o.down(e)
                    }
                    downstate[e.code] = n
                }
            })
            window.addEventListener('keyup', e=>{
                if(/^(Alt|Control|Shift)/.test(e.code))
                    return

                const n = downstate[e.code]
                downstate[e.code] = ''
                const o = n ? keymap[n] : null
                if(o){
                    e.preventDefault()
                    o.up && o.up(e)
                }

            })

            const RotPref = {
                angle: Math.PI*90/180/8,
            }
            const ZoomPref = {
                step: Math.pow(2, 1/2),
            }

            /*void function(){
                /// #debug
                for(const a of 'A: C: S: A:C: A:S: C:S: A:C:S:'.split(/\s+/).concat([''])) {
                    keymap[a+'KeyA'] = {down:e=>console.log(a+'a'), up:e=>console.log(a+'!a')}
                    keymap[a+'KeyS'] = {down:e=>console.log(a+'s'), up:e=>console.log(a+'!s')}
                }
                window.keymap = keymap
            }()*/

            State.urs = new UndoRedoStack()

            ///
            const ct = new CanvasTransform()
            State.canvasTransform = ct
            ct.activate('canvas-transform', 'canvas-container')
            ct.resetTransform()
            ct.update()
            State.canvasTransformOps = new CanvasTransformOps(ct)

            ///
            this.appinited = true
            this.$el.className=""
            const ini =  document.querySelector('#initializing')
            ini.parentNode.removeChild(ini)

            /// localStorage
            if(localStorage.uni) {
                try{
                    const los = JSON.parse(localStorage.uni)
                    this.showHelp = !!los.showHelp
                }catch(e){
                    console.warn(e)
                }
            }
            window.addEventListener('beforeunload', e=>{
                localStorage.uni = JSON.stringify({
                    showHelp: this.showHelp,
                })
            })

            ///
            void function(){
                const img = new Image()
                img.src = './res/a.png'
                img.onload = e=> app.initCanvas({name:'', img})
            }()
        }
    })

    void function(){
        /// color picker
        const ancp = new ANColorPicker(200)
        State.ancp = ancp

        const colorpickerStore = document.querySelector('#colorpicker-store')
        const colorpickerContainer = document.querySelector('#colorpicker')
        colorpickerContainer.appendChild(ancp.getContainer())
        ancp.onChange(e=>{
            if(!e.isTrusted)
                return
            const [r,g,b] = e.rgb
            // console.log(r,g,b)
            app.brushcolor.r = r
            app.brushcolor.g = g
            app.brushcolor.b = b
        })
    }()

    /// #debug
    // window.State = State
    window.app = app

    void function(){
        window.addEventListener('beforeunload', e=>{
            return (e || window.event).returnValue = 'leave?'
        })
    }()
}

class Color {
    constructor(r,g,b){
        this.r=r
        this.g=g
        this.b=b
    }
}

function pickColor(cnv, x, y){
    const ctx = cnv.getContext('2d')
    const imd = ctx.getImageData(x,y,1,1)
    const [r,g,b,a] = imd.data
    /// #todo - consider the alpha
    return new Color(r,g,b)
}

function changeBrushSize(self, uicnv, canvasTransform, x0, y0){
    const W = uicnv.width
    const H = uicnv.height
    const ctx = uicnv.getContext('2d')
    const move = e2=>{
        if(throttle(5))
            return
        const {x,y} = canvasTransform.mousePositionOnCanvas()
        const cx = (x+x0)/2
        const cy = (y+y0)/2
        const r = Math.sqrt((x-x0)**2+(y-y0)**2)/2
        ctx.clearRect(0,0,W,H)
        // uicnv.width = uicnv.width
        ctx.strokeStyle='rgba(0,0,0, 0.5)'
        ctx.beginPath()
        ctx.arc(cx,cy,r, 0, 2*Math.PI)
        ctx.stroke()
    }
    const up = e3=>{
        document.removeEventListener('mousemove', move)
        document.removeEventListener('mouseup', up)

        const {x,y} = canvasTransform.mousePositionOnCanvas()
        const r = Math.sqrt((x-x0)**2+(y-y0)**2)/2
        ctx.clearRect(0,0,W,H)
        self.brushsize = (Math.min(r, 200))<<0
    }
    document.addEventListener('mousemove', move)
    document.addEventListener('mouseup', up)
}

const throttle = ThrottleTime.create()

function revokeImgs(imgs){
    for(const img of imgs)
        URL.revokeObjectURL(img.src)
}

function loadImageFile(file, callback){
    assert(file.type.match(/image./))

    const img = new Image()
    img.onload = _=>{
        callback({name:file.name, img})
    }
    img.src = URL.createObjectURL(file)
}

function clearCanvas(cnv, fillStyle=null){
    const ctx = cnv.getContext('2d')
    if(fillStyle) {
        ctx.fillStyle = fillStyle
        ctx.fillRect(0,0,cnv.width,cnv.height)
    } else {
        ctx.clearRect(0,0,cnv.width,cnv.height)
    }
}

function startdrag(onMove=null, onUp=null, throttleInterval=5){
    const move = e2=>{
        if(throttle(throttleInterval))
            return
        onMove&&onMove(e2)
    }
    const up = e3=>{
        document.removeEventListener('mousemove', move)
        document.removeEventListener('mouseup', up)
        onUp&&onUp(e3)
    }
    document.addEventListener('mousemove', move)
    document.addEventListener('mouseup', up)
}

class CanvasTransformOps {
    constructor(canvasTransform){
        this.ct = this.canvasTransform = canvasTransform
    }
    startPan(){
        const ct = this.ct
        const mp0 = ct.mousePositionOnWindow()
        const m0 = ct.getMatrix()
        const f = e=>{
            const mp = ct.mousePositionOnWindow()
            const dp = mp.sub(mp0)
            ct.setMatrix(m0.clone())
            ct.translate(dp)
            ct.update()
        }
        startdrag(f,f)
    }
    flip(){
        this.ct.flipH()
        this.ct.update()
    }
    zoom(k=1.0){
        this.ct.scale(k)
        this.ct.update()

        /// test
        app.$refs.origimgpreviewcanvas.style['image-rendering'] =
            this.ct.zoom >= 1.0 ? 'pixelated' : ''
    }
    // resetZoom(){
    // }
    rotate(angle=0.0){
        this.ct.rotate(angle)
        this.ct.update()
    }
    resetRotation(){
        const tr0 = this.ct.translation
        const zm0 = this.ct.zoom
        const piv = this.ct.getTransformPivot()

        this.ct.resetTransform()
        const m = this.ct.getMatrix()
        m.translate_(-piv.x, -piv.y)
        m.scale_(zm0, zm0)
        m.translate_(piv.x, piv.y)
        this.ct.setMatrix(m)
        this.ct.update()

    }

    resetTransform(){
        this.ct.resetTransform()
        this.ct.update()
    }
}

main()


text:
<?php

namespace spec\GrumPHP\Locator;

use Gitonomy\Git\Diff\Diff;
use Gitonomy\Git\Diff\File;
use Gitonomy\Git\WorkingCopy;
use GrumPHP\Collection\FilesCollection;
use GrumPHP\Git\GitRepository;
use GrumPHP\Locator\ChangedFiles;
use GrumPHP\Util\Filesystem;
use GrumPHP\Util\Paths;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Prophecy\Prophet;

class ChangedFilesSpec extends ObjectBehavior
{
    function let(GitRepository $repository, Filesystem $filesystem, Paths $paths)
    {
        $this->beConstructedWith($repository, $filesystem, $paths);
        $paths->makePathRelativeToProjectDir(Argument::type('string'))->will(
            function (array $arguments): string {
                return $arguments[0];
            }
        );
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(ChangedFiles::class);
    }

    protected function mockFile($name, $isRename = false, $isDelete = false)
    {
        $prophet = new Prophet();
        $file = $prophet->prophesize(File::class);
        $file->getName()->willReturn($name);
        $file->getNewName()->willReturn($name);
        $file->isRename()->willReturn($isRename);
        $file->isDeletion()->willReturn($isDelete);
        return $file->reveal();
    }

    function it_will_list_all_diffed_files(GitRepository $repository, Filesystem $filesystem, Diff $diff, WorkingCopy $workingCopy)
    {
        $changedFile = $this->mockFile('file1.txt');
        $movedFile = $this->mockFile('file2.txt', true);
        $deletedFile = $this->mockFile('file3.txt', false, true);

        $filesystem->exists('file1.txt')->willReturn(true);
        $filesystem->exists('file2.txt')->willReturn(true);
        $filesystem->exists('file3.txt')->willReturn(false);

        $repository->getWorkingCopy()->willReturn($workingCopy);
        $workingCopy->getDiffStaged()->willReturn($diff);
        $diff->getFiles()->willReturn([$changedFile, $movedFile, $deletedFile]);

        $result = $this->locateFromGitRepository();
        $result->shouldBeAnInstanceOf(FilesCollection::class);
        $result[0]->getPathname()->shouldBe('file1.txt');
        $result[1]->getPathname()->shouldBe('file2.txt');
        $result->getIterator()->count()->shouldBe(2);
    }

    function it_will_not_list_non_existing_files(GitRepository $repository, Filesystem $filesystem, Diff $diff, WorkingCopy $workingCopy)
    {
        $changedFile = $this->mockFile('file1.txt');
        $filesystem->exists('file1.txt')->willReturn(false);

        $repository->getWorkingCopy()->willReturn($workingCopy);
        $workingCopy->getDiffStaged()->willReturn($diff);
        $diff->getFiles()->willReturn([$changedFile]);

        $result = $this->locateFromGitRepository();
        $result->shouldBeAnInstanceOf(FilesCollection::class);
        $result->getIterator()->count()->shouldBe(0);
    }

    function it_will_list_all_diffed_files_from_raw_diff_input(GitRepository $repository, Filesystem $filesystem)
    {
        $rawDiff = 'diff --git a/file.txt b/file.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9766475a4185a151dc9d56d614ffb9aaea3bfd42
--- /dev/null
+++ b/file.txt
@@ -0,0 +1 @@
+content
';

        $repository->createRawDiff($rawDiff)->willReturn(Diff::parse($rawDiff));
        $filesystem->exists('file.txt')->willReturn(true);

        $result = $this->locateFromRawDiffInput($rawDiff);
        $result->shouldBeAnInstanceOf(FilesCollection::class);
        $result[0]->getPathname()->shouldBe('file.txt');
        $result->getIterator()->count()->shouldBe(1);
    }
}

redpajama_set_name: RedPajamaGithub


text: module.exports = require('./bus');


text:
$here = $PSScriptRoot

$modulePath = "$here\..\..\.."
$moduleName = Split-Path -Path $modulePath -Leaf

InModuleScope $moduleName {
    $eseConnection = [DSCPullServerESEConnection]::new()
    $eseConnection.Index = 1

    $sqlConnection = [DSCPullServerSQLConnection]::new()
    $sqlConnection.Active = $true
    $sqlConnection.Index = 2

    $mdbConnection = [DSCPullServerMDBConnection]::new()
    $mdbConnection.Index = 3

    $script:DSCPullServerConnections = [System.Collections.ArrayList]::new()
    [void] $script:DSCPullServerConnections.Add($eseConnection)
    [void] $script:DSCPullServerConnections.Add($sqlConnection)
    [void] $script:DSCPullServerConnections.Add($mdbConnection)

    Describe Get-DSCPullServerAdminConnection {
        It 'Should return all connection types when no specific type is specified' {
            $result = Get-DSCPullServerAdminConnection
            $result | Should -HaveCount 3
            $result.Type | Should -Be @('ESE', 'SQL', 'MDB')
        }

        It 'Should return only SQL connection type when specified' {
            $result = Get-DSCPullServerAdminConnection -Type SQL
            $result | Should -HaveCount 1
            $result.Type | Should -Be 'SQL'
        }

        It 'Should return only ESE connection type when specified' {
            $result = Get-DSCPullServerAdminConnection -Type ESE
            $result | Should -HaveCount 1
            $result.Type | Should -Be 'ESE'
        }

        It 'Should return only MDB connection type when specified' {
            $result = Get-DSCPullServerAdminConnection -Type MDB
            $result | Should -HaveCount 1
            $result.Type | Should -Be 'MDB'
        }

        It 'Should return only correct index connection when specified' {
            $result = Get-DSCPullServerAdminConnection -Index 2
            $result | Should -HaveCount 1
            $result.Type | Should -Be 'SQL'
        }

        It 'Should return only active connection when specified' {
            $result = Get-DSCPullServerAdminConnection -OnlyShowActive
            $result | Should -HaveCount 1
            $result.Type | Should -Be 'SQL'
        }

        It 'Should return nothing when active connection specified and type is ESE which is not active' {
            $result = Get-DSCPullServerAdminConnection -OnlyShowActive -Type ESE
            $result | Should -HaveCount 0
        }
    }
}


text:
package org.artifactory.model.xstream.fs;

import org.artifactory.checksum.ChecksumInfo;
import org.artifactory.checksum.ChecksumsInfo;
import org.artifactory.md.MetadataInfo;
import org.artifactory.md.MutableMetadataInfo;
import org.artifactory.mime.NamingUtils;
import org.artifactory.repo.InternalRepoPathFactory;
import org.artifactory.repo.RepoPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author yoavl
 */
public class MetadataInfoImpl implements MutableMetadataInfo {
    private static final Logger log = LoggerFactory.getLogger(MetadataInfoImpl.class);

    private final RepoPath repoPath;
    private String name;
    private long created;
    private long lastModified;
    private String lastModifiedBy;
    private long size;
    private ChecksumsInfo checksumsInfo;

    public MetadataInfoImpl(RepoPath parentRepoPath, String metadataName) {
        this.repoPath = getMetadataRepoPath(parentRepoPath, metadataName);
        this.name = metadataName;
        this.checksumsInfo = new ChecksumsInfo();
    }

    public MetadataInfoImpl(RepoPath repoPath) {
        this.repoPath = repoPath;
        this.name = NamingUtils.getMetadataName(repoPath.getPath());
        this.checksumsInfo = new ChecksumsInfo();
    }

    public MetadataInfoImpl(MetadataInfo copy) {
        this.repoPath = copy.getRepoPath();
        this.name = copy.getName();
        this.created = copy.getCreated();
        this.lastModified = copy.getLastModified();
        this.lastModifiedBy = copy.getLastModifiedBy();
        this.size = copy.getSize();
        this.checksumsInfo = new ChecksumsInfo(copy.getChecksumsInfo());
    }

    @Override
    public RepoPath getRepoPath() {
        return repoPath;
    }

    @Override
    public ChecksumsInfo getChecksumsInfo() {
        return checksumsInfo;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public long getCreated() {
        return created;
    }

    @Override
    public void setCreated(long created) {
        this.created = created;
    }

    @Override
    public long getLastModified() {
        return lastModified;
    }

    @Override
    public void setLastModified(long lastModified) {
        this.lastModified = lastModified;
    }

    @Override
    public String getLastModifiedBy() {
        return lastModifiedBy;
    }

    @Override
    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    @Override
    public String getSha1() {
        return checksumsInfo.getSha1();
    }

    @Override
    public String getMd5() {
        return checksumsInfo.getMd5();
    }

    @Override
    public Set<ChecksumInfo> getChecksums() {
        return checksumsInfo.getChecksums();
    }

    @Override
    public void setChecksums(Set<ChecksumInfo> checksums) {
        checksumsInfo.setChecksums(checksums);
    }

    @Override
    public long getSize() {
        return size;
    }

    @Override
    public void setSize(long size) {
        this.size = size;
    }

    @Override
    public String toString() {
        return "MetadataInfo{repoPath=" + repoPath + '}';
    }

    private RepoPath getMetadataRepoPath(RepoPath parentRepoPath, String metadataName) {
        String path = parentRepoPath.getPath();
        boolean alreadyMetadataPath = NamingUtils.isMetadata(path);
        if (alreadyMetadataPath) {
            log.warn("Path {} is already a metadata path.", path);
        }
        //TODO: [by yl] Evaluate the impact of normalizing the path to use the standard metadata format (a.jar#mdname)

        return InternalRepoPathFactory.create(parentRepoPath.getRepoKey(),
                alreadyMetadataPath ? path : NamingUtils.getMetadataPath(path, metadataName));
    }
}


text:
package cc.ronch.util;

import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

public class RUCameraSufaceView extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private boolean isPreview = false;

    private RUCameraSufaceView(Context context) {
        super(context);
    }

    public RUCameraSufaceView(Context context, Camera camera) {
        super(context);
        mCamera = camera;
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
            isPreview = true;
        } catch (IOException e) {
            RULog.d("Error setting camera preview: " + e.getMessage());
        }
    }

    /**
     * 当预览变化或旋转时触发该事件,在旋转或改变预览视图大小前先停止预览,设置好后再重新开启预览
     *
     * @param holder SurfaceView的内容处理器
     * @param format 格式
     * @param w      宽度
     * @param h      高度
     */
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        if (mHolder.getSurface() == null) {
            return;
        }

        try {
            if (mCamera != null) {
                mCamera.stopPreview();

//                mCamera.setPreviewDisplay(mHolder);
//
//                Camera.Parameters parameters = mCamera.getParameters();
//                parameters.setPreviewSize(w, h);
//                parameters.setPreviewFormat(ImageFormat.NV21);
//                parameters.setRecordingHint(true);
//                parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
//                parameters.setAntibanding(Camera.Parameters.ANTIBANDING_AUTO);
//                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
//                parameters.set("contrast", "high");
//                parameters.set("brightness", "high");
//                parameters.set("brightness_value", "3");
//                parameters.set("shutter-value", "100");
//                RUCamera.Iso iso = RUCamera.getCameraIso(parameters);
//                parameters.set(iso.key, iso.allowedValues.get(iso.allowedValues.size() - 1));
//                parameters.setPictureSize(480, 320);
//                parameters.set("video-size", "480x320");
//                parameters.set("dynamic-frame-rate", "false");
//                parameters.setPreviewFrameRate(60);
//                parameters.setPreviewFpsRange(4, 10);
//
//                mCamera.setParameters(parameters);

                mCamera.startPreview();
            }
        } catch (Exception e) {
            RULog.d("Error starting camera preview: " + e.getMessage());
        }
    }

    /**
     * 视图被销毁时执行的事件,执行相机的停止预览与释放
     *
     * @param holder SurfaceView的内容处理器
     */
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            if (isPreview) {
                mCamera.stopPreview();
            }
            mCamera.release();
            mCamera = null;
        }
    }

}


text:
// AUTO-GENERATED: do not modify this file directly.
// If you need to make changes, modify generate-fp.ts (if necessary), then open a terminal in types/lodash/scripts, and do:
// npm run fp

interface Defaults {
    /**
     * Assigns own enumerable properties of source object(s) to the destination object for all destination
     * properties that resolve to undefined. Once a property is set, additional values of the same property are
     * ignored.
     *
     * Note: This method mutates object.
     *
     * @param object The destination object.
     * @param sources The source objects.
     * @return The destination object.
     */
    (): Defaults;
    /**
     * Assigns own enumerable properties of source object(s) to the destination object for all destination
     * properties that resolve to undefined. Once a property is set, additional values of the same property are
     * ignored.
     *
     * Note: This method mutates object.
     *
     * @param object The destination object.
     * @param sources The source objects.
     * @return The destination object.
     */
    <TSource>(source: TSource): Defaults1x1<TSource>;
    /**
     * Assigns own enumerable properties of source object(s) to the destination object for all destination
     * properties that resolve to undefined. Once a property is set, additional values of the same property are
     * ignored.
     *
     * Note: This method mutates object.
     *
     * @param object The destination object.
     * @param sources The source objects.
     * @return The destination object.
     */
    <TObject, TSource>(source: TSource, object: TObject): TSource & TObject;
}
interface Defaults1x1<TSource> {
    /**
     * Assigns own enumerable properties of source object(s) to the destination object for all destination
     * properties that resolve to undefined. Once a property is set, additional values of the same property are
     * ignored.
     *
     * Note: This method mutates object.
     *
     * @param object The destination object.
     * @param sources The source objects.
     * @return The destination object.
     */
    (): Defaults1x1<TSource>;
    /**
     * Assigns own enumerable properties of source object(s) to the destination object for all destination
     * properties that resolve to undefined. Once a property is set, additional values of the same property are
     * ignored.
     *
     * Note: This method mutates object.
     *
     * @param object The destination object.
     * @param sources The source objects.
     * @return The destination object.
     */
    <TObject>(object: TObject): TSource & TObject;
}

declare const defaults: Defaults;
export = defaults;


text:
using CudaManager;
using CudaManager.Manager;
using CudaManager.Matrix;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MonteCarlo
{
    public class CHestonEngine : CEngine
    {
        public CHestonEngine(SModelData input) : base(input)
        {
            if (input.beta > 1 || input.beta < 0)
                throw new ArgumentOutOfRangeException();
            if (input.csi < 0)
                throw new ArgumentOutOfRangeException();
            if (input.kappa < 0)
                throw new ArgumentOutOfRangeException();
            if (input.rho < -1 || input.rho > 1)
                throw new ArgumentOutOfRangeException();
            if (input.theta < 0)
                throw new ArgumentOutOfRangeException();
        }

        public override void UpdatePath()
        {
            base.UpdatePath();

            if (volPath_s == null || volPath_s.size != input.nScenarios)
                volPath_s = new CVector(input.nScenarios, EArchitectureType.Device, EFloatingPointPrecision.Single, "volPath_s");

            if (path_s.size != input.nScenarios)
                path_s = new CVector(input.nScenarios, EArchitectureType.Device, EFloatingPointPrecision.Single, "path_s");
            path_s.SetUniform(input.S);
            volPath_s.SetUniform(Math.Pow(input.sigma, 1.0 / input.beta));

            float dt = input.T / input.nTimes;
            CDeviceManager.UpdatePathHeston(path_s, volPath_s, scenarios_st, input.nScenarios, input.nTimes, input.r,
                input.beta, input.kappa, input.theta, input.csi, input.rho, dt);
        }

        public CVector volPath_s;
    }
}


text:
import {
  MessageBus,
  MessageBusSource,
  MessageBusSink,
  SourceListener
} from "angular2/src/web-workers/shared/message_bus";
import {Type, BaseException} from "angular2/src/facade/lang";
import {Binding} from "angular2/di";

import {bootstrapWebworkerCommon} from "angular2/src/web-workers/worker/application_common";
import {ApplicationRef} from "angular2/src/core/application";
import {Injectable} from "angular2/di";

/**
 * Bootstrapping a Webworker Application
 *
 * You instantiate the application side by calling bootstrapWebworker from your webworker index
 * script.
 * You can call bootstrapWebworker() exactly as you would call bootstrap() in a regular Angular
 * application
 * See the bootstrap() docs for more details.
 */
export function bootstrapWebworker(
    appComponentType: Type, componentInjectableBindings: List<Type | Binding | List<any>> = null):
    Promise<ApplicationRef> {
  var bus: WorkerMessageBus =
      new WorkerMessageBus(new WorkerMessageBusSink(), new WorkerMessageBusSource());

  return bootstrapWebworkerCommon(appComponentType, bus, componentInjectableBindings);
}

@Injectable()
export class WorkerMessageBus implements MessageBus {
  sink: WorkerMessageBusSink;
  source: WorkerMessageBusSource;

  constructor(sink: WorkerMessageBusSink, source: WorkerMessageBusSource) {
    this.sink = sink;
    this.source = source;
  }
}

export class WorkerMessageBusSink implements MessageBusSink {
  public send(message: Object) { postMessage(message, null); }
}

export class WorkerMessageBusSource implements MessageBusSource {
  private listenerStore: Map<int, SourceListener>;
  private numListeners: int;

  constructor() {
    this.numListeners = 0;
    this.listenerStore = new Map<int, SourceListener>();
  }

  public addListener(fn: SourceListener): int {
    addEventListener("message", fn);
    this.listenerStore[++this.numListeners] = fn;
    return this.numListeners;
  }

  public removeListener(index: int): void {
    removeEventListener("message", this.listenerStore[index]);
    this.listenerStore.delete(index);
  }
}


text:
module.exports = function(grunt) {
  'use strict';

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js',
        '<%= nodeunit.tests %>'
      ],
      options: {
        jshintrc: '.jshintrc'
      }
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      test: ['tmp']
    },

    // Configuration to be run (and then tested).
    yuidoc: {
      compileA: {
        'name': 'Grunt Test',
        'description': 'Grunt Test Description',
        'version': '1.2.1',
        'url': 'http://test.com/',
        options: {
          paths: 'test/fixtures/app/',
          outdir: 'tmp/yuidoca/'
        }
      },

      compileB: {
        'name': 'Grunt Test',
        'description': 'Grunt Test Description',
        'version': '1.2.1',
        'url': 'http://test.com/',
        options: {
          paths: [
            'test/fixtures/app/',
            'test/fixtures/otherapp/'
          ],
          outdir: 'tmp/yuidocb/'
        }
      },

      compileC: {
        'name': "Grunt Test <%= 'Title' %>",
        'description': 'Description Text for <%= pkg.name %>',
        'version': '<%= pkg.version %>',
        'url': 'http://test.com/',
        options: {
          paths: 'test/fixtures/app/',
          outdir: 'tmp/yuidocc/'
        }
      }
    },

    // Unit tests.
    nodeunit: {
      tests: ['test/*_test.js']
    }
  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');
  grunt.loadNpmTasks('grunt-contrib-internal');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('test', ['clean', 'yuidoc', 'nodeunit']);

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'test', 'build-contrib']);
};


text:
layout: post
title: Robber Board
categories: robot
series: Custom PCBs
excerpt:
tags: [robot, PCB, SMD, ATtiny84, HM-11, BLE]
image:
    feature: Robber-T_v01.PNG
comments: true
custom_css:
custom_js:
---

## The Robber Board

This board originated with a request from an LPC who was practicing [EMDR](https://www.emdr.com/what-is-emdr/) and wanted to upgrade his feedback machine.  He had requested it be wireless and provide both haptic and visual feedback.  The whole thing fell apart when he sent me an NDA which seemed typical of real professional level projects.  However, it would have prohibited me from sharing anything I discovered, and given the amount I could have made from it, well, it just wasn't worth it.  I thought I'd finish the project and share with everyone, since sharing is the greatest form of payment.

Here are some of the features of the board:

1.  OTA Uploading to an ATtiny84
2.  An on board charing circuit with load sharing capability ([thanks Zak Kemble](http://blog.zakkemble.co.uk/a-lithium-battery-charger-with-load-sharing/))
3.  Two RGB LEDs to provide visual feedback.
4.  One unidirectional, motor-driver meant to control a vibration motor.
5.  Three free pins

My purpose in completing the board is to continue to test my TinySafeBoot BLE uploader:

[Lumi(v2)](https://github.com/Ladvien/Lumi_Windows_App)

I'm also in the process of re-writing the uploader to be cross platform, targetting Android, iOS, and Windows 10\.  It'll be a feat, but I'm thinking I'll center the project around Dropbox.  The consumer would:

1.  Compile an AVR binary using Arduino, Atmel Studio, or AVRDude
2.  Save the binary in Dropbox
3.  Lumi3 will then connect to the target device, this could be done from Android, iOS, or Windows.
4.  Lumi3 would then pull the binary from Dropbox and upload it using the TinySafeBootoader.

Not sure if I can pull it off; wish me luck.  And feel free to follow the code base here:

[Lumi3](https://github.com/Ladvien/Lumi3)

![](/images/Robber_PCB_v1.JPG)

## Design Info

[Robber_Schematic.pdf](http://ladvien.com/images/Robber_Schematic.pdf)

![Robber v01 Schematic.PNG](/images/Robber_v01_Schematic.PNG)

![Robber v01 T Solder Guide.PNG](/images/Robber_v01_T_Solder_Guide.PNG)

![Robber v01 B Solder Guide.PNG](/images/Robber_v01_B_Solder_Guide.PNG)

## HM-11 Setup

 A few commands which are required to make the OTA process work correctly

1. AT+AFTC3FF  --  This command sets all IO pins to go HIGH after connection.  This isn't needed for OTA but, since the AVR would be pulled low as soon as it connects, any sketch you have running would immediately be shutdown as the AVR's RESET is pulled low.
2. AT+BEFC3FF -- This is like the AFTC command, however, it set IO pins HIGH after the HM-11 is powered.  For the Robber, if this is not setup the AVR will stay reset until connected.  Initially, I didn't notice this and spent a lot of time trying to figure out what the AVR wouldn't respond.  Sigh.
3. AT+MODE2 -- this put the HM-11 into "Remote" mode.  This will allow AT commands to be sent to the HM-11 after it has been connected, through the BLE connection.  This is what allows the commands to be sent to remotely toggle the PIO connected to the AVR's RESET.

A few commands which I _think_ make the connection more reliable:

1. AT+BAUD2 -- this sets the communication rate between the HM-11 and AVR to 38400\.  After testing, this is about the highest speed ATtiny's can for the TSB auto-baud.
2. AT+POWE3 -- this raises the radio gain of the HM-11\.  Power-convseration is not the friend of prototyping.
3. AT+GAIN1 -- I think this raises the gain on the HM-11's RX?  I'm not sure.  The documentation is a little crappy.

## Debugging First Iteration

The boards came in from OSHPark.  They look sharp--but, it's time to test the board and see what mistakes were made.

Circuits tested:

|Circuit Abstraction|Tested|Pass|Description of Issues|
| Mini USB | Yes | 100% | |
| MCP73831 | Yes | 100% | Battery Charges.  Used a 2k resistor for the charge rate. |
| MCP73831 - LED Charge Indicator | Yes | 100% |
| Load Sharing | Yes | 100% | Shesh, I love this circuit.  Thanks Zak. |
| LM1117 -- 3.3v | Yes | 50% | The OUTPUT voltage was calculated based upon 5V INPUT, however, when the USB connection is removed the INPUT voltage is equal to VBAT voltage.  In short, the output is ~3.29v when connected to USB and 2.9v when running on battery.  This will drop even more when the battery discharges.  I've selected a fixed VREG to drop in later ([NCP186-AMX330TAG](http://www.mouser.com/Search/ProductDetail.aspx?R=NCP186AMX330TAGvirtualkey58410000virtualkey863-NCP186AMX330TAG)). |
| Tacit Reset Switch | Yes | 75% | The reset line was being pulled HIGH with a 10k resistor.  This might have been causing issues.  It was removed for the time and will be re-added if needed. |
| ATtiny84 -- Wireless UART Connection | Yes | 85% | I cannot get the ATtiny84's TSB bootloader to respond.  I've tried both wireless TSB HELLO and jumpering directly to the UART.  No response.  I'm currently waiting on a [SOIC-14 ATtiny AVR programme](http://www.ebay.com/itm/250670056425?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT)r to arrive to more easily troubleshoot the ATtiny84 chip. One thing I'd like to test is the BROWNOUT fuse setting.  It seems like this fuse was set different than usual.  Also, testing the UART on the naked chip would be helpful. Update:  Ok, not sure what happened to the chip, but apparently I killed it?  Regardless, when a new one was programmed and swapped out using a heat gun--the new one worked like a charm. I've provided more details below.|
| Battery Voltage Monitor | No | | |
| RGB LEDs | No | | |
| HM-11 Reset of ATtiny84 | Yes | 0% | BAD IDEA! I've wasted a lot of time because the program I uploaded was sending the HM-11 RESET pin HIGH and LOW.  This made it difficult to re-program, since the HM-11 would lose connection before the upload finished.  Dear lord, what was I thinking? |
| Vibration Motor | Yes | 100% | It doesn't work too well when powered by USB alone.  Probably need to get a lower powered vibration motor.  Also, I don't like the wire connections.  They get all tangled and pull off.  It'd be better with a PCB mounted vibration motor. |

![IMG_1616_0.JPG](/images/IMG_1616_0.JPG)

![IMG_1617_0.JPG](/images/IMG_1617_0.JPG)

## Debugging Wireless UART Connection

When the ATtiny84 and HM-11 combination were tested using Lumi the Robber board failed to handshake.  It was disheartening.  The connections were double checked, routing was checked, jumper wires soldered on, ATtiny84 fuses checked, even checked the TSB build used. Nothing.  Frankly, the reason it was such a problem to troubleshoot was lack of foresight in prototyping.  Here are a couple things which should be in every prototype:

1.  Jumpers.  This is especially true if there is a UART connection.  They just beg to be miswired.  By providing solder-jumpers the UART connection can be tested a device at a time; ATtiny84, then, HM-11
2.  Test points.  Gah, this is a no-brainer, but in inevitably there end up being leads soldered on at the most precarious place.

Back to the Robber board issue.  I got wore out trying to do stuff like this:

![2017-01-22 14.16.09.jpg](/images/2017-01-22_14.16.09.jpg)

The wires kept popping off, they'd need to be resoldered, then pop off again.  Finally, I broke down and bought a [SOIC-14 AVR Programmer](http://www.ebay.com/itm/ATtiny24A-SSU-ATtiny24-ATtiny44-ATtiny84-SOIC14-150-mil-AVR-Programmer-Adapter-/250670056425?hash=item3a5d1983e9:g:ijAAAOxyyFhTdw1-).  _Dear lord,_ where has this thing been all of my life?  Instead of taking two hours of setting up a chip, wiring leads, and programming it, I was done in about 10 minutes.  If you like SOIC ATtiny85/84 chips, get one!

Here's an action shot!
![2017-02-01 08.56.38.jpg](/images/2017-02-01_08.56.38.jpg)

## SMD RGB LED

There was trouble testing the SMD RGB LEDs.  During the solder-desoldering process the voltage traces for the green LED came off the board.  However, this shouldn't affect the second LED--but for some reason the green channel on the other LED is the only one working properly.  The red and blue do not seem to be lighting up.

I thought I'd take a moment and diagram the SMD RGBs I'm using, as I can't ever seem to get directionality correct.
![SMD_RGB_Closeup.jpg](/images/SMD_RGB_Closeup.jpg)

# 2017-12-24 -- v3

I've almost finished testing the Robber board v3.  A few changes:

### ISP Key

I've added a special ISP header to the board.  It works with [Tiny AVR-ISP pogo-pin programming adapter](https://www.tindie.com/products/madworm/tiny-avr-isp-pogo-pin-programming-adapter/)

It's a bit of a pain to solder, but it's pretty darn sweet once it's in place.  Of course, the header is backwards.  More on that later.

![](/images/isp-key.png)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is part of dependency-check-core.

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.

Copyright (c) 2017 The OWASP Foundation. All Rights Reserved.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.owasp.test</groupId>
    <artifactId>test-broken-suppression-files</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- These can be replaced by any other vulnerable dependency -->
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.4.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.owasp</groupId>
                <artifactId>dependency-check-maven</artifactId>
                <configuration>
                    <suppressionFiles>
                        <suppressionFile>${project.basedir}/broken-suppression.xml</suppressionFile>
                    </suppressionFiles>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
This rule suggests using a function type instead of an interface or object type literal with a single call signature.

Examples of **incorrect** code for this rule:

```ts
interface Foo {
  (): string;
}
```

```ts
function foo(bar: { (): number }): number {
  return bar();
}
```

```ts
interface Foo extends Function {
  (): void;
}
```

```ts
interface MixinMethod {
  // returns the function itself, not the `this` argument.
  (arg: string): this;
}
```

Examples of **correct** code for this rule:

```ts
interface Foo {
  (): void;
  bar: number;
}
```

```ts
function foo(bar: { (): string; baz: number }): string {
  return bar();
}
```

```ts
interface Foo {
  bar: string;
}
interface Bar extends Foo {
  (): void;
}
```

```ts
// returns the `this` argument of function, retaining it's type.
type MixinMethod = <TSelf>(this: TSelf, arg: string) => TSelf;
// a function that returns itself is much clearer in this form.
type ReturnsSelf = (arg: string) => ReturnsSelf;
```

```ts
// multiple call signatures (overloads) is allowed:
interface Overloaded {
  (data: string): number;
  (id: number): string;
}
// this is equivelent to Overloaded interface.
type Intersection = ((data: string) => number) & ((id: number) => string);
```

## When Not To Use It

If you specifically want to use an interface or type literal with a single call signature for stylistic reasons, you can disable this rule.

## Further Reading

- TSLint: [`callable-types`](https://palantir.github.io/tslint/rules/callable-types/)


text:
/*
 *  You are free to use this code anywhere, copy, modify and redistribute at your
 *  own risk.
 *  Your are solely responsibly for any damage that may occur by using this code.
 *
 *  This code is not tested for all boundary conditions. Use it at your own risk.
 *
 *  Original code: http://www.codenlearn.com/2011/07/simple-selection-sort.html
 */
package com.zhokhov.interview.sorting;

import static com.zhokhov.interview.util.Console.*;

/**
 * @author Alexey Zhokhov
 */
public class SelectionSort {

    private int COMPARISONS_COUNT;
    private int SWAPS_COUNT;
    private int LOOP_COUNT;

    public void sort(int array[]) {
        COMPARISONS_COUNT = 0;
        SWAPS_COUNT = 0;
        LOOP_COUNT = 0;

        // Start from first
        for (int index = 0; index < array.length; index++) {
            LOOP_COUNT++;
            ____cyan("\n--------\nindex: " + index);

            // find the next smallest element
            int minIndex = findNextSmallestElement(index, array);

            ____grey("found smallest element index: " + minIndex);

            SWAPS_COUNT++;
            ____blue("Swapping: " + index + " and " + minIndex);

            // Swap code
            int temp = array[minIndex];

            array[minIndex] = array[index];
            array[index] = temp;

            __red("==> ");
            __dump(array);
        }
    }

    /*
     * Finds the smallest element starting startIndex
     *
     * @ returns the index of the smallest element.
     */
    private int findNextSmallestElement(int startIndex, int array[]) {
        int minIndex = startIndex;

        int value = array[startIndex];

        for (int i = startIndex; i < array.length; i++) {
            LOOP_COUNT++;
            COMPARISONS_COUNT++;
            if (value > array[i]) {
                minIndex = i;
                value = array[minIndex];
            }
        }

        return minIndex;
    }

    public static void main(String[] args) {
        int array[] = {7, 1, 8, 2, 0, 12, 10, 6, 5, 3};

        __yellow("\nNew array: ");
        __dump(array);

        System.out.println("\nSorting");

        SelectionSort selectionSort = new SelectionSort();
        selectionSort.sort(array);

        __green("\nResult: ");
        __dump(array);

        ____grey("\nStatistics");
        __green("  Comparisons: ");
        System.out.print(selectionSort.COMPARISONS_COUNT);
        __green("\n  Swaps: ");
        System.out.print(selectionSort.SWAPS_COUNT);
        __green("\n  Loops: ");
        System.out.println(selectionSort.LOOP_COUNT);
    }

}


text:
You want a canvas that fills a div in at least one dimension,
as the browser window is resized.

# Solution

We are going to use `create-class` and a Reagent `atom` to listen for
events necessary to ensure that the canvas within a div fills the
containing div. As the window changes size,

*Steps*

1. Create a new project
2. Add CSS to `resources/public/index.html`
3. Add an atom and event handler for tracking the size of the window
4. Create a `div-with-canvas` component
5. Create a function to draw the contents of the canvas
6. Refer to the `div-with-canvas` component in the `home` definition.

#### Step 1: Create a new project

```
$ lein new rc canvas-fills-div
```

#### Step 2: Add CSS to `resources/public/index.html`

Add some simple css styling to get a div that fills the window. Most
of this is here to ensure that the `with-canvas` div fills all
available vertical space. If all you need is a div/canvas that fills
the width, all but the `display: block` can be removed.

```html
<head>
  <style>
    html, body {
      margin:0;
      padding:0;
      height:100%;
    }

    div#app {
        height: 100%;
    }

    div.with-canvas {
        margin: 0px;
        padding: 0px;
        border: 0px;

        height: 100%;
    }

    div.with-canvas canvas {
        display: block;
    }
  </style>
</head>
```

#### Step 3: Add an atom and event handler for tracking the size of the window

Define a Reagent atom to track the current width of the window.  The
canvas component will refer to this atom so that it's re-rendered as the
window size changes.

```clojure
(def window-width (reagent/atom nil))
```

Define an event handler to update `window-width` when the window
resizes. The size of the canvas is taken from the enclosing div, so
the main point of this is that the atom is updated rather than the
specific value.

```clojure
(defn on-window-resize [ evt ]
  (reset! window-width (.-innerWidth js/window)))
```

Add `on-window-resize` as a window event listener for resize events.

```clojure
(defn ^:export main []
  (reagent/render [home]
                  (.getElementById js/document "app"))
  (.addEventListener js/window "resize" on-window-resize))
```

#### Step 4: Create a `div-with-canvas` component

Navigate to `src/cljs/div_fills_canvasc/core.cljs`. This uses
`create-class` because we need to capture the DOM node at the time the
component is mounted as well as render into the canvas when the
component updates.

```clojure
(defn div-with-canvas [ ]
  (let [dom-node (reagent/atom nil)]
    (reagent/create-class
     {:component-did-update
      (fn [ this ]
        (draw-canvas-contents (.-firstChild @dom-node)))

      :component-did-mount
      (fn [ this ]
        (reset! dom-node (reagent/dom-node this)))

      :reagent-render
      (fn [ ]
        @window-width ;; Trigger re-render on window resizes
        [:div.with-canvas
         ;; reagent-render is called before the compoment mounts, so
         ;; protect against the null dom-node that occurs on the first
         ;; render
         [:canvas (if-let [ node @dom-node ]
                    {:width (.-clientWidth node)
                     :height (.-clientHeight node)})]])})))
```

#### Step 5: Create a function to draw the contents of the canvas

```clojure
(defn draw-canvas-contents [ canvas ]
  (let [ ctx (.getContext canvas "2d")
        w (.-clientWidth canvas)
        h (.-clientHeight canvas)]
    (.beginPath ctx)
    (.moveTo ctx 0 0)
    (.lineTo ctx w h)
    (.moveTo ctx w 0)
    (.lineTo ctx 0 h)
    (.stroke ctx)))
```

#### Step 6: Refer to the `div-with-canvas` component in the `home` definition.

```clojure
(defn home []
  [div-with-canvas])
```

# Usage

Compile cljs files.

```
$ lein clean
$ lein cljsbuild once prod
```

Open `resources/public/index.html`.


text:
passport-google-googleapis
==========================

Implementation of Google's OAuth Connect endpoints for PassportJS


text:
@interface UILabel (Convenience)

+ (instancetype)ybzy_labelWithText:(NSString*)text andTextColor:(UIColor*)textColor andFontSize:(CGFloat)fontSize;

@end


text:
package br.com.moip.helpers;

import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class PayloadFactory {

    /**
     * This method was created to simplify the construction of request payloads. However, the use of this method
     * shouldn't be compulsory and you can also use plain old Maps.
     *
     * @param   entries
     *          {@code Map.Entry<String, Object>} the entries that will describe the request payload.
     *
     * @return  {@code Map<String, Object>}
     */
    @SafeVarargs
    public static Map<String, Object> payloadFactory(Map.Entry<String, Object>... entries) {
        Map<String, Object> map = new HashMap<>();

        for (Map.Entry<String, Object> entry : entries)
            map.put(entry.getKey(), entry.getValue());

        return Collections.unmodifiableMap(map);
    }

    /**
     * This is a auxiliary method used to load the {@code Map} returned from {@code payloadFactory}. The usage
     * is similar to {@code Map} interaction, but its simplify the dynamic usage of {@code payloadFactory}.
     *
     * @param   key
     *          {@code String} the attribute key.
     *
     * @param   value
     *          {@code Object} the attribute value.
     *
     * @return  {@code Map.Entry<String, Object>}
     */
    public static Map.Entry<String, Object> value(String key, Object value) {
        return new AbstractMap.SimpleImmutableEntry<>(key, value);
    }
}


text:
'use strict';

// MODULES //

var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );

// MAIN //

/**
* Tests if a value is a square triangular number.
*
* ## Notes
*
* -   Return values are not reliable for numbers greater than `1125899906842624`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a square triangular number
*
* @example
* var bool = isSquareTriangularNumber( 36.0 );
* // returns true
*
* @example
* var bool = isSquareTriangularNumber( new Number( 36.0 ) );
* // returns true
*
* @example
* var bool = isSquareTriangularNumber( 3.14 );
* // returns false
*
* @example
* var bool = isSquareTriangularNumber( -5.0 );
* // returns false
*
* @example
* var bool = isSquareTriangularNumber( null );
* // returns false
*/
function isSquareTriangularNumber( value ) {
	return ( isPrimitive( value ) || isObject( value ) );
}

// EXPORTS //

module.exports = isSquareTriangularNumber;


text:
void printHelp()
{
	std::cout << "Usage: file_writer NAME TYPE NUMITEMS" << std::endl;
	std::cout << "writes NUMITEMS many variables of TYPE to the file NAME" << std::endl;
	std::cout << std::endl << "NAME\t\tthe name of the file file_writer will output." << std::endl;
	std::cout << "TYPE\t\tthe type of file to be written. Choices: random sequential" << std::endl;
	std::cout << "NUMITEMS\tthe number of records being written to the file." << std::endl;
	std::cout << std::endl << "The record data type of file must be set in writer_config.hpp before the file_writer is called.";
	std::cout << " Example:" << std::endl << "\t./file_writer outfile.dat sequential 6000" << std::endl;
	std::cout << "This would create a file called outfile.dat of 6000 records (of the type defined in writer_config.hpp, let's say int) in ascending, sequential order" << std::endl;

	std::cout << std::endl << "Help usage: file_writer help" << std::endl;
}

int main(int argc, char **argv)
{
	if (argc == 2 && strncmp(argv[1],"help",4) == 0) {
		printHelp();
		exit(EXIT_SUCCESS);
	} else if (argc != 4) {
		printHelp();
		exit(EXIT_FAILURE);
	}

    try {
		long num_entries;
		num_entries = atol(argv[3]);

		if (strncmp(argv[2],"random",6) == 0) {
			writeUnorderedFile(argv[1], num_entries);
		} else if (strncmp(argv[2],"sequential",10) == 0) {
			writeOrderedFile(argv[1], num_entries);
		} else {
			std::cout << "The choices for the type are either <random> or <sequential>, without the <>" << std::endl;
			std::cout << std::endl << "Help usage: file_writer help" << std::endl;
			exit(EXIT_FAILURE);
		}
    }
	catch (const char* c) {
        perror(c);
        exit(EXIT_FAILURE);
    }

    return 0;
}


text:
//
//  SA_DiceEvaluator.h
//
//	Copyright (c) 2016 Said Achmiz.
//
//	This software is licensed under the MIT license.
//	See the file "LICENSE" for more information.

#import <Foundation/Foundation.h>

@class SA_DiceBag;
@class SA_DiceExpression;

/************************************************/
#pragma mark SA_DiceEvaluator class declaration
/************************************************/

@interface SA_DiceEvaluator : NSObject

/************************/
#pragma mark - Properties
/************************/

@property NSUInteger maxDieCount;
@property NSUInteger maxDieSize;

/****************************/
#pragma mark - Public methods
/****************************/

-(SA_DiceExpression *) resultOfExpression:(SA_DiceExpression *)expression;

@end


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

/**
\file

\brief non_base_dimension.cpp

\details
Another example of user-defined units with conversions.

Output:
@verbatim

//[non_base_dimension_output
//]

@endverbatim
**/

#include <iostream>

#include <boost/units/io.hpp>
#include <boost/units/conversion.hpp>
#include <boost/units/unit.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/physical_dimensions.hpp>
#include <boost/units/base_unit.hpp>
#include <boost/units/make_system.hpp>

namespace boost {

namespace units {

//[non_base_dimension_snippet_1

struct imperial_gallon_tag :
    base_unit<imperial_gallon_tag, volume_dimension, 1> { };

typedef make_system<imperial_gallon_tag>::type imperial;

typedef unit<volume_dimension,imperial> imperial_gallon;

struct us_gallon_tag : base_unit<us_gallon_tag, volume_dimension, 2> { };

typedef make_system<us_gallon_tag>::type us;

typedef unit<volume_dimension,us> us_gallon;

//]

} // namespace units

} // namespace boost

BOOST_UNITS_DEFINE_CONVERSION_FACTOR(boost::units::imperial_gallon_tag,
                                     boost::units::us_gallon_tag,
                                     double, 1.2009499255);

using namespace boost::units;

int main(void)
{
    quantity<imperial_gallon>   ig1(1.0*imperial_gallon());
    quantity<us_gallon>         ug1(1.0*us_gallon());

    quantity<imperial_gallon>   ig2(ug1);
    quantity<us_gallon>         ug2(ig1);

    return 0;
}


text:
@implementation NWIODemoViewController {
    IBOutlet UITextView *textView;
    IBOutlet UIButton *button;
    NWIODemo *demo;
    BOOL isDone;
}

#pragma mark - Object life cycle

- (id)initWithDemo:(NWIODemo *)_demo {
    self = [super init];
    if (self) {
        demo = _demo;
    }
    return self;
}

#pragma mark - View life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = demo.title;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [demo goWithDelegate:self];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [demo abort];
}

#pragma mark - Events

- (IBAction)run {
    button.enabled = NO;
    if (isDone) {
        [demo goWithDelegate:self];
        textView.text = @"";
        isDone = NO;
    } else {
        [demo.console input:@"<click>"];
    }
}

#pragma mark - NWIOConsole delegate

- (void)console:(NWIOConsole *)console received:(NSString *)text {
    textView.text = [textView.text stringByAppendingString:text];
    // scroll to bottom
    [textView scrollRangeToVisible:NSMakeRange(textView.text.length, 0)];
}

- (void)consoleWaitingForInput:(NWIOConsole *)console {
    button.enabled = YES;
}

- (void)consoleFinished:(NWIOConsole *)console {
    button.enabled = YES;
    isDone = YES;
}

@end


text:
A PDF of the slides is [available here](https://github.com/craigatk/tdd-spock-slides/blob/master/tdd-spock-slides.pdf)

## Presentation Setup

1) Install [Node](http://nodejs.org/download/)

2) Install [Grunt](http://gruntjs.com/getting-started#installing-the-cli)

3) Install dependencies with ```npm install```

## Running Presentation

```grunt serve```

The slides will be available at [http://localhost:8000](http://localhost:8000)

## Content

The presentation is based on the [Reveal.js framework](https://github.com/hakimel/reveal.js/). Slides are in Markdown in ```slides.md```

## Generating PDF

To generate a PDF of the slides:

1) Run the presentation with ```grunt serve```

2) Open the presentation in Chrome

3) Append ?print-pdf to the URL [http://localhost:8000?print-pdf](http://localhost:8000?print-pdf)

4) Print to PDF from Chrome


text:
require 'rails_helper'

describe Invitations, "#reject" do
  describe "when recepient attempts to reject the invitation" do
    before :each do
      @recepient = create_user
      @invitation = create_invitation :for => @recepient
    end

    it "redirects to dashboard"

    it "deletes the invitation" do
      perform_request :as_user => @recepient
      Invitation.exists?(@invitation.id).should be_false
    end
  end

  describe "when captain (sender) attempts to reject the invitation" do
    before :each do
      @captain = create_user
      team = create_team :captain => @captain
      @invitation = create_invitation :for => create_user, :from => team
    end

    it "raises Unauthorized" do
      assert_unauthorized { perform_request :as_user => @captain }
    end

    it "does not delete any invitation" do
      assert_does_not_delete_invitation { perform_rescued_request :as_user => @captain }
    end
  end

  describe "when other logged in user attempts to reject the invitation" do
    before :each do
      @some_user = create_user
      @invitation = create_invitation
    end

    it "raises Unauthorized" do
      assert_unauthorized { perform_request :as_user => @some_user }
    end

    it "does not delete any invitation" do
      assert_does_not_delete_invitation { perform_rescued_request :as_user => @some_user }
    end
  end

  describe "when guest attempts to reject the invitation" do
    before :each do
      @invitation = create_invitation
    end

    it "raises Unauthenticated" do
      assert_unauthenticated { perform_request }
    end

    it "does not delete any invitation" do
      assert_does_not_delete_invitation { perform_rescued_request }
    end
  end

  def assert_does_not_delete_invitation(&block)
    block.should_not change(Invitation, :count)
  end

  def perform_rescued_request(opts={})
    begin
      perform_request opts
    rescue
    end
  end

  def perform_request(opts={})
    params = { :id => @invitation.id }
    dispatch_to Invitations, :reject, params do |controller|
      controller.session.stub!(:authenticated?).and_return(opts.key?(:as_user))
      controller.session.stub!(:user).and_return(opts[:as_user])
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="ISO-8859-1">
    <title>Form Validation Plugin</title>
    <link rel="stylesheet" href="css/custom.css">
    <link rel="stylesheet" href="src/formvalidation.css">

        <fieldset>
            <legend>Sign up form</legend>
            <form action="javascript:void(0)" id="test">

                    Name
                    <input type="text" data-formValidate="alpha" isRequired="true" id="fname" />

                    Password
                    <input type="password" data-formValidate="password" isRequired="true" />

                    Email
                    <input type="text" data-formValidate="email" isRequired="true" />

                    Phone(optional)
                    <input type="text" data-formValidate="telephone" maxlength="10" isRequired="false" />

                    From Date(optional)
                    <input type="text" data-formValidate="dateRange" placeholder="mm/dd/yyyy" fromdate="mmddyyyy" maxlength="10">

                    To Date(optional)
                    <input type="text" data-formValidate="dateRange" placeholder="mm/dd/yyyy" todate="mmddyyyy" maxlength="10">

                <button class="submit">Submit</button>

            </form>
        </fieldset>


text:
"use strict";

exports.__esModule = true;

exports.default = function (props, fallbackTheme, defaultProps) {
  // Props should take precedence over ThemeProvider, which should take precedence over
  // defaultProps, but React automatically puts defaultProps on props.

  /* eslint-disable react/prop-types */
  var isDefaultTheme = defaultProps && props.theme === defaultProps.theme;
  var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme;
  /* eslint-enable */

  return theme;
};

module.exports = exports["default"];


text:
<?php

namespace Rentlio\Api;

use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Uri;
use Rentlio\Api\Request\AbstractRequest;
use Rentlio\Api\Request\CheckInRequest;
use Rentlio\Api\Request\CheckOutRequest;
use Rentlio\Api\Request\CreateInvoiceItemForReservationInBulkRequest;
use Rentlio\Api\Request\CreateInvoiceItemForReservationRequest;
use Rentlio\Api\Request\CreateInvoiceItemForSmartCardInBulk;
use Rentlio\Api\Request\CreateNewReservationRequest;
use Rentlio\Api\Request\GetInvoiceDetailsRequest;
use Rentlio\Api\Request\GetInvoicesByPropertyRequest;
use Rentlio\Api\Request\GetInvoicesByReservationRequest;
use Rentlio\Api\Request\GetMyDataRequest;
use Rentlio\Api\Request\ListAllArrivalArrangementsRequest;
use Rentlio\Api\Request\ListAllCheckedInGuestsRequest;
use Rentlio\Api\Request\ListAllCurrenciesRequest;
use Rentlio\Api\Request\ListAllDocumentTypesRequest;
use Rentlio\Api\Request\ListAllPropertiesRequest;
use Rentlio\Api\Request\ListAllProvidedServiceTypesRequest;
use Rentlio\Api\Request\ListAllReservationsRequest;
use Rentlio\Api\Request\ListAllReservationStatusesRequest;
use Rentlio\Api\Request\ListAllReservationsTodayForUnitRequest;
use Rentlio\Api\Request\ListAllServicesForPropertyRequest;
use Rentlio\Api\Request\ListAllServicesPaymentTypesRequest;
use Rentlio\Api\Request\ListAllTouristTaxCategoriesRequest;
use Rentlio\Api\Request\ListAllUnitsRequest;
use Rentlio\Api\Request\ListAllUnitTypesRequest;
use Rentlio\Api\Request\ListAvailableUnitTypesRequest;
use Rentlio\Api\Request\ListCheckedInGuestForSmartCodeRequest;
use Rentlio\Api\Request\ListGuestsForReservationRequest;
use Rentlio\Api\Request\ListUnitTypeAvailabilityRequest;
use Rentlio\Api\Request\ListUnitTypeRatesRequest;
use Rentlio\Api\Request\ListUnitTypeRestrictionsRequest;
use Rentlio\Api\Request\RequestInterface;
use Rentlio\Api\Request\UpdateAvailabilityAndRatesForUnitTypeRequest;

/**
 * Class Client
 * @package Rentlio\Api
 *
 * Client for public rentl.io api.
 * Api docs can be found @ https://docs.rentl.io
 *
 * Instructions on usage can be found inside README.md and unit tests.
 */
class Client
{
    /**
     * Base URL for rentl.io production API. Currently v1 version
     *
     * @var string
     */
    protected $baseApiUrl = 'https://api.rentl.io/v1';

    /**
     * Api key has to be sent in request header for Authentication and Authorization
     *
     * @var string
     */
    protected $apiKey;

    /**
     * GuzzleHttp client that is used as transport for sending http requests
     *
     * @var \GuzzleHttp\Client
     */
    protected $transport;

    /**
     * Request timeout in seconds.
     *
     * @var integer
     */
    protected $timeout = 10;

    /**
     * Client constructor.
     * @param $apiKey string
     */
    public function __construct($apiKey)
    {
        $this->apiKey    = $apiKey;
        $this->transport = new \GuzzleHttp\Client([
            'timeout'  => $this->timeout,
            'base_url' => $this->baseApiUrl,
            'curl'     => [
                CURLOPT_SSLVERSION     => CURL_SSLVERSION_TLSv1_2,
                CURLOPT_SSL_VERIFYPEER => false
            ]
        ]);
    }

    /**
     * Allow to change base url. Can be used for staging or test mock servers
     *
     * @param $baseUrl string
     * @return $this
     */
    public function setBaseUrl($baseUrl)
    {
        $this->baseApiUrl = $baseUrl;
        return $this;
    }

    /**
     * Change timeout for all rentl.io requests
     *
     * @param $timeout
     * @return $this
     */
    public function setTimeout($timeout)
    {
        $this->timeout = $timeout;
        return $this;
    }

    /**
     * We allow you to change GuzzleHttp\Client with your own, if you would like to
     * tweak options of default one.
     *
     * @param \GuzzleHttp\Client $transport
     * @return $this
     */
    public function setTransport(\GuzzleHttp\Client $transport)
    {
        $this->transport = $transport;
        return $this;
    }

    /**
     * Send http request to rentl.io api
     *
     * @param RequestInterface $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function send(RequestInterface $request)
    {
        $uri = new Uri($this->baseApiUrl . $request->getUri());

        /**
         * @var $request AbstractRequest
         */
        $request = $request
            ->withUri($uri)
            ->withAddedHeader('apiKey', $this->apiKey);

        if ($request->jsonSerialize() != null) {
            $request = $request->withBody(Psr7\stream_for(json_encode($request->jsonSerialize())));
        }

        return $this->transport->send($request);
    }

    /**
     * Calls api endpoint for getting user data associated with provided api key
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function getMyData()
    {
        $request = new GetMyDataRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all rentl.io currencies enumeration
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllCurrencies()
    {
        $request = new ListAllCurrenciesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all properties (hotels) associated with provided api key
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllProperties()
    {
        $request = new ListAllPropertiesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all reservations with different filtering options
     * Since this request can take multiple query params for filtering reservations
     * complete request should be passed to this method. Filters can be set on request itself
     *
     * @param ListAllReservationsRequest $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllReservations(ListAllReservationsRequest $request)
    {
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all rentl.io reservation statuses enumeration
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllReservationStatuses()
    {
        $request = new ListAllReservationStatusesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all checkedIn reservations today in a unit (room)
     *
     * @param $unitId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllReservationsTodayForUnit($unitId)
    {
        $request = new ListAllReservationsTodayForUnitRequest((int)$unitId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all services for a property (hotel)
     *
     * @param $propertyId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllServicesForProperty($propertyId)
    {
        $request = new ListAllServicesForPropertyRequest($propertyId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all payment types enumeration
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllServicesPaymentTypes()
    {
        $request = new ListAllServicesPaymentTypesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all units for specified propertyId
     *
     * @param $propertyId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllUnits($propertyId)
    {
        $request = new ListAllUnitsRequest($propertyId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all unit types for specified propertyId
     *
     * @param $propertyId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllUnitTypes($propertyId)
    {
        $request = new ListAllUnitTypesRequest($propertyId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all available unit types in date range
     * for specified propertyId
     *
     * @param $propertyId
     * @param \DateTime $dateFrom
     * @param \DateTime $dateTo
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAvailableUnitTypes($propertyId, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $request = new ListAvailableUnitTypesRequest($propertyId);
        $request->setDateFrom($dateFrom->format('Y-m-d'));
        $request->setDateTo($dateTo->format('Y-m-d'));
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting availability status for Unit Type in some date range
     *
     * @param $unitTypeId
     * @param \DateTime $dateFrom
     * @param \DateTime $dateTo
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listUnitTypeAvailability($unitTypeId, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $request = new ListUnitTypeAvailabilityRequest($unitTypeId);
        $request->setDateFrom($dateFrom->format('Y-m-d'));
        $request->setDateTo($dateTo->format('Y-m-d'));
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting rates for Unit Type in some date range
     *
     * @param $unitTypeId
     * @param \DateTime $dateFrom
     * @param \DateTime $dateTo
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listUnitTypeRates($unitTypeId, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $request = new ListUnitTypeRatesRequest($unitTypeId);
        $request->setDateFrom($dateFrom->format('Y-m-d'));
        $request->setDateTo($dateTo->format('Y-m-d'));
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting restrictions for Unit Type in some date range
     *
     * @param $unitTypeId
     * @param \DateTime $dateFrom
     * @param \DateTime $dateTo
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listUnitTypeRestrictions($unitTypeId, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $request = new ListUnitTypeRestrictionsRequest($unitTypeId);
        $request->setDateFrom($dateFrom->format('Y-m-d'));
        $request->setDateTo($dateTo->format('Y-m-d'));
        return $this->send($request);
    }

    /**
     * Calls api endpoint for listing invoices attached to specific property.
     *
     * @param  $propertyId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function getInvoicesByProperty($propertyId)
    {
        $request = new GetInvoicesByPropertyRequest($propertyId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for listing invoices attached to specific reservation.
     *
     * @param  $reservationsId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function getInvoicesByReservation($reservationsId)
    {
        $request = new GetInvoicesByReservationRequest($reservationsId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for adding new invoice item to reservation invoice.
     * If there are no invoices for this reservation in draft status, new one will be created.
     *
     * @param CreateInvoiceItemForReservationRequest $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function createInvoiceItem(CreateInvoiceItemForReservationRequest $request)
    {
        return $this->send($request);
    }

    /**
     * Calls api endpoint for adding new invoice items in bulk to reservation invoice.
     * If there are no invoices for this reservation in draft status, new one will be created.
     *
     * @param CreateInvoiceItemForReservationInBulkRequest $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function createInvoiceItems(CreateInvoiceItemForReservationInBulkRequest $request)
    {
        return $this->send($request);
    }

    /**
     * Calls api endpoint for adding new invoice items in bulk to reservation invoice. It uses smart card attached to the
     * guest on checked-in reservation and it enables creating the draft invoice on each guest on reservation separately.
     * If there are no invoices for this reservation in draft status, new one will be created.
     *
     * @param CreateInvoiceItemForSmartCardInBulk $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function createSmartCardInvoiceItems(CreateInvoiceItemForSmartCardInBulk $request)
    {
        return $this->send($request);
    }

    /**
     * Calls api endpoint for updating availability, price and minStay restriction
     * on specific days for specified unit type.
     *
     * @param UpdateAvailabilityAndRatesForUnitTypeRequest $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function updateAvailabilityAndRatesForUnitType(UpdateAvailabilityAndRatesForUnitTypeRequest $request)
    {
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all rentl.io document types enumeration used for a guest
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllDocumentTypes()
    {
        $request = new ListAllDocumentTypesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all rentl.io arrival arrangements enumeration used for a guest
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllArrivalArrangements()
    {
        $request = new ListAllArrivalArrangementsRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all rentl.io tourist tax categories enumeration used for a guest
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllTouristTaxCategories()
    {
        $request = new ListAllTouristTaxCategoriesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all rentl.io provided service types enumeration used for a guest
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllProvidedServiceTypes()
    {
        $request = new ListAllProvidedServiceTypesRequest();
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all reservations in date range
     * for specified propertyId where reservation holders that are checked-in in some date range
     *
     * @param $propertyId
     * @param \DateTime $dateFrom
     * @param \DateTime $dateTo
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listAllCheckedInGuests($propertyId, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $request = new ListAllCheckedInGuestsRequest($propertyId);
        $request->setDateFrom($dateFrom->format('Y-m-d'));
        $request->setDateTo($dateTo->format('Y-m-d'));
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting invoice details
     *
     * @param integer $invoiceId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function getInvoiceDetails($invoiceId)
    {
        $request = new GetInvoiceDetailsRequest($invoiceId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all reservations in date range
     * for specified propertyId where reservation holders that are checked-in in some date range
     *
     * @param integer $reservationsId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listGuestsForReservation($reservationsId)
    {
        $request = new ListGuestsForReservationRequest($reservationsId);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for making check-in of the reservation
     *
     * @param integer $reservationsId
     * @param boolean $checkIn
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function checkInReservation($reservationsId, $checkIn)
    {
        $request = new CheckInRequest($reservationsId, $checkIn);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for making check-out of the reservation
     *
     * @param integer $reservationsId
     * @param boolean $checkOut
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function checkOutReservation($reservationsId, $checkOut)
    {
        $request = new CheckOutRequest($reservationsId, $checkOut);
        return $this->send($request);
    }

    /**
     * Calls api endpoint for creating new reservation in Rentlio.
     *
     * @param CreateNewReservationRequest $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function createReservation(CreateNewReservationRequest $request)
    {
        return $this->send($request);
    }

    /**
     * Calls api endpoint for getting all reservations in date range
     * for specified propertyId where reservation holders that are checked-in in some date range
     *
     * @param integer $propertiesId
     * @param string $smartCardCode
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function listCheckedInGuestForSmartCode($propertiesId, $smartCardCode)
    {
        $request = new ListCheckedInGuestForSmartCodeRequest($propertiesId, $smartCardCode);
        return $this->send($request);
    }
}