<commit_before>/**
 *
 * Tiramisu Unit Tests
 * ~~~~~~~~~~~~~~~~~~~
 *
 * Use the online version for working AJAX tests:
 * http://dl.dropbox.com/u/2060843/tiramisu/test/runtests.html
 *
 **/

module('Generic tests');

test('Should pass', function() {
    ok( true, "Ok");
});

test('1 plus 2', function() {
    equal(1 + 2, 3, 'equals 3');
});

test('[1, 2, 3] + [4, 5, 6]', function() {
    var a = [1, 2, 3];
    var b = [4, 5, 6];
    var sum = function(a, b) {
        var i, c = [];
        for (i = 0; i < a.length; i++) {
            c[i] = a[i] + b[i];
        }
        return c;
    }
    deepEqual(sum(a, b), [5, 7, 9], '= [5, 7, 9]');
});

module('Selector Tests');

test('Selecting #headline', function() {
    var rs = tiramisu.get('#headline');
    ok(rs, 'Should not be empty');
    equal(rs[0].id, "headline", "Should have an element node with id headline");
    equal(rs[0].innerHTML, "Tiramisu Tests", "Should contain Tiramisu Tests");
});

test('Selecting h3 .red', function() {
    var rs = tiramisu.get('h3 .red');
    ok(rs, 'Should not be empty');
    equal(rs[0].className, "red", "Should have an element node with class red");
    equal(rs[0].innerHTML, "tiramisu", "Should contain tiramisu");
});

test('Selecting p.underlined', function() {
    var rs = tiramisu.get('p.underlined');
    ok(rs, 'Should not be empty');
    equal(rs[0].className, "underlined", "Should have an element node with class underlined");
    equal(rs[0].nodeName, "P", "Should be a P node");
    equal(rs[0].innerHTML, "This text is underlined", "Should contain This text is underlined");
});

test('Selecting h1#headline', function() {
    var rs = tiramisu.get('h1#headline');
    ok(rs, 'Should not be empty');
    equal(rs[0].id, "headline", "Should have an element node with id headline");
    equal(rs[0].nodeName, "H1", "Should be an H1 node")
    equal(rs[0].innerHTML, "Tiramisu Tests", "Should contain Tiramisu Tests");
});

module('Browser detection tests');

test('Detect check', function() {
    var browser = tiramisu.detect('browser');
    ok(browser, 'Ok result : '+browser);
	//equal(tiramisu.detect('isChrome'), true, "We are into Chrome");
	//equal(tiramisu.detect('isFirefox'), true, "We are into Firefox");
	//equal(tiramisu.detect('isIE'), true, "We are into IE 'BOOOO'");
});

module('Selector list methods tests');

test('Calling t.get("h2").each(function() { this.innerHTML = "Test"; })', function() {
    var i;

    t.get('#qunit-fixture h2').each(function() {
        this.innerHTML = "Test";
    });

    var rs = t.get('#qunit-fixture h2');

    var all = true;
    for (i = 0; i < rs.length; i++) {
        if (rs[i].innerHTML !== "Test") { all = false; break; }
    }

    ok(all, "Should set all H2's content to Test");

});

test('Calling t.get("ul li").each(function() { return this.innerHTML; })', function() {
    t.get('ul#selector_test li').each(function() {
        t.get('#append-here')[0].innerHTML += this.innerHTML;
    });

    equal(t.get("#append-here")[0].innerHTML, '
This text is underlined
Another lineOki-Doki.');
});

test('Calling t.get("#qunit-fixture h2 .red").html()', function() {
    var rs = t.get('#qunit-fixture h2 .red').html();
    equal(rs, 'good', 'should return good');
});

test('Calling t.get("#qunit-fixture h2 .red").html("bad")', function() {
    t.get('#qunit-fixture h2 .red').html('bad');
    var rs = t.get('#qunit-fixture h2 .red').html();
    equal(rs, 'bad', 'should set element\'s HTML value to bad');
});

test('Calling t.get("#qunit-fixture select").value()', function() {
    var rs = t.get('#qunit-fixture select').value();
    equal(rs, 'First.', 'should return First.');
});

test('Calling t.get("#hola_id").value()', function() {
    var rs = t.get('#hola_id').value();
    equal(rs, 'hola', 'should return hola');
});

test('Calling t.get("#qunit-fixture select").value("Second.")', function() {
    t.get('#qunit-fixture select').value("Second.");
    var rs = t.get('#qunit-fixture select').value();
    equal(rs, 'Second.', 'should set element\'s HTML value to Second');
});

test('Element Index (Found)', function() {
    var el = t.get('#selector_test li')[2];
    var rs = t.get('#selector_test li').index(el);
    equal(rs, 2);
});

test('Element Index (Not Found)', function() {
    var rs = t.get('#selector_test li').index('
Does not exist
');
    equal(rs, -1);
});

module('DOM Manipulation tests');

test('Single after', function() {
    t.get('#after_test h1').after('
new
');
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
Hello Tiramisu

new
\n
ciao
\n
mondo
\n    ';
    equal(rs, attended);
});

test('Multiple after', function() {
    t.get('#after_test .inner').after('
ciccio
')
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
Hello Tiramisu
\n
ciao

ciccio
\n
mondo

ciccio
\n    ';
    equal(rs, attended);
});

test('Single before', function() {
    t.get('#after_test h1').before('
new
');
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
new

Hello Tiramisu
\n
ciao
\n
mondo
\n    ';
    equal(rs, attended);
});

test('Multiple before', function() {
    t.get('#after_test .inner').before('
ciccio
')
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
Hello Tiramisu
\n
ciccio

ciao
\n
ciccio

mondo
\n    ';
    equal(rs, attended);
});

test('Single append', function() {
    t.get('#append_test').append('
Three
')
    var rs = t.get('#append_test')[0].innerHTML;
    var attended = '\n
One
\n
Two
\n
Three
'
    equal(rs, attended);
});

test('Multiple append', function() {
    t.get('#append_test2 li').append('
ciccio
')
    var rs = t.get('#append_test2')[0].innerHTML;
    var attended ='\n

First

ciccio

\n

First

ciccio

\n    ';
    equal(rs, attended);
});

test('Single prepend', function() {
    t.get('#append_test').prepend('
Zero
')
    var rs = t.get('#append_test')[0].innerHTML;
    var attended = '
Zero
\n
One
\n
Two
\n    '
    equal(rs, attended);
});

test('Multiple prepend', function() {
    t.get('#append_test2 li').prepend('
ciccio
')
    var rs = t.get('#append_test2')[0].innerHTML;
    var attended ='\n

ciccio

First

\n

ciccio

First

\n    ';
    equal(rs, attended);
});

test('Empty childrens (single element)', function() {
    t.get('#selector_test').empty();
    var rs1 = t.get('#selector_test')[0].innerHTML,
        rs2 = t.get('#selector_test li').length;

    equal(rs1, "");
    equal(rs2, 0);
});

test('Filter function using :even', function() {
    var rs = t.get('#selector_test li').filter(':even');

    equal(rs[0].innerHTML, '
This text is underlined
');
    equal(rs[1].innerHTML, 'Oki-Doki.');
    equal(rs.length, 2);
});

test('Filter function using :odd', function() {
    var rs = t.get('#selector_test li').filter(':odd');

    equal(rs[0].innerHTML, 'Another line');
    equal(rs.length, 1)
});

test('Empty childrens (multiple elements)', function() {
    t.get('#selector_test li').empty();
    var rs = t.get('#selector_test')[0].innerHTML;
    var attended = '\n

\n

\n

\n    ';

    equal(rs, attended);
});

module('CSS Manipulation tests');

test('Setting the color of a node to #f6f6f6', function() {
    t.get('#headline').css({
        'color': '#f6f6f6'
    });

    equal(t.get('#headline')[0].style['color'], 'rgb(246, 246, 246)');
});

test('Setting the opacity of a node to 0.45', function() {
    t.get('#headline').css({
        'opacity': '0.45'
    });

    equal(t.get('#headline').css('opacity'), '0.45');
});

module('AJAX module tests');

asyncTest('Calling a basic AJAX GET', function() {
    var success = function(result) {
        ok(true);
        ok(result, "the result is not undefined/null");
        equal(result, '
Hello GET
\n');
        start();
    };

    var error = function(errorType, message) {
        ok(false, "error called");
        start();
    }

    expect(3);

    tiramisu.ajax({
        'method': 'GET',
        'url': 'data/async.html',
        'success': success,
        'error': error
    });
});

asyncTest('Calling a basic AJAX POST', function() {
    var success = function(result) {
        ok(true);
        ok(result, "the result is not undefined/null");
        equal(result, '
Hello GET
\n');
        start();
    };

    var error = function(errorType, message) {
        ok(false, "error called");
        start();
    }

    expect(3);

    tiramisu.ajax({
        'method': 'POST',
        'url': 'data/async.html',
        'success': success,
        'error': error
    });
});

module('Event tests');

test('Pressing any key on the keyboard', function() {
    var event = document.createEvent('HTMLEvents');
    event.initEvent('keydown', true, true);

    t.get(document).on('keydown', function() {
        t.get('#headline').html('A key was pressed.');
    });

    document.dispatchEvent(event);

    equal(t.get('#headline').html(), 'A key was pressed.');
});

module('Attribute tests');

test('Getting the attribute "id" of "#headline"', function() {
    var rs = t.get('#headline').attr('id');
    equals(rs, 'headline', 'should equal to "headline"');
});
<commit_msg>Added 'focus' Unit test<commit_after>/**
 *
 * Tiramisu Unit Tests
 * ~~~~~~~~~~~~~~~~~~~
 *
 * Use the online version for working AJAX tests:
 * http://dl.dropbox.com/u/2060843/tiramisu/test/runtests.html
 *
 **/

module('Generic tests');

test('Should pass', function() {
    ok( true, "Ok");
});

test('1 plus 2', function() {
    equal(1 + 2, 3, 'equals 3');
});

test('[1, 2, 3] + [4, 5, 6]', function() {
    var a = [1, 2, 3];
    var b = [4, 5, 6];
    var sum = function(a, b) {
        var i, c = [];
        for (i = 0; i < a.length; i++) {
            c[i] = a[i] + b[i];
        }
        return c;
    }
    deepEqual(sum(a, b), [5, 7, 9], '= [5, 7, 9]');
});

module('Selector Tests');

test('Selecting #headline', function() {
    var rs = tiramisu.get('#headline');
    ok(rs, 'Should not be empty');
    equal(rs[0].id, "headline", "Should have an element node with id headline");
    equal(rs[0].innerHTML, "Tiramisu Tests", "Should contain Tiramisu Tests");
});

test('Selecting h3 .red', function() {
    var rs = tiramisu.get('h3 .red');
    ok(rs, 'Should not be empty');
    equal(rs[0].className, "red", "Should have an element node with class red");
    equal(rs[0].innerHTML, "tiramisu", "Should contain tiramisu");
});

test('Selecting p.underlined', function() {
    var rs = tiramisu.get('p.underlined');
    ok(rs, 'Should not be empty');
    equal(rs[0].className, "underlined", "Should have an element node with class underlined");
    equal(rs[0].nodeName, "P", "Should be a P node");
    equal(rs[0].innerHTML, "This text is underlined", "Should contain This text is underlined");
});

test('Selecting h1#headline', function() {
    var rs = tiramisu.get('h1#headline');
    ok(rs, 'Should not be empty');
    equal(rs[0].id, "headline", "Should have an element node with id headline");
    equal(rs[0].nodeName, "H1", "Should be an H1 node")
    equal(rs[0].innerHTML, "Tiramisu Tests", "Should contain Tiramisu Tests");
});

module('Browser detection tests');

test('Detect check', function() {
    var browser = tiramisu.detect('browser');
    ok(browser, 'Ok result : '+browser);
	//equal(tiramisu.detect('isChrome'), true, "We are into Chrome");
	//equal(tiramisu.detect('isFirefox'), true, "We are into Firefox");
	//equal(tiramisu.detect('isIE'), true, "We are into IE 'BOOOO'");
});

module('Selector list methods tests');

test('Calling t.get("h2").each(function() { this.innerHTML = "Test"; })', function() {
    var i;

    t.get('#qunit-fixture h2').each(function() {
        this.innerHTML = "Test";
    });

    var rs = t.get('#qunit-fixture h2');

    var all = true;
    for (i = 0; i < rs.length; i++) {
        if (rs[i].innerHTML !== "Test") { all = false; break; }
    }

    ok(all, "Should set all H2's content to Test");

});

test('Calling t.get("ul li").each(function() { return this.innerHTML; })', function() {
    t.get('ul#selector_test li').each(function() {
        t.get('#append-here')[0].innerHTML += this.innerHTML;
    });

    equal(t.get("#append-here")[0].innerHTML, '
This text is underlined
Another lineOki-Doki.');
});

test('Calling t.get("#qunit-fixture h2 .red").html()', function() {
    var rs = t.get('#qunit-fixture h2 .red').html();
    equal(rs, 'good', 'should return good');
});

test('Calling t.get("#qunit-fixture h2 .red").html("bad")', function() {
    t.get('#qunit-fixture h2 .red').html('bad');
    var rs = t.get('#qunit-fixture h2 .red').html();
    equal(rs, 'bad', 'should set element\'s HTML value to bad');
});

test('Calling t.get("#qunit-fixture select").value()', function() {
    var rs = t.get('#qunit-fixture select').value();
    equal(rs, 'First.', 'should return First.');
});

test('Calling t.get("#hola_id").value()', function() {
    var rs = t.get('#hola_id').value();
    equal(rs, 'hola', 'should return hola');
});

test('Calling t.get("#qunit-fixture select").value("Second.")', function() {
    t.get('#qunit-fixture select').value("Second.");
    var rs = t.get('#qunit-fixture select').value();
    equal(rs, 'Second.', 'should set element\'s HTML value to Second');
});

test('Calling t.get("#hola_id").focus()', function() {
    t.get('#hola_id').focus();
    rs = document.activeElement.id;
    equal(rs, 'hola_id', 'should return hola');
});

test('Element Index (Found)', function() {
    var el = t.get('#selector_test li')[2];
    var rs = t.get('#selector_test li').index(el);
    equal(rs, 2);
});

test('Element Index (Not Found)', function() {
    var rs = t.get('#selector_test li').index('
Does not exist
');
    equal(rs, -1);
});

module('DOM Manipulation tests');

test('Single after', function() {
    t.get('#after_test h1').after('
new
');
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
Hello Tiramisu

new
\n
ciao
\n
mondo
\n    ';
    equal(rs, attended);
});

test('Multiple after', function() {
    t.get('#after_test .inner').after('
ciccio
')
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
Hello Tiramisu
\n
ciao

ciccio
\n
mondo

ciccio
\n    ';
    equal(rs, attended);
});

test('Single before', function() {
    t.get('#after_test h1').before('
new
');
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
new

Hello Tiramisu
\n
ciao
\n
mondo
\n    ';
    equal(rs, attended);
});

test('Multiple before', function() {
    t.get('#after_test .inner').before('
ciccio
')
    var rs = t.get('#after_test')[0].innerHTML;
    var attended = '\n
Hello Tiramisu
\n
ciccio

ciao
\n
ciccio

mondo
\n    ';
    equal(rs, attended);
});

test('Single append', function() {
    t.get('#append_test').append('
Three
')
    var rs = t.get('#append_test')[0].innerHTML;
    var attended = '\n
One
\n
Two
\n
Three
'
    equal(rs, attended);
});

test('Multiple append', function() {
    t.get('#append_test2 li').append('
ciccio
')
    var rs = t.get('#append_test2')[0].innerHTML;
    var attended ='\n

First

ciccio

\n

First

ciccio

\n    ';
    equal(rs, attended);
});

test('Single prepend', function() {
    t.get('#append_test').prepend('
Zero
')
    var rs = t.get('#append_test')[0].innerHTML;
    var attended = '
Zero
\n
One
\n
Two
\n    '
    equal(rs, attended);
});

test('Multiple prepend', function() {
    t.get('#append_test2 li').prepend('
ciccio
')
    var rs = t.get('#append_test2')[0].innerHTML;
    var attended ='\n

ciccio

First

\n

ciccio

First

\n    ';
    equal(rs, attended);
});

test('Empty childrens (single element)', function() {
    t.get('#selector_test').empty();
    var rs1 = t.get('#selector_test')[0].innerHTML,
        rs2 = t.get('#selector_test li').length;

    equal(rs1, "");
    equal(rs2, 0);
});

test('Filter function using :even', function() {
    var rs = t.get('#selector_test li').filter(':even');

    equal(rs[0].innerHTML, '
This text is underlined
');
    equal(rs[1].innerHTML, 'Oki-Doki.');
    equal(rs.length, 2);
});

test('Filter function using :odd', function() {
    var rs = t.get('#selector_test li').filter(':odd');

    equal(rs[0].innerHTML, 'Another line');
    equal(rs.length, 1)
});

test('Empty childrens (multiple elements)', function() {
    t.get('#selector_test li').empty();
    var rs = t.get('#selector_test')[0].innerHTML;
    var attended = '\n

\n

\n

\n    ';

    equal(rs, attended);
});

module('CSS Manipulation tests');

test('Setting the color of a node to #f6f6f6', function() {
    t.get('#headline').css({
        'color': '#f6f6f6'
    });

    equal(t.get('#headline')[0].style['color'], 'rgb(246, 246, 246)');
});

test('Setting the opacity of a node to 0.45', function() {
    t.get('#headline').css({
        'opacity': '0.45'
    });

    equal(t.get('#headline').css('opacity'), '0.45');
});

module('AJAX module tests');

asyncTest('Calling a basic AJAX GET', function() {
    var success = function(result) {
        ok(true);
        ok(result, "the result is not undefined/null");
        equal(result, '
Hello GET
\n');
        start();
    };

    var error = function(errorType, message) {
        ok(false, "error called");
        start();
    }

    expect(3);

    tiramisu.ajax({
        'method': 'GET',
        'url': 'data/async.html',
        'success': success,
        'error': error
    });
});

asyncTest('Calling a basic AJAX POST', function() {
    var success = function(result) {
        ok(true);
        ok(result, "the result is not undefined/null");
        equal(result, '
Hello GET
\n');
        start();
    };

    var error = function(errorType, message) {
        ok(false, "error called");
        start();
    }

    expect(3);

    tiramisu.ajax({
        'method': 'POST',
        'url': 'data/async.html',
        'success': success,
        'error': error
    });
});

module('Event tests');

test('Pressing any key on the keyboard', function() {
    var event = document.createEvent('HTMLEvents');
    event.initEvent('keydown', true, true);

    t.get(document).on('keydown', function() {
        t.get('#headline').html('A key was pressed.');
    });

    document.dispatchEvent(event);

    equal(t.get('#headline').html(), 'A key was pressed.');
});

module('Attribute tests');

test('Getting the attribute "id" of "#headline"', function() {
    var rs = t.get('#headline').attr('id');
    equals(rs, 'headline', 'should equal to "headline"');
});
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2015 Richard Rodger */
"use strict";

// mocha transport.test.js

var seneca  = require('seneca')

var assert = require('assert')

var needle = require('needle')
var test   = require('seneca-transport-test')

var no_t = {transport:false}

process.setMaxListeners(999)

function run_client( type, port, done ) {
  require('seneca')({log:'silent',default_plugins:no_t})
    .use('../transport')
    .client({type:type,port:port})
    .ready( function() {

      this.act('c:1,d:A',function(err,out){
        if(err) return fin(err);

        assert.equal( '{"s":"1-A"}', JSON.stringify(out) )

        this.act('c:1,d:AA',function(err,out){
          if(err) return fin(err);

          assert.equal( '{"s":"1-AA"}', JSON.stringify(out) )
          done()
        })
      })
    })
}

describe('transport', function() {

  it('happy-tcp', function( fin ) {
    test.foo_test( 'transport', require, fin, 'tcp' )
  })

  it('happy-pin-tcp', function( fin ) {
    test.foo_pintest( 'transport', require, fin, 'tcp' )
  })

  it('happy-web', function( fin ) {
    test.foo_test( 'transport', require, fin, 'web' )
  })

  it('happy-pin-web', function( fin ) {
    test.foo_pintest( 'transport', require, fin, 'web' )
  })

  it('tcp-basic', function( fin ) {

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .add( 'c:1', function(args,done){done(null,{s:'1-'+args.d})} )
      .listen({type:'tcp',port:20102})
      .ready( function() {

        var count = 0
        function check() {
          count++
          if( 3 == count ) fin()
        }

        run_client( 'tcp', 20102, check )
        run_client( 'tcp', 20102, check )
        run_client( 'tcp', 20102, check )
      })
  })

  it('web-basic', function( fin ) {
    require('seneca')({log:'silent',errhandler:fin,default_plugins:no_t})
      .use('../transport.js')
      .add( 'c:1', function(args,done){done(null,{s:'1-'+args.d})} )
      .listen({type:'web',port:20202})
      .ready( function() {

        var count = 0
        function check() {
          count++
          if( 4 == count ) fin()
        }

        run_client( 'web', 20202, check )
        run_client( 'web', 20202, check )
        run_client( 'web', 20202, check )

        // special case for non-seneca clients
        needle.post(
          'http://localhost:20202/act',
          {c:1,d:'A'},{json:true},
          function(err,res,body){
            if( err ) return fin(err)
            assert.equal( '{"s":"1-A"}', JSON.stringify(body) )
            check()
          })
      })
  })

  it('error-passing-http', function(fin){

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .add('a:1',function(args,done){
        done(new Error('bad-wire'))
      })
      .listen(30303)

    require('seneca')({log:'silent'})
      .use('../transport.js')
      .client(30303)
      .act('a:1',function(err,out){
        assert.equal('seneca: Action a:1 failed: bad-wire.',err.message)
        fin()
      })

  })

  it('error-passing-tcp', function(fin){

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .add('a:1',function(args,done){
        done(new Error('bad-wire'))
      })
      .listen({type:'tcp',port:40404})

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .client({type:'tcp',port:40404})
      .act('a:1',function(err,out){
        //console.log(err)
        assert.equal('seneca: Action a:1 failed: bad-wire.',err.message)
        fin()
      })
  })

  it('own-message', function(fin){

    // a -> b -> a

    do_type('tcp',function(err){
      if(err) return fin(err);
      do_type('http',fin)
    })

    function do_type(type,fin){

      function a(args,done){counters.a++;done(null,{aa:args.a})}
      function b(args,done){counters.b++;done(null,{bb:args.b})}

      var counters = {log_a:0,log_b:0,own:0,a:0,b:0,c:0}

      var log_a = function(){counters.log_a++;}
      var log_b = function(){counters.log_b++;}
      var own_a = function(){counters.own++;}

      var a = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{a=1\}/, handler:log_a},
          {level:'warn', regex: /own_message/, handler:own_a}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js',{
              check:{message_loop:false},
              warn:{own_message:true}
            })
            .add('a:1',a)
            .listen({type:type,port:40405})
            .client({type:type,port:40406})

      var b = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{b=1\}/, handler:log_b}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js')
            .add('b:1',b)
            .listen({type:type,port:40406})
            .client({type:type,port:40405})

      a.ready(function(){
        b.ready(function(){
          a.act('a:1',function(err,out){
            if(err) return fin(err);assert.equal(1,out.aa)})

          a.act('b:1',function(err,out){
            if(err) return fin(err);assert.equal(1,out.bb)})

          a.act('c:1',function(err,out){
            if(!err) assert.fail()
            assert.ok(err.timeout)
          })
        })})

      setTimeout(function(){
        a.close(function(err){
          if(err) return fin(err);

        ;b.close(function(err){
          if(err) return fin(err);

        ;try {
          assert.equal(1,counters.a)
          assert.equal(1,counters.b)
          assert.equal(1,counters.log_a)
          assert.equal(1,counters.log_b)
          assert.equal(1,counters.own)
        }
        catch(e) { return fin(e) }

        ;fin()

        })})
      },222)

    }
  })

  it('message-loop', function(fin){

    // a -> b -> c -> a

    do_type('tcp',function(err){
      if(err) return fin(err);
      do_type('http',fin)
    })

    function do_type(type,fin){

      function a(args,done){counters.a++;done(null,{aa:args.a})}
      function b(args,done){counters.b++;done(null,{bb:args.b})}
      function c(args,done){counters.c++;done(null,{cc:args.c})}

      var counters = {log_a:0,log_b:0,log_c:0,loop:0,a:0,b:0,c:0,d:0}

      var log_a = function(){counters.log_a++;}
      var log_b = function(){counters.log_b++;}
      var log_c = function(){counters.log_c++;}
      var loop_a = function(){counters.loop++;}

      var a = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{a=1\}/, handler:log_a},
          {level:'warn', regex: /message_loop/, handler:loop_a}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js',{
              check:{own_message:false},
              warn:{message_loop:true}
            })
            .add('a:1',a)
            .listen({type:type,port:40405})
            .client({type:type,port:40406})

      var b = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{b=1\}/, handler:log_b}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js')
            .add('b:1',b)
            .listen({type:type,port:40406})
            .client({type:type,port:40407})

      var c = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{c=1\}/, handler:log_c}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js')
            .add('c:1',c)
            .listen({type:type,port:40407})
            .client({type:type,port:40405})

      a.ready(function(){
        b.ready(function(){
          c.ready(function(){
            a.act('a:1',function(err,out){
              if(err) return fin(err);assert.equal(1,out.aa)})

            a.act('b:1',function(err,out){
              if(err) return fin(err);assert.equal(1,out.bb)})

            a.act('c:1',function(err,out){
              if(err) return fin(err);assert.equal(1,out.cc)})

            a.act('d:1',function(err){
              if(!err) assert.fail()
              assert.ok(err.timeout)
            })
          })})})

      setTimeout(function(){
        a.close(function(err){
          if(err) return fin(err);

        ;b.close(function(err){
          if(err) return fin(err);

        ;c.close(function(err){
          if(err) return fin(err);

        ;try {
          assert.equal(1,counters.a)
          assert.equal(1,counters.b)
          assert.equal(1,counters.c)
          assert.equal(1,counters.log_a)
          assert.equal(1,counters.log_b)
          assert.equal(1,counters.log_c)
          assert.equal(1,counters.loop)
        }
        catch(e) { return fin(e) }

        ;fin()

        })})})
      },222)

    }
  })
})
<commit_msg>test uses tagging for log clarity<commit_after>/* Copyright (c) 2013-2015 Richard Rodger */
"use strict";

// mocha transport.test.js

var seneca  = require('seneca')

var assert = require('assert')

var needle = require('needle')
var test   = require('seneca-transport-test')

var no_t = {transport:false}

process.setMaxListeners(999)

function run_client( type, port, done, tag ) {
  require('seneca')({tag:tag,log:'silent',default_plugins:no_t,debug:{short_logs:true}})
    .use('../transport')
    .client({type:type,port:port})
    .ready( function() {

      this.act('c:1,d:A',function(err,out){
        if(err) return fin(err);

        assert.equal( '{"s":"1-A"}', JSON.stringify(out) )

        this.act('c:1,d:AA',function(err,out){
          if(err) return fin(err);

          assert.equal( '{"s":"1-AA"}', JSON.stringify(out) )
          done()
        })
      })
    })
}

describe('transport', function() {

  it('happy-tcp', function( fin ) {
    test.foo_test( 'transport', require, fin, 'tcp' )
  })

  it('happy-pin-tcp', function( fin ) {
    test.foo_pintest( 'transport', require, fin, 'tcp' )
  })

  it('happy-web', function( fin ) {
    test.foo_test( 'transport', require, fin, 'web' )
  })

  it('happy-pin-web', function( fin ) {
    test.foo_pintest( 'transport', require, fin, 'web' )
  })

  it('tcp-basic', function( fin ) {

    require('seneca')({tag:'srv',log:'silent',default_plugins:no_t,debug:{short_logs:true}})
      .use('../transport.js')
      .add( 'c:1', function(args,done){done(null,{s:'1-'+args.d})} )
      .listen({type:'tcp',port:20102})
      .ready( function() {

        var count = 0
        function check() {
          count++
          if( 3 == count ) fin()
        }

        run_client( 'tcp', 20102, check, 'cln0' )
        run_client( 'tcp', 20102, check, 'cln1' )
        run_client( 'tcp', 20102, check, 'cln2' )
      })
  })

  it('web-basic', function( fin ) {
    require('seneca')({log:'silent',errhandler:fin,default_plugins:no_t})
      .use('../transport.js')
      .add( 'c:1', function(args,done){done(null,{s:'1-'+args.d})} )
      .listen({type:'web',port:20202})
      .ready( function() {

        var count = 0
        function check() {
          count++
          if( 4 == count ) fin()
        }

        run_client( 'web', 20202, check )
        run_client( 'web', 20202, check )
        run_client( 'web', 20202, check )

        // special case for non-seneca clients
        needle.post(
          'http://localhost:20202/act',
          {c:1,d:'A'},{json:true},
          function(err,res,body){
            if( err ) return fin(err)
            assert.equal( '{"s":"1-A"}', JSON.stringify(body) )
            check()
          })
      })
  })

  it('error-passing-http', function(fin){

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .add('a:1',function(args,done){
        done(new Error('bad-wire'))
      })
      .listen(30303)

    require('seneca')({log:'silent'})
      .use('../transport.js')
      .client(30303)
      .act('a:1',function(err,out){
        assert.equal('seneca: Action a:1 failed: bad-wire.',err.message)
        fin()
      })

  })

  it('error-passing-tcp', function(fin){

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .add('a:1',function(args,done){
        done(new Error('bad-wire'))
      })
      .listen({type:'tcp',port:40404})

    require('seneca')({log:'silent',default_plugins:no_t})
      .use('../transport.js')
      .client({type:'tcp',port:40404})
      .act('a:1',function(err,out){
        //console.log(err)
        assert.equal('seneca: Action a:1 failed: bad-wire.',err.message)
        fin()
      })
  })

  it('own-message', function(fin){

    // a -> b -> a

    do_type('tcp',function(err){
      if(err) return fin(err);
      do_type('http',fin)
    })

    function do_type(type,fin){

      function a(args,done){counters.a++;done(null,{aa:args.a})}
      function b(args,done){counters.b++;done(null,{bb:args.b})}

      var counters = {log_a:0,log_b:0,own:0,a:0,b:0,c:0}

      var log_a = function(){counters.log_a++;}
      var log_b = function(){counters.log_b++;}
      var own_a = function(){counters.own++;}

      var a = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{a=1\}/, handler:log_a},
          {level:'warn', regex: /own_message/, handler:own_a}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js',{
              check:{message_loop:false},
              warn:{own_message:true}
            })
            .add('a:1',a)
            .listen({type:type,port:40405})
            .client({type:type,port:40406})

      var b = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{b=1\}/, handler:log_b}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js')
            .add('b:1',b)
            .listen({type:type,port:40406})
            .client({type:type,port:40405})

      a.ready(function(){
        b.ready(function(){
          a.act('a:1',function(err,out){
            if(err) return fin(err);assert.equal(1,out.aa)})

          a.act('b:1',function(err,out){
            if(err) return fin(err);assert.equal(1,out.bb)})

          a.act('c:1',function(err,out){
            if(!err) assert.fail()
            assert.ok(err.timeout)
          })
        })})

      setTimeout(function(){
        a.close(function(err){
          if(err) return fin(err);

        ;b.close(function(err){
          if(err) return fin(err);

        ;try {
          assert.equal(1,counters.a)
          assert.equal(1,counters.b)
          assert.equal(1,counters.log_a)
          assert.equal(1,counters.log_b)
          assert.equal(1,counters.own)
        }
        catch(e) { return fin(e) }

        ;fin()

        })})
      },222)

    }
  })

  it('message-loop', function(fin){

    // a -> b -> c -> a

    do_type('tcp',function(err){
      if(err) return fin(err);
      do_type('http',fin)
    })

    function do_type(type,fin){

      function a(args,done){counters.a++;done(null,{aa:args.a})}
      function b(args,done){counters.b++;done(null,{bb:args.b})}
      function c(args,done){counters.c++;done(null,{cc:args.c})}

      var counters = {log_a:0,log_b:0,log_c:0,loop:0,a:0,b:0,c:0,d:0}

      var log_a = function(){counters.log_a++;}
      var log_b = function(){counters.log_b++;}
      var log_c = function(){counters.log_c++;}
      var loop_a = function(){counters.loop++;}

      var a = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{a=1\}/, handler:log_a},
          {level:'warn', regex: /message_loop/, handler:loop_a}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js',{
              check:{own_message:false},
              warn:{message_loop:true}
            })
            .add('a:1',a)
            .listen({type:type,port:40405})
            .client({type:type,port:40406})

      var b = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{b=1\}/, handler:log_b}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js')
            .add('b:1',b)
            .listen({type:type,port:40406})
            .client({type:type,port:40407})

      var c = require('seneca')({
        log:{map:[
          {level:'debug', regex: /\{c=1\}/, handler:log_c}
        ]},
        timeout: 111,
        default_plugins:no_t
      })
            .use('../transport.js')
            .add('c:1',c)
            .listen({type:type,port:40407})
            .client({type:type,port:40405})

      a.ready(function(){
        b.ready(function(){
          c.ready(function(){
            a.act('a:1',function(err,out){
              if(err) return fin(err);assert.equal(1,out.aa)})

            a.act('b:1',function(err,out){
              if(err) return fin(err);assert.equal(1,out.bb)})

            a.act('c:1',function(err,out){
              if(err) return fin(err);assert.equal(1,out.cc)})

            a.act('d:1',function(err){
              if(!err) assert.fail()
              assert.ok(err.timeout)
            })
          })})})

      setTimeout(function(){
        a.close(function(err){
          if(err) return fin(err);

        ;b.close(function(err){
          if(err) return fin(err);

        ;c.close(function(err){
          if(err) return fin(err);

        ;try {
          assert.equal(1,counters.a)
          assert.equal(1,counters.b)
          assert.equal(1,counters.c)
          assert.equal(1,counters.log_a)
          assert.equal(1,counters.log_b)
          assert.equal(1,counters.log_c)
          assert.equal(1,counters.loop)
        }
        catch(e) { return fin(e) }

        ;fin()

        })})})
      },222)

    }
  })
})
<|endoftext|>


<commit_before>import assert from 'power-assert';

import {truncate} from '../src/truncator';

describe('truncate methods', () => {
  let el, input, expected;

  input = 'Grumpy wizards make toxic brew for the evil Queen and Jack';

  beforeEach(() => {
    el = document.createElement('p');
    document.body.appendChild(el);
  });

  afterEach(() => {
    document.body.removeChild(el);
  });

  describe('Truncate by count', () => {
    it('truncates text by character count', () => {
      expected = 'Grumpy wiz...';
      truncate(el, input, { count: 10 });

      assert.strictEqual(el.innerHTML, expected);
    });

    it('should not truncate if given count equals given text length', () => {
      expected = input;
      truncate(el, input, { count: 59 });

      assert.strictEqual(el.innerHTML, expected);
    });

    it('should not truncate if given count exceeds given text length', () => {
      expected = input;
      truncate(el, input, { count: 70 });

      assert.strictEqual(el.innerHTML, expected);
    });
  });

  describe('Truncate options', () => {
    it('accept an ellipsis option for trailing characters', () => {
      expected = 'Grumpy wiz???';
      truncate(el, input, { count: 10, ellipsis: '???' });

      assert(el.innerHTML === expected);
    });
  });
});
<commit_msg>Add tests for truncateByHeight<commit_after>import assert from 'power-assert';

import {truncate} from '../src/truncator';

describe('truncate methods', () => {
  let el, expected;

  const input = 'Grumpy wizards make toxic brew for the evil Queen and Jack';

  beforeEach(() => {
    el = document.createElement('p');
    document.body.appendChild(el);
  });

  afterEach(() => {
    document.body.removeChild(el);
  });

  describe('Truncate by count', () => {
    it('truncates text by character count', () => {
      expected = 'Grumpy wiz...';
      truncate(el, input, { count: 10 });

      assert.strictEqual(el.innerHTML, expected);
    });

    it('should not truncate if given count equals given text length', () => {
      expected = input;
      truncate(el, input, { count: 59 });

      assert.strictEqual(el.innerHTML, expected);
    });

    it('should not truncate if given count exceeds given text length', () => {
      expected = input;
      truncate(el, input, { count: 70 });

      assert.strictEqual(el.innerHTML, expected);
    });
  });

  describe('Truncate by height', () => {
    let style;

    beforeEach(() => {
      el.style.lineHeight = '15px';
      el.style.width = '50px';

      style = window.getComputedStyle(el);
    });

    it('truncates text until the element height is less than given height', () => {
      truncate(el, input, { height: 30 });

      assert(parseFloat(style.height) === 30); // 15px x 2lines
    });

    it('should truncate if given height can contain whole text', () => {
      expected = input;
      truncate(el, input, { height: 1000 });

      assert(el.innerHTML === expected);
    });
  });

  describe('Truncate options', () => {
    it('accept an ellipsis option for trailing characters', () => {
      expected = 'Grumpy wiz???';
      truncate(el, input, { count: 10, ellipsis: '???' });

      assert(el.innerHTML === expected);
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

import test from 'tape'
import Grid from '../../'

const WIDTH = 1600
const HEIGHT = 900

function StubWindow (id, width, height) {
  this.id = id
  this.width = width
  this.height = height
}

test('new Grid(width, height): can create grid', t => {
  t.plan(2)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    t.deepEquals(grid.size, {width: WIDTH, height: HEIGHT}, 'grid.size() returns grid size')
    t.equals(grid.windows.length, 0, 'grid.windows is a 0 length array')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('new Grid(width, height): bad parameters', t => {
  t.plan(5)
  try {
    t.throws(() => new Grid(), Error, 'cannot create grid with no params')
    t.throws(() => new Grid(undefined, HEIGHT), Error, 'cannot create grid with no width')
    t.throws(() => new Grid(WIDTH), Error, 'cannot create grid with no height')
    t.throws(() => new Grid('foo', HEIGHT), Error, 'cannot create grid with non-numeric width')
    t.throws(() => new Grid(WIDTH, 'bar'), Error, 'cannot create grid with non-numeric height')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('grid.add(window): can add window to grid', t => {
  t.plan(2)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    const stubWindow1 = new StubWindow(1, 400, 600)
    const stubWindow2 = new StubWindow(2, 400, 600)
    grid.add(stubWindow1)
    t.equals(grid.windows.length, 1, 'first window added to grid')
    grid.add(stubWindow2, 950, 0)
    t.equals(grid.windows.length, 2, 'second window added to grid')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('grid.getWindow(id): can get window by its id from a grid', t => {
  t.plan(2)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    const stubWindow1 = new StubWindow(1, 400, 600)
    const stubWindow2 = new StubWindow(2, 400, 600)
    grid.add(stubWindow1)
    grid.add(stubWindow2, 950, 0)
    t.equals(grid.getWindow(1).id, 1, 'got first window by its id')
    t.equals(grid.getWindow(2).id, 2, 'got second window by its id')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test.skip('grid.getWindow(id): bad parameters', t => {
  // TBD
})
<commit_msg>grid.getWindow bad parameters test<commit_after>'use strict'

import test from 'tape'
import Grid from '../../'

const WIDTH = 1600
const HEIGHT = 900

function StubWindow (id, width, height) {
  this.id = id
  this.width = width
  this.height = height
}

test('new Grid(width, height): can create grid', t => {
  t.plan(2)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    t.deepEquals(grid.size, {width: WIDTH, height: HEIGHT}, 'grid.size() returns grid size')
    t.equals(grid.windows.length, 0, 'grid.windows is a 0 length array')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('new Grid(width, height): bad parameters', t => {
  t.plan(5)
  try {
    t.throws(() => new Grid(), Error, 'cannot create grid with no params')
    t.throws(() => new Grid(undefined, HEIGHT), Error, 'cannot create grid with no width')
    t.throws(() => new Grid(WIDTH), Error, 'cannot create grid with no height')
    t.throws(() => new Grid('foo', HEIGHT), Error, 'cannot create grid with non-numeric width')
    t.throws(() => new Grid(WIDTH, 'bar'), Error, 'cannot create grid with non-numeric height')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('grid.add(window): can add window to grid', t => {
  t.plan(2)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    const stubWindow1 = new StubWindow(1, 400, 600)
    const stubWindow2 = new StubWindow(2, 400, 600)
    grid.add(stubWindow1)
    t.equals(grid.windows.length, 1, 'first window added to grid')
    grid.add(stubWindow2, 950, 0)
    t.equals(grid.windows.length, 2, 'second window added to grid')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('grid.getWindow(id): can get window by its id from a grid', t => {
  t.plan(2)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    const stubWindow1 = new StubWindow(1, 400, 600)
    const stubWindow2 = new StubWindow(2, 400, 600)
    grid.add(stubWindow1)
    grid.add(stubWindow2, 950, 0)
    t.equals(grid.getWindow(1).id, 1, 'got first window by its id')
    t.equals(grid.getWindow(2).id, 2, 'got second window by its id')
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})

test('grid.getWindow(id): bad parameters', t => {
  t.plan(1)
  try {
    const grid = new Grid(WIDTH, HEIGHT)
    const stubWindow1 = new StubWindow(1, 400, 600)
    grid.add(stubWindow1)
    t.throws(
      grid.getWindow(2),
      Error,
      'cannot get non-existent window'
    )
  } catch (e) {
    t.fail(e.toString())
    t.end()
  }
})
<|endoftext|>


<commit_before>// ConsenSys Truffle contract test

contract('Chainy', function(accounts){

    //nohup testrpc --account="0x967a7b8992be2482650fc470fc28bee8aab5f71c23a05db26e15878ad600af72, 81408483200000000000" --account="0x202ad4c87a83317e8180f88255b4017c65cde113b0314807bba0802758317134, 97538264000000000000" --account="0xe7b4cb45748ef5f3c953dbce5097b4ad84aec901d1613266a84a252af87953c3, 100000000000000000000" --account="0x72714ddb2ccad9c0d4c64cb645a6cff299b0c3eb8726c8a015c2b6c0fb4badd1, 100000000000000000000" --account="0x3f7a166c8e07f3731ea298642189a76ffbe9e5978852684f2e9d29bf194efae4, 100000000000000000000" --account="0x94a61afbe400c53b2bc30cd88fb3899d37afbf8e9a424fbfbaad26a2a397ba03, 0" --account="0x02ab91143f14eaaed7a84e61a51e7abb6f5c876dbcaeda580736a3b1f1c0bfad, 2000000000000000" --account="0x00d6b4b7ca5b6bb394bb96a5fb7ee52c820fab2a71108f45dbe3e9ce047bb19a, 4000000000000000" --account="0xe53790d832901b920328fb0c225644ba6037b7a304f6031aec33c35635f70486, 78765137500000000000" --account="0x4164bb78e401a6b045139dc76890cd436df0f65be81f0bc002740d1133edf7c8, 100000000000000000000" > /var/log/testrpc.log 2>&1 &

    // owner = accounts[0]
    // not_owner = accounts[8]
    // 0 balance = accounts[5]
    // 0.002 balance = accounts[6]
    // 0.004 balance = accounts[7]

    var clog = function(message){
        if(1){
            console.log(message);
        }
    }

    var aTests = [
        // config
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '0'],
                    'from'  : 'not_owner',
                    'result': 'fail'
                },
                {
                    'params': ['ne|fee', '5230000000000000'],
                    'from'  : 'owner',
                    'result': 'success'
                },
                {
                    'params': ['ne|blockoffset', '0'],
                    'from'  : 'owner',
                    'result': 'success'
                },
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'getConfig',
            'type'    : 'call',
            'tests'   : [
                {
                    'params': ['ne|fee'],
                    'from'  : 'not_owner',
                    'result': '5230000000000000'
                },
                {
                    'params': ['ne|fee'],
                    'from'  : 'owner',
                    'result': '5230000000000000'
                },
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '0'],
                    'from'  : 'owner',
                    'result': 'success'
                }
            ],
        },
        // setServiceAccount
        {
            'contract': 'Chainy',
            'method'  : 'setServiceAccount',
            'tests'   : [
                {
                    'params': ['accounts[1]', 'true'],
                    'from'  : 'not_owner',
                    'result': 'fail'
                },
                {
                    'params': ['accounts[1]', 'false'],
                    'from'  : 'owner',
                    'result': 'success'
                },
                {
                    'params': ['accounts[2]', 'true'],
                    'from'  : 'owner',
                    'result': 'success'
                },
            ],
        },
        // setReceiverAddress
        {
            'contract': 'Chainy',
            'method'  : 'setReceiverAddress',
            'tests'   : [
                {
                    'params': ['accounts[1]'],
                    'from'  : 'not_owner',
                    'result': 'fail'
                },
                {
                    'params': ['accounts[4]'],
                    'from'  : 'owner',
                    'result': 'success'
                },
            ],
        },
        // set fee to 5000000000000001
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '5000000000000001'],
                    'from'  : 'owner',
                    'result': 'success'
                }
            ],
        },
        // add Chainy data
        {
            'contract': 'Chainy',
            'method'  : 'addChainyData',
            'tests'   : [
                {
                    'params': ['ne|{"id":"CHAINY", version: 1, type: "L", url: "http:\/\/site.com\/file.zip", hash: "24356450ab5de1cf7b07a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}'],
                    'from'  : 'accounts[8]',
                    'value' : '5000000000000000',
                    'result': 'fail'
                }
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'addChainyData',
            'tests'   : [
                {
                    'params': ['ne|{"id":"CHAINY", version: 1, type: "L", url: "http:\/\/site.com\/file.zip", hash: "24356450ab5de1cf7b07a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}'],
                    'from'  : 'accounts[8]',
                    'value' : '5000000000000001',
                    'result': 'success'
                }
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '0'],
                    'from'  : 'owner',
                    'result': 'success'
                }
            ],
        },
    ];

    it("/Should check initial balance of receiver address/", function(){
        clog(web3.eth.getBalance(accounts[4]));
        assert.equal(web3.eth.getBalance(accounts[4]), 100000000000000000000, '');
    });

    aTests.forEach(function(oTest){
        oTest.tests.forEach(function(curTest){

            oTest.name = oTest.contract + "." + oTest.method + (curTest.err ? (' (' + curTest.err + ')') : '') + " from " + curTest.from + " should " + curTest.result + ", params: " + JSON.stringify(curTest.params);

            it('/' + oTest.name + '/', function(){
                //clog('Test: ' + JSON.stringify(curTest));

                var chainy = Chainy.deployed();

                var result = null;
                var from;
                if(curTest.from.substring(0, 8) == 'accounts'){
                    from = eval(curTest.from);
                }else{
                    from = ((curTest.from == 'owner') ? accounts[0] : accounts[8]);
                }
                //clog('From: ' + from);
                var aParams = [];
                if('undefined' === typeof(oTest.type)){
                    oTest.type = 'tx';
                }

                var callMethod = 'chainy.' + oTest.method + (oTest.type === 'call' ? '.call' : '') + '(';
                //clog('Params:');
                for(var i = 0; i < curTest.params.length; i++){
                    if(curTest.params[i].substring(0, 3) == 'ne|'){
                        aParams.push(curTest.params[i].substring(3));
                        //clog(curTest.params[i].substring(3));
                    }else{
                        aParams.push(eval(curTest.params[i]));
                        clog(eval(curTest.params[i]));
                    }
                    //clog(aParams[i]);
                    if(i > 0){
                        callMethod += ',';
                    }
                    callMethod += 'aParams[' + i + ']';
                }
                callMethod += ',{from: from' + (curTest.value ? (',value: ' + curTest.value) : '') + '})';
                clog('Contract method = ' + callMethod);

                return eval(callMethod)
                .then(function(res){
                    if(oTest.type == 'tx'){
                        result = 'success';
                        clog("Tx: " + res);
                    }else{
                        result = res;
                        clog("Call result: " + res);
                    }
                })
                .catch(function(e){
                    // search 'invalid JUMP'
                    if(e.toString().indexOf('invalid JUMP') >= 0){
                        result = 'fail';
                    }else{
                        result = e.toString();
                    }
                })
                .then(function(){
                    assert.equal(result, curTest.result, '');
                });
            });

        });
    });

    var aEventsData = [];
    var aChainyJson = [
        {
            'json': '{"id":"CHAINY", version: 1, type: "L", url: "http:\/\/site.com\/file.zip", hash: "24356450ab5de1cf7b07a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}',
            'result': 'success',
            'watch': true
        },
        {
            'json': '{version: 1, type: "H", hash: "ea18dbtryrtyet1eb7122c75435133b9f5002c8a19aec7e787287dc1bec83","id":"CHAINY"}',
            'result': 'fail'
        },
        {
            'json': '{version: 1, type: "T", "id":"CHAINY", description: "some text here"}',
            'result': 'fail'
        },
        {
            'json': '{"id": "CHAINY",version: 1, type: "L", url: "http://site.com/file.zip", hash: "76wert456546t7a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}',
            'result': 'fail'
        },
        {
            'json': '',
            'result': 'fail'
        },
        {
            'json': '{"id":"CHAINY"}',
            'result': 'fail'
        },
    ];

    aChainyJson.forEach(function(aData){
        it("/Add Chainy data '" + aData.json + '\' should ' + aData.result + '/', function(done){
            var chainy = Chainy.deployed();

            setTimeout(done, 2000);

            if(aData.watch){
                var events = chainy.chainyShortLink();
                events.watch(function(error, result){
                    if(error == null){
                        aEventsData.push(result.args);
                        events.stopWatching();
                        clog(JSON.stringify(aEventsData));
                    }else{
                        clog(error);
                    }
                });
            }

            chainy.addChainyData(aData.json, {from: accounts[3]})
            .then(function(res){
                result = 'success';
                clog("Tx: " + res);
                //var txReceipt = web3.eth.getTransactionReceipt(res);
                //clog(txReceipt);
            })
            .catch(function(e){
                if(e.toString().indexOf('invalid JUMP') >= 0){
                    result = 'fail';
                }else{
                    result = e.toString();
                }
            })
            .then(function(){
                assert.equal(result, aData.result, '');
            });
        });
    });

    var chainyCode = 'zzz';

    it("/Should check Chainy data timestamp/", function(){
        var chainy = Chainy.deployed();
        var chainyTS = 1;

        if(aEventsData.length){
            chainyTS = aEventsData[0].timestamp;

            var aCode = aEventsData[0].code.split('/');
            if(aCode.length){
                chainyCode = aCode[aCode.length - 1];
            }
        }
        return chainy.getChainyTimestamp.call(chainyCode, {from: accounts[2]})
        .then(function(res){
            assert.equal(res.valueOf(), chainyTS, '');
        });
    });

    it("/Should check Chainy data json/", function(){
        var chainy = Chainy.deployed();

        return chainy.getChainyData.call(chainyCode, {from: accounts[2]})
        .then(function(res){
            assert.equal(res.valueOf(), aChainyJson[0].json, '');
        });
    });

    it("/Should check Chainy data sender/", function(){
        var chainy = Chainy.deployed();

        return chainy.getChainySender.call(chainyCode, {from: accounts[2]})
        .then(function(res){
            assert.equal(res.valueOf(), accounts[3], '');
        });
    });

    it("/Should check final balance of receiver address/", function(){
        clog(web3.eth.getBalance(accounts[4]));
        assert.equal(web3.eth.getBalance(accounts[4]), 100005000000000000001, '');
    });

});
<commit_msg>Chainy contract tests added.<commit_after>// ConsenSys Truffle contract test

contract('Chainy', function(accounts){

    //nohup testrpc --account="0x967a7b8992be2482650fc470fc28bee8aab5f71c23a05db26e15878ad600af72, 81408483200000000000" --account="0x202ad4c87a83317e8180f88255b4017c65cde113b0314807bba0802758317134, 97538264000000000000" --account="0xe7b4cb45748ef5f3c953dbce5097b4ad84aec901d1613266a84a252af87953c3, 100000000000000000000" --account="0x72714ddb2ccad9c0d4c64cb645a6cff299b0c3eb8726c8a015c2b6c0fb4badd1, 100000000000000000000" --account="0x3f7a166c8e07f3731ea298642189a76ffbe9e5978852684f2e9d29bf194efae4, 100000000000000000000" --account="0x94a61afbe400c53b2bc30cd88fb3899d37afbf8e9a424fbfbaad26a2a397ba03, 0" --account="0x02ab91143f14eaaed7a84e61a51e7abb6f5c876dbcaeda580736a3b1f1c0bfad, 2000000000000000" --account="0x00d6b4b7ca5b6bb394bb96a5fb7ee52c820fab2a71108f45dbe3e9ce047bb19a, 4000000000000000" --account="0xe53790d832901b920328fb0c225644ba6037b7a304f6031aec33c35635f70486, 78765137500000000000" --account="0x4164bb78e401a6b045139dc76890cd436df0f65be81f0bc002740d1133edf7c8, 100000000000000000000" > /var/log/testrpc.log 2>&1 &

    // owner = accounts[0]
    // not_owner = accounts[8]
    // 0 balance = accounts[5]
    // 0.002 balance = accounts[6]
    // 0.004 balance = accounts[7]

    var clog = function(message){
        if(1){
            console.log(message);
        }
    }

    var int2base58 = function(value){
        var alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ',
            base = alphabet.length;
        if(typeof(value) !== 'number' || value !== parseInt(value)){
            clog('"int2base58" only accepts integers');
            return null;
        }
        var encoded = '';
        while(value){
            var remainder = value % base;
            value = Math.floor(value / base);
            encoded = alphabet[remainder].toString() + encoded;
        }
        return encoded;
    }

    var aTests = [
        // config
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '0'],
                    'from'  : 'not_owner',
                    'result': 'fail'
                },
                {
                    'params': ['ne|fee', '5230000000000000'],
                    'from'  : 'owner',
                    'result': 'success'
                },
                {
                    'params': ['ne|blockoffset', '0'],
                    'from'  : 'owner',
                    'result': 'success'
                },
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'getConfig',
            'type'    : 'call',
            'tests'   : [
                {
                    'params': ['ne|fee'],
                    'from'  : 'not_owner',
                    'result': '5230000000000000'
                },
                {
                    'params': ['ne|fee'],
                    'from'  : 'owner',
                    'result': '5230000000000000'
                },
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '0'],
                    'from'  : 'owner',
                    'result': 'success'
                }
            ],
        },
        // setServiceAccount
        {
            'contract': 'Chainy',
            'method'  : 'setServiceAccount',
            'tests'   : [
                {
                    'params': ['accounts[1]', 'true'],
                    'from'  : 'not_owner',
                    'result': 'fail'
                },
                {
                    'params': ['accounts[1]', 'false'],
                    'from'  : 'owner',
                    'result': 'success'
                },
                {
                    'params': ['accounts[2]', 'true'],
                    'from'  : 'owner',
                    'result': 'success'
                },
            ],
        },
        // setReceiverAddress
        {
            'contract': 'Chainy',
            'method'  : 'setReceiverAddress',
            'tests'   : [
                {
                    'params': ['accounts[1]'],
                    'from'  : 'not_owner',
                    'result': 'fail'
                },
                {
                    'params': ['accounts[4]'],
                    'from'  : 'owner',
                    'result': 'success'
                },
            ],
        },
        // set fee to 5000000000000001
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '5000000000000001'],
                    'from'  : 'owner',
                    'result': 'success'
                }
            ],
        },
        // add Chainy data
        {
            'contract': 'Chainy',
            'method'  : 'addChainyData',
            'tests'   : [
                {
                    'params': ['ne|{"id":"CHAINY", version: 1, type: "L", url: "http:\/\/site.com\/file.zip", hash: "24356450ab5de1cf7b07a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}'],
                    'from'  : 'accounts[8]',
                    'value' : '5000000000000000',
                    'result': 'fail'
                }
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'addChainyData',
            'tests'   : [
                {
                    'params': ['ne|{"id":"CHAINY", version: 1, type: "L", url: "http:\/\/site.com\/file.zip", hash: "24356450ab5de1cf7b07a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}'],
                    'from'  : 'accounts[8]',
                    'value' : '5000000000000001',
                    'result': 'success'
                }
            ],
        },
        {
            'contract': 'Chainy',
            'method'  : 'setConfig',
            'tests'   : [
                {
                    'params': ['ne|fee', '0'],
                    'from'  : 'owner',
                    'result': 'success'
                }
            ],
        },
    ];

    it("/Should check initial balance of receiver address/", function(){
        clog(web3.eth.getBalance(accounts[4]));
        assert.equal(web3.eth.getBalance(accounts[4]), 100000000000000000000, '');
    });

    aTests.forEach(function(oTest){
        oTest.tests.forEach(function(curTest){

            oTest.name = oTest.contract + "." + oTest.method + (curTest.err ? (' (' + curTest.err + ')') : '') + " from " + curTest.from + " should " + curTest.result + ", params: " + JSON.stringify(curTest.params);

            it('/' + oTest.name + '/', function(){
                //clog('Test: ' + JSON.stringify(curTest));

                var chainy = Chainy.deployed();

                var result = null;
                var from;
                if(curTest.from.substring(0, 8) == 'accounts'){
                    from = eval(curTest.from);
                }else{
                    from = ((curTest.from == 'owner') ? accounts[0] : accounts[8]);
                }
                //clog('From: ' + from);
                var aParams = [];
                if('undefined' === typeof(oTest.type)){
                    oTest.type = 'tx';
                }

                var callMethod = 'chainy.' + oTest.method + (oTest.type === 'call' ? '.call' : '') + '(';
                //clog('Params:');
                for(var i = 0; i < curTest.params.length; i++){
                    if(curTest.params[i].substring(0, 3) == 'ne|'){
                        aParams.push(curTest.params[i].substring(3));
                        //clog(curTest.params[i].substring(3));
                    }else{
                        aParams.push(eval(curTest.params[i]));
                        clog(eval(curTest.params[i]));
                    }
                    //clog(aParams[i]);
                    if(i > 0){
                        callMethod += ',';
                    }
                    callMethod += 'aParams[' + i + ']';
                }
                callMethod += ',{from: from' + (curTest.value ? (',value: ' + curTest.value) : '') + '})';
                clog('Contract method = ' + callMethod);

                return eval(callMethod)
                .then(function(res){
                    if(oTest.type == 'tx'){
                        result = 'success';
                        clog("Tx: " + res);
                    }else{
                        result = res;
                        clog("Call result: " + res);
                    }
                })
                .catch(function(e){
                    // search 'invalid JUMP'
                    if(e.toString().indexOf('invalid JUMP') >= 0){
                        result = 'fail';
                    }else{
                        result = e.toString();
                    }
                })
                .then(function(){
                    assert.equal(result, curTest.result, '');
                });
            });

        });
    });

    var aEventsData = [],
        aTxData = [],
        aChainyJson = [
        {
            'json': '{"id":"CHAINY", version: 1, type: "L", url: "http:\/\/site.com\/file.zip", hash: "24356450ab5de1cf7b07a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}',
            'result': 'success',
            'watch': true
        },
        {
            'json': '{version: 1, type: "H", hash: "ea18dbtryrtyet1eb7122c75435133b9f5002c8a19aec7e787287dc1bec83","id":"CHAINY"}',
            'result': 'fail'
        },
        {
            'json': '{version: 1, type: "T", "id":"CHAINY", description: "some text here"}',
            'result': 'fail'
        },
        {
            'json': '{"id": "CHAINY",version: 1, type: "L", url: "http://site.com/file.zip", hash: "76wert456546t7a85cda0ff91c0b44a347b731402c4fa6729ec7c98", filetype: "arc", filesize: 1024, description: "reports.everex.one"}',
            'result': 'fail'
        },
        {
            'json': '',
            'result': 'fail'
        },
        {
            'json': '{"id":"CHAINY"}',
            'result': 'fail'
        },
    ];

    var chainyCode = 'zzz';

    aChainyJson.forEach(function(aData){
        it("/Add Chainy data '" + aData.json + '\' should ' + aData.result + '/', function(done){
            var chainy = Chainy.deployed();

            setTimeout(done, 2000);

            if(aData.watch){
                var events = chainy.chainyShortLink();
                events.watch(function(error, result){
                    if(error == null){
                        aEventsData.push(result.args);
                        events.stopWatching();
                        clog(JSON.stringify(aEventsData));
                    }else{
                        clog(error);
                    }
                });
            }

            chainy.addChainyData(aData.json, {from: accounts[3]})
            .then(function(res){
                result = 'success';
                clog("Tx: " + res);
                var txReceipt = web3.eth.getTransactionReceipt(res);
                //clog(txReceipt);
                aTxData.push(txReceipt);
            })
            .catch(function(e){
                if(e.toString().indexOf('invalid JUMP') >= 0){
                    result = 'fail';
                }else{
                    result = e.toString();
                }
            })
            .then(function(){
                assert.equal(result, aData.result, '');
            });
        });
    });

    it("/Should check Chainy short link/", function(){
        var chainyLink = aEventsData[0].code.slice(0, -2),
            correctLink = 'https://txn.me/' + int2base58(parseInt(aTxData[0].blockNumber));

        assert.equal(chainyLink, correctLink, '');
    });

    it("/Should check Chainy data timestamp/", function(){
        var chainy = Chainy.deployed();
        var chainyTS = 1;

        if(aEventsData.length){
            chainyTS = aEventsData[0].timestamp;

            var aCode = aEventsData[0].code.split('/');
            if(aCode.length){
                chainyCode = aCode[aCode.length - 1];
            }
        }
        return chainy.getChainyTimestamp.call(chainyCode, {from: accounts[2]})
        .then(function(res){
            assert.equal(res.valueOf(), chainyTS, '');
        });
    });

    it("/Should check Chainy data json/", function(){
        var chainy = Chainy.deployed();

        return chainy.getChainyData.call(chainyCode, {from: accounts[2]})
        .then(function(res){
            assert.equal(res.valueOf(), aChainyJson[0].json, '');
        });
    });

    it("/Should check Chainy data sender/", function(){
        var chainy = Chainy.deployed();

        return chainy.getChainySender.call(chainyCode, {from: accounts[2]})
        .then(function(res){
            assert.equal(res.valueOf(), accounts[3], '');
        });
    });

    it("/Should check final balance of receiver address/", function(){
        clog(web3.eth.getBalance(accounts[4]));
        assert.equal(web3.eth.getBalance(accounts[4]), 100005000000000000001, '');
    });

});
<|endoftext|>


<commit_before>(function (require, module) {
  'use strict';

  var MoussakaClient = require('../libs/MoussakaClient.js');
  var chance = require('chance').Chance();
  var _ = require('lodash');

  var chai = require('chai');
  if (!chai.factory) {
    throw new Error('You need to make sure the chai js-factories plugin' +
      'is installed (chai.use(chaiJsFactories);)');
  }

  chai.factory.define('client', function (args) {

    // Required Params
    // deviceName:        The identifier for this client
    // apiKey:            User's API key for authentication
    // projectId:         The id of the associated project
    // projectVersion:    The version of this this application

    var defaultArgs = {
        deviceName: chance.name(),
        apiKey: chance.guid(),
        projectId: chance.guid(),
        projectVersion: chance.word()
    };

    args = _.assign(defaultArgs, args);

    return new MoussakaClient(args);
  });

})(require, module);
<commit_msg>Fixed case sensitivity issue with Travis<commit_after>(function (require, module) {
  'use strict';

  var MoussakaClient = require('../libs/moussakaClient.js');
  var chance = require('chance').Chance();
  var _ = require('lodash');

  var chai = require('chai');
  if (!chai.factory) {
    throw new Error('You need to make sure the chai js-factories plugin' +
      'is installed (chai.use(chaiJsFactories);)');
  }

  chai.factory.define('client', function (args) {

    // Required Params
    // deviceName:        The identifier for this client
    // apiKey:            User's API key for authentication
    // projectId:         The id of the associated project
    // projectVersion:    The version of this this application

    var defaultArgs = {
        deviceName: chance.name(),
        apiKey: chance.guid(),
        projectId: chance.guid(),
        projectVersion: chance.word()
    };

    args = _.assign(defaultArgs, args);

    return new MoussakaClient(args);
  });

})(require, module);
<|endoftext|>


<commit_before>//Player base entity class.  Should b used for any player.

ig.module('game.entities.player').requires('game.entities.character').defines(function() {
	EntityPlayer = EntityCharacter.extend({

		size:{x:32,y:64},

		maxVel: {x: 400, y: 400},

		animSheet: new ig.AnimationSheet( 'media/images/sprites/player.png', 32, 64 ), //Default spritesheet.  Lil' Schmitty with one arm.

		type:ig.Entity.TYPE.A, //Player type
		collides: ig.Entity.COLLIDES.PASSIVE,

		flip: false, //Boolean for if it's facing the default direction (left) or flipped (right)
		accelGround: 2000, //X acceleration rate when moving on ground
		friction: {x:2000, y:0}, //Friction.  We want to slow down when moving left-right but not when jumping.
		accelAir: 1000, //X acceleration rate when moving through the air
		jump: 1000, //Velocity to apply when the jump key is pressed
		health: 100,
		maxHealth: 100, //maxHealth is used to draw the percentage of health in the healthbar, as well as to make sure the player is not healed past a certain point by healthPowerUp
		shootTimer: 40/60, //Time between shots

		hitTimer: new ig.Timer(), //Time between hits
		hitFlashDuration: 3, //Time the player should be flashing when hit.  The player is also invincible during this time.
		hitFlashTick: .5, //Time between flashes
		hitFlashCurrTick: 0, //Current time between flashes
		hitFlashAlpha: .3, //Alpha for the flash
		hitFlashCurrAlpha: 1, //Current alpha for the flash

		zIndex: -9, //Drawn before most things

		init: function( x, y, settings ) {
			this.parent( x, y, settings );

			if (!ig.global.wm) {
				this.spawnArm(); //Spawn the arm
				this.shootTimer = new ig.Timer(this.shootTimer); //Set the timer for shots.  This is used to dtermine how much time should occur between shots.
			}

			// Add the default animations
			this.addAnims();
		},

		//Add the default animations
		addAnims: function() {
			this.addAnim( 'idle', .5, [0,1,2,3] );
			this.addAnim( 'run', 0.25, [4,5,6,7,8,9] );
		},

		spawnArm: function() {
			this.arm = ig.game.spawnEntity(EntityArm, this.pos.x,this.pos.y, {attachee: this});
		},

		update: function() {
			// move left or right
			var accel = this.standing ? this.accelGround : this.accelAir;
			if( ig.input.state('left') ) {
				if (this.vel.x > 0) {
					this.vel.x -= this.friction.x/60;
				}
				this.accel.x = -accel;
				this.flip = true;
			}
			else if( ig.input.state('right') ) {
				if (this.vel.x < 0) {
					this.vel.x += this.friction.x/60;
				}
				this.accel.x = accel;
				this.flip = false;
			}
			else {
				this.accel.x = 0;
			}

			// jump
			if( this.standing && (ig.input.pressed('jump') || ig.input.pressed('up')) ) {
				this.vel.y = -this.jump;
			}

			// shoot
			if( ig.input.state('lbtn') && this.shootTimer.delta() >= 0) {
				this.shoot();
				this.shootTimer.reset();
			}

			// set the current animation, based on the player's speed
			if( this.vel.y < 0 ) {
				this.currentAnim = this.anims.run;
			}
			else if( this.vel.y > 0 ) {
				this.currentAnim = this.anims.run;
			}
			else if( this.vel.x != 0 ) {
				this.currentAnim = this.anims.run;
			}
			else {
				this.currentAnim = this.anims.idle;
			}

			this.currentAnim.flip.x = this.flip;

			//hit flashing code
			if (this.hitTimer.delta() < 0) {
				this.hitFlashCurrTick += this.hitTimer.tick();
				if (this.hitFlashCurrTick >= this.hitFlashTick) {
					this.hitFlashCurrAlpha == this.hitFlashAlpha ? this.hitFlashCurrAlpha = 1 : this.hitFlashCurrAlpha = this.hitFlashAlpha;
					this.hitFlashCurrTick = 0;
				}
				this.currentAnim.alpha = this.hitFlashCurrAlpha;
			} else {
				this.currentAnim.alpha = 1;
			}
			// move!
			this.parent();

			this.arm.attacheeUpdate(this.pos.x, this.pos.y, this.flip, this.currentAnim.alpha);
			//console.log(this.arm.pos, this.pos);
		},

		receiveDamage: function(amount, other) {
			if (this.hitTimer.delta() >= 0) {
				if (this.health - amount <= 0) {
					ig.music.stop();
					this.endOfLevel(false);
				}
				this.hitTimer.set(this.hitFlashDuration);
				this.hitTimer.tick();
				this.hitFlashCurrAlpha = this.hitFlashAlpha;
				this.hitFlashCurrTick = 0;
				this.parent(amount, other);
			}
		},

		healthPowerup: function(amount) {
			this.health += amount;
			if (this.health > this.maxHealth)
				this.health = this.maxHealth;
		},

		shoot: function() {
			console.log('shooting...');
		},

		pickup: function(other) {
			console.log('picked up' + other);
		},

		endOfLevel: function(win) {
			console.log("No end of level logic supplied.");
		}
	});

	EntityArm = ig.Entity.extend({
		animSheet: new ig.AnimationSheet('media/images/sprites/arm.png', 32, 8),
		size: {x:32, y:8},
		type: ig.Entity.TYPE.NONE,
		collides: ig.Entity.COLLIDES.NONE,
		gravityFactor: 0,

		flip: false,

		zIndex: -8,

		receiveDamage: function(amount, other) {
			this.attachedTo.receiveDamage(amount,other);
		},

		init: function(x,y,settings) {
			this.parent(x,y,settings);

			this.pos.x = x;
			this.pos.y = y;

			this.attachedTo = settings.attachee;
		},

		attacheeUpdate: function(x,y, shouldFlip, alpha) { //you can't just set the pos of the arm to the pos of the attachee.  What the fuck?
			this.pos = {x:x+10, y:y+25};
			this.flip = shouldFlip;
			this.currentAnim.alpha = alpha;
		},

		draw: function() {
			this.parent();
		}
	});
});<commit_msg>Continued commenting base player entity. #19<commit_after>//Player base entity class.  Should b used for any player.

ig.module('game.entities.player').requires('game.entities.character').defines(function() {
	EntityPlayer = EntityCharacter.extend({

		size:{x:32,y:64},

		maxVel: {x: 400, y: 400},

		animSheet: new ig.AnimationSheet( 'media/images/sprites/player.png', 32, 64 ), //Default spritesheet.  Lil' Schmitty with one arm.

		type:ig.Entity.TYPE.A, //Player type
		collides: ig.Entity.COLLIDES.PASSIVE,

		flip: false, //Boolean for if it's facing the default direction (left) or flipped (right)
		accelGround: 2000, //X acceleration rate when moving on ground
		friction: {x:2000, y:0}, //Friction.  We want to slow down when moving left-right but not when jumping.
		accelAir: 1000, //X acceleration rate when moving through the air
		jump: 1000, //Velocity to apply when the jump key is pressed
		health: 100,
		maxHealth: 100, //maxHealth is used to draw the percentage of health in the healthbar, as well as to make sure the player is not healed past a certain point by healthPowerUp
		shootTimer: 40/60, //Time between shots

		hitTimer: new ig.Timer(), //Time between hits
		hitFlashDuration: 3, //Time the player should be flashing when hit.  The player is also invincible during this time.
		hitFlashTick: .5, //Time between flashes
		hitFlashCurrTick: 0, //Current time between flashes
		hitFlashAlpha: .3, //Alpha for the flash
		hitFlashCurrAlpha: 1, //Current alpha for the flash

		zIndex: -9, //Drawn before most things

		init: function( x, y, settings ) {
			this.parent( x, y, settings );

			if (!ig.global.wm) {
				this.spawnArm(); //Spawn the arm
				this.shootTimer = new ig.Timer(this.shootTimer); //Set the timer for shots.  This is used to dtermine how much time should occur between shots.
			}

			// Add the default animations
			this.addAnims();
		},

		//Add the default animations
		addAnims: function() {
			this.addAnim( 'idle', .5, [0,1,2,3] );
			this.addAnim( 'run', 0.25, [4,5,6,7,8,9] );
		},

		//Spawn the arm.  Player should probably have a subclass, playerWithArm, which should be used by all the players that use arms, like the one on level 1.
		spawnArm: function() {
			this.arm = ig.game.spawnEntity(EntityArm, this.pos.x,this.pos.y, {attachee: this});
		},

		update: function() {
			// move left or right
			var accel = this.standing ? this.accelGround : this.accelAir;
			if( ig.input.state('left') ) {
				if (this.vel.x > 0) {
					this.vel.x -= this.friction.x/60;
				}
				this.accel.x = -accel;
				this.flip = true;
			}
			else if( ig.input.state('right') ) {
				if (this.vel.x < 0) {
					this.vel.x += this.friction.x/60;
				}
				this.accel.x = accel;
				this.flip = false;
			}
			else {
				this.accel.x = 0;
			}

			// jump
			if( this.standing && (ig.input.pressed('jump') || ig.input.pressed('up')) ) {
				this.vel.y = -this.jump;
			}

			// shoot
			if( ig.input.state('lbtn') && this.shootTimer.delta() >= 0) {
				this.shoot();
				this.shootTimer.reset();
			}

			// set the current animation, based on the player's speed
			if( this.vel.y < 0 ) {
				this.currentAnim = this.anims.run;
			}
			else if( this.vel.y > 0 ) {
				this.currentAnim = this.anims.run;
			}
			else if( this.vel.x != 0 ) {
				this.currentAnim = this.anims.run;
			}
			else {
				this.currentAnim = this.anims.idle;
			}

			this.currentAnim.flip.x = this.flip;

			//hit flashing code
			if (this.hitTimer.delta() < 0) {
				this.hitFlashCurrTick += this.hitTimer.tick();
				if (this.hitFlashCurrTick >= this.hitFlashTick) {
					this.hitFlashCurrAlpha == this.hitFlashAlpha ? this.hitFlashCurrAlpha = 1 : this.hitFlashCurrAlpha = this.hitFlashAlpha;
					this.hitFlashCurrTick = 0;
				}
				this.currentAnim.alpha = this.hitFlashCurrAlpha;
			} else {
				this.currentAnim.alpha = 1;
			}
			// move!
			this.parent();

			this.arm.attacheeUpdate(this.pos.x, this.pos.y, this.flip, this.currentAnim.alpha);
			//console.log(this.arm.pos, this.pos);
		},

		receiveDamage: function(amount, other) {
			if (this.hitTimer.delta() >= 0) {
				if (this.health - amount <= 0) {
					ig.music.stop();
					this.endOfLevel(false);
				}
				this.hitTimer.set(this.hitFlashDuration);
				this.hitTimer.tick();
				this.hitFlashCurrAlpha = this.hitFlashAlpha;
				this.hitFlashCurrTick = 0;
				this.parent(amount, other);
			}
		},

		healthPowerup: function(amount) {
			this.health += amount;
			if (this.health > this.maxHealth)
				this.health = this.maxHealth;
		},

		shoot: function() {
			console.log('shooting...');
		},

		pickup: function(other) {
			console.log('picked up' + other);
		},

		endOfLevel: function(win) {
			console.log("No end of level logic supplied.");
		}
	});

	EntityArm = ig.Entity.extend({
		animSheet: new ig.AnimationSheet('media/images/sprites/arm.png', 32, 8),
		size: {x:32, y:8},
		type: ig.Entity.TYPE.NONE,
		collides: ig.Entity.COLLIDES.NONE,
		gravityFactor: 0,

		flip: false,

		zIndex: -8,

		receiveDamage: function(amount, other) {
			this.attachedTo.receiveDamage(amount,other);
		},

		init: function(x,y,settings) {
			this.parent(x,y,settings);

			this.pos.x = x;
			this.pos.y = y;

			this.attachedTo = settings.attachee;
		},

		attacheeUpdate: function(x,y, shouldFlip, alpha) { //you can't just set the pos of the arm to the pos of the attachee.  What the fuck?
			this.pos = {x:x+10, y:y+25};
			this.flip = shouldFlip;
			this.currentAnim.alpha = alpha;
		},

		draw: function() {
			this.parent();
		}
	});
});<|endoftext|>


<commit_before>/*!
 * Angular Input Types v2.0.2-SNAPSHOT
 * (c) 2017 Jon Wikman. https://github.com/FlaxHaxx/angular-input-types
 * License: MIT
 */
!function(e){function n(t){if(r[t])return r[t].exports;var i=r[t]={i:t,l:!1,exports:{}};return e[t].call(i.exports,i,i.exports,n),i.l=!0,i.exports}var r={};n.m=e,n.c=r,n.i=function(e){return e},n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:t})},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n(n.s=6)}([function(e,n){angular.module("inputTypes").service("inputUtils",function(){this.getCursorPos=function(e){return e.selectionEnd},this.setCursorPos=function(e,n){if(e.setSelectionRange)e.focus(),window.setTimeout(function(){e.setSelectionRange(n,n)});else if(e.createTextRange){var r=e.createTextRange();r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",n),r.select()}}})},function(e,n){angular.module("inputTypes").provider("inputNumber",function(){this.nrOfDecimals=0,this.$get=function(){return this}}).directive("inputNumber",["$browser","$filter","$locale","$parse","$sniffer","inputNumber","inputUtils","validate",function(e,n,r,t,i,u,l,a){function c(e){if(null==e)return null;var n=(""+e).replace(".",p).replace(new RegExp("[^\\d|\\-+|\\"+p+"+]","g"),""),r="^\\-?\\d+";return d>0&&(r+="(\\"+p+"\\d{0,"+d+"})?"),n=n.match(new RegExp(r,"g")),null===n?null:n[0]}function o(e,n,r){var t=l.getCursorPos(e[0]);if(e.val(null===n?"":g(n)),null!==n){var i=n.toString().split(p)[0].length;i>0&&"-"==n.charAt(0)&&i--,i>1&&i%3==1&&t<=i+Math.floor(i/3)&&t++,t>1&&v>i&&v%3>0&&t--,r.$evalAsync(l.setCursorPos(e[0],t)),v=i}}function g(e){var n=(e+"").split(p);return n[0]=n[0].replace(/\B(?=(\d{3})+(?!\d))/g,f),n.join(p)}function s(e,n){return e.indexOf(n)==-1?0:e.split(n)[1].length}var f=r.NUMBER_FORMATS.GROUP_SEP,p=r.NUMBER_FORMATS.DECIMAL_SEP,d=u.nrOfDecimals,v=0;return{restrict:"A",require:"ngModel",link:function(e,n,r,u){var l=e.$eval(r.decimals);void 0!==l&&(d=l);var a=e.$eval(r.min);if(u.$parsers.unshift(function(r){if(r){var t=c(r);if(!(null==t||s(t,p)>d))return o(n,t,e),s(r,p)>d&&(i.hasEvent("input")?n.triggerHandler("input"):n.triggerHandler("change")),u.$validators.min=function(e,n){return u.$isEmpty(e)||void 0===a||e>=a},null===t?null:t.replace(p,".").replace(/\.$/,"")}}),r.ngModel){var g=t(r.ngModel)(e);g&&o(n,c(g),e)}}}}])},function(e,n){angular.module("inputTypes").directive("inputOrgnr",["$browser","$sniffer","validate",function(e,n,r){function t(e){var n=e.slice(0,2),t=16==n||18==n||19==n||20==n;if((6==e.length&&!t||8==e.length&&t)&&e.indexOf("-")==-1&&(e+="-"),10==e.length&&!t||12==e.length&&t){var i=e.slice(0,e.length-4)+"-"+e.slice(e.length-4);r.orgnr(i)&&(e=i)}return e}function i(e){if(e.length<2)return e;var n=e.slice(0,2),r=16==n||18==n||19==n||20==n;return(10==e.length&&!r||12==e.length&&r)&&e.indexOf("-")==-1&&(e=e.slice(0,e.length-4)+"-"+e.slice(e.length-4)),e}return{restrict:"A",require:"ngModel",link:function(u,l,a,c){c.$validators.orgnr=function(e,n){return c.$isEmpty(e)||r.orgnr(n)};var o=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=t(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))},g=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=i(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))};l.bind("keydown",function(n){var r=n.keyCode;8==r||46==r||91==r||15<r&&r<19||37<=r&&r<=40||e.defer(o)}),l.bind("paste cut",function(){e.defer(g)}),l.bind("change",o)}}}])},function(e,n){angular.module("inputTypes").directive("inputPersonnummer",["$browser","$sniffer","validate",function(e,n,r){function t(e){if(2==e.length&&e!=l-1&&e!=l&&(e=u(e)+e),7==e.length&&"-"==e[6]&&(e=u(e.slice(0,2))+e),8==e.length&&e.indexOf("-")==-1&&(e+="-"),12==e.length&&e.indexOf("-")==-1){var n=e.slice(0,8)+"-"+e.slice(8);r.personnummer(n)&&(e=n)}return e}function i(e){return e.length<2?e:(10==e.length&&(e=u(e.slice(0,2))+e),12==e.length&&(e=e.slice(0,8)+"-"+e.slice(8)),e)}function u(e){return e>a?l-1:l}var l=String((new Date).getFullYear()).slice(0,2),a=String((new Date).getFullYear()).slice(2,4);return{restrict:"A",require:"ngModel",link:function(u,l,a,c){c.$validators.personnummer=function(e,n){return c.$isEmpty(e)||r.personnummer(n)};var o=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=t(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))},g=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=i(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))};l.bind("keydown",function(n){var r=n.keyCode;8==r||46==r||91==r||15<r&&r<19||37<=r&&r<=40||e.defer(o)}),l.bind("paste cut",function(){e.defer(g)}),l.bind("change",g)}}}])},function(e,n){angular.module("inputTypes").directive("inputTime",["$browser","$parse","validate",function(e,n,r){function t(e){if(e.length>5)return e.substring(0,5);if(":"==e.charAt(e.length-1))for(;e.length<3;)e="0"+e;return 2==e.length?e+":":e.length>4&&":"==e.charAt(4)?e.substring(0,4):e}function i(e){return e.match(/\d{1,2}:\d{2}/g)[0],5==e.length?e:4==e.length?"0"+e:""}function u(e,n){e.val(null===n?"":n),e.triggerHandler("input")}function l(e){return e.replace(/[^0-9\:]/g,"").replace("::",":")}function a(e){return("0"+e).slice(-2)}return{restrict:"A",require:"ngModel",link:function(c,o,g,s){s.$parsers.unshift(function(e){e&&e.length>5&&(e=e.substring(0,5));var n=s.$isEmpty(e)||r.time(e);return s.$setValidity("time",n),n?e:void 0});var f=function(){o.val()&&u(o,t(l(o.val())))},p=function(){u(o,i(l(o.val())))};if(o.bind("keydown",function(n){var r=n.keyCode;8==r||46==r||91==r||15<r&&r<19||37<=r&&r<=40||e.defer(f)}),o.bind("paste cut",function(){e.defer(p)}),o.bind("change",p),g.ngModel){var d=n(g.ngModel)(c);d&&(u(o,a(d.getHours())+":"+a(d.getMinutes())),o.triggerHandler("change"))}}}}])},function(e,n){angular.module("inputTypes").factory("validate",function(){function e(e){return!isNaN(e)}function n(e){return 13==e.length&&i(e)&&u(e)}function r(e){return(11==e.length||13==e.length)&&(!!e.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})\-(\d{4})$/)&&(parseInt(RegExp.$3)<20?n(11==e.length?"20"+e:e):(""==RegExp.$1||16==RegExp.$1)&&u(e)))}function t(e){if(5!=e.length)return!1;if(":"!==e.charAt(2))return!1;var n=e.substring(0,2);if(n<0||n>23)return!1;var r=e.substring(3,5);return!(r<0||r>59)}function i(e){if(!e.match(/^(\d{4})(\d{2})(\d{2})\-(\d{4})$/))return!1;var n=new Date(RegExp.$1,RegExp.$2-1,RegExp.$3<61?RegExp.$3:1);return!(RegExp.$1<1840||n.getFullYear()!=RegExp.$1||n.getMonth()!=RegExp.$2-1||n.getDate()!=RegExp.$3&&(RegExp.$3<61||RegExp.$3>91))}function u(e){e=e.replace("-",""),12==e.length&&(e=e.substring(2));for(var n=0,r=0;r<10;r++){var t=parseInt(e.charAt(r));r%2==0&&(t*=2),t>9&&(t-=9),n+=t}return n%10==0}return{number:e,personnummer:n,orgnr:r,time:t}})},function(e,n,r){angular.module("inputTypes",[]),r(0),r(5),r(1),r(2),r(3),r(4)}]);<commit_msg>Version 2.0.2 built<commit_after>/*!
 * Angular Input Types v2.0.2
 * (c) 2017 Jon Wikman. https://github.com/FlaxHaxx/angular-input-types
 * License: MIT
 */
!function(e){function n(t){if(r[t])return r[t].exports;var i=r[t]={i:t,l:!1,exports:{}};return e[t].call(i.exports,i,i.exports,n),i.l=!0,i.exports}var r={};n.m=e,n.c=r,n.i=function(e){return e},n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:t})},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n(n.s=6)}([function(e,n){angular.module("inputTypes").service("inputUtils",function(){this.getCursorPos=function(e){return e.selectionEnd},this.setCursorPos=function(e,n){if(e.setSelectionRange)e.focus(),window.setTimeout(function(){e.setSelectionRange(n,n)});else if(e.createTextRange){var r=e.createTextRange();r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",n),r.select()}}})},function(e,n){angular.module("inputTypes").provider("inputNumber",function(){this.nrOfDecimals=0,this.$get=function(){return this}}).directive("inputNumber",["$browser","$filter","$locale","$parse","$sniffer","inputNumber","inputUtils","validate",function(e,n,r,t,i,u,l,a){function c(e){if(null==e)return null;var n=(""+e).replace(".",p).replace(new RegExp("[^\\d|\\-+|\\"+p+"+]","g"),""),r="^\\-?\\d+";return d>0&&(r+="(\\"+p+"\\d{0,"+d+"})?"),n=n.match(new RegExp(r,"g")),null===n?null:n[0]}function o(e,n,r){var t=l.getCursorPos(e[0]);if(e.val(null===n?"":g(n)),null!==n){var i=n.toString().split(p)[0].length;i>0&&"-"==n.charAt(0)&&i--,i>1&&i%3==1&&t<=i+Math.floor(i/3)&&t++,t>1&&v>i&&v%3>0&&t--,r.$evalAsync(l.setCursorPos(e[0],t)),v=i}}function g(e){var n=(e+"").split(p);return n[0]=n[0].replace(/\B(?=(\d{3})+(?!\d))/g,f),n.join(p)}function s(e,n){return e.indexOf(n)==-1?0:e.split(n)[1].length}var f=r.NUMBER_FORMATS.GROUP_SEP,p=r.NUMBER_FORMATS.DECIMAL_SEP,d=u.nrOfDecimals,v=0;return{restrict:"A",require:"ngModel",link:function(e,n,r,u){var l=e.$eval(r.decimals);void 0!==l&&(d=l);var a=e.$eval(r.min);if(u.$parsers.unshift(function(r){if(r){var t=c(r);if(!(null==t||s(t,p)>d))return o(n,t,e),s(r,p)>d&&(i.hasEvent("input")?n.triggerHandler("input"):n.triggerHandler("change")),u.$validators.min=function(e,n){return u.$isEmpty(e)||void 0===a||e>=a},null===t?null:t.replace(p,".").replace(/\.$/,"")}}),r.ngModel){var g=t(r.ngModel)(e);g&&o(n,c(g),e)}}}}])},function(e,n){angular.module("inputTypes").directive("inputOrgnr",["$browser","$sniffer","validate",function(e,n,r){function t(e){var n=e.slice(0,2),t=16==n||18==n||19==n||20==n;if((6==e.length&&!t||8==e.length&&t)&&e.indexOf("-")==-1&&(e+="-"),10==e.length&&!t||12==e.length&&t){var i=e.slice(0,e.length-4)+"-"+e.slice(e.length-4);r.orgnr(i)&&(e=i)}return e}function i(e){if(e.length<2)return e;var n=e.slice(0,2),r=16==n||18==n||19==n||20==n;return(10==e.length&&!r||12==e.length&&r)&&e.indexOf("-")==-1&&(e=e.slice(0,e.length-4)+"-"+e.slice(e.length-4)),e}return{restrict:"A",require:"ngModel",link:function(u,l,a,c){c.$validators.orgnr=function(e,n){return c.$isEmpty(e)||r.orgnr(n)};var o=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=t(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))},g=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=i(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))};l.bind("keydown",function(n){var r=n.keyCode;8==r||46==r||91==r||15<r&&r<19||37<=r&&r<=40||e.defer(o)}),l.bind("paste cut",function(){e.defer(g)}),l.bind("change",o)}}}])},function(e,n){angular.module("inputTypes").directive("inputPersonnummer",["$browser","$sniffer","validate",function(e,n,r){function t(e){if(2==e.length&&e!=l-1&&e!=l&&(e=u(e)+e),7==e.length&&"-"==e[6]&&(e=u(e.slice(0,2))+e),8==e.length&&e.indexOf("-")==-1&&(e+="-"),12==e.length&&e.indexOf("-")==-1){var n=e.slice(0,8)+"-"+e.slice(8);r.personnummer(n)&&(e=n)}return e}function i(e){return e.length<2?e:(10==e.length&&(e=u(e.slice(0,2))+e),12==e.length&&(e=e.slice(0,8)+"-"+e.slice(8)),e)}function u(e){return e>a?l-1:l}var l=String((new Date).getFullYear()).slice(0,2),a=String((new Date).getFullYear()).slice(2,4);return{restrict:"A",require:"ngModel",link:function(u,l,a,c){c.$validators.personnummer=function(e,n){return c.$isEmpty(e)||r.personnummer(n)};var o=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=t(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))},g=function(){var e=l.val().replace(/[^0-9\-]/g,"").replace("--","-");(e=i(e))!=l.val()&&(l.val(e),n.hasEvent("input")?l.triggerHandler("input"):l.triggerHandler("change"))};l.bind("keydown",function(n){var r=n.keyCode;8==r||46==r||91==r||15<r&&r<19||37<=r&&r<=40||e.defer(o)}),l.bind("paste cut",function(){e.defer(g)}),l.bind("change",g)}}}])},function(e,n){angular.module("inputTypes").directive("inputTime",["$browser","$parse","validate",function(e,n,r){function t(e){if(e.length>5)return e.substring(0,5);if(":"==e.charAt(e.length-1))for(;e.length<3;)e="0"+e;return 2==e.length?e+":":e.length>4&&":"==e.charAt(4)?e.substring(0,4):e}function i(e){return e.match(/\d{1,2}:\d{2}/g)[0],5==e.length?e:4==e.length?"0"+e:""}function u(e,n){e.val(null===n?"":n),e.triggerHandler("input")}function l(e){return e.replace(/[^0-9\:]/g,"").replace("::",":")}function a(e){return("0"+e).slice(-2)}return{restrict:"A",require:"ngModel",link:function(c,o,g,s){s.$parsers.unshift(function(e){e&&e.length>5&&(e=e.substring(0,5));var n=s.$isEmpty(e)||r.time(e);return s.$setValidity("time",n),n?e:void 0});var f=function(){o.val()&&u(o,t(l(o.val())))},p=function(){u(o,i(l(o.val())))};if(o.bind("keydown",function(n){var r=n.keyCode;8==r||46==r||91==r||15<r&&r<19||37<=r&&r<=40||e.defer(f)}),o.bind("paste cut",function(){e.defer(p)}),o.bind("change",p),g.ngModel){var d=n(g.ngModel)(c);d&&(u(o,a(d.getHours())+":"+a(d.getMinutes())),o.triggerHandler("change"))}}}}])},function(e,n){angular.module("inputTypes").factory("validate",function(){function e(e){return!isNaN(e)}function n(e){return 13==e.length&&i(e)&&u(e)}function r(e){return(11==e.length||13==e.length)&&(!!e.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})\-(\d{4})$/)&&(parseInt(RegExp.$3)<20?n(11==e.length?"20"+e:e):(""==RegExp.$1||16==RegExp.$1)&&u(e)))}function t(e){if(5!=e.length)return!1;if(":"!==e.charAt(2))return!1;var n=e.substring(0,2);if(n<0||n>23)return!1;var r=e.substring(3,5);return!(r<0||r>59)}function i(e){if(!e.match(/^(\d{4})(\d{2})(\d{2})\-(\d{4})$/))return!1;var n=new Date(RegExp.$1,RegExp.$2-1,RegExp.$3<61?RegExp.$3:1);return!(RegExp.$1<1840||n.getFullYear()!=RegExp.$1||n.getMonth()!=RegExp.$2-1||n.getDate()!=RegExp.$3&&(RegExp.$3<61||RegExp.$3>91))}function u(e){e=e.replace("-",""),12==e.length&&(e=e.substring(2));for(var n=0,r=0;r<10;r++){var t=parseInt(e.charAt(r));r%2==0&&(t*=2),t>9&&(t-=9),n+=t}return n%10==0}return{number:e,personnummer:n,orgnr:r,time:t}})},function(e,n,r){angular.module("inputTypes",[]),r(0),r(5),r(1),r(2),r(3),r(4)}]);<|endoftext|>


<commit_before>$(document).ready(function() {
    $(".fa-bars").click(function() {
        $(".text-menu").toggleClass('menu-appear');
    });

    $("nav .text-menu a").click(function() {
        $(".text-menu").toggleClass('menu-appear');
    });
});
<commit_msg>nav2js: initial version<commit_after>$(document).ready(function() {
    $(".mobile-toggle").click(function() {
        $(".nav-items").toggleClass("menu-appear");
    });

    $(".nav .nav-items a").click(function() {
        $(".nav-items").toggleClass("menu-appear");
    });
});
<|endoftext|>