<commit_before>/* this file contains all grammatical productions in ECMA-262 edition 5.1 ** * **/
<!-- HTML-style comments -->

import i0 from "module";
import * as i1 from "module";
import {} from "module";
import { i2, a as i3, } from "module";
import i4, * as i5 from "module";
import i6, {} from "module";
import i7, { i8, var as i9 } from "module";
import "module";

export * from "module";
export {} from "module";
export { i0, i1 as a, i2 as var, } from "module";
export {};
export { i3, i4 as in };
export var i5, i6 = 0;
export let i7, i8 = 0;
export const i9 = 0, i10 = 0;
export function i11(){}
export function* i12(){}
export class i13 {}
export class i13 extends i14 {}
export default function i15(){}
// Unfortunately (for us), we can only have a single default export.
/*
export default function (){}
export default function* i16(){}
export default function* (){}
export default class i17 {}
export default class i18 extends i19 {}
export default class {}
export default x = 0;
export default 0;
export default (0, 1);
*/

// whitespace
tab:for(;;)break	tab;
verticalTab:for(;;)breakverticalTab;
formFeed:for(;;)breakformFeed;
space:for(;;)break space;
nbsp:for(;;)break nbsp;
bom:for(;;)breakbom;

// line terminators
lineFeed:0
0;
carriageReturn:0
0;
carriageReturnLineFeed:0
0;
lineSeparator:0
0;
paragraphSeparator:0
0;

// identifier names
var $, _, \u0078, x$, x_, x\u0030, xa, x0, x0a, x0123456789,
  qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM;
// a representative sample of unicode letters and numbers
var œ一, ǻ둘, ɤ〩, φ, ﬁⅷ, ユニコード, x;
var yield; let letx; let[x] = 0; const constx = 0;
{ let x; let y = 0; const z = 0; }

null; true; false;

0; 00; 1234567890; 01234567;
0.; 0.00; 10.00; .0; .00
0e0; 0E0; 0.e0; 0.00e+0; .00e-0;
0x0; 0X0; 0x0123456789abcdefABCDEF;
0b0; 0B0; 0b01; 0b10; 0b10101010;
0o0; 0O0; 0o01234567;
2e308;

""; "'"; "\'\"\\\b\f\n\r\t\v\0";
"\1\00\400\000";
"\x01\x23\x45\x67\x89\xAB\xCD\xEF\xab\xcd\xef";
"\u0123\u4567\u89AB\uCDEF\u00ab\ucdef";
"\uD834\uDF06\u2603\u03C6 \u{1D306}\u{2603}\u{3c6} 𝌆☃φ"; "\
";

''; '"'; '\'\"\\\b\f\n\r\t\v\0';
'\1\00\400\000';
'\x01\x23\x45\x67\x89\xAB\xCD\xEF\xab\xcd\xef';
'\u0123\u4567\u89AB\uCDEF\u00ab\ucdef';
'\uD834\uDF06\u2603\u03C6 \u{1D306}\u{2603}\u{3c6} 𝌆☃φ'; '\
';

/x/; /|/; /|||/;
/^$\b\B/; /(?=(?!(?:(.))))/;
/a.\f\n\r\t\v\0\[\-\/\\\x00\u0000\uD834\uDF06\u{1d306}/; /\d\D\s\S\w\W/;
/\ca\cb\cc\cd\ce\cf\cg\ch\ci\cj\ck\cl\cm\cn\co\cp\cq\cr\cs\ct\cu\cv\cw\cx\cy\cz/;
/\cA\cB\cC\cD\cE\cF\cG\cH\cI\cJ\cK\cL\cM\cN\cO\cP\cQ\cR\cS\cT\cU\cV\cW\cX\cY\cZ/;
/[a-z-]/; /[^\b\-^]/; /[/\]\\]/;
/./i; /./g; /./m; /./igm;
/.*/; /.*?/; /.+/; /.+?/; /.?/; /.??/;
/.{0}/; /.{0,}/; /.{0,0}/;

`a`; `${0}`; `0${0,1}2`; `0${`1${2}3`}4`;
`\``; `a\${b`; `\0\n\x0A\u000A\u{A}`;

this;

x;

[]; [,]; [0]; [0,]; [,0]; [0,0]; [0,0,]; [0,,0]; [,,];

({}); ({x}); ({x:0}); ({x:0,y:0}); ({x:0,}); ({'x':0,"y":0,in:0});
({
  0: 0, 0.: 0, 0.0: 0, .0: 0, 0e0: 0, 0x0: 0, [0]: 0,
  get x(){}, set x(a){}, get 'y'(){}, set "y"(a){},
  get 0(){}, set 0(a){}, get var(){}, set var(a){},
  get [0](){}, set [0](a){}, [1](){},
  a(){}, 'b'(){}, "c"(){}, 0(){}, .1(){}, 1.(){}, 1e1(){},
  var(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){},
  set in([a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k]){},
  *d(){}, *'e'(){}, *"f"(){}, *2(){}, *.2(){}, *3.(){}, *2e2(){}, *in(){},
});
({ __proto__: null, get __proto__(){}, set __proto__(a){}, });
({ "__proto__": null, __proto__(){}, });

0..a; 0 .a; (0).a;

0[0];

// this function makes the NewExpression and CallExpression tests not throw at runtime
x = function f(){ return f; }; x[0] = x; x.a = x;

new x(); new new x()();
new x[0](); new x.a(); new x[0].a(); new x.a[0]();
new x; new new x; new new x();
new new x().a; new new x()[0];

x(); x()(); x(x); x(x, x);
x.a().a(); x[0]()[0](); x().a[0]();
x(...[0,1,], ...[], ...function* f(){ return yield 2; });
x`a`; x`0${1}2`;

x++; x--;

delete void typeof+-~!x; ++x; --x;

0*0; 0/0; 0%0;

0+0; 0-0;

0<<0; 0>>0; 0>>>0;

0<0; 0>0; 0<=0; 0>=0;
0 instanceof function(){};
0 in{};

0==0; 0!=0; 0===0; 0!==0;

0&0; 0^0; 0|0; 0&&0; 0||0;

0?0:0; 0?0?0:0:0; 0||0?x=0:x=0;

x=0; x*=0; x/=0; x%=0; x+=0; x-=0;
x<<=0; x>>=0; x>>>=0; x&=0; x^=0; x|=0;

0,0; 0,0,0; x=0,x=0;

{} {;} {0} {0;} {0;0} {0;0;}

var x; var x,y; var x,y,z;
var x=0; var x=0,y; var x,y=0; var x=0,y=0;

;

if(0); if(0);else;

do;while(0) 0;
do;while(0);
do;while(0) 0
while(0);
for(;;)break; for(0;0;0); for((0 in[]);0;);
for(var a;;)break; for(var a,b;0;0);
for(var a=0;;)break; for(var a=(0 in[]);0;);
for(x in{}); for(var x in{});
for(var x=[]in{}); for(var x=(0 in[])in{});
for(x of[]); for(var x of[]);

for(;0;)continue; x:for(;0;)continue x;

for(;;)break; x:for(;;)break x;
switch(0){case 0:break;}

function f(){ return; }
function f(){ return 0; }

with(0);

switch(0){} switch(0){case 0:} switch(0){case 0:case 0:}
switch(0){default:} switch(0){case 0:default:case 0:}
switch(0){case 0:;} switch(0){case 0:;;}
switch(0){default:;} switch(0){default:;;}

x:; x:y:;

try { throw 0; }catch(x){}

try{}catch(x){}
try{}finally{}
try{}catch(x){}finally{}

debugger;

function f(){}
function f(x){}
function f(x,y){}
function f(){ function f(){} }
{ function f(){} };
for (;0;) label: function f(){} 0
do label: function f(){} while(0)

function f(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){}
function f(){ "use strict" }
function f(){ 'use strict' }
function f(){ "other directive" }
function f(){ 'other directive' }
function f(){ ("string") }
function f(){ ('string') }
function f(){
  'string'
  +0
}

function*g(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){
  return a = yield* b = yield c = yield yield;
}
(function * g(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){
  return a = yield* b = yield c = yield yield;
})
yield;
yield +0;
yield * 0;

(function(){});
(function(x){});
(function(x,y){});
(function(){ function f(){} });
(function f(){});
(function f(x){});
(function f(x,y){});
(function f(){ function f(){} });

() => 0
() => {;}
x => x
x => x = 0
x => y => x
x => {x}
x => ({x})
(x) => x
(x) => {return x}
(x) => ({x})
({x}) => ({x})
(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k) = {;}

[a] = [...[0]];
({a} = {});
try{}catch([e]){}
try{}catch({e}){}

class A {}
class B extends new A {
  constructor(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k) {
    super(new.target);
    super()`template`;
    () => super(this);
  }
  m(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k) {
    super.m();
    super.m`template`;
    () => super.m(this);
  }

  static a(){} static 'b'(){} static 0(){} static [0](){}
  static *c(){ yield; } static *"d"() { yield; } static *1(){ yield; } static *[1](){ yield; }
  static var(){} static *in(){}

  static get e(){} static get 'f'(){} static get 2(){} static get [2](){}
  static set g(a){} static set "h"(a){} static set 3(a){} static set [3](a){}
  static get if(){} static set if(a){}

  a(){} 'b'(){} 0(){} [0](){}
  *c(){ yield; } *"d"(){ yield; } *1(){ yield; } *[1](){ yield; }
  var(){} *in(){ yield; }

  get e(){} get 'f'(){} get 2(){} get [2](){}
  set g(a){} set "h"(a){} set 3(a){} set [3](a){}
  get if() {} set if(f) {}
}
class C { "constructor"(){ super(); } }
<commit_msg>Use ES6 identifiers<commit_after>/* this file contains all grammatical productions in ECMA-262 edition 5.1 ** * **/
<!-- HTML-style comments -->

import i0 from "module";
import * as i1 from "module";
import {} from "module";
import { i2, a as i3, } from "module";
import i4, * as i5 from "module";
import i6, {} from "module";
import i7, { i8, var as i9 } from "module";
import "module";

export * from "module";
export {} from "module";
export { i0, i1 as a, i2 as var, } from "module";
export {};
export { i3, i4 as in };
export var i5, i6 = 0;
export let i7, i8 = 0;
export const i9 = 0, i10 = 0;
export function i11(){}
export function* i12(){}
export class i13 {}
export class i13 extends i14 {}
export default function i15(){}
// Unfortunately (for us), we can only have a single default export.
/*
export default function (){}
export default function* i16(){}
export default function* (){}
export default class i17 {}
export default class i18 extends i19 {}
export default class {}
export default x = 0;
export default 0;
export default (0, 1);
*/

// whitespace
tab:for(;;)break	tab;
verticalTab:for(;;)breakverticalTab;
formFeed:for(;;)breakformFeed;
space:for(;;)break space;
nbsp:for(;;)break nbsp;
bom:for(;;)breakbom;

// line terminators
lineFeed:0
0;
carriageReturn:0
0;
carriageReturnLineFeed:0
0;
lineSeparator:0
0;
paragraphSeparator:0
0;

// identifier names
var $, _, \u0078, \u{2F9F9}, x$, x_, x\u0030, x\u{e01d5}, xa, x0, x0a,
  x0123456789, qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM;
// a representative sample of ID_Start and ID_Continue
var 䩶, x, œ一, ǻ둘, ɤ〩, φ, ﬁⅷ, ユニコード, x;
var yield; let letx; let[x] = 0; const constx = 0;
{ let x; let y = 0; const z = 0; }

null; true; false;

0; 00; 1234567890; 01234567;
0.; 0.00; 10.00; .0; .00
0e0; 0E0; 0.e0; 0.00e+0; .00e-0;
0x0; 0X0; 0x0123456789abcdefABCDEF;
0b0; 0B0; 0b01; 0b10; 0b10101010;
0o0; 0O0; 0o01234567;
2e308;

""; "'"; "\'\"\\\b\f\n\r\t\v\0";
"\1\00\400\000";
"\x01\x23\x45\x67\x89\xAB\xCD\xEF\xab\xcd\xef";
"\u0123\u4567\u89AB\uCDEF\u00ab\ucdef";
"\uD834\uDF06\u2603\u03C6 \u{1D306}\u{2603}\u{3c6} 𝌆☃φ"; "\
";

''; '"'; '\'\"\\\b\f\n\r\t\v\0';
'\1\00\400\000';
'\x01\x23\x45\x67\x89\xAB\xCD\xEF\xab\xcd\xef';
'\u0123\u4567\u89AB\uCDEF\u00ab\ucdef';
'\uD834\uDF06\u2603\u03C6 \u{1D306}\u{2603}\u{3c6} 𝌆☃φ'; '\
';

/x/; /|/; /|||/;
/^$\b\B/; /(?=(?!(?:(.))))/;
/a.\f\n\r\t\v\0\[\-\/\\\x00\u0000\uD834\uDF06\u{1d306}/; /\d\D\s\S\w\W/;
/\ca\cb\cc\cd\ce\cf\cg\ch\ci\cj\ck\cl\cm\cn\co\cp\cq\cr\cs\ct\cu\cv\cw\cx\cy\cz/;
/\cA\cB\cC\cD\cE\cF\cG\cH\cI\cJ\cK\cL\cM\cN\cO\cP\cQ\cR\cS\cT\cU\cV\cW\cX\cY\cZ/;
/[a-z-]/; /[^\b\-^]/; /[/\]\\]/;
/./i; /./g; /./m; /./igm;
/.*/; /.*?/; /.+/; /.+?/; /.?/; /.??/;
/.{0}/; /.{0,}/; /.{0,0}/;

`a`; `${0}`; `0${0,1}2`; `0${`1${2}3`}4`;
`\``; `a\${b`; `\0\n\x0A\u000A\u{A}`;

this;

x;

[]; [,]; [0]; [0,]; [,0]; [0,0]; [0,0,]; [0,,0]; [,,];

({}); ({x}); ({x:0}); ({x:0,y:0}); ({x:0,}); ({'x':0,"y":0,in:0});
({
  0: 0, 0.: 0, 0.0: 0, .0: 0, 0e0: 0, 0x0: 0, [0]: 0,
  get x(){}, set x(a){}, get 'y'(){}, set "y"(a){},
  get 0(){}, set 0(a){}, get var(){}, set var(a){},
  get [0](){}, set [0](a){}, [1](){},
  a(){}, 'b'(){}, "c"(){}, 0(){}, .1(){}, 1.(){}, 1e1(){},
  var(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){},
  set in([a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k]){},
  *d(){}, *'e'(){}, *"f"(){}, *2(){}, *.2(){}, *3.(){}, *2e2(){}, *in(){},
});
({ __proto__: null, get __proto__(){}, set __proto__(a){}, });
({ "__proto__": null, __proto__(){}, });

0..a; 0 .a; (0).a;

0[0];

// this function makes the NewExpression and CallExpression tests not throw at runtime
x = function f(){ return f; }; x[0] = x; x.a = x;

new x(); new new x()();
new x[0](); new x.a(); new x[0].a(); new x.a[0]();
new x; new new x; new new x();
new new x().a; new new x()[0];

x(); x()(); x(x); x(x, x);
x.a().a(); x[0]()[0](); x().a[0]();
x(...[0,1,], ...[], ...function* f(){ return yield 2; });
x`a`; x`0${1}2`;

x++; x--;

delete void typeof+-~!x; ++x; --x;

0*0; 0/0; 0%0;

0+0; 0-0;

0<<0; 0>>0; 0>>>0;

0<0; 0>0; 0<=0; 0>=0;
0 instanceof function(){};
0 in{};

0==0; 0!=0; 0===0; 0!==0;

0&0; 0^0; 0|0; 0&&0; 0||0;

0?0:0; 0?0?0:0:0; 0||0?x=0:x=0;

x=0; x*=0; x/=0; x%=0; x+=0; x-=0;
x<<=0; x>>=0; x>>>=0; x&=0; x^=0; x|=0;

0,0; 0,0,0; x=0,x=0;

{} {;} {0} {0;} {0;0} {0;0;}

var x; var x,y; var x,y,z;
var x=0; var x=0,y; var x,y=0; var x=0,y=0;

;

if(0); if(0);else;

do;while(0) 0;
do;while(0);
do;while(0) 0
while(0);
for(;;)break; for(0;0;0); for((0 in[]);0;);
for(var a;;)break; for(var a,b;0;0);
for(var a=0;;)break; for(var a=(0 in[]);0;);
for(x in{}); for(var x in{});
for(var x=[]in{}); for(var x=(0 in[])in{});
for(x of[]); for(var x of[]);

for(;0;)continue; x:for(;0;)continue x;

for(;;)break; x:for(;;)break x;
switch(0){case 0:break;}

function f(){ return; }
function f(){ return 0; }

with(0);

switch(0){} switch(0){case 0:} switch(0){case 0:case 0:}
switch(0){default:} switch(0){case 0:default:case 0:}
switch(0){case 0:;} switch(0){case 0:;;}
switch(0){default:;} switch(0){default:;;}

x:; x:y:;

try { throw 0; }catch(x){}

try{}catch(x){}
try{}finally{}
try{}catch(x){}finally{}

debugger;

function f(){}
function f(x){}
function f(x,y){}
function f(){ function f(){} }
{ function f(){} };
for (;0;) label: function f(){} 0
do label: function f(){} while(0)

function f(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){}
function f(){ "use strict" }
function f(){ 'use strict' }
function f(){ "other directive" }
function f(){ 'other directive' }
function f(){ ("string") }
function f(){ ('string') }
function f(){
  'string'
  +0
}

function*g(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){
  return a = yield* b = yield c = yield yield;
}
(function * g(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k){
  return a = yield* b = yield c = yield yield;
})
yield;
yield +0;
yield * 0;

(function(){});
(function(x){});
(function(x,y){});
(function(){ function f(){} });
(function f(){});
(function f(x){});
(function f(x,y){});
(function f(){ function f(){} });

() => 0
() => {;}
x => x
x => x = 0
x => y => x
x => {x}
x => ({x})
(x) => x
(x) => {return x}
(x) => ({x})
({x}) => ({x})
(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k) = {;}

[a] = [...[0]];
({a} = {});
try{}catch([e]){}
try{}catch({e}){}

class A {}
class B extends new A {
  constructor(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k) {
    super(new.target);
    super()`template`;
    () => super(this);
  }
  m(a, b = 0, [c,, d = 0, ...e], {f, g: h, i = 0, i: j = 0}, ...k) {
    super.m();
    super.m`template`;
    () => super.m(this);
  }

  static a(){} static 'b'(){} static 0(){} static [0](){}
  static *c(){ yield; } static *"d"() { yield; } static *1(){ yield; } static *[1](){ yield; }
  static var(){} static *in(){}

  static get e(){} static get 'f'(){} static get 2(){} static get [2](){}
  static set g(a){} static set "h"(a){} static set 3(a){} static set [3](a){}
  static get if(){} static set if(a){}

  a(){} 'b'(){} 0(){} [0](){}
  *c(){ yield; } *"d"(){ yield; } *1(){ yield; } *[1](){ yield; }
  var(){} *in(){ yield; }

  get e(){} get 'f'(){} get 2(){} get [2](){}
  set g(a){} set "h"(a){} set 3(a){} set [3](a){}
  get if() {} set if(f) {}
}
class C { "constructor"(){ super(); } }
<|endoftext|>


<commit_before>/* jshint ignore:start */
if (callback) {
    if(typeof define === 'function' && define.amd){
        //For backwards compatability
        var n_callback = callback;
        requirejs(["strophe"],function(o){
            n_callback(o.Strophe,o.$build,o.$msg,o.$iq,o.$pres);
        });
    }else{
        return callback(Strophe, $build, $msg, $iq, $pres);
    }
}

})(function (Strophe, build, msg, iq, pres) {
    window.Strophe = Strophe;
    window.$build = build;
    window.$msg = msg;
    window.$iq = iq;
    window.$pres = pres;
});
/* jshint ignore:end */
<commit_msg>Fix for webpack<commit_after>/* jshint ignore:start */
if (callback) {
    if(typeof define === 'function' && define.amd){
        //For backwards compatability
        var n_callback = callback;
        if (typeof requirejs === 'function') {
            requirejs(["strophe"], function(o){
                n_callback(o.Strophe,o.$build,o.$msg,o.$iq,o.$pres);
            });
        } else {
            require(["strophe"], function(o){
                n_callback(o.Strophe,o.$build,o.$msg,o.$iq,o.$pres);
            });
        }
    }else{
        return callback(Strophe, $build, $msg, $iq, $pres);
    }
}

})(function (Strophe, build, msg, iq, pres) {
    window.Strophe = Strophe;
    window.$build = build;
    window.$msg = msg;
    window.$iq = iq;
    window.$pres = pres;
});
/* jshint ignore:end */
<|endoftext|>


<commit_before>import $ from "jquery";
import _ from "lodash";
import io from "socket.io-client";
import initMap from "./map/index";
import initGraphs from "./graphs/index";
import initMenu from "./menu";
import Sessions from "./sessions";
import Parser from "./parse/index";

let socket = io();
let map = initMap($("#map")[0]);
let graphs = initGraphs($("#graphs")[0]);
let menu = initMenu($("#sessions")[0]);
let sessions = new Sessions(socket);

window.graphs = graphs;
window.map = map;

function renderMenu() {
  menu.render(sessions.allMetadata());
}

function renderMap(parser) {
  let state = parser.getState();
  map.robot.position(state.pos);
  map.robot.angle(state.angle);
  map.robot.irAngles(state.ir_angle);
  map.robot.bumpers(state.bumper);
  map.robot.irFront(state.ir_front);
  map.robot.irSide(state.ir_side);
  map.trail(parser.get("trail"));
  map.obstructions(parser.get("obstructions"));
}

function renderMapAt(parser, time) {
  let filterTime = (d) => d.time < time;
  let trail         = parser.get("trail").filter(filterTime);
  let obstructions  = parser.get("obstructions").filter(filterTime);
  let irAngles      = parser.get("ir_angles").filter(filterTime);
  let irFront       = parser.get("ir_front").filter(filterTime);
  let irSide        = parser.get("ir_side").filter(filterTime);
  let ultrasound    = parser.get("us").filter(filterTime);
  let bumpers       = parser.get("bumpers").filter(filterTime);
  map.trail(trail);
  map.obstructions(obstructions);
  if (trail.length) {
    let last = _.last(trail);
    map.robot.position(last.pos);
    map.robot.angle(last.angle);
  }
  if (irAngles.length) {
    map.robot.irAngles(_.last(irAngles).ir_angle);
  }
  if (irFront.length) {
    map.robot.irFront(_.last(irFront).ir_front);
  }
  if (irSide.length) {
    map.robot.irSide(_.last(irSide).ir_side);
  }
  if (ultrasound.length) {
    map.robot.ultrasound(_.last(ultrasound).us);
  }
  if (bumpers.length) {
    map.robot.bumpers(_.last(bumpers).bumper)
  }
}

function renderGraphs(parser) {
  // graphs.voltages(parser.get("voltages"));
  console.log(parser.get("ir_side"))
  graphs.frontIR.update(parser.get("ir_front"));
  graphs.sideIR.update(parser.get("ir_side"));
}

let throttledRenderMap = _.throttle(renderMap, 1000/25);
let throttledRenderGraphs = _.throttle(renderGraphs, 1000/5);

sessions.on("load", renderMenu);
sessions.on("add", renderMenu);

let animFrame;

menu.on("select", function(id) {
  let session = sessions.get(id);
  let messages = session.messages();
  let parser = new Parser(messages);
  map.obstructions([]);
  renderMap(parser);
  renderGraphs(parser);
  session.on("message", function(message) {
    parser.add(message);
    throttledRenderMap(parser);
    throttledRenderGraphs(parser);
  });
  graphs.onTimeChange(function(time) {
    renderMapAt(parser, time);
  });

  // if (animFrame) window.cancelAnimationFrame(animFrame);
  // play();
  // let start = Date.now();
  // function play() {
  //   renderMapAt(parser, Date.now() - start);
  //   animFrame = window.requestAnimationFrame(play);
  // }
});

$("#address").on("submit", function() {
  let host = $("#host").val();
  socket.emit("setAddress", { host });
  return false;
});
<commit_msg>Load static extract<commit_after>import $ from "jquery";
import _ from "lodash";
import io from "socket.io-client";
import initMap from "./map/index";
import initGraphs from "./graphs/index";
import initMenu from "./menu";
import Sessions from "./sessions";
import Parser from "./parse/index";

let socket = io();
let map = initMap($("#map")[0]);
let graphs = initGraphs($("#graphs")[0]);
let menu = initMenu($("#sessions")[0]);
let sessions = new Sessions(socket);

window.graphs = graphs;
window.map = map;

function renderMenu() {
  menu.render(sessions.allMetadata());
}

function renderMap(parser) {
  let state = parser.getState();
  map.robot.position(state.pos);
  map.robot.angle(state.angle);
  map.robot.irAngles(state.ir_angle);
  map.robot.bumpers(state.bumper);
  map.robot.irFront(state.ir_front);
  map.robot.irSide(state.ir_side);
  map.trail(parser.get("trail"));
  map.obstructions(parser.get("obstructions"));
}

function renderMapAt(parser, time) {
  let filterTime = (d) => d.time < time;
  let trail         = parser.get("trail").filter(filterTime);
  let obstructions  = parser.get("obstructions").filter(filterTime);
  let irAngles      = parser.get("ir_angles").filter(filterTime);
  let irFront       = parser.get("ir_front").filter(filterTime);
  let irSide        = parser.get("ir_side").filter(filterTime);
  let ultrasound    = parser.get("us").filter(filterTime);
  let bumpers       = parser.get("bumpers").filter(filterTime);
  map.trail(trail);
  map.obstructions(obstructions);
  if (trail.length) {
    let last = _.last(trail);
    map.robot.position(last.pos);
    map.robot.angle(last.angle);
  }
  if (irAngles.length) {
    map.robot.irAngles(_.last(irAngles).ir_angle);
  }
  if (irFront.length) {
    map.robot.irFront(_.last(irFront).ir_front);
  }
  if (irSide.length) {
    map.robot.irSide(_.last(irSide).ir_side);
  }
  if (ultrasound.length) {
    map.robot.ultrasound(_.last(ultrasound).us);
  }
  if (bumpers.length) {
    map.robot.bumpers(_.last(bumpers).bumper)
  }
}

function renderGraphs(parser) {
  // graphs.voltages(parser.get("voltages"));
  console.log(parser.get("ir_side"))
  graphs.frontIR.update(parser.get("ir_front"));
  graphs.sideIR.update(parser.get("ir_side"));
}

let throttledRenderMap = _.throttle(renderMap, 1000/25);
let throttledRenderGraphs = _.throttle(renderGraphs, 1000/5);

sessions.on("load", renderMenu);
sessions.on("add", renderMenu);

let animFrame;

menu.on("select", function(id) {
  let session = sessions.get(id);
  let messages = session.messages();
  let parser = new Parser(messages);
  map.obstructions([]);
  renderMap(parser);
  renderGraphs(parser);
  session.on("message", function(message) {
    parser.add(message);
    throttledRenderMap(parser);
    throttledRenderGraphs(parser);
  });
  graphs.onTimeChange(function(time) {
    renderMapAt(parser, time);
  });

  // if (animFrame) window.cancelAnimationFrame(animFrame);
  // play();
  // let start = Date.now();
  // function play() {
  //   renderMapAt(parser, Date.now() - start);
  //   animFrame = window.requestAnimationFrame(play);
  // }
});

$("#address").on("submit", function() {
  let host = $("#host").val();
  socket.emit("setAddress", { host });
  return false;
});

// load static JSON data from race.
$.getJSON("extracts/race-sessions.json", function(data) {
  sessions.load(data);
});
<|endoftext|>


<commit_before>import logger from 'chayns-logger';
import ConsoleLogger from './utils/console-logger';
import { decodeTobitAccessToken } from './utils/convert';
import { getUrlParameters } from './utils/helper';
import { getTobitAccessToken } from './json-native-calls/calls/index';
import Request from './utils/request';

import LOGIN_TAPP from './constants/login-tapp';
import { DEFAULT_LOCATIONID } from './constants/defaults';
import VERSION from './constants/version';

const consoleLoggerLocation = new ConsoleLogger('loadLocation(chayns-info.js)');
const consoleLoggerTapps = new ConsoleLogger('loadTapps(chayns-info.js)');

export let chaynsInfo;
let globalData;

export async function loadLocation(locationId = DEFAULT_LOCATIONID) {
    try {
        const locationSettingsRequest = await Request.get(`https://chaynssvc.tobit.com/v0.4/${locationId}/LocationSettings`);

        if (locationSettingsRequest.status === 204) {
            consoleLoggerLocation.warn('no location found');
            logger.warning({
                message: 'No location found.',
                fileName: 'chaynsInfo.js',
                section: 'loadLocation',
                locationId
            });
            return false;
        }

        const locationSettingsRequestResponse = await locationSettingsRequest.json();
        const locationSettings = await locationSettingsRequestResponse.data;

        locationSettings.design.color = `#${locationSettings.design.color}`;

        const getTobitAccessTokenRes = await getTobitAccessToken();
        const accessToken = getTobitAccessTokenRes.data.tobitAccessToken;

        const payload = decodeTobitAccessToken(accessToken);

        chaynsInfo = {
            Version: VERSION,
            BaseUrl: '/',
            User: {
                ID: payload && payload.TobitUserID ? payload.TobitUserID : 0,
                FirstName: payload && payload.FirstName ? payload.FirstName : '',
                LastName: payload && payload.LastName ? payload.LastName : '',
                PersonID: payload && payload.PersonID ? payload.PersonID : '',
                TobitAccessToken: accessToken,
                UACGroups: []
            },
            LocationID: locationId,
            SiteID: locationSettings.siteId,
            LocationName: locationSettings.locationName,
            IsMobile: false,
            ExclusiveMode: false,
            IsFacebook: (document.referrer.indexOf('staticxx.facebook') > -1 || location.href.indexOf('fb=1') > -1),
            Tapps: [],
            LocationPersonID: locationSettings.locationPersonId,
            Domain: window.location.host,
            ColorMode: getUrlParameters().colormode || locationSettings.design.colorMode,
            Color: getUrlParameters().color || locationSettings.design.color,
            Webshadow: {
                MenuPosition: 0
            },
            getGlobalData: () => globalData
        };

        globalData = {
            AppUser: {
                UACGroups: [],
                FacebookAccessToken: '',
                FacebookUserName: payload && payload.FirstName && payload.LastName ? `${payload.FirstName} ${payload.LastName}` : '',
                FacebookID: payload && payload.FacebookUserID ? payload.FacebookUserID : '',
                PersonID: payload && payload.PersonID ? payload.PersonID : '',
                TobitUserID: payload && payload.TobitUserID ? payload.TobitUserID : 0,
                TobitAccessToken: accessToken,
                AdminMode: false
            },
            Device: {},
            AppInfo: {
                Version: 4014,
                domain: location.host,
                Tapps: [],
                TappSelected: {},
                FacebookAppID: locationSettings.facebookAppId,
                FacebookPageID: locationSettings.facebookId,
                Title: chaynsInfo.LocationName,
                CurrentUrl: window.location.href,
                SiteID: chaynsInfo.SiteID,
                LocationID: chaynsInfo.LocationID,
                IsColorSchemeDark: false,
                colorMode: chaynsInfo.ColorMode,
                color: chaynsInfo.Color,
            }
        };

        chaynsInfo.Tapps = await loadTapps(locationId);

        globalData.AppInfo.Tapps = chaynsInfo.Tapps;

        window.chaynsInfo = chaynsInfo;

        return true;
    } catch (e) {
        logger.error({
            message: 'Load location failed.',
            locationId,
            fileName: 'chaynsInfo.js',
            section: 'loadLocation',
            ex: {
                message: e.message,
                stackTrace: e.stack
            }
        });
        consoleLoggerLocation.error('Load location failed.', e);
        return false;
    }
}

async function loadTapps(locationId) {
    try {
        const request = await Request.get(`https://chaynssvc.tobit.com/v0.4/${locationId}/Tapp?forWeb=true`);

        if (request.status === 204) {
            consoleLoggerTapps.warn('Location has no tapps');
            logger.warning({
                message: 'Location has no tapps. (CustomNumber:Status)',
                locationId,
                customNumber: request.status,
                fileName: 'chaynsInfo.js',
                section: 'loadTapps',
            });
        } else if (request.status !== 200) {
            consoleLoggerTapps.warn('Get locationTapps failed.', request.status);
            logger.error({
                message: 'Get locationTapps failed. (CustomNumber:Status)',
                locationId,
                customNumber: request.status,
                fileName: 'chaynsInfo.js',
                section: 'loadTapps',
            });
        }

        const jsonResponse = await request.json();
        const data = jsonResponse.data || [];

        const tapps = [];
        for (const entry of data) {
            if (entry.tapps && typeof entry.tapps === 'object') {
                tapps.push(...entry.tapps);
            } else {
                tapps.push(entry);
            }
        }

        tapps.push(LOGIN_TAPP);

        return tapps;
    } catch
        (e) {
        logger.error({
            message: 'Load Tapps failed.',
            locationId,
            fileName: 'chaynsInfo.js',
            section: 'loadTapps',
            ex: {
                message: e.message,
                stackTrace: e.stack
            }
        });
        consoleLoggerTapps.error('Load Tapps failed.', e);
        return [LOGIN_TAPP];
    }
}

export function setSelectedTapp(tapp) {
    if (tapp && typeof tapp === 'object') {
        chaynsInfo.ExclusiveMode = tapp.exclusiveView || false;
        globalData.AppInfo.TappSelected = {
            Id: tapp.id,
            InternalName: tapp.internalName,
            ShowName: tapp.showName,
            SortID: tapp.sortId,
            ExclusiveMode: tapp.exclusiveView,
            LoadAsAjax: tapp.loadAsAjax,
            Url: tapp.url,
            Link: tapp.link,
            SendAuthenticationHeader: tapp.sendAuthenticationHeader,
            PostTobitAccessToken: tapp.postTobitAccessToken,
            UserGroupIds: tapp.uacGroupIds || [],
            HideFromMenu: tapp.hideFromMenu,
            Mobile: tapp.mobile,
            Desktop: tapp.desktop,
            ShowOnlyInAdminMode: tapp.showOnlyInAdminMode,
            Icon: tapp.icon,
            FallbackTapp: tapp.fallbackTapp,
            isExclusiveView: tapp.isExclusiveView
        };
    }
}
<commit_msg>adds chayns-web-light version to getGlobalData<commit_after>import logger from 'chayns-logger';
import ConsoleLogger from './utils/console-logger';
import { decodeTobitAccessToken } from './utils/convert';
import { getUrlParameters } from './utils/helper';
import { getTobitAccessToken } from './json-native-calls/calls/index';
import Request from './utils/request';

import LOGIN_TAPP from './constants/login-tapp';
import { DEFAULT_LOCATIONID } from './constants/defaults';
import VERSION from './constants/version';

const consoleLoggerLocation = new ConsoleLogger('loadLocation(chayns-info.js)');
const consoleLoggerTapps = new ConsoleLogger('loadTapps(chayns-info.js)');

export let chaynsInfo;
let globalData;

export async function loadLocation(locationId = DEFAULT_LOCATIONID) {
    try {
        const locationSettingsRequest = await Request.get(`https://chaynssvc.tobit.com/v0.4/${locationId}/LocationSettings`);

        if (locationSettingsRequest.status === 204) {
            consoleLoggerLocation.warn('no location found');
            logger.warning({
                message: 'No location found.',
                fileName: 'chaynsInfo.js',
                section: 'loadLocation',
                locationId
            });
            return false;
        }

        const locationSettingsRequestResponse = await locationSettingsRequest.json();
        const locationSettings = await locationSettingsRequestResponse.data;

        locationSettings.design.color = `#${locationSettings.design.color}`;

        const getTobitAccessTokenRes = await getTobitAccessToken();
        const accessToken = getTobitAccessTokenRes.data.tobitAccessToken;

        const payload = decodeTobitAccessToken(accessToken);

        chaynsInfo = {
            Version: VERSION,
            BaseUrl: '/',
            User: {
                ID: payload && payload.TobitUserID ? payload.TobitUserID : 0,
                FirstName: payload && payload.FirstName ? payload.FirstName : '',
                LastName: payload && payload.LastName ? payload.LastName : '',
                PersonID: payload && payload.PersonID ? payload.PersonID : '',
                TobitAccessToken: accessToken,
                UACGroups: []
            },
            LocationID: locationId,
            SiteID: locationSettings.siteId,
            LocationName: locationSettings.locationName,
            IsMobile: false,
            ExclusiveMode: false,
            IsFacebook: (document.referrer.indexOf('staticxx.facebook') > -1 || location.href.indexOf('fb=1') > -1),
            Tapps: [],
            LocationPersonID: locationSettings.locationPersonId,
            Domain: window.location.host,
            ColorMode: getUrlParameters().colormode || locationSettings.design.colorMode,
            Color: getUrlParameters().color || locationSettings.design.color,
            Webshadow: {
                MenuPosition: 0
            },
            getGlobalData: () => globalData
        };

        globalData = {
            AppUser: {
                UACGroups: [],
                FacebookAccessToken: '',
                FacebookUserName: payload && payload.FirstName && payload.LastName ? `${payload.FirstName} ${payload.LastName}` : '',
                FacebookID: payload && payload.FacebookUserID ? payload.FacebookUserID : '',
                PersonID: payload && payload.PersonID ? payload.PersonID : '',
                TobitUserID: payload && payload.TobitUserID ? payload.TobitUserID : 0,
                TobitAccessToken: accessToken,
                AdminMode: false
            },
            Device: {},
            AppInfo: {
                Version: parseInt(VERSION) || 2,
                domain: location.host,
                Tapps: [],
                TappSelected: {},
                FacebookAppID: locationSettings.facebookAppId,
                FacebookPageID: locationSettings.facebookId,
                Title: chaynsInfo.LocationName,
                CurrentUrl: window.location.href,
                SiteID: chaynsInfo.SiteID,
                LocationID: chaynsInfo.LocationID,
                IsColorSchemeDark: false,
                colorMode: chaynsInfo.ColorMode,
                color: chaynsInfo.Color,
            }
        };

        chaynsInfo.Tapps = await loadTapps(locationId);

        globalData.AppInfo.Tapps = chaynsInfo.Tapps;

        window.chaynsInfo = chaynsInfo;

        return true;
    } catch (e) {
        logger.error({
            message: 'Load location failed.',
            locationId,
            fileName: 'chaynsInfo.js',
            section: 'loadLocation',
            ex: {
                message: e.message,
                stackTrace: e.stack
            }
        });
        consoleLoggerLocation.error('Load location failed.', e);
        return false;
    }
}

async function loadTapps(locationId) {
    try {
        const request = await Request.get(`https://chaynssvc.tobit.com/v0.4/${locationId}/Tapp?forWeb=true`);

        if (request.status === 204) {
            consoleLoggerTapps.warn('Location has no tapps');
            logger.warning({
                message: 'Location has no tapps. (CustomNumber:Status)',
                locationId,
                customNumber: request.status,
                fileName: 'chaynsInfo.js',
                section: 'loadTapps',
            });
        } else if (request.status !== 200) {
            consoleLoggerTapps.warn('Get locationTapps failed.', request.status);
            logger.error({
                message: 'Get locationTapps failed. (CustomNumber:Status)',
                locationId,
                customNumber: request.status,
                fileName: 'chaynsInfo.js',
                section: 'loadTapps',
            });
        }

        const jsonResponse = await request.json();
        const data = jsonResponse.data || [];

        const tapps = [];
        for (const entry of data) {
            if (entry.tapps && typeof entry.tapps === 'object') {
                tapps.push(...entry.tapps);
            } else {
                tapps.push(entry);
            }
        }

        tapps.push(LOGIN_TAPP);

        return tapps;
    } catch
        (e) {
        logger.error({
            message: 'Load Tapps failed.',
            locationId,
            fileName: 'chaynsInfo.js',
            section: 'loadTapps',
            ex: {
                message: e.message,
                stackTrace: e.stack
            }
        });
        consoleLoggerTapps.error('Load Tapps failed.', e);
        return [LOGIN_TAPP];
    }
}

export function setSelectedTapp(tapp) {
    if (tapp && typeof tapp === 'object') {
        chaynsInfo.ExclusiveMode = tapp.exclusiveView || false;
        globalData.AppInfo.TappSelected = {
            Id: tapp.id,
            InternalName: tapp.internalName,
            ShowName: tapp.showName,
            SortID: tapp.sortId,
            ExclusiveMode: tapp.exclusiveView,
            LoadAsAjax: tapp.loadAsAjax,
            Url: tapp.url,
            Link: tapp.link,
            SendAuthenticationHeader: tapp.sendAuthenticationHeader,
            PostTobitAccessToken: tapp.postTobitAccessToken,
            UserGroupIds: tapp.uacGroupIds || [],
            HideFromMenu: tapp.hideFromMenu,
            Mobile: tapp.mobile,
            Desktop: tapp.desktop,
            ShowOnlyInAdminMode: tapp.showOnlyInAdminMode,
            Icon: tapp.icon,
            FallbackTapp: tapp.fallbackTapp,
            isExclusiveView: tapp.isExclusiveView
        };
    }
}
<|endoftext|>


<commit_before>class ContextMenu
{
  constructor(x, y)
  {
    this.element = document.createElement("div");
    this.element.className = "contextmenu";
    this.element.style.left = x + "px";
    this.element.style.top = y + "px";
    this.element.tabIndex = 0;
    this.destroyed = false;

    this.submenu = undefined;

    this.element.addEventListener("blur", (e) =>
    {
      if(!this.isChildElement(e.relatedTarget))
        this.destroy();
    });

    this.rootMenu = this;
  }

  isChildElement(element)
  {
    while(element != null)
    {
      if(this.element == element)
        return true;

      element = element.parentElement;
    }
    return false;
  }

  appendToElement(parentElement)
  {
    parentElement.appendChild(this.element);
    this.element.focus();
  }

  addButton(label, clickDelegate, destroy)
  {
    if(destroy == null)
      destroy = true;

    let menuItem = document.createElement("div");
    menuItem.className = "menuitem";
    menuItem.innerText = label;

    menuItem.addEventListener("click", () => {
      if(clickDelegate)
        clickDelegate();

      if(destroy)
        this.rootMenu.destroy();
    });

    menuItem.addEventListener("mouseover", () => {
      if(this.submenu != undefined)
        this.submenu.destroy();
    });

    this.element.appendChild(menuItem);
    return menuItem;
  }

  addBreak()
  {
    let breakElement = document.createElement("hr");
    this.element.appendChild(breakElement);
    return breakElement;
  }

  addSubmenu(label)
  {
    let submenu = new ContextMenu(0, this.element.clientY);
    submenu.rootMenu = this;

    let button = this.addButton(label);
    button.style.cursor = "default";

    let rightArrow = document.createElement("span");
    rightArrow.style.float = "right";
    rightArrow.innerText = ">";
    button.appendChild(rightArrow);

    button.addEventListener("mouseover", () => {
      let x = this.element.offsetWidth;
      submenu.element.style.top = "0px";
      submenu.element.style.left = x + "px";
      submenu.destroyed = false;

      this.element.appendChild(submenu.element);
      this.submenu = submenu;
    });

    this.element.appendChild(button);

    return submenu;
  }

  destroy()
  {
    if(this.destroyed)
      return;

    this.destroyed = true;
    this.element.remove();
  }
}<commit_msg>Create AddButtonBefore and AddButtonAfter functions for ContextMenu<commit_after>class ContextMenu
{
  constructor(x, y)
  {
    this.element = document.createElement("div");
    this.element.className = "contextmenu";
    this.element.style.left = x + "px";
    this.element.style.top = y + "px";
    this.element.tabIndex = 0;
    this.destroyed = false;

    this.submenu = undefined;

    this.element.addEventListener("blur", (e) =>
    {
      if(!this.isChildElement(e.relatedTarget))
        this.destroy();
    });

    this.rootMenu = this;
  }

  isChildElement(element)
  {
    while(element != null)
    {
      if(this.element == element)
        return true;

      element = element.parentElement;
    }
    return false;
  }

  appendToElement(parentElement)
  {
    parentElement.appendChild(this.element);
    this.element.focus();
  }

  getButton(label)
  {
    for(let node of this.element.childNodes)
      if(node.innerText == label)
        return node;
    return undefined;
  }

  addButton(label, clickDelegate, destroy)
  {
    let menuItem = this.createButton(label, clickDelegate, destroy);
    this.element.appendChild(menuItem);

    return menuItem;
  }

  addButtonBefore(nextLabel, label, clickDelegate, destroy)
  {
    let menuItem = this.createButton(label, clickDelegate, destroy);
    let nextButton = this.getButton(nextLabel);

    this.element.insertBefore(nextButton, menuItem);

    return menuItem;
  }

  addButtonAfter(previousLabel, label, clickDelegate, destroy)
  {
    let menuItem = this.createButton(label, clickDelegate, destroy);
    let previousButton = this.getButton(previousLabel);

    this.element.insertBefore(previousButton.nextSibling, menuItem);

    return menuItem;
  }

  createButton(label, clickDelegate, destroy)
  {
    if(destroy == null)
      destroy = true;

    let menuItem = document.createElement("div");
    menuItem.className = "menuitem";
    menuItem.innerText = label;

    menuItem.addEventListener("click", () => {
      if(clickDelegate)
        clickDelegate();

      if(destroy)
        this.rootMenu.destroy();
    });

    menuItem.addEventListener("mouseover", () => {
      if(this.submenu != undefined)
        this.submenu.destroy();
  });
  }

  addBreak()
  {
    let breakElement = document.createElement("hr");
    this.element.appendChild(breakElement);
    return breakElement;
  }

  addSubmenu(label)
  {
    let submenu = new ContextMenu(0, this.element.clientY);
    submenu.rootMenu = this;

    let button = this.addButton(label);
    button.style.cursor = "default";

    let rightArrow = document.createElement("span");
    rightArrow.style.float = "right";
    rightArrow.innerText = ">";
    button.appendChild(rightArrow);

    button.addEventListener("mouseover", () => {
      let x = this.element.offsetWidth;
      submenu.element.style.top = "0px";
      submenu.element.style.left = x + "px";
      submenu.destroyed = false;

      this.element.appendChild(submenu.element);
      this.submenu = submenu;
    });

    this.element.appendChild(button);

    return submenu;
  }

  destroy()
  {
    if(this.destroyed)
      return;

    this.destroyed = true;
    this.element.remove();
  }
}<|endoftext|>


<commit_before>'use strict';

const Schema = require('../').Schema;
const StandardError = require('standard-error');
const ValidateError = require('./error');
const _ = require('lodash');
const checkRequired = require('../required');
const debug = require('debug')('archetype:umarshal');
const handleCast = require('./util').handleCast;
const inspect = require('util').inspect;
const join = require('./util').join;
const mpath = require('mpath');
const realPathToSchemaPath = require('./util').realPathToSchemaPath;
const shouldSkipPath = require('../util').shouldSkipPath;

module.exports = castDocument;

function markSubpaths(projection, path, val) {
  const pieces = path.split('.');
  let cur = pieces[0];
  projection[cur] = val;
  for (let i = 1; i < pieces.length; ++i) {
    cur += `.${pieces[i]}`;
    projection[cur] = val;
  }
}

function handleProjection(projection) {
  if (!projection) {
    return { $inclusive: true };
  }
  projection = _.cloneDeep(projection);
  let inclusive = null;
  for (const key of Object.keys(projection)) {
    if (key.startsWith('$')) {
      continue;
    }
    if (projection[key] > 0) {
      if (inclusive === true) {
        throw new Error("Can't mix inclusive and exclusive in projection");
      }
      markSubpaths(projection, key, projection[key]);
      inclusive = false;
    } else {
      if (inclusive === false) {
        throw new Error("Can't mix inclusive and exclusive in projection");
      }
      inclusive = true;
    }
  }

  if (inclusive === null) {
    inclusive = true;
  }
  projection.$inclusive = inclusive;
  return projection;
}

function castDocument(obj, schema, projection) {
  projection = handleProjection(projection);
  if (obj == null) {
    throw new Error(`Can't cast null or undefined`);
  }
  obj = _.cloneDeep(obj);
  applyDefaults(obj, schema, projection);
  const error = new ValidateError();
  error.merge(visitObject(obj, schema, projection, '').error);
  error.merge(checkRequired(obj, schema, projection));
  error.merge(runValidation(obj, schema, projection));
  if (error.hasError) {
    throw error;
  }
  return obj;
}

function visitArray(arr, schema, projection, path) {
  debug('visitArray', arr, path, schema);
  let error = new ValidateError();
  let curPath = realPathToSchemaPath(path);
  let newPath = join(curPath, '$');
  if (!schema._paths[newPath] || !schema._paths[newPath].$type) {
    debug('skipping', newPath);
    return {
      value: arr,
      error: null
    };
  }

  if (arr == null) {
    return {
      value: arr,
      error: null
    };
  }

  if (!Array.isArray(arr)) {
    arr = [arr];
  }

  debug('newPath', newPath, schema._paths[newPath].$type);
  arr.forEach(function(value, index) {
    if (schema._paths[newPath].$type === Array ||
        Array.isArray(schema._paths[newPath].$type)) {
      let res = visitArray(value, schema, projection, join(path, index, true));
      if (res.error) {
        error.merge(res.error);
      }
      arr[index] = res.value;
      return;
    } else if (schema._paths[newPath].$type === Object) {
      let res = visitObject(value, schema, projection, join(path, index, true));
      if (res.error) {
        error.merge(res.error);
      }
      arr[index] = res.value;
      return;
    }

    try {
      handleTerminus(arr, index, schema, newPath);
    } catch(err) {
      error.markError(join(path, index, true), err);
    }
  });

  return {
    value: arr,
    error: (error.hasError ? error : null)
  };
}

function visitObject(obj, schema, projection, path) {
  debug('visitObject', obj, schema, projection, path);
  let error = new ValidateError();
  if (typeof obj !== 'object' || Array.isArray(obj)) {
    let err = new Error('Could not cast ' + require('util').inspect(obj) +
      ' to Object');
    error.markError(path, err);
    return {
      value: null,
      error: error
    };
  }

  let fakePath = realPathToSchemaPath(path);
  debug('fakePath', fakePath, obj);
  const curSchema = schema._paths[fakePath];
  if (fakePath && !curSchema.$schema) {
    return {
      value: obj,
      error: (error.hasError ? error : null)
    };
  }

  _.each(obj, function(value, key) {
    let newPath = join(fakePath, key);
    debug('visit', key);
    if (!schema._paths[newPath] || shouldSkipPath(projection, newPath)) {
      delete obj[key];
      return;
    }
    const newSchema = schema._paths[newPath];
    if (newSchema.$type == null) {
      // If type not specified, no type casting
      return;
    }

    if (schema._paths[newPath].$type === Array ||
        Array.isArray(schema._paths[newPath].$type)) {
      let res = visitArray(value, schema, projection, newPath);
      if (res.error) {
        debug('merge', res.error.errors);
        error.merge(res.error);
      }
      obj[key] = res.value;
      return;
    } else if (schema._paths[newPath].$type === Object) {
      if (value == null) {
        delete obj[key];
        return;
      }
      let res = visitObject(value, schema, projection, newPath);
      if (res.error) {
        debug('merge', res.error.errors);
        error.merge(res.error);
      }
      obj[key] = res.value;
      return;
    }

    try {
      handleTerminus(obj, key, schema, newPath);
    } catch(err) {
      error.markError(join(path, key, true), err);
    }
  });

  return {
    value: obj,
    error: (error.hasError ? error : null)
  };
}

function handleTerminus(value, key, schema, path) {
  schema = schema._paths[path];
  handleCast(value, key, schema.$type);
}

function runValidation(obj, schema, projection) {
  const error = new ValidateError();
  _.each(Object.keys(schema._paths), path => {
    debug(`Checking validation for "${path}"`);
    if (shouldSkipPath(projection, path)) {
      debug(`Skip validation for "${path}"`);
      return;
    }

    const _path = path.replace(/\.\$\./g, '.').replace(/\.\$$/g, '');
    const val = mpath.get(_path, obj);

    if (!schema._paths[path].$validate && !schema._paths[path].$enum) {
      debug(`No validation for "${path}"`);
      return true;
    }

    if (val == null) {
      return;
    }

    if (Array.isArray(schema._paths[path].$enum)) {
      if (Array.isArray(val)) {
        _.each(val, (val, index) => {
          if (schema._paths[path].$enum.indexOf(val) === -1) {
            const msg = `Value "${val}" invalid, allowed values are ` +
              `"${inspect(schema._paths[path].$enum)}"`;
            error.markError([path, index].join('.'), new Error(msg));
            return;
          }
        });
      } else {
        if (schema._paths[path].$enum.indexOf(val) === -1) {
          const msg = `Value "${val}" invalid, allowed values are ` +
            `"${inspect(schema._paths[path].$enum)}"`;
          error.markError(path, new Error(msg));
          return;
        }
      }
    }

    if (schema._paths[path].$validate) {
      if (Array.isArray(val)) {
        if (path.indexOf('$') === -1) {
          debug(`Path "${path}" is plain array`);
          try {
            schema._paths[path].$validate(val, schema._paths[path], obj);
          } catch(_error) {
            error.markError(path, _error);
          }
        } else {
          debug(`Validate each element for "${path}"`);
          _.each(val, (val, index) => {
            try {
              schema._paths[path].$validate(val, schema._paths[path], obj);
            } catch(_error) {
              error.markError(`${path}.${index}`, _error);
            }
          });
        }
      } else {
        try {
          schema._paths[path].$validate(val, schema._paths[path], obj);
        } catch(_error) {
          error.markError(path, _error);
        }
      }
    }
  });
  return error;
}

function applyDefaults(obj, schema, projection) {
  _.each(Object.keys(schema._paths), path => {
    if (!('$default' in schema._paths[path])) {
      return;
    }
    if (shouldSkipPath(projection, path) || projection.$noDefaults) {
      return;
    }
    const _path = path.replace(/\.\$\./g, '.').replace(/\.\$$/g, '');
    const val = mpath.get(_path, obj);
    if (Array.isArray(val)) {
      for (let i = 0; i < val.length; ++i) {
        if (val[i] == null) {
          val[i] = handleDefault(schema._paths[path].$default, obj);
        }
      }
      mpath.set(_path, val, obj);
    } else if (val == null) {
      mpath.set(_path, handleDefault(schema._paths[path].$default, obj), obj);
    }
  });
}

function handleDefault(obj, ctx) {
  if (typeof obj === 'function') {
    return obj(ctx);
  }
  return obj;
}
<commit_msg>refactor: remove unused function<commit_after>'use strict';

const Schema = require('../').Schema;
const StandardError = require('standard-error');
const ValidateError = require('./error');
const _ = require('lodash');
const checkRequired = require('../required');
const debug = require('debug')('archetype:umarshal');
const handleCast = require('./util').handleCast;
const inspect = require('util').inspect;
const join = require('./util').join;
const mpath = require('mpath');
const realPathToSchemaPath = require('./util').realPathToSchemaPath;
const shouldSkipPath = require('../util').shouldSkipPath;

module.exports = castDocument;

function markSubpaths(projection, path, val) {
  const pieces = path.split('.');
  let cur = pieces[0];
  projection[cur] = val;
  for (let i = 1; i < pieces.length; ++i) {
    cur += `.${pieces[i]}`;
    projection[cur] = val;
  }
}

function handleProjection(projection) {
  if (!projection) {
    return { $inclusive: true };
  }
  projection = _.cloneDeep(projection);
  let inclusive = null;
  for (const key of Object.keys(projection)) {
    if (key.startsWith('$')) {
      continue;
    }
    if (projection[key] > 0) {
      if (inclusive === true) {
        throw new Error("Can't mix inclusive and exclusive in projection");
      }
      markSubpaths(projection, key, projection[key]);
      inclusive = false;
    } else {
      if (inclusive === false) {
        throw new Error("Can't mix inclusive and exclusive in projection");
      }
      inclusive = true;
    }
  }

  if (inclusive === null) {
    inclusive = true;
  }
  projection.$inclusive = inclusive;
  return projection;
}

function castDocument(obj, schema, projection) {
  projection = handleProjection(projection);
  if (obj == null) {
    throw new Error(`Can't cast null or undefined`);
  }
  obj = _.cloneDeep(obj);
  applyDefaults(obj, schema, projection);
  const error = new ValidateError();
  error.merge(visitObject(obj, schema, projection, '').error);
  error.merge(checkRequired(obj, schema, projection));
  error.merge(runValidation(obj, schema, projection));
  if (error.hasError) {
    throw error;
  }
  return obj;
}

function visitArray(arr, schema, projection, path) {
  debug('visitArray', arr, path, schema);
  let error = new ValidateError();
  let curPath = realPathToSchemaPath(path);
  let newPath = join(curPath, '$');
  if (!schema._paths[newPath] || !schema._paths[newPath].$type) {
    debug('skipping', newPath);
    return {
      value: arr,
      error: null
    };
  }

  if (arr == null) {
    return {
      value: arr,
      error: null
    };
  }

  if (!Array.isArray(arr)) {
    arr = [arr];
  }

  debug('newPath', newPath, schema._paths[newPath].$type);
  arr.forEach(function(value, index) {
    if (schema._paths[newPath].$type === Array ||
        Array.isArray(schema._paths[newPath].$type)) {
      let res = visitArray(value, schema, projection, join(path, index, true));
      if (res.error) {
        error.merge(res.error);
      }
      arr[index] = res.value;
      return;
    } else if (schema._paths[newPath].$type === Object) {
      let res = visitObject(value, schema, projection, join(path, index, true));
      if (res.error) {
        error.merge(res.error);
      }
      arr[index] = res.value;
      return;
    }

    try {
      handleCast(arr, index, schema._paths[newPath].$type);
    } catch(err) {
      error.markError(join(path, index, true), err);
    }
  });

  return {
    value: arr,
    error: (error.hasError ? error : null)
  };
}

function visitObject(obj, schema, projection, path) {
  debug('visitObject', obj, schema, projection, path);
  let error = new ValidateError();
  if (typeof obj !== 'object' || Array.isArray(obj)) {
    let err = new Error('Could not cast ' + require('util').inspect(obj) +
      ' to Object');
    error.markError(path, err);
    return {
      value: null,
      error: error
    };
  }

  let fakePath = realPathToSchemaPath(path);
  debug('fakePath', fakePath, obj);
  const curSchema = schema._paths[fakePath];
  if (fakePath && !curSchema.$schema) {
    return {
      value: obj,
      error: (error.hasError ? error : null)
    };
  }

  _.each(obj, function(value, key) {
    let newPath = join(fakePath, key);
    debug('visit', key);
    if (!schema._paths[newPath] || shouldSkipPath(projection, newPath)) {
      delete obj[key];
      return;
    }
    const newSchema = schema._paths[newPath];
    if (newSchema.$type == null) {
      // If type not specified, no type casting
      return;
    }

    if (schema._paths[newPath].$type === Array ||
        Array.isArray(schema._paths[newPath].$type)) {
      let res = visitArray(value, schema, projection, newPath);
      if (res.error) {
        debug('merge', res.error.errors);
        error.merge(res.error);
      }
      obj[key] = res.value;
      return;
    } else if (schema._paths[newPath].$type === Object) {
      if (value == null) {
        delete obj[key];
        return;
      }
      let res = visitObject(value, schema, projection, newPath);
      if (res.error) {
        debug('merge', res.error.errors);
        error.merge(res.error);
      }
      obj[key] = res.value;
      return;
    }

    try {
      handleCast(obj, key, schema._paths[newPath].$type);
    } catch(err) {
      error.markError(join(path, key, true), err);
    }
  });

  return {
    value: obj,
    error: (error.hasError ? error : null)
  };
}

function runValidation(obj, schema, projection) {
  const error = new ValidateError();
  _.each(Object.keys(schema._paths), path => {
    debug(`Checking validation for "${path}"`);
    if (shouldSkipPath(projection, path)) {
      debug(`Skip validation for "${path}"`);
      return;
    }

    const _path = path.replace(/\.\$\./g, '.').replace(/\.\$$/g, '');
    const val = mpath.get(_path, obj);

    if (!schema._paths[path].$validate && !schema._paths[path].$enum) {
      debug(`No validation for "${path}"`);
      return true;
    }

    if (val == null) {
      return;
    }

    if (Array.isArray(schema._paths[path].$enum)) {
      if (Array.isArray(val)) {
        _.each(val, (val, index) => {
          if (schema._paths[path].$enum.indexOf(val) === -1) {
            const msg = `Value "${val}" invalid, allowed values are ` +
              `"${inspect(schema._paths[path].$enum)}"`;
            error.markError([path, index].join('.'), new Error(msg));
            return;
          }
        });
      } else {
        if (schema._paths[path].$enum.indexOf(val) === -1) {
          const msg = `Value "${val}" invalid, allowed values are ` +
            `"${inspect(schema._paths[path].$enum)}"`;
          error.markError(path, new Error(msg));
          return;
        }
      }
    }

    if (schema._paths[path].$validate) {
      if (Array.isArray(val)) {
        if (path.indexOf('$') === -1) {
          debug(`Path "${path}" is plain array`);
          try {
            schema._paths[path].$validate(val, schema._paths[path], obj);
          } catch(_error) {
            error.markError(path, _error);
          }
        } else {
          debug(`Validate each element for "${path}"`);
          _.each(val, (val, index) => {
            try {
              schema._paths[path].$validate(val, schema._paths[path], obj);
            } catch(_error) {
              error.markError(`${path}.${index}`, _error);
            }
          });
        }
      } else {
        try {
          schema._paths[path].$validate(val, schema._paths[path], obj);
        } catch(_error) {
          error.markError(path, _error);
        }
      }
    }
  });
  return error;
}

function applyDefaults(obj, schema, projection) {
  _.each(Object.keys(schema._paths), path => {
    if (!('$default' in schema._paths[path])) {
      return;
    }
    if (shouldSkipPath(projection, path) || projection.$noDefaults) {
      return;
    }
    const _path = path.replace(/\.\$\./g, '.').replace(/\.\$$/g, '');
    const val = mpath.get(_path, obj);
    if (Array.isArray(val)) {
      for (let i = 0; i < val.length; ++i) {
        if (val[i] == null) {
          val[i] = handleDefault(schema._paths[path].$default, obj);
        }
      }
      mpath.set(_path, val, obj);
    } else if (val == null) {
      mpath.set(_path, handleDefault(schema._paths[path].$default, obj), obj);
    }
  });
}

function handleDefault(obj, ctx) {
  if (typeof obj === 'function') {
    return obj(ctx);
  }
  return obj;
}
<|endoftext|>


<commit_before>module.exports = function( grunt ) {

    // Create a new multi task.
    grunt.registerMultiTask( 'compass', 'This triggers the `compass compile` command.', function() {

        // Tell grunt this task is asynchronous.
        var done = this.async(),
            exec = require('child_process').exec,
            command = "compass compile",
            src = undefined,
            dest = undefined,
            config = this.data.config,
            images = this.data.images,
            fonts = this.data.fonts,
            outputstyle = this.data.outputstyle,
            linecomments = this.data.linecomments,
            forcecompile = this.data.forcecompile,
            debugsass = this.data.debugsass,
            relativeassets = this.data.relativeassets,
            libRequire = this.data.require,
            bundleExec = this.data.bundleExec;
            environment = this.data.environment;

        if ( this.data.src !== undefined ) {
            src = grunt.template.process(this.data.src);
        }

        if ( this.data.dest !== undefined ) {
            dest = grunt.template.process(this.data.dest);
        }

        if ( bundleExec ) {
            command = 'bundle exec ' + command;
        }

        if ( src !== undefined && dest !== undefined ) {
            command += ' --sass-dir="' + src + '" --css-dir="' + dest + '"';
        }

        if ( config !== undefined ) {
            command += ' --config="' + config + '"';
        }

        if ( images !== undefined ) {
            command += ' --images-dir="' + images + '"';
        }

        if ( fonts !== undefined ) {
            command += ' --fonts-dir="' + fonts + '"';
        }

        if ( debugsass !== undefined ) {
            if ( debugsass === true ) {
                command += ' --debug-info';
            }
        }

        if ( relativeassets !== undefined ) {
            if ( relativeassets === true ) {
                command += ' --relative-assets';
            }
        }

        if ( outputstyle !== undefined ) {
            command += ' --output-style ' + outputstyle;
        }

        if ( linecomments === false ) {
            command += ' --no-line-comments';
        }

        if ( libRequire !== undefined ) {
            command += ' --require '+ libRequire;
        }

        if ( forcecompile === true ) {
            command += ' --force';
        }

        if ( environment !== undefined ) {
            command += ' -e ' + environment;
        }

        function puts( error, stdout, stderr ) {

            grunt.log.write( '\n\nCOMPASS output:\n' );
            grunt.log.write( stdout );
            /* grunt.log.error( stderr );
             * compass sends falsy error message to stderr... real sass/compass errors come in through the "error" variable.
             */

            if ( error !== null ) {
                grunt.log.error( error );
                done(false);
            }
            else {
                done(true);
            }
        }

        exec( command, puts );
        grunt.log.write( '`' + command + '` was initiated.' );
    });
};
<commit_msg>Add support for IMPORT_PATH.<commit_after>module.exports = function( grunt ) {

    // Create a new multi task.
    grunt.registerMultiTask( 'compass', 'This triggers the `compass compile` command.', function() {

        // Tell grunt this task is asynchronous.
        var done = this.async(),
            exec = require('child_process').exec,
            command = "compass compile",
            src = undefined,
            dest = undefined,
            config = this.data.config,
            images = this.data.images,
            fonts = this.data.fonts,
            outputstyle = this.data.outputstyle,
            linecomments = this.data.linecomments,
            forcecompile = this.data.forcecompile,
            debugsass = this.data.debugsass,
            relativeassets = this.data.relativeassets,
            libRequire = this.data.require,
            bundleExec = this.data.bundleExec;
            environment = this.data.environment,
            importPath = this.data.importPath;

        if ( this.data.src !== undefined ) {
            src = grunt.template.process(this.data.src);
        }

        if ( this.data.dest !== undefined ) {
            dest = grunt.template.process(this.data.dest);
        }

        if ( bundleExec ) {
            command = 'bundle exec ' + command;
        }

        if ( src !== undefined && dest !== undefined ) {
            command += ' --sass-dir="' + src + '" --css-dir="' + dest + '"';
        }

        if ( config !== undefined ) {
            command += ' --config="' + config + '"';
        }

        if ( images !== undefined ) {
            command += ' --images-dir="' + images + '"';
        }

        if ( fonts !== undefined ) {
            command += ' --fonts-dir="' + fonts + '"';
        }

        if ( debugsass !== undefined ) {
            if ( debugsass === true ) {
                command += ' --debug-info';
            }
        }

        if ( relativeassets !== undefined ) {
            if ( relativeassets === true ) {
                command += ' --relative-assets';
            }
        }

        if ( outputstyle !== undefined ) {
            command += ' --output-style ' + outputstyle;
        }

        if ( linecomments === false ) {
            command += ' --no-line-comments';
        }

        if ( libRequire !== undefined ) {
            command += ' --require '+ libRequire;
        }

        if ( forcecompile === true ) {
            command += ' --force';
        }

        if ( environment !== undefined ) {
            command += ' -e ' + environment;
        }

        if ( importPath !== undefined ) {
            command += ' -I ' + importPath;
        }

        function puts( error, stdout, stderr ) {

            grunt.log.write( '\n\nCOMPASS output:\n' );
            grunt.log.write( stdout );
            /* grunt.log.error( stderr );
             * compass sends falsy error message to stderr... real sass/compass errors come in through the "error" variable.
             */

            if ( error !== null ) {
                grunt.log.error( error );
                done(false);
            }
            else {
                done(true);
            }
        }

        exec( command, puts );
        grunt.log.write( '`' + command + '` was initiated.' );
    });
};
<|endoftext|>


<commit_before>import App from '../lib/components/App'
import React from 'react'
import { shallow, mount } from 'enzyme'

describe('App', () => {
  it('should have a greeting', () => {
    let wrapper = shallow(<App />)
    let greeting = wrapper.find('#greeting')

    expect(greeting.props().children).toEqual('Good Afternoon');
  })
})
<commit_msg>begin writing more tests<commit_after>import App from '../lib/components/App'
import React from 'react'
import { shallow, mount } from 'enzyme'

describe('App', () => {
  it('should start with no location', () => {
    let app = new App;
    expect(app.state.location).toEqual('');
  } )

  it('should have a greeting', () => {
    let wrapper = shallow(<App />)
    let greeting = wrapper.find('#greeting')

    expect(greeting.props().children).toEqual('Good Afternoon');
  })
})
<|endoftext|>


<commit_before>function UpDownGenes (job_id) {
  Job.call(this, job_id);
}
UpDownGenes.prototype = Object.create(Job.prototype);
UpDownGenes.prototype.constructor = UpDownGenes;

UpDownGenes.prototype.run = function () {
  // create paths for files on the disk
  var workDir = ntemp.mkdirSync("UpDownGenes");
  console.log("workDir: ", workDir);

  var deferred = Q.defer();
  var self = this;

  var exportScript = getSetting("expression3_export");
  Q.all([
      // single sample data
      spawnCommand(exportScript, [
        "--study_label", self.job.args.study_label,
        "--sample_label", self.job.args.sample_label,
      ], workDir),
      // sample group data
      spawnCommand(exportScript, [
        "--sample_group_id", self.job.args.sample_group_id,
      ], workDir),
    ])
    .then(function (spawnResults) {
      // save this result for use in a future chained promise
      self.testSamplePath = spawnResults[0].stdoutPath;
      var sampleGroupPath = spawnResults[1].stdoutPath;

      // // pulled from upDownGenes.sh
      // # arg 1: matrix file
      // # arg 2: default 1.5
      // /usr/bin/Rscript outlier.R mRNA.NBL.POG.pancan.combat.5.tab 2

      var rscript = getSetting("rscript");
      var outlierGenesPath = getSetting("calculate_outlier_genes");

      return spawnCommand(rscript, [
        outlierGenesPath,
        sampleGroupPath,
        1.5
      ], workDir);
    })
    .then(function (commandResult) {
      if (commandResult.exitCode !== 0) {
        throw new Error("Error code running up/down genes Rscript");
      }

      var sh = getSetting("sh");
      var outlierAnalysis = getSetting("outlier_analysis");

      return spawnCommand(sh, [
        outlierAnalysis,
        self.testSamplePath
      ], workDir);
    })
    .then(Meteor.bindEnvironment(function (commandResult) {
      console.log("done with single sample analysis");
      console.log("commandResult:", commandResult);

      // calculate the paths for the output files
      upPath = path.join(workDir, "up_outlier_genes")
      downPath = path.join(workDir, "down_outlier_genes")

      // insert blobs into mongo
      var upBlob = Blobs.insert(upPath);
      var downBlob = Blobs.insert(downPath);

      // parse strings
      var output = {};
      _.each([
        { name: "upGenes", fileString: fs.readFileSync(upPath, "utf8") },
        { name: "downGenes", fileString: fs.readFileSync(downPath, "utf8") },
      ], function (outlier) {
        var lineArray = outlier.fileString.split("\n");
        var filteredLines = _.filter(lineArray, function (line) {
          return line !== "";
        });

        // loop for each line
        output[outlier.name] = _.map(filteredLines, function (line) {
          console.log("line:", line);
          var tabSplit = line.split(" ");
          return {
            gene_label: tabSplit[0],
            background_median: parseFloat(tabSplit[1]),
            sample_value: parseFloat(tabSplit[2]),
          };
        });
      });

      deferred.resolve(output);
    }, deferred.reject))
    // NOTE: Meteor.bindEnvironment returns immidiately, meaning we can't
    // quite use the nice promise syntax of chainging .thens
    .catch(deferred.reject);
  return deferred.promise;
};

JobClasses.UpDownGenes = UpDownGenes;
<commit_msg>last small bugfixes<commit_after>function UpDownGenes (job_id) {
  Job.call(this, job_id);
}
UpDownGenes.prototype = Object.create(Job.prototype);
UpDownGenes.prototype.constructor = UpDownGenes;

UpDownGenes.prototype.run = function () {
  // create paths for files on the disk
  var workDir = ntemp.mkdirSync("UpDownGenes");
  console.log("workDir: ", workDir);

  var deferred = Q.defer();
  var self = this;

  var exportScript = getSetting("expression3_export");
  Q.all([
      // single sample data
      spawnCommand(exportScript, [
        "--study_label", self.job.args.study_label,
        "--sample_label", self.job.args.sample_label,
      ], workDir),
      // sample group data
      spawnCommand(exportScript, [
        "--sample_group_id", self.job.args.sample_group_id,
      ], workDir),
    ])
    .then(function (spawnResults) {
      // save this result for use in a future chained promise
      self.testSamplePath = spawnResults[0].stdoutPath;
      var sampleGroupPath = spawnResults[1].stdoutPath;

      // // pulled from upDownGenes.sh
      // # arg 1: matrix file
      // # arg 2: default 1.5
      // /usr/bin/Rscript outlier.R mRNA.NBL.POG.pancan.combat.5.tab 2

      var rscript = getSetting("rscript");
      var outlierGenesPath = getSetting("calculate_outlier_genes");

      return spawnCommand(rscript, [
        outlierGenesPath,
        sampleGroupPath,
        1.5
      ], workDir);
    })
    .then(function (commandResult) {
      if (commandResult.exitCode !== 0) {
        throw new Error("Error code running up/down genes Rscript");
      }

      var sh = getSetting("sh");
      var outlierAnalysis = getSetting("outlier_analysis");

      return spawnCommand(sh, [
        outlierAnalysis,
        self.testSamplePath
      ], workDir);
    })
    .then(Meteor.bindEnvironment(function (commandResult) {
      console.log("done with single sample analysis");
      console.log("commandResult:", commandResult);

      // calculate the paths for the output files
      upPath = path.join(workDir, "up_outlier_genes")
      downPath = path.join(workDir, "down_outlier_genes")

      // insert blobs into mongo
      var output = {
        up_blob_id: Blobs.insert(upPath)._id,
        down_blob_id: Blobs.insert(downPath)._id,
      };

      // parse strings
      _.each([
        { name: "up_genes", fileString: fs.readFileSync(upPath, "utf8") },
        { name: "down_genes", fileString: fs.readFileSync(downPath, "utf8") },
      ], function (outlier) {
        var lineArray = outlier.fileString.split("\n");
        var filteredLines = _.filter(lineArray, function (line) {
          return line !== "";
        });

        // loop for each line
        output[outlier.name] = _.map(filteredLines, function (line) {
          var tabSplit = line.split(" ");
          return {
            gene_label: tabSplit[0],
            background_median: parseFloat(tabSplit[1]),
            sample_value: parseFloat(tabSplit[2]),
          };
        });
      });

      deferred.resolve(output);
    }, deferred.reject))
    // NOTE: Meteor.bindEnvironment returns immidiately, meaning we can't
    // quite use the nice promise syntax of chainging .thens
    .catch(deferred.reject);
  return deferred.promise;
};

JobClasses.UpDownGenes = UpDownGenes;
<|endoftext|>


<commit_before>'use strict';

var Chess = require('chess.js').Chess;
var _ = require('lodash');
var interact = window.interact;

function Chessground(element, cfg) {

  var defaults = {
    orientation: 'white',
    draggable: {
      enabled: 'both', // 'white' | 'black' | 'both' | false
      events: {
        start: function( /* e, piece, pos */ ) {
          return true; // return false to prevent the drag from happening
        }
      }
    }
  };

  var constants = {
    files: 'abcdefgh',
    types: {
      p: 'pawn',
      r: 'rook',
      b: 'bishop',
      n: 'knight',
      q: 'queen',
      k: 'king'
    },
    colors: {
      w: 'white',
      b: 'black'
    },
    squares: _.flatten(_.map(_.range(1, 8), function(rank) {
      return _.map('abcdefgh', function(file) {
        return '' + rank + file;
      });
    }))
  };

  // all mutable data goes in there
  // use the fen config to create a chess object,
  // then drop the fen. The chess object will provide it.
  var state = _.omit(_.merge(defaults, cfg), 'fen');
  state.chess = new Chess();
  state.selected = null;
  if (cfg && cfg.fen) state.chess.load(cfg.fen); else state.chess.reset();

  function drawSquares() {
    element.innerHTML = _.flatten(_.map(_.range(8, 0, -1), function(rank) {
      return _.map(_.range(1, 9), function(file) {
        var key = state.orientation === 'white' ?
          (constants.files[file - 1] + rank) :
          (constants.files[8 - file] + (9 - rank));
        var xpos = (file - 1) * 12.5;
        var ypos = (rank - 1) * 12.5;
        var style = (getOrientation() === 'white') ?
          'left:' + xpos + '%; bottom:' + ypos + '%;' :
          'right:' + xpos + '%; top:' + ypos + '%;' ;

        return '

';
      });
    })).join('');
  }

  function drawPieces() {
    var html;
    _.forEach(element.children, function($square) {
      var piece = state.chess.get($square.getAttribute('data-key'));
      if (piece) {
        var classes = ['piece', constants.types[piece.type], constants.colors[piece.color]].join(' ');
        html = '

';
      } else {
        html = '';
      }
      $square.innerHTML = html;
    });
  }

  function makeDraggable() {
    var transformProp = 'transform' in document.body.style?
    'transform': 'webkitTransform' in document.body.style?
    'webkitTransform': 'mozTransform' in document.body.style?
    'mozTransform': 'oTransform' in document.body.style?
    'oTransform': 'msTransform';

    interact('.square').dropzone(true)
    .on('dragenter', function (event) {
      var dropzoneElement = event.target;
      dropzoneElement.classList.add('drag-over');
    })
    .on('dragleave', function (event) {
      event.target.classList.remove('drag-over');
      event.target.classList.remove('selected');
    })
    .on('drop', function (event) {
      var piece = event.relatedTarget;
      var square = event.target;
      movePiece(piece, square, true);
      state.selected = null;
    });

    interact('.piece').draggable({
      onmove: function (event) {
        var target = event.target;
        target.classList.add('dragging');

        target.x = (target.x|0) + event.dx;
        target.y = (target.y|0) + event.dy;

        target.style[transformProp] = target.style.transform =
        'translate(' + target.x + 'px, ' + target.y + 'px)';
      }
    });

  }

  function bindEvents() {
    // touchstart, mousedown
    var squares = element.querySelectorAll('div.square');

    function selectHandler(e) {
      selectPiece(getSquare(e.target));
    }

    for (var i=0 ; i < squares.length ; i++) {
      squares[i].addEventListener('touchstart', selectHandler);
      squares[i].addEventListener('mousedown', selectHandler);
    }
  }

  function getSquare(el) {
    if (el.classList.contains('piece')) {
      return el.parentNode;
    }
    return el;
  }

  function selectPiece(square) {
    var pieceInSquare = square.querySelector('.piece');
    var selectedPiece = state.selected;
    // there is a piece and no other selected
    if (pieceInSquare && !selectedPiece) {
      square.classList.add('selected');
      state.selected = pieceInSquare;
    }
    // there is a piece selected
    else if (selectedPiece) {
      if (square !== selectedPiece.parentNode) {
        movePiece(selectedPiece, square);
        state.selected = null;
      }
    }
  }

  function movePiece(piece, destSquare, isDragging) {
    var destPiece = destSquare.querySelector('.piece');
    piece.parentNode.classList.remove('selected');
    piece.parentNode.removeChild(piece);

    if (destPiece && destPiece !== piece) {
      destSquare.removeChild(destPiece);
    }

    var newPiece = document.createElement('div');
    newPiece.className = isDragging ? piece.className.replace('dragging', '') : piece.className;
    destSquare.appendChild(newPiece);

    if (isDragging) destSquare.classList.remove('drag-over');
  }

  function setFen(fen) {
    if (state.chess.load(fen)) {
      drawPieces();
      return true;
    }
    return false;
  }

  function getFen() {
    return state.chess.fen();
  }

  function setOrientation(color) {
    if (isValidColor(color)) state.orientation = color;
    drawSquares();
    drawPieces();
  }

  function getOrientation() {
    return state.orientation;
  }

  function setDraggable(value) {
    if (['both', 'white', 'black', null].contains(value)) {
      state.draggable.enabled = value;
      makeDraggable();
    }
  }

  function toggleOrientation() {
    setOrientation(state.orientation === 'white' ? 'black' : 'white');
  }

  function clear() {
    state.chess.clear();
    drawPieces();
  }

  // [{type: 'p', color: 'w', square: 'a2'}, ...]
  function getPieces() {
    return _.compact(_.map(constants.squares, function(s) {
      var piece = state.chess.get(s);
      if (piece) {
        piece.square = s;
        return piece;
      }
    }));
  }

  function isValidColor(color) {
    return color === 'white' || color === 'black';
  }

  drawSquares();
  drawPieces();
  makeDraggable();
  bindEvents();

  return {
    setFen: setFen,
    getFen: getFen,
    getPieces: getPieces,
    setOrientation: setOrientation,
    getOrientation: getOrientation,
    toggleOrientation: toggleOrientation,
    setDraggable: setDraggable,
    clear: clear
  };
}

module.exports = Chessground;
<commit_msg>Fix touch/mouse events<commit_after>'use strict';

var Chess = require('chess.js').Chess;
var _ = require('lodash');
var interact = window.interact;

function Chessground(element, cfg) {

  var defaults = {
    orientation: 'white',
    draggable: {
      enabled: 'both', // 'white' | 'black' | 'both' | false
      events: {
        start: function( /* e, piece, pos */ ) {
          return true; // return false to prevent the drag from happening
        }
      }
    }
  };

  var constants = {
    files: 'abcdefgh',
    types: {
      p: 'pawn',
      r: 'rook',
      b: 'bishop',
      n: 'knight',
      q: 'queen',
      k: 'king'
    },
    colors: {
      w: 'white',
      b: 'black'
    },
    squares: _.flatten(_.map(_.range(1, 8), function(rank) {
      return _.map('abcdefgh', function(file) {
        return '' + rank + file;
      });
    }))
  };

  // all mutable data goes in there
  // use the fen config to create a chess object,
  // then drop the fen. The chess object will provide it.
  var state = _.omit(_.merge(defaults, cfg), 'fen');
  state.chess = new Chess();
  state.selected = null;
  if (cfg && cfg.fen) state.chess.load(cfg.fen); else state.chess.reset();

  function drawSquares() {
    element.innerHTML = _.flatten(_.map(_.range(8, 0, -1), function(rank) {
      return _.map(_.range(1, 9), function(file) {
        var key = state.orientation === 'white' ?
          (constants.files[file - 1] + rank) :
          (constants.files[8 - file] + (9 - rank));
        var xpos = (file - 1) * 12.5;
        var ypos = (rank - 1) * 12.5;
        var style = (getOrientation() === 'white') ?
          'left:' + xpos + '%; bottom:' + ypos + '%;' :
          'right:' + xpos + '%; top:' + ypos + '%;' ;

        return '

';
      });
    })).join('');
  }

  function drawPieces() {
    var html;
    _.forEach(element.children, function($square) {
      var piece = state.chess.get($square.getAttribute('data-key'));
      if (piece) {
        var classes = ['piece', constants.types[piece.type], constants.colors[piece.color]].join(' ');
        html = '

';
      } else {
        html = '';
      }
      $square.innerHTML = html;
    });
  }

  function makeDraggable() {
    var transformProp = 'transform' in document.body.style?
    'transform': 'webkitTransform' in document.body.style?
    'webkitTransform': 'mozTransform' in document.body.style?
    'mozTransform': 'oTransform' in document.body.style?
    'oTransform': 'msTransform';

    interact('.square').dropzone(true)
    .on('dragenter', function (event) {
      var dropzoneElement = event.target;
      dropzoneElement.classList.add('drag-over');
    })
    .on('dragleave', function (event) {
      event.target.classList.remove('drag-over');
      event.target.classList.remove('selected');
    })
    .on('drop', function (event) {
      var piece = event.relatedTarget;
      var square = event.target;
      movePiece(piece, square, true);
      state.selected = null;
    });

    interact('.piece').draggable({
      onmove: function (event) {
        var target = event.target;
        target.classList.add('dragging');

        target.x = (target.x|0) + event.dx;
        target.y = (target.y|0) + event.dy;

        target.style[transformProp] = target.style.transform =
        'translate(' + target.x + 'px, ' + target.y + 'px)';
      }
    });

  }

  function bindEvents() {
    // touchstart, mousedown
    var squares = element.querySelectorAll('div.square');

    function selectHandler(e) {
      e.preventDefault();
      selectPiece(getSquare(e.target));
    }

    for (var i=0 ; i < squares.length ; i++) {
      squares[i].addEventListener('touchstart', selectHandler);
      squares[i].addEventListener('mousedown', selectHandler);
    }
  }

  function getSquare(el) {
    if (el.classList.contains('piece')) {
      return el.parentNode;
    }
    return el;
  }

  function selectPiece(square) {
    var pieceInSquare = square.querySelector('.piece');
    var selectedPiece = state.selected;
    // there is a piece and no other selected
    if (pieceInSquare && !selectedPiece) {
      square.classList.add('selected');
      state.selected = pieceInSquare;
    }
    // there is a piece selected
    else if (selectedPiece) {
      if (square !== selectedPiece.parentNode) {
        movePiece(selectedPiece, square);
        state.selected = null;
      }
    }
  }

  function movePiece(piece, destSquare, isDragging) {
    var destPiece = destSquare.querySelector('.piece');
    piece.parentNode.classList.remove('selected');
    piece.parentNode.removeChild(piece);

    if (destPiece && destPiece !== piece) {
      destSquare.removeChild(destPiece);
    }

    var newPiece = document.createElement('div');
    newPiece.className = isDragging ? piece.className.replace('dragging', '') : piece.className;
    destSquare.appendChild(newPiece);

    if (isDragging) destSquare.classList.remove('drag-over');
  }

  function setFen(fen) {
    if (state.chess.load(fen)) {
      drawPieces();
      return true;
    }
    return false;
  }

  function getFen() {
    return state.chess.fen();
  }

  function setOrientation(color) {
    if (isValidColor(color)) state.orientation = color;
    drawSquares();
    drawPieces();
  }

  function getOrientation() {
    return state.orientation;
  }

  function setDraggable(value) {
    if (['both', 'white', 'black', null].contains(value)) {
      state.draggable.enabled = value;
      makeDraggable();
    }
  }

  function toggleOrientation() {
    setOrientation(state.orientation === 'white' ? 'black' : 'white');
  }

  function clear() {
    state.chess.clear();
    drawPieces();
  }

  // [{type: 'p', color: 'w', square: 'a2'}, ...]
  function getPieces() {
    return _.compact(_.map(constants.squares, function(s) {
      var piece = state.chess.get(s);
      if (piece) {
        piece.square = s;
        return piece;
      }
    }));
  }

  function isValidColor(color) {
    return color === 'white' || color === 'black';
  }

  drawSquares();
  drawPieces();
  makeDraggable();
  bindEvents();

  return {
    setFen: setFen,
    getFen: getFen,
    getPieces: getPieces,
    setOrientation: setOrientation,
    getOrientation: getOrientation,
    toggleOrientation: toggleOrientation,
    setDraggable: setDraggable,
    clear: clear
  };
}

module.exports = Chessground;
<|endoftext|>


<commit_before>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const assert = require('assert');

module.exports = async function invite(session, userId) {
    session.log.step(`invites "${userId}" to room`);
    await session.delay(1000);
    const inviteButton = await session.waitAndQuery(".mx_MemberList_invite");
    await inviteButton.click();
    const inviteTextArea = await session.waitAndQuery(".mx_ChatInviteDialog textarea");
    await inviteTextArea.type(userId);
    await inviteTextArea.press("Enter");
    const confirmButton = await session.query(".mx_Dialog_primary");
    await confirmButton.click();
    session.log.done();
}
<commit_msg>fix broken selector<commit_after>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const assert = require('assert');

module.exports = async function invite(session, userId) {
    session.log.step(`invites "${userId}" to room`);
    await session.delay(1000);
    const inviteButton = await session.waitAndQuery(".mx_MemberList_invite");
    await inviteButton.click();
    const inviteTextArea = await session.waitAndQuery(".mx_AddressPickerDialog textarea");
    await inviteTextArea.type(userId);
    await inviteTextArea.press("Enter");
    const confirmButton = await session.query(".mx_Dialog_primary");
    await confirmButton.click();
    session.log.done();
}
<|endoftext|>


<commit_before>/*globals define, document, console, eval, GME*/

define('webgme.classes',
    [
        'client',
        'blob/BlobClient',
        'executor/ExecutorClient',
        'js/Utils/InterpreterManager',
        'core/core',
        'storage/clientstorage'
  ], function (Client, BlobClient, ExecutorClient, InterpreterManager, Core, Storage) {

        // Setting global classes

        GME.classes.Client = Client;
        GME.classes.BlobClient = BlobClient;
        GME.classes.ExecutorClient = ExecutorClient;
        GME.classes.InterpreterManager = InterpreterManager;
        GME.classes.Core = Core;
        GME.classes.Storage = Storage;

        // Pure JavaScript equivalent to jQuery's $.ready() from https://github.com/jfriend00/docReady

        (function(funcName, baseObj) {
            // The public function name defaults to window.docReady
            // but you can pass in your own object and own function name and those will be used
            // if you want to put them in a different namespace
            funcName = funcName || "docReady";
            baseObj = baseObj || window;
            var readyList = [];
            var readyFired = false;
            var readyEventHandlersInstalled = false;

            // call this when the document is ready
            // this function protects itself against being called more than once
            function ready() {
                if (!readyFired) {
                    // this must be set to true before we start calling callbacks
                    readyFired = true;
                    for (var i = 0; i < readyList.length; i++) {
                        // if a callback here happens to add new ready handlers,
                        // the docReady() function will see that it already fired
                        // and will schedule the callback to run right after
                        // this event loop finishes so all handlers will still execute
                        // in order and no new ones will be added to the readyList
                        // while we are processing the list
                        readyList[i].fn.call(window, readyList[i].ctx);
                    }
                    // allow any closures held by these functions to free
                    readyList = [];
                }
            }

            function readyStateChange() {
                if ( document.readyState === "complete" ) {
                    ready();
                }
            }

            // This is the one public interface
            // docReady(fn, context);
            // the context argument is optional - if present, it will be passed
            // as an argument to the callback
            baseObj[funcName] = function(callback, context) {
                // if ready has already fired, then just schedule the callback
                // to fire asynchronously, but right away
                if (readyFired) {
                    setTimeout(function() {callback(context);}, 1);
                    return;
                } else {
                    // add the function and context to the list
                    readyList.push({fn: callback, ctx: context});
                }
                // if document already ready to go, schedule the ready function to run
                if (document.readyState === "complete") {
                    setTimeout(ready, 1);
                } else if (!readyEventHandlersInstalled) {
                    // otherwise if we don't have event handlers installed, install them
                    if (document.addEventListener) {
                        // first choice is DOMContentLoaded event
                        document.addEventListener("DOMContentLoaded", ready, false);
                        // backup is window load event
                        window.addEventListener("load", ready, false);
                    } else {
                        // must be IE
                        document.attachEvent("onreadystatechange", readyStateChange);
                        window.attachEvent("onload", ready);
                    }
                    readyEventHandlersInstalled = true;
                }
            }
        })("docReady", window);

        // See if there is handler attached to body tag when ready

        docReady(function() {

            if (document.body.getAttribute("on-gme-init")) {
                eval(document.body.getAttribute("on-gme-init"));
            } else {
                console.warn('To use GME, define a javascript function and set the body element\'s on-gme-init property.');
            }
        });

    });
<commit_msg>Conflicts: 	utils/build/webgme.classes/webgme.classes.js<commit_after>/*globals define, document, console, window, eval, GME, docReady, setTimeout*/

define('webgme.classes',
    [
        'client',
        'blob/BlobClient',
        'executor/ExecutorClient',
        'js/Utils/InterpreterManager',
        'core/core',
        'storage/clientstorage'
    ], function (Client, BlobClient, ExecutorClient, InterpreterManager, Core, Storage) {

        'use strict';
        // Setting global classes

        GME.classes.Client = Client;
        GME.classes.BlobClient = BlobClient;
        GME.classes.ExecutorClient = ExecutorClient;
        GME.classes.InterpreterManager = InterpreterManager;
        GME.classes.Core = Core;
        GME.classes.Storage = Storage;

        // Pure JavaScript equivalent to jQuery's $.ready() from https://github.com/jfriend00/docReady

        (function(funcName, baseObj) {
            // The public function name defaults to window.docReady
            // but you can pass in your own object and own function name and those will be used
            // if you want to put them in a different namespace
            funcName = funcName || 'docReady';
            baseObj = baseObj || window;
            var readyList = [];
            var readyFired = false;
            var readyEventHandlersInstalled = false;

            // call this when the document is ready
            // this function protects itself against being called more than once
            function ready() {
                if (!readyFired) {
                    // this must be set to true before we start calling callbacks
                    readyFired = true;
                    for (var i = 0; i < readyList.length; i++) {
                        // if a callback here happens to add new ready handlers,
                        // the docReady() function will see that it already fired
                        // and will schedule the callback to run right after
                        // this event loop finishes so all handlers will still execute
                        // in order and no new ones will be added to the readyList
                        // while we are processing the list
                        readyList[i].fn.call(window, readyList[i].ctx);
                    }
                    // allow any closures held by these functions to free
                    readyList = [];
                }
            }

            function readyStateChange() {
                if ( document.readyState === 'complete' ) {
                    ready();
                }
            }

            // This is the one public interface
            // docReady(fn, context);
            // the context argument is optional - if present, it will be passed
            // as an argument to the callback
            baseObj[funcName] = function(callback, context) {
                // if ready has already fired, then just schedule the callback
                // to fire asynchronously, but right away
                if (readyFired) {
                    setTimeout(function() {callback(context);}, 1);
                    return;
                } else {
                    // add the function and context to the list
                    readyList.push({fn: callback, ctx: context});
                }
                // if document already ready to go, schedule the ready function to run
                if (document.readyState === 'complete') {
                    setTimeout(ready, 1);
                } else if (!readyEventHandlersInstalled) {
                    // otherwise if we don't have event handlers installed, install them
                    if (document.addEventListener) {
                        // first choice is DOMContentLoaded event
                        document.addEventListener('DOMContentLoaded', ready, false);
                        // backup is window load event
                        window.addEventListener('load', ready, false);
                    } else {
                        // must be IE
                        document.attachEvent('onreadystatechange', readyStateChange);
                        window.attachEvent('onload', ready);
                    }
                    readyEventHandlersInstalled = true;
                }
            };
        })('docReady', window);

        // See if there is handler attached to body tag when ready

        docReady(function() {

            if (document.body.getAttribute('on-gme-init')) {
                eval(document.body.getAttribute('on-gme-init'));
            } else {
                console.warn('To use GME, define a javascript function and set the body element\'s on-gme-init property.');
            }
        });

    });
<|endoftext|>