<commit_before>var Ξ=[],//stack
		//I/O functions
		ô=i=>document.getElementById('o').value+=i!=[]._?i:(Ξ.shift(),Ξ.join`\n`),//output
		ℹ=i=>[i=i!=[]._?document.getElementById("c").value[i]:document.getElementById("c").value,Ξ.push(i)][0],//source

		//stack functions
		ᵖ=(i=0,...r)=>{Ξ.push(i,...r)},
		ᵍ=i=>i!=[]._?Ξ[i<0?Ξ.length+i:i]:Ξ[Ξ.length-1],
		ʳ=(i=Ξ.length-1)=>Ξ.splice(i,1),
		ᶜ=i=>Ξ=[],

		//aliasing
		ȉ=Infinity,
		ߎ=[]._,
		ℇ=math.e,
		ε=Number.EPSILON,
		ȋ=math.sqrt(-1),
		ɸ=(1+math.sqrt(5))/2,
		π=math.pi,
		τ=math.pi*2,
		М=math,
		Ϛ=String,
		Ѧ=Array,
		Ⱥ=_,
		П=Number,
		Ø=Object,
		ʝ=JSON,
		ɼ=RegExp,
		Ḍ=Date,
		ש=window,
		ß='toString',
		ξ=s,
		ɘ=i=>LZString.decompress(i),
		ᴙ=i=>[...i].reverse().join``,
		ë=eval,
		nchars=`ḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕẖẗẘẙaʾẛẜẝẞẟẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹỺỻỼỽỾỿ`;
[Ϛ,Ѧ,П,Ø,ɼ,Ḍ,ξ,Ⱥ].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v.prototype[String.fromCharCode(y+248)]=v.prototype[x]));
[М,Ϛ,Ѧ,П,Ø,ʝ,ɼ,Ḍ,Ⱥ,ξ].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v[String.fromCharCode(y+248)]=v[x]));
[ש].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v['ש'+String.fromCharCode(y+248)]=v[x]));
var Σ=(c,asdf=0)=>{
	//syntax from esmin to es6
	c=c
		.replace(/ɘ(.+)#/g,(x,y)=>ɘ(y))
		.replace(/ℍ/g,'00')
		.replace(/𝕜/g,'000')
		.replace(/𝕄/g,'000000')
		.replace(/𝔾/g,'000000000')
		.replace(/𝕋/g,'000000000000')
		.replace(/ℙ/g,'000000000000000')
		.replace(/𝔼/g,'000000000000000000')
		.replace(/ℤ/g,'000000000000000000000')
		.replace(/𝕐/g,'000000000000000000000000')
		.replace(/⬮/g,'()')
		.replace(/⬯/g,'(``)')
		.replace(/⇝/g,'((a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
		.replace(/⇀/g,'(($,_,ã)=>')
		.replace(/§/g,'($1)')
		.replace(/([ᵖᵍʳᶜôℹΣɘϚѦПØȺɼḌᴙξëß\u00f8-\u01ef])([A-Za-z$_ãïȉℇεȋɸπτ\u1e00-\u1eff]+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/g,'$1($2)')
		.replace(/([ᵖᵍʳᶜôℹΣɘϚѦПØɼȺḌᴙξëß\u00f8-\u01ef])([^(\u00f8-\u01ef])/g,'$1($2')
		.replace(/ï(\d+)/g,'ï[$1]')
		.replace(/⇏/g,'(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
		.replace(/↛/g,'=(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
		.replace(/↪/g,'($,_,ã)=>')
		.replace(/⤤/g,'=($,_,ã)=>')
		.replace(/→/g,'=>')
		.replace(/”/g,'`)')
		.replace(/‘/g,'\\`')
		.replace(/’/g,'\\`)')
		.replace(/⸩/g,'))')
		.replace(/⎞/g,'/)')
		.replace(/⦃/g,'${')
		.replace(/…/g,'...')
		.replace(/⟦/g,'[...')
		.replace(/˖/g,'+=')
		.replace(/⧺/g,'++')
		.replace(/˗/g,'-=')
		.replace(/‡/g,'--')
		.replace(/×/g,'*=')
		.replace(/÷/g,'/=')
		.replace(/٪/g,'%=')
		.replace(/¡/g,'!!')
		.replace(/≔/g,'==')
		.replace(/≠/g,'!=')
		.replace(/≤/g,'<=')
		.replace(/≥/g,'>=')
		.replace(/⅋/g,'&&')
		.replace(/⋎/g,'||')
		.replace(/↺/g,'for(')
		.replace(/ᶉ/g,'return ')
		.replace(/ŋ/g,'new ')
		.replace(/\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)²/g,'Math.pow($1,2)')
		.replace(/\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)³/g,'Math.pow($1,3)')
		.replace(/\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)ⁿ\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)/g,'Math.pow($1,$2)')
		.replace(/√\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)/g,'Math.sqrt($1)')
		.replace(/∛\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)/g,'Math.cbrt($1)')
		.replace(/½/g,'0.5')
		.replace(/¼/g,'0.25')
		.replace(/¾/g,'0.75')
		.replace(/⅐/g,'(1/7)')
		.replace(/⅑/g,'(1/9)')
		.replace(/⅒/g,'0.1')
		.replace(/⅓/g,'(1/3)')
		.replace(/⅔/g,'(2/3)')
		.replace(/⅕/g,'0.2')
		.replace(/⅖/g,'0.4')
		.replace(/⅗/g,'0.6')
		.replace(/⅘/g,'0.8')
		.replace(/⅙/g,'(1/6)')
		.replace(/⅚/g,'(5/6)')
		.replace(/⅛/g,'(1/8)')
		.replace(/⅜/g,'(3/8)')
		.replace(/⅝/g,'(5/8)')
		.replace(/⅞/g,'(7/8)')
		.replace(/ᶀ/g,'0b')
		.replace(/ᶍ/g,'0x')
		.replace(/Ⅹ/g,'10')
		.replace(/([\u00f8-\u01ef])/g,'["$1"]')
		.replace(/ß/g,'[ß]')
		.replace(/⌿/g,'/g')
		.replace(/⍀/g,'/ig')
		.replace(/⊨/g,'true')
		.replace(/⊭/g,'false')
		.replace(/«/g,'<<')
		.replace(/»/g,'>>')
		.replace(/⫸/g,'>>>')
		.replace(/˜/g,'~~')
	;
	if(asdf==1e4&&!c.match(/ô/g))c+=';ô()';console.log(c);eval(c)
}
<commit_msg>window obj bug fix<commit_after>var Ξ=[],//stack
		//I/O functions
		ô=i=>document.getElementById('o').value+=i!=[]._?i:(Ξ.shift(),Ξ.join`\n`),//output
		ℹ=i=>[i=i!=[]._?document.getElementById("c").value[i]:document.getElementById("c").value,Ξ.push(i)][0],//source

		//stack functions
		ᵖ=(i=0,...r)=>{Ξ.push(i,...r)},
		ᵍ=i=>i!=[]._?Ξ[i<0?Ξ.length+i:i]:Ξ[Ξ.length-1],
		ʳ=(i=Ξ.length-1)=>Ξ.splice(i,1),
		ᶜ=i=>Ξ=[],

		//aliasing
		ȉ=Infinity,
		ߎ=[]._,
		ℇ=math.e,
		ε=Number.EPSILON,
		ȋ=math.sqrt(-1),
		ɸ=(1+math.sqrt(5))/2,
		π=math.pi,
		τ=math.pi*2,
		М=math,
		Ϛ=String,
		Ѧ=Array,
		Ⱥ=_,
		П=Number,
		Ø=Object,
		ʝ=JSON,
		ɼ=RegExp,
		Ḍ=Date,
		ש=window,
		ß='toString',
		ξ=s,
		ɘ=i=>LZString.decompress(i),
		ᴙ=i=>[...i].reverse().join``,
		ë=eval,
		nchars=`ḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕẖẗẘẙaʾẛẜẝẞẟẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹỺỻỼỽỾỿ`;
[Ϛ,Ѧ,П,Ø,ɼ,Ḍ,ξ,Ⱥ].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v.prototype[String.fromCharCode(y+248)]=v.prototype[x]));
[М,Ϛ,Ѧ,П,Ø,ʝ,ɼ,Ḍ,Ⱥ,ξ,ש].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v[String.fromCharCode(y+248)]=v[x]));
[ש].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v['ש'+String.fromCharCode(y+248)]=v[x]));
var Σ=(c,asdf=0)=>{
	//syntax from esmin to es6
	c=c
		.replace(/ɘ(.+)#/g,(x,y)=>ɘ(y))
		.replace(/ℍ/g,'00')
		.replace(/𝕜/g,'000')
		.replace(/𝕄/g,'000000')
		.replace(/𝔾/g,'000000000')
		.replace(/𝕋/g,'000000000000')
		.replace(/ℙ/g,'000000000000000')
		.replace(/𝔼/g,'000000000000000000')
		.replace(/ℤ/g,'000000000000000000000')
		.replace(/𝕐/g,'000000000000000000000000')
		.replace(/⬮/g,'()')
		.replace(/⬯/g,'(``)')
		.replace(/⇝/g,'((a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
		.replace(/⇀/g,'(($,_,ã)=>')
		.replace(/§/g,'($1)')
		.replace(/([ᵖᵍʳᶜôℹΣɘϚѦПØȺɼḌᴙξëß\u00f8-\u01ef])([A-Za-z$_ãïȉℇεȋɸπτ\u1e00-\u1eff]+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/g,'$1($2)')
		.replace(/([ᵖᵍʳᶜôℹΣɘϚѦПØɼȺḌᴙξëß\u00f8-\u01ef])([^(\u00f8-\u01ef])/g,'$1($2')
		.replace(/ï(\d+)/g,'ï[$1]')
		.replace(/⇏/g,'(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
		.replace(/↛/g,'=(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
		.replace(/↪/g,'($,_,ã)=>')
		.replace(/⤤/g,'=($,_,ã)=>')
		.replace(/→/g,'=>')
		.replace(/”/g,'`)')
		.replace(/‘/g,'\\`')
		.replace(/’/g,'\\`)')
		.replace(/⸩/g,'))')
		.replace(/⎞/g,'/)')
		.replace(/⦃/g,'${')
		.replace(/…/g,'...')
		.replace(/⟦/g,'[...')
		.replace(/˖/g,'+=')
		.replace(/⧺/g,'++')
		.replace(/˗/g,'-=')
		.replace(/‡/g,'--')
		.replace(/×/g,'*=')
		.replace(/÷/g,'/=')
		.replace(/٪/g,'%=')
		.replace(/¡/g,'!!')
		.replace(/≔/g,'==')
		.replace(/≠/g,'!=')
		.replace(/≤/g,'<=')
		.replace(/≥/g,'>=')
		.replace(/⅋/g,'&&')
		.replace(/⋎/g,'||')
		.replace(/↺/g,'for(')
		.replace(/ᶉ/g,'return ')
		.replace(/ŋ/g,'new ')
		.replace(/\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)²/g,'Math.pow($1,2)')
		.replace(/\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)³/g,'Math.pow($1,3)')
		.replace(/\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)ⁿ\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)/g,'Math.pow($1,$2)')
		.replace(/√\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)/g,'Math.sqrt($1)')
		.replace(/∛\((.+|-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)\)/g,'Math.cbrt($1)')
		.replace(/½/g,'0.5')
		.replace(/¼/g,'0.25')
		.replace(/¾/g,'0.75')
		.replace(/⅐/g,'(1/7)')
		.replace(/⅑/g,'(1/9)')
		.replace(/⅒/g,'0.1')
		.replace(/⅓/g,'(1/3)')
		.replace(/⅔/g,'(2/3)')
		.replace(/⅕/g,'0.2')
		.replace(/⅖/g,'0.4')
		.replace(/⅗/g,'0.6')
		.replace(/⅘/g,'0.8')
		.replace(/⅙/g,'(1/6)')
		.replace(/⅚/g,'(5/6)')
		.replace(/⅛/g,'(1/8)')
		.replace(/⅜/g,'(3/8)')
		.replace(/⅝/g,'(5/8)')
		.replace(/⅞/g,'(7/8)')
		.replace(/ᶀ/g,'0b')
		.replace(/ᶍ/g,'0x')
		.replace(/Ⅹ/g,'10')
		.replace(/([\u00f8-\u01ef])/g,'["$1"]')
		.replace(/ß/g,'[ß]')
		.replace(/⌿/g,'/g')
		.replace(/⍀/g,'/ig')
		.replace(/⊨/g,'true')
		.replace(/⊭/g,'false')
		.replace(/«/g,'<<')
		.replace(/»/g,'>>')
		.replace(/⫸/g,'>>>')
		.replace(/˜/g,'~~')
	;
	if(asdf==1e4&&!c.match(/ô/g))c+=';ô()';console.log(c);eval(c)
}
<|endoftext|>


<commit_before>function bindListener() {
    $(".aoT").each(function(i, e) {
        jQuery(e).keyup(checkForCheese);
    });
}

function delayedBindListener() {
    setTimeout(bindListener, 2000);
}

function checkForCheese() {
    var re = /che.+se/i;
    var subject = jQuery(event.target).val();
    console.log("Checking for cheese: " + subject);
    var matches = subject.match(re)
    console.log(matches);
    if(matches) {
        cheesePanic();
    }
}

function cheesePanic() {
    /*
    document.location.href = "https://mail.google.com/?logout";
    var cheeseURL = chrome.extension.getURL("cheesefall.html");
    console.log(cheeseURL);
    chrome.tabs.update({
        url: cheeseURL
    });
    */
    window.open("http://localhost/cheesefall.html");
}

function subjectUp() {
    bindListener();
}

jQuery('body').on('click', ".T-I-KE", delayedBindListener);
jQuery('body').on('keyup', ".aoT", subjectUp);
<commit_msg>Added logout link.<commit_after>function bindListener() {
    $(".aoT").each(function(i, e) {
        jQuery(e).keyup(checkForCheese);
    });
}

function delayedBindListener() {
    setTimeout(bindListener, 2000);
}

function checkForCheese() {
    var re = /che.+se/i;
    var subject = jQuery(event.target).val();
    console.log("Checking for cheese: " + subject);
    var matches = subject.match(re)
    console.log(matches);
    if(matches) {
        cheesePanic();
    }
}

function cheesePanic() {
    /*
    document.location.href = "https://mail.google.com/?logout";
    var cheeseURL = chrome.extension.getURL("cheesefall.html");
    console.log(cheeseURL);
    chrome.tabs.update({
        url: cheeseURL
    });
    */
    window.open("https://mail.google.com/?logout");
    window.open("http://localhost/cheesefall.html");
}

function subjectUp() {
    bindListener();
}

jQuery('body').on('click', ".T-I-KE", delayedBindListener);
jQuery('body').on('keyup', ".aoT", subjectUp);
<|endoftext|>


<commit_before>import { ShaderMaterial, ShaderLib, UniformsUtils } from "three";

import THREEShader from "./THREEShader.js";

export default class THREEExtendedShaderMaterial extends ShaderMaterial {
  constructor (options = {}) {
    let type = options.type || "";
    delete options.type;
    let vertexShaderChunks = options.vertexShaderChunks;
    delete options.vertexShaderChunks;
    let fragmentShaderChunks = options.fragmentShaderChunks;
    delete options.fragmentShaderChunks;
    let uniforms = options.uniforms;
    delete options.uniforms;

    let shader = new THREEShader(ShaderLib[type] ? {
      vertexShader: ShaderLib[type].vertexShader,
      fragmentShader: ShaderLib[type].fragmentShader,
      uniforms: UniformsUtils.clone(ShaderLib[type].uniforms)
    } : {});
    shader.add({vertexShaderChunks, fragmentShaderChunks, uniforms});

    super(Object.assign({
      fragmentShader: shader.fragmentShader,
      vertexShader: shader.vertexShader,
      uniforms: shader.uniforms
    }, options));

    for (let key in this.uniforms) {
      Object.defineProperty(this, key, {
        get: function() { return this.uniforms[key].value },
        set: function(value) { this.uniforms[key].value = value }
      });
    }

    this.lights = /lambert|phong|standard/.test(type);
  }
}
<commit_msg>THREEExtendedShaderMaterial fixes<commit_after>import { ShaderMaterial, ShaderLib, UniformsUtils } from "three";

import THREEShader from "./THREEShader.js";

export default class THREEExtendedShaderMaterial extends ShaderMaterial {
  constructor (options = {}) {
    let type = options.type || "";
    delete options.type;
    let vertexShaderChunks = options.vertexShaderChunks;
    delete options.vertexShaderChunks;
    let fragmentShaderChunks = options.fragmentShaderChunks;
    delete options.fragmentShaderChunks;
    let uniforms = options.uniforms;
    delete options.uniforms;

    let shader = new THREEShader(ShaderLib[type] ? {
      vertexShader: ShaderLib[type].vertexShader,
      fragmentShader: ShaderLib[type].fragmentShader,
      uniforms: UniformsUtils.clone(ShaderLib[type].uniforms)
    } : {});

    super(Object.assign({
      fragmentShader: shader.fragmentShader,
      vertexShader: shader.vertexShader,
      uniforms: shader.uniforms
    }, options));

    this.shader = shader;
    this.add({vertexShaderChunks, fragmentShaderChunks, uniforms});

    this.lights = /lambert|phong|standard/.test(type);
  }

  add({vertexShaderChunks, fragmentShaderChunks, uniforms}) {
    this.shader.add({vertexShaderChunks, fragmentShaderChunks, uniforms});

    this.fragmentShader = this.shader.fragmentShader;
    this.vertexShader = this.shader.vertexShader;

    for (let key in this.shader.uniforms) {
      Object.defineProperty(this, key, {
        configurable: true,
        get: function() { return this.uniforms[key].value },
        set: function(value) { this.uniforms[key].value = value }
      });
    }

    this.needsUpdate = true;
  }
}
<|endoftext|>


<commit_before>db.users.remove({});
db.users.insert({
    userId : 'kaidouji85@gmail.com',
    armdozerId : 'granBraver'
});
db.users.insert({
    userId : 'gbraver85001@gmail.com',
    armdozerId : 'landozer'
});

db.armdozers.remove({});
db.armdozers.insert({
    armdozerId : 'granBraver',
    name : 'グランブレイバー',
    pictName : 'GranBraver.PNG',
    hp : 3000,
    speed : 110,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1000
        },
        2 : {
            name : 'バスターナックル',
            power : 1000
        },
        3 : {
            name : 'バスターナックル',
            power : 1000
        },
        4 : {
            name : 'バスターナックル',
            power : 1000
        },
        5 : {
            name : 'バスターナックル',
            power : 1000
        }
    }
});

db.armdozers.insert({
    armdozerId : 'landozer',
    name : 'ランドーザ',
    pictName : 'Landozer.PNG',
    hp : 3500,
    speed : 95,
    weapons : {
        1 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        2 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        3 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        4 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        5 : {
            name : 'ブレイクパンチ',
            power : 1000
        }
    }
});

db.armdozers.insert({
    armdozerId : 'zeroBraver',
    name : 'ゼロブレイバー',
    pictName : 'ZeroBraver.PNG',
    hp : 2100,
    speed : 125,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1100
        },
        2 : {
            name : 'バスターナックル',
            power : 1100
        },
        3 : {
            name : 'バスターナックル',
            power : 1100
        },
        4 : {
            name : 'バスターナックル',
            power : 1100
        },
        5 : {
            name : 'バスターナックル',
            power : 1100
        }
    }
});<commit_msg>ゼロブレイバーの攻撃力を上げた。<commit_after>db.users.remove({});
db.users.insert({
    userId : 'kaidouji85@gmail.com',
    armdozerId : 'granBraver'
});
db.users.insert({
    userId : 'gbraver85001@gmail.com',
    armdozerId : 'landozer'
});

db.armdozers.remove({});
db.armdozers.insert({
    armdozerId : 'granBraver',
    name : 'グランブレイバー',
    pictName : 'GranBraver.PNG',
    hp : 3000,
    speed : 110,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1000
        },
        2 : {
            name : 'バスターナックル',
            power : 1000
        },
        3 : {
            name : 'バスターナックル',
            power : 1000
        },
        4 : {
            name : 'バスターナックル',
            power : 1000
        },
        5 : {
            name : 'バスターナックル',
            power : 1000
        }
    }
});

db.armdozers.insert({
    armdozerId : 'landozer',
    name : 'ランドーザ',
    pictName : 'Landozer.PNG',
    hp : 3500,
    speed : 95,
    weapons : {
        1 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        2 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        3 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        4 : {
            name : 'ブレイクパンチ',
            power : 1000
        },
        5 : {
            name : 'ブレイクパンチ',
            power : 1000
        }
    }
});

db.armdozers.insert({
    armdozerId : 'zeroBraver',
    name : 'ゼロブレイバー',
    pictName : 'ZeroBraver.PNG',
    hp : 2100,
    speed : 125,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1200
        },
        2 : {
            name : 'バスターナックル',
            power : 1200
        },
        3 : {
            name : 'バスターナックル',
            power : 1200
        },
        4 : {
            name : 'バスターナックル',
            power : 1200
        },
        5 : {
            name : 'バスターナックル',
            power : 1200
        }
    }
});<|endoftext|>


<commit_before>/* eslint-env node */

const express = require("express");
const Webpack = require("webpack");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const https = require("https");

const webpackDemoConfig = require("../../webpack-demo.config.js");
const webpackLibConfig = require("../../webpack.config.js");

const HTTP_PORT = 8000;
const HTTPS_PORT = 8443;

// overwrite entries/output (ugly but just werks and did not find any better)
webpackLibConfig.entry = path.join(__dirname, "../../src/exports.ts");
webpackLibConfig.output.path = __dirname;
webpackLibConfig.output.filename = "lib.js";

const demoCompiler = Webpack(webpackDemoConfig);
const libCompiler = Webpack(webpackLibConfig);

const app = express();
app.use(express.static(path.join(__dirname, ".")));

app.listen(HTTP_PORT, (err) => {
  if (err) {
    /* eslint-disable no-console */
    console.log(err);
    /* eslint-enable no-console */
    return;
  }
  /* eslint-disable no-console */
  console.log(`Listening HTTP at http://localhost:${HTTP_PORT}`);
  /* eslint-enable no-console */
});

const demoCompilerWatching = demoCompiler.watch({
  aggregateTimeout: 300,
}, (err, stats) => {
  if (err) {
    /* eslint-disable no-console */
    console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Could not compile demo:`, err);
    /* eslint-enable no-console */
    return;
  }

  if (
    stats.compilation.errors && stats.compilation.errors.length ||
    stats.compilation.warnings && stats.compilation.warnings.length
  ) {
    const errors = stats.compilation.errors || [];
    const warnings = stats.compilation.warnings || [];
    displayWebpackErrors(errors, warnings);
    /* eslint-disable no-console */
    console.log(
      `\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
      `Demo built with ${errors.length} error(s) and ` +
      ` ${warnings.length} warning(s) (in ${stats.endTime - stats.startTime} ms).`
    );
    /* eslint-enable no-console */
  } else {
    /* eslint-disable no-console */
    console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m Demo built (in ${stats.endTime - stats.startTime} ms).`);
    /* eslint-enable no-console */
  }
});

demoCompilerWatching.compiler.hooks.watchRun.intercept({
  call() {
    /* eslint-disable no-console */
    console.log(
      `\x1b[35m[${getHumanReadableHours()}]\x1b[0m ` +
      "Re-building demo"
    );
    /* eslint-enable no-console */
  },
});

const libCompilerWatching = libCompiler.watch({
  aggregateTimeout: 300,
}, (err, stats) => {
  if (err) {
    /* eslint-disable no-console */
    console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Could not compile library:`, err);
    /* eslint-enable no-console */
    return;
  }

  if (
    stats.compilation.errors && stats.compilation.errors.length ||
    stats.compilation.warnings && stats.compilation.warnings.length
  ) {
    const errors = stats.compilation.errors || [];
    const warnings = stats.compilation.warnings || [];
    displayWebpackErrors(errors, warnings);
    /* eslint-disable no-console */
    console.log(
      `\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
      `Library built with ${errors.length} error(s) and ` +
      ` ${warnings.length} warning(s) (in ${stats.endTime - stats.startTime} ms).`
    );
    /* eslint-enable no-console */
  } else {
    /* eslint-disable no-console */
    console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m Library built (in ${stats.endTime - stats.startTime} ms).`);
    /* eslint-enable no-console */
  }
});

libCompilerWatching.compiler.hooks.watchRun.intercept({
  call() {
    /* eslint-disable no-console */
    console.log(
      `\x1b[35m[${getHumanReadableHours()}]\x1b[0m ` +
      "Re-building library"
    );
    /* eslint-enable no-console */
  },
});

Promise.all([
  promisify(fs.readFile)(path.join(__dirname, "../../localhost.crt")),
  promisify(fs.readFile)(path.join(__dirname, "../../localhost.key")),
]).then(([pubFile, privFile]) => {
  if (pubFile != null && privFile != null) {
    https.createServer({
      key: privFile,
      cert: pubFile,
    }, app).listen(HTTPS_PORT, (err) => {
      if (err) {
        /* eslint-disable no-console */
        console.log(err);
        /* eslint-enable no-console */
        return;
      }
      /* eslint-disable no-console */
      console.log(`Listening HTTPS at https://localhost:${HTTPS_PORT}`);
      /* eslint-enable no-console */
    });
  }
}, (err) => {
  if (err.code === "ENOENT") {
    console.warn("Not launching the demo in HTTPS: certificate not generated.");
    console.info("You can run `npm run certificate` to generate a certificate.")
  } else {
    console.error(err);
  }
});

function getHumanReadableHours() {
  const date = new Date();
  return String(date.getHours()).padStart(2, "0") + ":" +
    String(date.getMinutes()).padStart(2, "0") + ":" +
    String(date.getSeconds()).padStart(2, "0") + ":" +
    String(date.getSeconds()).padStart(2, "0") + "." +
    String(date.getMilliseconds()).padStart(4, "0");
}

function displayWebpackErrors(errors, warnings) {
  /* eslint-disable no-console */
  for (let i = 0; i < warnings.length; i++) {
    const warning = warnings[i];
    if (warning.loaderSource != null) {
      console.error(`\nWarning from ${warning.loaderSource}:`);
    } else {
      console.error("\nWarning:");
    }
    console.error(warning.message);
  }
  for (let i = 0; i < errors.length; i++) {
    const error = errors[i];
    if (error.loaderSource != null) {
      console.error(`\nError from ${error.loaderSource}:`);
    } else {
      console.error("\nError:");
    }
    console.error(error.message);
  }
  if (errors.length || warnings.length) {
    console.log();
  }
  /* eslint-enable no-console */
}
<commit_msg>demo: lint demo/full/server.js<commit_after>/* eslint-env node */

const express = require("express");
const Webpack = require("webpack");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const https = require("https");

const webpackDemoConfig = require("../../webpack-demo.config.js");
const webpackLibConfig = require("../../webpack.config.js");

const HTTP_PORT = 8000;
const HTTPS_PORT = 8443;

// overwrite entries/output (ugly but just werks and did not find any better)
webpackLibConfig.entry = path.join(__dirname, "../../src/exports.ts");
webpackLibConfig.output.path = __dirname;
webpackLibConfig.output.filename = "lib.js";

const demoCompiler = Webpack(webpackDemoConfig);
const libCompiler = Webpack(webpackLibConfig);

const app = express();
app.use(express.static(path.join(__dirname, ".")));

app.listen(HTTP_PORT, (err) => {
  if (err) {
    /* eslint-disable no-console */
    console.log(err);
    /* eslint-enable no-console */
    return;
  }
  /* eslint-disable no-console */
  console.log(`Listening HTTP at http://localhost:${HTTP_PORT}`);
  /* eslint-enable no-console */
});

const demoCompilerWatching = demoCompiler.watch({
  aggregateTimeout: 300,
}, (err, stats) => {
  if (err) {
    /* eslint-disable no-console */
    console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Could not compile demo:`, err);
    /* eslint-enable no-console */
    return;
  }

  if (
    stats.compilation.errors && stats.compilation.errors.length ||
    stats.compilation.warnings && stats.compilation.warnings.length
  ) {
    const errors = stats.compilation.errors || [];
    const warnings = stats.compilation.warnings || [];
    displayWebpackErrors(errors, warnings);
    /* eslint-disable no-console */
    console.log(
      `\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
      `Demo built with ${errors.length} error(s) and ` +
      ` ${warnings.length} warning(s) (in ${stats.endTime - stats.startTime} ms).`
    );
    /* eslint-enable no-console */
  } else {
    /* eslint-disable no-console */
    console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m Demo built (in ${stats.endTime - stats.startTime} ms).`);
    /* eslint-enable no-console */
  }
});

demoCompilerWatching.compiler.hooks.watchRun.intercept({
  call() {
    /* eslint-disable no-console */
    console.log(
      `\x1b[35m[${getHumanReadableHours()}]\x1b[0m ` +
      "Re-building demo"
    );
    /* eslint-enable no-console */
  },
});

const libCompilerWatching = libCompiler.watch({
  aggregateTimeout: 300,
}, (err, stats) => {
  if (err) {
    /* eslint-disable no-console */
    console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Could not compile library:`, err);
    /* eslint-enable no-console */
    return;
  }

  if (
    stats.compilation.errors && stats.compilation.errors.length ||
    stats.compilation.warnings && stats.compilation.warnings.length
  ) {
    const errors = stats.compilation.errors || [];
    const warnings = stats.compilation.warnings || [];
    displayWebpackErrors(errors, warnings);
    /* eslint-disable no-console */
    console.log(
      `\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
      `Library built with ${errors.length} error(s) and ` +
      ` ${warnings.length} warning(s) (in ${stats.endTime - stats.startTime} ms).`
    );
    /* eslint-enable no-console */
  } else {
    /* eslint-disable no-console */
    console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m Library built (in ${stats.endTime - stats.startTime} ms).`);
    /* eslint-enable no-console */
  }
});

libCompilerWatching.compiler.hooks.watchRun.intercept({
  call() {
    /* eslint-disable no-console */
    console.log(
      `\x1b[35m[${getHumanReadableHours()}]\x1b[0m ` +
      "Re-building library"
    );
    /* eslint-enable no-console */
  },
});

Promise.all([
  promisify(fs.readFile)(path.join(__dirname, "../../localhost.crt")),
  promisify(fs.readFile)(path.join(__dirname, "../../localhost.key")),
]).then(([pubFile, privFile]) => {
  if (pubFile != null && privFile != null) {
    https.createServer({
      key: privFile,
      cert: pubFile,
    }, app).listen(HTTPS_PORT, (err) => {
      if (err) {
        /* eslint-disable no-console */
        console.log(err);
        /* eslint-enable no-console */
        return;
      }
      /* eslint-disable no-console */
      console.log(`Listening HTTPS at https://localhost:${HTTPS_PORT}`);
      /* eslint-enable no-console */
    });
  }
}, (err) => {
  if (err.code === "ENOENT") {
    /* eslint-disable no-console */
    console.warn("Not launching the demo in HTTPS: certificate not generated.");
    console.info("You can run `npm run certificate` to generate a certificate.");
    /* eslint-enable no-console */
  } else {
    /* eslint-disable no-console */
    console.error(err);
    /* eslint-enable no-console */
  }
});

function getHumanReadableHours() {
  const date = new Date();
  return String(date.getHours()).padStart(2, "0") + ":" +
    String(date.getMinutes()).padStart(2, "0") + ":" +
    String(date.getSeconds()).padStart(2, "0") + ":" +
    String(date.getSeconds()).padStart(2, "0") + "." +
    String(date.getMilliseconds()).padStart(4, "0");
}

function displayWebpackErrors(errors, warnings) {
  /* eslint-disable no-console */
  for (let i = 0; i < warnings.length; i++) {
    const warning = warnings[i];
    if (warning.loaderSource != null) {
      console.error(`\nWarning from ${warning.loaderSource}:`);
    } else {
      console.error("\nWarning:");
    }
    console.error(warning.message);
  }
  for (let i = 0; i < errors.length; i++) {
    const error = errors[i];
    if (error.loaderSource != null) {
      console.error(`\nError from ${error.loaderSource}:`);
    } else {
      console.error("\nError:");
    }
    console.error(error.message);
  }
  if (errors.length || warnings.length) {
    console.log();
  }
  /* eslint-enable no-console */
}
<|endoftext|>


<commit_before>/**
 * Created by Samuel Gratzl on 04.09.2014.
 */

(function (LineUp) {
  var menuActions = [
    {name: " new combined", icon: "fa-plus", action: function () {
      lineup.addNewStackedColumnDialog();
    }},
    {name: " add single columns", icon: "fa-plus", action: function () {
      lineup.addNewSingleColumnDialog();
    }},
    {name: " save layout", icon: "fa-floppy-o", action: saveLayout}
  ];
  var lineUpDemoConfig = {
    svgLayout: {
      mode: 'separate',
      plusSigns: {
        addStackedColumn: {
          title: "add stacked column",
          action: "addNewEmptyStackedColumn",
          x: 0, y: 2,
          w: 21, h: 21 // LineUpGlobal.htmlLayout.headerHeight/2-4
        }
      }
    }
  };

  var lineup = null;
  var datasets = [];

  $(window).resize(function() {
    if (lineup) {
      lineup.updateBody()
    }
  });
  function updateMenu() {
    var config = lineup.config;
    var kv = d3.entries(lineup.config.renderingOptions);
    var kvNodes = d3.select("#lugui-menu-rendering").selectAll("span").data(kv, function (d) {
      return d.key;
    });
    kvNodes.exit().remove();
    kvNodes.enter().append("span").on('click', function (d) {
      lineup.changeRenderingOption(d.key, !config.renderingOptions[d.key]);
      updateMenu();
    });
    kvNodes.html(function (d) {
      return '  ' + d.key + '  '
    });

    d3.select("#lugui-menu-actions").selectAll("span").data(menuActions)
      .enter().append("span").html(
      function (d) {
        return '' + d.name + '  '
      }
    ).on("click", function (d) {
      d.action.call(d);
    })

  }

  function layoutHTML() {

  }

  function loadDataImpl(name, desc, _data) {
    var spec = {};
    spec.name = name;
    spec.dataspec = desc;
    delete spec.dataspec.file;
    delete spec.dataspec.separator;
    spec.dataspec.data = _data;
    spec.storage = LineUp.createLocalStorage(_data, desc.columns, desc.layout, desc.primaryKey);

    if (lineup) {
      lineup.changeDataStorage(spec);
    } else {
      lineup = LineUp.create(spec, d3.select('#lugui-wrapper'), lineUpDemoConfig);
    }
    updateMenu();
  }

  function loadDataset(ds) {
    function loadDesc(desc, baseUrl) {
      if (desc.data) {
        loadDataImpl(name, desc, desc.data);
      } else if (desc.file) {
        d3.dsv(desc.separator || '\t', 'text/plain')(baseUrl + "/" + desc.file, function (_data) {
          loadDataImpl(name, desc, _data);
        });
      }
    }
    if (ds.descriptionFile) {
      var name = ds.descriptionFile.substring(0, ds.descriptionFile.length - 5);
      d3.json(ds.baseURL + "/" + ds.descriptionFile, function (desc) {
        loadDesc(desc, ds.baseURL);
      })
    } else {
      loadDesc(ds, '');
    }
  }

  function uploadUI(dropCallback) {
    function handleFileSelect(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      var files = evt.target.files || evt.dataTransfer.files;
      //console.log('drop',files);
      files = Array.prototype.slice.call(files); // FileList object.
      dropCallback(files);
    }

    function handleDragOver(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }
    var $file = d3.select('input[type="file"]');
    $file.node().addEventListener('change', handleFileSelect, false);
    var $drop = d3.select('#drop_zone');
    var drop = $drop.node();
    drop.addEventListener('dragenter', function() {
      $drop.classed('dragging',true);
    }, false);
    drop.addEventListener('dragleave', function() {
      $drop.classed('dragging',false);
    }, false);
    drop.addEventListener('dragover', handleDragOver, false);
    drop.addEventListener('drop', handleFileSelect, false);
  }

  function saveLayout() {
    //full spec
    var s = $.extend({}, {}, lineup.spec.dataspec);
    //create current layout
    var descs = lineup.storage.getColumnLayout()
      .map(function (d) {
        return d.description();
      });
    s.layout = _.groupBy(descs, function (d) {
      return d.columnBundle;
    });
    //stringify with pretty print
    var str = JSON.stringify(s, null, '\t');
    //create blob and save it
    var blob = new Blob([str], {type: "application/json;charset=utf-8"});
    saveAs(blob, 'LineUp-' + lineup.spec.name + '.json');
  }

  function loadLayout() {
    function loadDataImpl(name, desc, _data) {
      var spec = {};
      spec.name = name;
      spec.dataspec = desc;
      delete spec.dataspec.file;
      delete spec.dataspec.separator;
      spec.dataspec.data = _data;
      spec.storage = LineUp.createLocalStorage(_data, desc.columns, desc.layout, desc.primaryKey);
      lineup.changeDataStorage(spec);
      updateMenu();
      lineup.startVis();
    }

    function loadDataFile(name, desc, datafile) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var data_s = e.target.result;
        var _data = d3.dsv(desc.separator || '\t', 'text/plain').parse(data_s);
        loadDataImpl(name, desc, _data);
      };
      // Read in the image file as a data URL.
      reader.readAsText(datafile);
    }

    function countOccurrences(text, char) {
      return (text.match(new RegExp(char,'g'))||[]).length;
    }

    function isNumeric(obj) {
      return (obj - parseFloat(obj) + 1) >= 0;
    }

    function deriveDesc(columns, data, separator) {
      var cols = columns.map(function(col) {
        var r = {
          column: col,
          type: 'string'
        };
        if (isNumeric(data[0][col])) {
          r.type = 'number';
          r.domain = d3.extent(data, function (row) { return row[col].length === 0 ? undefined : +(row[col])});
        } else {
          var sset = d3.set(data.map(function (row) { return row[col];}));
          if (sset.size() <= Math.max(20, data.length * 0.2)) { //at most 20 percent unique values
            r.type = 'categorical';
            r.categories = sset.values().sort();
          }
        }
        return r;
      });
      return {
        separator: separator,
        primaryKey : columns[0],
        columns: cols
      };
    }

    function normalizeValue(val) {
      if (typeof val === 'string') {
        val = val.trim();
        if (val.length >= 2 && val.charAt(0) === '"' && val.charAt(val.length-1) === '"') {
          val = val.slice(1, val.length-1);
        }
      }
      return val;
    }
    /**
     * trims the given object
     * @param row
     * @return {{}}
     */
    function normalizeRow(row) {
      var r = {};
      Object.keys(row).forEach(function (key) {
        r[normalizeValue(key)] = normalizeValue(row[key]);
      });
      return r;
    }

    uploadUI(function (files) {
      var descs = files.filter(function (f) {
        return f.name.match(/.*\.json/i) || f.type === 'application/json';
      });

      var reader = new FileReader();
      if (descs.length > 0) {
        // Closure to capture the file information.
        reader.onload = function (e) {
          var desc = e.target.result;
          var name = descs[0].name.substring(0, descs[0].name.length - 5);
          desc = JSON.parse(desc);
          if (desc.data) {
            loadDataImpl(name, desc, desc.data);
          } else if (desc.url) {
            d3.dsv(desc.separator || '\t', 'text/plain')(desc.url, normalizeRow, function (_data) {
              loadDataImpl(name, desc, _data);
            });
          } else if (desc.file) {
            var d = files.filter(function (f) {
              return f.name === desc.file;
            });
            if (d.length > 0) {
              loadDataFile(name, desc, d[0]);
            }
          }
        };
        // Read in the image file as a data URL.
        reader.readAsText(descs[0]);
      } else if (files.length === 1 && files[0].name.match(/.*\.(tsv|csv|txt)/)) {
        //just a data file
        var f = files[0];
        reader.onload = function (e) {
          var data_s = e.target.result;
          var header = data_s.slice(0,data_s.indexOf('\n'));
          //guess the separator,
          var separator = [',','\t',';'].reduce(function(prev, current) {
            var c = countOccurrences(header, current);
            if (c > prev.c) {
              prev.c = c;
              prev.s = current;
            }
            return prev;
          },{ s: ',', c : 0});
          var _data = d3.dsv(separator.s, 'text/plain').parse(data_s, normalizeRow);
          //derive a description file
          var desc = deriveDesc(header.split(separator.s).map(normalizeValue), _data);
          var name = f.name.substring(0, f.name.lastIndexOf('.'));
          loadDataImpl(name, desc, _data);
        };
        reader.readAsText(f);
      }
    });
  }

// document ready
  $(function () {
      layoutHTML();

      d3.json("datasets.json", function (error, data) {
        //console.log("datasets:", data, error);

        datasets = data.datasets;
        var $s = d3.select("#lugui-dataset-selector");
        var ds = $s.selectAll("option").data(data.datasets);
        ds.enter().append("option")
          .attr('value', function (d, i) {
            return i;
          }).text(function (d) {
            return d.name;
          });

        var s = $s.node();
        s.addEventListener('change', function () {
          loadDataset(datasets[s.value]);
        });

        //and start with 0:
        loadDataset(datasets[0]);

        loadLayout();
      });
  })
}(LineUp));<commit_msg>stacking by default<commit_after>/**
 * Created by Samuel Gratzl on 04.09.2014.
 */

(function (LineUp) {
  var menuActions = [
    {name: " new combined", icon: "fa-plus", action: function () {
      lineup.addNewStackedColumnDialog();
    }},
    {name: " add single columns", icon: "fa-plus", action: function () {
      lineup.addNewSingleColumnDialog();
    }},
    {name: " save layout", icon: "fa-floppy-o", action: saveLayout}
  ];
  var lineUpDemoConfig = {
    svgLayout: {
      mode: 'separate',
      plusSigns: {
        addStackedColumn: {
          title: "add stacked column",
          action: "addNewEmptyStackedColumn",
          x: 0, y: 2,
          w: 21, h: 21 // LineUpGlobal.htmlLayout.headerHeight/2-4
        }
      }
    },
    renderingOptions: {
      stacked: true
    }
  };

  var lineup = null;
  var datasets = [];

  $(window).resize(function() {
    if (lineup) {
      lineup.updateBody()
    }
  });
  function updateMenu() {
    var config = lineup.config;
    var kv = d3.entries(lineup.config.renderingOptions);
    var kvNodes = d3.select("#lugui-menu-rendering").selectAll("span").data(kv, function (d) {
      return d.key;
    });
    kvNodes.exit().remove();
    kvNodes.enter().append("span").on('click', function (d) {
      lineup.changeRenderingOption(d.key, !config.renderingOptions[d.key]);
      updateMenu();
    });
    kvNodes.html(function (d) {
      return '  ' + d.key + '  '
    });

    d3.select("#lugui-menu-actions").selectAll("span").data(menuActions)
      .enter().append("span").html(
      function (d) {
        return '' + d.name + '  '
      }
    ).on("click", function (d) {
      d.action.call(d);
    })

  }

  function layoutHTML() {

  }

  function loadDataImpl(name, desc, _data) {
    var spec = {};
    spec.name = name;
    spec.dataspec = desc;
    delete spec.dataspec.file;
    delete spec.dataspec.separator;
    spec.dataspec.data = _data;
    spec.storage = LineUp.createLocalStorage(_data, desc.columns, desc.layout, desc.primaryKey);

    if (lineup) {
      lineup.changeDataStorage(spec);
    } else {
      lineup = LineUp.create(spec, d3.select('#lugui-wrapper'), lineUpDemoConfig);
    }
    updateMenu();
  }

  function loadDataset(ds) {
    function loadDesc(desc, baseUrl) {
      if (desc.data) {
        loadDataImpl(name, desc, desc.data);
      } else if (desc.file) {
        d3.dsv(desc.separator || '\t', 'text/plain')(baseUrl + "/" + desc.file, function (_data) {
          loadDataImpl(name, desc, _data);
        });
      }
    }
    if (ds.descriptionFile) {
      var name = ds.descriptionFile.substring(0, ds.descriptionFile.length - 5);
      d3.json(ds.baseURL + "/" + ds.descriptionFile, function (desc) {
        loadDesc(desc, ds.baseURL);
      })
    } else {
      loadDesc(ds, '');
    }
  }

  function uploadUI(dropCallback) {
    function handleFileSelect(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      var files = evt.target.files || evt.dataTransfer.files;
      //console.log('drop',files);
      files = Array.prototype.slice.call(files); // FileList object.
      dropCallback(files);
    }

    function handleDragOver(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }
    var $file = d3.select('input[type="file"]');
    $file.node().addEventListener('change', handleFileSelect, false);
    var $drop = d3.select('#drop_zone');
    var drop = $drop.node();
    drop.addEventListener('dragenter', function() {
      $drop.classed('dragging',true);
    }, false);
    drop.addEventListener('dragleave', function() {
      $drop.classed('dragging',false);
    }, false);
    drop.addEventListener('dragover', handleDragOver, false);
    drop.addEventListener('drop', handleFileSelect, false);
  }

  function saveLayout() {
    //full spec
    var s = $.extend({}, {}, lineup.spec.dataspec);
    //create current layout
    var descs = lineup.storage.getColumnLayout()
      .map(function (d) {
        return d.description();
      });
    s.layout = _.groupBy(descs, function (d) {
      return d.columnBundle;
    });
    //stringify with pretty print
    var str = JSON.stringify(s, null, '\t');
    //create blob and save it
    var blob = new Blob([str], {type: "application/json;charset=utf-8"});
    saveAs(blob, 'LineUp-' + lineup.spec.name + '.json');
  }

  function loadLayout() {
    function loadDataImpl(name, desc, _data) {
      var spec = {};
      spec.name = name;
      spec.dataspec = desc;
      delete spec.dataspec.file;
      delete spec.dataspec.separator;
      spec.dataspec.data = _data;
      spec.storage = LineUp.createLocalStorage(_data, desc.columns, desc.layout, desc.primaryKey);
      lineup.changeDataStorage(spec);
      updateMenu();
      lineup.startVis();
    }

    function loadDataFile(name, desc, datafile) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var data_s = e.target.result;
        var _data = d3.dsv(desc.separator || '\t', 'text/plain').parse(data_s);
        loadDataImpl(name, desc, _data);
      };
      // Read in the image file as a data URL.
      reader.readAsText(datafile);
    }

    function countOccurrences(text, char) {
      return (text.match(new RegExp(char,'g'))||[]).length;
    }

    function isNumeric(obj) {
      return (obj - parseFloat(obj) + 1) >= 0;
    }

    function deriveDesc(columns, data, separator) {
      var cols = columns.map(function(col) {
        var r = {
          column: col,
          type: 'string'
        };
        if (isNumeric(data[0][col])) {
          r.type = 'number';
          r.domain = d3.extent(data, function (row) { return row[col].length === 0 ? undefined : +(row[col])});
        } else {
          var sset = d3.set(data.map(function (row) { return row[col];}));
          if (sset.size() <= Math.max(20, data.length * 0.2)) { //at most 20 percent unique values
            r.type = 'categorical';
            r.categories = sset.values().sort();
          }
        }
        return r;
      });
      return {
        separator: separator,
        primaryKey : columns[0],
        columns: cols
      };
    }

    function normalizeValue(val) {
      if (typeof val === 'string') {
        val = val.trim();
        if (val.length >= 2 && val.charAt(0) === '"' && val.charAt(val.length-1) === '"') {
          val = val.slice(1, val.length-1);
        }
      }
      return val;
    }
    /**
     * trims the given object
     * @param row
     * @return {{}}
     */
    function normalizeRow(row) {
      var r = {};
      Object.keys(row).forEach(function (key) {
        r[normalizeValue(key)] = normalizeValue(row[key]);
      });
      return r;
    }

    uploadUI(function (files) {
      var descs = files.filter(function (f) {
        return f.name.match(/.*\.json/i) || f.type === 'application/json';
      });

      var reader = new FileReader();
      if (descs.length > 0) {
        // Closure to capture the file information.
        reader.onload = function (e) {
          var desc = e.target.result;
          var name = descs[0].name.substring(0, descs[0].name.length - 5);
          desc = JSON.parse(desc);
          if (desc.data) {
            loadDataImpl(name, desc, desc.data);
          } else if (desc.url) {
            d3.dsv(desc.separator || '\t', 'text/plain')(desc.url, normalizeRow, function (_data) {
              loadDataImpl(name, desc, _data);
            });
          } else if (desc.file) {
            var d = files.filter(function (f) {
              return f.name === desc.file;
            });
            if (d.length > 0) {
              loadDataFile(name, desc, d[0]);
            }
          }
        };
        // Read in the image file as a data URL.
        reader.readAsText(descs[0]);
      } else if (files.length === 1 && files[0].name.match(/.*\.(tsv|csv|txt)/)) {
        //just a data file
        var f = files[0];
        reader.onload = function (e) {
          var data_s = e.target.result;
          var header = data_s.slice(0,data_s.indexOf('\n'));
          //guess the separator,
          var separator = [',','\t',';'].reduce(function(prev, current) {
            var c = countOccurrences(header, current);
            if (c > prev.c) {
              prev.c = c;
              prev.s = current;
            }
            return prev;
          },{ s: ',', c : 0});
          var _data = d3.dsv(separator.s, 'text/plain').parse(data_s, normalizeRow);
          //derive a description file
          var desc = deriveDesc(header.split(separator.s).map(normalizeValue), _data);
          var name = f.name.substring(0, f.name.lastIndexOf('.'));
          loadDataImpl(name, desc, _data);
        };
        reader.readAsText(f);
      }
    });
  }

// document ready
  $(function () {
      layoutHTML();

      d3.json("datasets.json", function (error, data) {
        //console.log("datasets:", data, error);

        datasets = data.datasets;
        var $s = d3.select("#lugui-dataset-selector");
        var ds = $s.selectAll("option").data(data.datasets);
        ds.enter().append("option")
          .attr('value', function (d, i) {
            return i;
          }).text(function (d) {
            return d.name;
          });

        var s = $s.node();
        s.addEventListener('change', function () {
          loadDataset(datasets[s.value]);
        });

        //and start with 0:
        loadDataset(datasets[0]);

        loadLayout();
      });
  })
}(LineUp));
<|endoftext|>


<commit_before>import express from 'express';
import path from 'path';
import open from 'open';

/*eslint-disable no-console*/

const port = 3000;
const app = express();

app.use(express.static('dist'));

app.get('*', (req,res) => {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

app.listen(port, error => {
  if (error) {
    console.log(error);
  } else {
    console.log(`Server started at http://localhost:${port}`);
  }
});
<commit_msg>Add gzip compression to dist server<commit_after>import express from 'express';
import path from 'path';
import open from 'open';
import compression from 'compression';

/*eslint-disable no-console*/

const port = 3000;
const app = express();

app.use(compression());

app.use(express.static('dist'));

app.get('*', (req,res) => {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

app.listen(port, error => {
  if (error) {
    console.log(error);
  } else {
    console.log(`Server started at http://localhost:${port}`);
  }
});
<|endoftext|>


<commit_before>/*
 *@description ensure the func is async function or not
 *@author xtx1130
 *@return {boolean} ture\false
 */
'use strict';
exports = module.exports = func => {
	return Object.prototype.toString.call(func) === '[object AsyncFunction]'
}<commit_msg>change async function judgement<commit_after>/*
 *@description ensure the func is async function or not
 *@author xtx1130
 *@return {boolean} ture\false
 */
'use strict';
exports = module.exports = func => {
	return func.constructor.name === 'AsyncFunction';
}<|endoftext|>


<commit_before>/**
 * 表格组件
 * @author Cc
 * @date 2016/12/15
 */
var Table = {
  // 局部变量
  localVal: {
    tableSelf: "",
    staticDataObj: {},
    reqDataObj: {},
    columns: [],
    tableHead: [],
    isFirstRender: true
  },

  /**
   * public function 初始化组件
   *
   */
  init: function() {
    console.log('table init');
    var that = this;

    var proto = Object.create(HTMLElement.prototype);
    // 创建元素实例回调
    proto.createdCallback = function() {
      // console.log("createdCallback");
      that.localVal.tableSelf = this;
      that.localVal.staticDataObj = JSON.parse(this.getAttribute('data-staticData'));
      that.localVal.reqDataObj = JSON.parse(this.getAttribute('data-reqData'));

      eval("that.prepareDataFunc = " + this.getAttribute('data-prepareDataFunc') ); // 额外对请求的数据做处理
      eval("that.afterGetDataFunc = " +  this.getAttribute('data-afterGetDataFunc') );// 收到数据后回调

      that.requestData();
    };

    // 向文档插入实例回调
    proto.attachedCallback = function() {
      // console.log("attachedCallback");
    };

    // debugger
    document.registerElement('tag-table', {prototype: proto});
  },

  /**
   * public function 请求数据
   * @param {boolean} isTriggered // 判断是否手动触发
   *
   */
  requestData: function(isTriggered) {
    var that = this;
    var _this = this.localVal.tableSelf,
        _staticDataObj = this.localVal.staticDataObj,
        _reqDataObj = this.localVal.reqDataObj;
    // 读取cookies中form表单的参数
    var reqData = window.PubFunc.getCookie(_staticDataObj.reqCookie);
    if(reqData.hasOwnProperty("undefined")) return false;

    // 组装request data，主要是翻页相关的和额外的参数
    for(var _reqDataObjItem in _reqDataObj) {
      reqData[_reqDataObjItem] = _reqDataObj[_reqDataObjItem];
    }

    if(that.prepareDataFunc) that.prepareDataFunc(_this,reqData);

    // 返回数据前
    this._renderTable();

    // 再次触发更新表格
    if(isTriggered === true) {
      this._mainTable(reqData);
      return false;
    }

    // 返回数据后
    $.ajax({
      type: _staticDataObj.ajaxType,
      url: _staticDataObj.url,
      data: JSON.stringify(reqData),
      dataType: "json",
      contentType: "application/json",
      success: function(res) {
        console.log('%csuccess', 'background: green; color: white;');
        // 为了延迟看loading
        setTimeout(function() {
          that._renderTable(reqData, res.data);
        }, 1000)

      },
      error: function() {
        console.log('%cerror', 'background: red; color: white;');
      }
    });
  },

  /**
   * private function 渲染表格
   * @param {object} __reqDataObj // 请求参数
   * @param {object} resData // 返回数据
   *
   */
  _renderTable: function(__reqDataObj, resData) {
    var __this = this.localVal.tableSelf,
        __staticDataObj = this.localVal.staticDataObj;

    // 返回数据前
    $(__this).html('

');

    // 返回数据后
    if(resData && resData.head.length > 0) {
      // 设置列表表头字段顺序
      var sort = resData.sort;
      for(var i=0; i<sort.length; i++) {
        this.localVal.columns.push({
          "data": sort[i]
        })
      }

      // 存储表头
      this.localVal.tableHead = resData.head;

      this._mainTable(__reqDataObj, resData);
    }

  },

  /**
   * private function 渲染表格主体，操作表格
   * @param {object} ___reqDataObj // 请求参数
   * @param {object} _resData  // 返回数据
   *
   */
  _mainTable: function(___reqDataObj, _resData) {
    var that = this,
        ___this = this.localVal.tableSelf
        ___staticDataObj = this.localVal.staticDataObj,
        columns = this.localVal.columns;

    // 添加表头
    var tableToolbar = '

<button class="btn btn-success">导出Excel</button><button class="btn btn-success showAllColumns">显示所有列</button>

';
    var headTemp = "",
        headData = this.localVal.tableHead;
    for(var i=0; i<headData.length; i++) {
      headTemp += '' + headData[i] + '	';
    }
    $(___this).html('
' + tableToolbar + '

' + headTemp + '

');

    // 渲染主体
    var dataTableContent = $('#'+___staticDataObj.id).DataTable({
      "pageLength": parseInt(this.localVal.reqDataObj.pageSize),
      "lengthChange": false,
      "searching": false,
      "language": that._dataTableConfig.lang,
      // "order": [[1, "desc"]],
      "ordering": false, // 因为开启了serverSide，所以排序也会发起ajax请求，但又因为只对当前页进行排序，因此要禁用这个排序
      "columns": columns, // 设置列表表头字段顺序
      "processing": true,
      "serverSide": true,  //启用服务器端分页
      "ajax": function(data, callback, settings) {
        // console.log(data);
        var param = ___reqDataObj;
        console.log("%cmaintable", "background: red", data);
        param.currentPage = (data.start / data.length) + 1;
        if(this.prepareDataFunc) this.prepareDataFunc(__this,param);//回调

        // 初次加载
        if(that.localVal.isFirstRender) {
          that._getTable(data, _resData, callback);
          that.localVal.isFirstRender = false;
          return false;
        }

        $.ajax({
          type: ___staticDataObj.ajaxType,
          url: ___staticDataObj.url,
          cache: false,  //禁用缓存
          data: JSON.stringify(param),  //传入组装的参数
          dataType: "json",
          contentType: "application/json",
          success: function (result) {
              console.log("%cmaintableReqSucc", "background: green", result);
              //封装返回数据
              that._getTable(data, result.data, callback);
          }
        })
      },

    });

    // 设置table的横向滚动态
    // display: block时才能出现滚动条
    // display: table时才能在内容少的时候自适应宽度撑满table
    var _setTableLayout = function() {
      if($('table.dataTable tbody').width() > $('.dataTables_wrapper').width()) {
        $('table.dataTable').css({
          'display': 'block',
          'overflow-x': 'auto'
        })
      } else {
        $('table.dataTable').css({
          'display': 'table'
        })
      }
    }
    _setTableLayout();

    // 显示隐藏列
    $('.hideColumn').bind('click', function(e) {
      e.stopPropagation();
      dataTableContent.column($(this).attr('data-column')).visible(false);
      _setTableLayout();

    });
    $('.showAllColumns').bind('click', function() {
      dataTableContent.columns().visible(true);
      _setTableLayout();
    })
  },

  /**
   * private function 主体数据插入
   * @param {object} dataTableAjaxData // dataTable自带的ajax data
   * @param {object} __resData // 返回数据
   * @param {function} _callback // dataTable回调方法
   *
   */
  _getTable: function(dataTableAjaxData, __resData, _callback) {
    var ____staticDataObj = this.localVal.staticDataObj;
    var returnData = {};
    returnData.draw = dataTableAjaxData.draw; //这里直接自行返回了draw计数器,应该由后台返回
    returnData.recordsTotal = __resData.page.recordCount; //返回数据全部记录
    returnData.recordsFiltered = __resData.page.recordCount; //后台不实现过滤功能，每次查询均视作全部结果

    var resList = __resData.page.resList;
    if(__resData.total) resList.push(__resData.total); // 加上“总计”行，用于显示，但不计入pageLength，见上
    returnData.data = resList; //返回的数据列表
    // console.log(returnData);
    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
    _callback(returnData);

    // 动态插入数据排序
    $('#'+____staticDataObj.id).trigger("update").tablesorter();
    // 初始化排序
    setTimeout(function() {
      var sorting = [[____staticDataObj.orderColumn,____staticDataObj.orderDir]];
      $('#'+____staticDataObj.id).trigger("sorton",[sorting]);
    }, 1)
  },

  /**
   * private object datatable配置
   *
   */
  _dataTableConfig: {
    lang: {
      "sProcessing": "处理中...",
      "sLengthMenu": "每页 _MENU_ 项",
      "sZeroRecords": "没有匹配结果",
      "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项",
      "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
      "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
      "sInfoPostFix": "",
      "sSearch": "搜索:",
      "sUrl": "",
      "sEmptyTable": "表中数据为空",
      "sLoadingRecords": "载入中...",
      "sInfoThousands": ",",
      "oPaginate": {
          "sFirst": "首页",
          "sPrevious": "上一页",
          "sNext": "下一页",
          "sLast": "末页",
          "sJump": "跳转"
      },
      "oAria": {
          "sSortAscending": ": 以升序排列此列",
          "sSortDescending": ": 以降序排列此列"
      },
    },
  },

}

Table.init();<commit_msg>young luo modification<commit_after>/**
 * 表格组件
 * @author Cc
 * @date 2016/12/15
 */
var Table = {
  // 局部变量
  localVal: {
    tableSelf: "",
    staticDataObj: {},
    reqDataObj: {},
    columns: [],
    tableHead: [],
    isFirstRender: true
  },

  /**
   * public function 初始化组件
   *
   */
  init: function() {
    console.log('table init');
    var that = this;

    var proto = Object.create(HTMLElement.prototype);
    // 创建元素实例回调
    proto.createdCallback = function() {
      // console.log("createdCallback");
      that.localVal.tableSelf = this;
      that.localVal.staticDataObj = JSON.parse(this.getAttribute('data-staticData'));
      that.localVal.reqDataObj = JSON.parse(this.getAttribute('data-reqData'));

      // young.luo
      eval("that.prepareDataFunc = " + this.getAttribute('data-prepareDataFunc') ); // 额外对请求的数据做处理
      eval("that.afterGetDataFunc = " +  this.getAttribute('data-afterGetDataFunc') );// 收到数据后回调

      that.requestData();
    };

    // 向文档插入实例回调
    proto.attachedCallback = function() {
      // console.log("attachedCallback");
    };

    // debugger
    document.registerElement('tag-table', {prototype: proto});
  },

  /**
   * public function 请求数据
   * @param {boolean} isTriggered // 判断是否手动触发
   *
   */
  requestData: function(isTriggered) {
    var that = this;
    var _this = this.localVal.tableSelf,
        _staticDataObj = this.localVal.staticDataObj,
        _reqDataObj = this.localVal.reqDataObj;
    // 读取cookies中form表单的参数
    var reqData = window.PubFunc.getCookie(_staticDataObj.reqCookie);
    if(reqData.hasOwnProperty("undefined")) return false;

    // 组装request data，主要是翻页相关的和额外的参数
    for(var _reqDataObjItem in _reqDataObj) {
      reqData[_reqDataObjItem] = _reqDataObj[_reqDataObjItem];
    }

    // young.luo
    if(that.prepareDataFunc) that.prepareDataFunc(_this,reqData);

    // 返回数据前
    this._renderTable();

    // 再次触发更新表格
    if(isTriggered === true) {
      this._mainTable(reqData);
      return false;
    }

    // 返回数据后
    $.ajax({
      type: _staticDataObj.ajaxType,
      url: _staticDataObj.url,
      data: JSON.stringify(reqData),
      dataType: "json",
      contentType: "application/json",
      success: function(res) {
        console.log('%csuccess', 'background: green; color: white;');
        // 为了延迟看loading
        setTimeout(function() {
          that._renderTable(reqData, res.data);
        }, 1000);

        // young.luo
        if(that.afterGetDataFunc) {
        	that.afterGetDataFunc(that,res);
        }
      },
      error: function() {
        console.log('%cerror', 'background: red; color: white;');
      }
    });
  },

  /**
   * private function 渲染表格
   * @param {object} __reqDataObj // 请求参数
   * @param {object} resData // 返回数据
   *
   */
  _renderTable: function(__reqDataObj, resData) {
    var __this = this.localVal.tableSelf,
        __staticDataObj = this.localVal.staticDataObj;

    // 返回数据前
    $(__this).html('

');

    // 返回数据后
    if(resData && resData.head.length > 0) {
      // 设置列表表头字段顺序
      var sort = resData.sort;
      for(var i=0; i<sort.length; i++) {
        this.localVal.columns.push({
          "data": sort[i]
        })
      }

      // 存储表头
      this.localVal.tableHead = resData.head;

      this._mainTable(__reqDataObj, resData);
    }

  },

  /**
   * private function 渲染表格主体，操作表格
   * @param {object} ___reqDataObj // 请求参数
   * @param {object} _resData  // 返回数据
   *
   */
  _mainTable: function(___reqDataObj, _resData) {
    var that = this,
        ___this = this.localVal.tableSelf
        ___staticDataObj = this.localVal.staticDataObj,
        columns = this.localVal.columns;

    // 添加表头
    var tableToolbar = '

<button class="btn btn-success">导出Excel</button><button class="btn btn-success showAllColumns">显示所有列</button>

';
    var headTemp = "",
        headData = this.localVal.tableHead;
    for(var i=0; i<headData.length; i++) {
      headTemp += '' + headData[i] + '	';
    }
    $(___this).html('
' + tableToolbar + '

' + headTemp + '

');

    // 渲染主体
    var dataTableContent = $('#'+___staticDataObj.id).DataTable({
      "pageLength": parseInt(this.localVal.reqDataObj.pageSize),
      "lengthChange": false,
      "searching": false,
      "language": that._dataTableConfig.lang,
      // "order": [[1, "desc"]],
      "ordering": false, // 因为开启了serverSide，所以排序也会发起ajax请求，但又因为只对当前页进行排序，因此要禁用这个排序
      "columns": columns, // 设置列表表头字段顺序
      "processing": true,
      "serverSide": true,  //启用服务器端分页
      "ajax": function(data, callback, settings) {
        // console.log(data);
        var param = ___reqDataObj;
        console.log("%cmaintable", "background: red", data);
        param.currentPage = (data.start / data.length) + 1;

        // young.luo 回调
        if(this.prepareDataFunc) this.prepareDataFunc(__this,param);

        // 初次加载
        if(that.localVal.isFirstRender) {
          that._getTable(data, _resData, callback);
          that.localVal.isFirstRender = false;
          return false;
        }

        $.ajax({
          type: ___staticDataObj.ajaxType,
          url: ___staticDataObj.url,
          cache: false,  //禁用缓存
          data: JSON.stringify(param),  //传入组装的参数
          dataType: "json",
          contentType: "application/json",
          success: function (result) {
              console.log("%cmaintableReqSucc", "background: green", result);
              //封装返回数据
              that._getTable(data, result.data, callback);

              // young.luo
              if(that.afterGetDataFunc) {
              	that.afterGetDataFunc(that,result);
              }
          }
        })
      },

    });

    // 设置table的横向滚动态
    // display: block时才能出现滚动条
    // display: table时才能在内容少的时候自适应宽度撑满table
    var _setTableLayout = function() {
      if($('table.dataTable tbody').width() > $('.dataTables_wrapper').width()) {
        $('table.dataTable').css({
          'display': 'block',
          'overflow-x': 'auto'
        })
      } else {
        $('table.dataTable').css({
          'display': 'table'
        })
      }
    }
    _setTableLayout();

    // 显示隐藏列
    $('.hideColumn').bind('click', function(e) {
      e.stopPropagation();
      dataTableContent.column($(this).attr('data-column')).visible(false);
      _setTableLayout();

    });
    $('.showAllColumns').bind('click', function() {
      dataTableContent.columns().visible(true);
      _setTableLayout();
    })
  },

  /**
   * private function 主体数据插入
   * @param {object} dataTableAjaxData // dataTable自带的ajax data
   * @param {object} __resData // 返回数据
   * @param {function} _callback // dataTable回调方法
   *
   */
  _getTable: function(dataTableAjaxData, __resData, _callback) {
    var ____staticDataObj = this.localVal.staticDataObj;
    var returnData = {};
    returnData.draw = dataTableAjaxData.draw; //这里直接自行返回了draw计数器,应该由后台返回
    returnData.recordsTotal = __resData.page.recordCount; //返回数据全部记录
    returnData.recordsFiltered = __resData.page.recordCount; //后台不实现过滤功能，每次查询均视作全部结果

    var resList = __resData.page.resList;
    if(__resData.total) resList.push(__resData.total); // 加上“总计”行，用于显示，但不计入pageLength，见上
    returnData.data = resList; //返回的数据列表
    // console.log(returnData);
    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
    _callback(returnData);

    // 动态插入数据排序
    $('#'+____staticDataObj.id).trigger("update").tablesorter();
    // 初始化排序
    setTimeout(function() {
      var sorting = [[____staticDataObj.orderColumn,____staticDataObj.orderDir]];
      $('#'+____staticDataObj.id).trigger("sorton",[sorting]);
    }, 1)
  },

  /**
   * private object datatable配置
   *
   */
  _dataTableConfig: {
    lang: {
      "sProcessing": "处理中...",
      "sLengthMenu": "每页 _MENU_ 项",
      "sZeroRecords": "没有匹配结果",
      "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项",
      "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
      "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
      "sInfoPostFix": "",
      "sSearch": "搜索:",
      "sUrl": "",
      "sEmptyTable": "表中数据为空",
      "sLoadingRecords": "载入中...",
      "sInfoThousands": ",",
      "oPaginate": {
          "sFirst": "首页",
          "sPrevious": "上一页",
          "sNext": "下一页",
          "sLast": "末页",
          "sJump": "跳转"
      },
      "oAria": {
          "sSortAscending": ": 以升序排列此列",
          "sSortDescending": ": 以降序排列此列"
      },
    },
  },

}

Table.init();<|endoftext|>


<commit_before>// @flow
import React from 'react'
import {WebView, StyleSheet} from 'react-native'
import LoadingView from '../components/loading'
import {text as faqs} from '../../docs/faqs.json'
import {tracker} from '../../analytics'

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 30,
    paddingTop: 10,
    paddingBottom: 20,
    backgroundColor: 'transparent',
  },
})

export class FaqView extends React.Component {
  state = {
    html: faqs,
  }

  componentWillMount() {
    this.fetchData()
  }

  url = 'https://stodevx.github.io/AAO-React-Native/faqs.json'

  fetchData = async () => {
    let html = faqs
    try {
      let blob: {text: string} = await fetchJson(this.url)
      html = blob.text
    } catch (err) {
      tracker.trackException(err.message)
      console.warn(err.message)
    }
    this.setState({html: html})
  }

  render() {
    if (!this.state.html) {
      return <LoadingView />
    }
    return <WebView style={styles.container} source={{html: this.state.html}} />
  }
}
<commit_msg>load local faqs on development (#619)<commit_after>// @flow
import React from 'react'
import {WebView, StyleSheet} from 'react-native'
import LoadingView from '../components/loading'
import {text as faqs} from '../../docs/faqs.json'
import {tracker} from '../../analytics'

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 30,
    paddingTop: 10,
    paddingBottom: 20,
    backgroundColor: 'transparent',
  },
})

export class FaqView extends React.Component {
  state = {
    html: faqs,
  }

  componentWillMount() {
    this.fetchData()
  }

  url = 'https://stodevx.github.io/AAO-React-Native/faqs.json'

  fetchData = async () => {
    let html = faqs
    try {
      let blob: {text: string} = await fetchJson(this.url)
      html = blob.text
    } catch (err) {
      html = faqs
      tracker.trackException(err.message)
      console.warn(err.message)
    }

    if (__DEV__) {
      html = faqs
    }

    this.setState({html: html})
  }

  render() {
    if (!this.state.html) {
      return <LoadingView />
    }
    return <WebView style={styles.container} source={{html: this.state.html}} />
  }
}
<|endoftext|>


<commit_before>/* eslint-env browser */
/* global cmUtil, CodeMirror, ohm, refreshParseTree, Storage */

'use strict';

function $(sel) { return document.querySelector(sel); }
var options = {};

var inputEditor = CodeMirror.fromTextArea($('#input'));
var grammarEditor = CodeMirror.fromTextArea($('#grammar'));
var grammar;

// Misc Helpers
// ------------

function createElement(sel, optContent) {
  var parts = sel.split('.');
  var tagName = parts[0];
  if (tagName.length === 0) {
    tagName = 'div';
  }

  var el = document.createElement(tagName);
  el.className = parts.slice(1).join(' ');
  if (optContent) {
    el.textContent = optContent;
  }
  return el;
}

var errorMarks = {
  grammar: null,
  input: null
};

function hideError(category, editor) {
  var errInfo = errorMarks[category];
  if (errInfo) {
    errInfo.mark.clear();
    clearTimeout(errInfo.timeout);
    if (errInfo.widget) {
      errInfo.widget.clear();
    }
    errorMarks[category] = null;
  }
}

function setError(category, editor, interval, message) {
  hideError(category, editor);

  errorMarks[category] = {
    mark: cmUtil.markInterval(editor, interval, 'error-interval', false),
    timeout: setTimeout(function() { showError(category, editor, interval, message); }, 1500),
    widget: null
  };
}

function showError(category, editor, interval, message) {
  var errorEl = createElement('.error', message);
  var line = editor.posFromIndex(interval.endIdx).line;
  errorMarks[category].widget = editor.addLineWidget(line, errorEl);
}

function useLocalStorage() {
  return typeof localStorage !== 'undefined' &&
         typeof Storage === 'function' &&
         localStorage instanceof Storage;
}

function setEditorValueFromLocalStorage(editor, key) {
  if (useLocalStorage()) {
    var contents = localStorage.getItem(key);
    if (contents != null) {
      editor.setValue(contents);
    }
  }
}

function hideBottomOverlay() {
  $('#bottomSection .overlay').style.width = 0;
}

function showBottomOverlay() {
  $('#bottomSection .overlay').style.width = '100%';
}

// Main
// ----

(function main() {
  var checkboxes = document.querySelectorAll('#options input[type=checkbox]');
  var refreshTimeout;
  var grammarChanged = true;

  function triggerRefresh(delay) {
    showBottomOverlay();
    if (refreshTimeout) {
      clearTimeout(refreshTimeout);
    }
    refreshTimeout = setTimeout(refresh, delay || 0);
  }
  Array.prototype.forEach.call(checkboxes, function(cb) {
    cb.addEventListener('click', function(e) { triggerRefresh(); });
  });

  setEditorValueFromLocalStorage(inputEditor, 'input');
  setEditorValueFromLocalStorage(grammarEditor, 'grammar');

  inputEditor.on('change', function() { triggerRefresh(250); });
  grammarEditor.on('change', function() {
    grammarChanged = true;
    hideError('grammar', grammarEditor);
    triggerRefresh(250);
  });

  function refresh() {
    hideError('input', inputEditor);
    if (useLocalStorage()) {
      localStorage.setItem('input', inputEditor.getValue());
    }

    // Refresh the option values.
    for (var i = 0; i < checkboxes.length; ++i) {
      var checkbox = checkboxes[i];
      options[checkbox.name] = checkbox.checked;
    }

    if (grammarChanged) {
      grammarChanged = false;

      var grammarSrc = grammarEditor.getValue();
      if (useLocalStorage()) {
        localStorage.setItem('grammar', grammarSrc);
      }
      try {
        grammar = ohm.grammar(grammarSrc);
      } catch (e) {
        console.log(e);  // eslint-disable-line no-console

        var message = e.shortMessage ? e.shortMessage : e.message;
        setError('grammar', grammarEditor, e.interval, message);
        // If the grammar is unusable, prevent the input from being parsed.
        grammar = null;
        return;
      }
    }

    if (!grammar) {
      return;
    }
    hideBottomOverlay();
    $('#expandedInput').innerHTML = '';
    $('#parseResults').innerHTML = '';

    refreshParseTree(grammar, inputEditor.getValue());
  }
  refresh();
})();
<commit_msg>Visualizer nit: restrict the scope of `grammar` var.<commit_after>/* eslint-env browser */
/* global cmUtil, CodeMirror, ohm, refreshParseTree, Storage */

'use strict';

function $(sel) { return document.querySelector(sel); }
var options = {};

var inputEditor = CodeMirror.fromTextArea($('#input'));
var grammarEditor = CodeMirror.fromTextArea($('#grammar'));

// Misc Helpers
// ------------

function createElement(sel, optContent) {
  var parts = sel.split('.');
  var tagName = parts[0];
  if (tagName.length === 0) {
    tagName = 'div';
  }

  var el = document.createElement(tagName);
  el.className = parts.slice(1).join(' ');
  if (optContent) {
    el.textContent = optContent;
  }
  return el;
}

var errorMarks = {
  grammar: null,
  input: null
};

function hideError(category, editor) {
  var errInfo = errorMarks[category];
  if (errInfo) {
    errInfo.mark.clear();
    clearTimeout(errInfo.timeout);
    if (errInfo.widget) {
      errInfo.widget.clear();
    }
    errorMarks[category] = null;
  }
}

function setError(category, editor, interval, message) {
  hideError(category, editor);

  errorMarks[category] = {
    mark: cmUtil.markInterval(editor, interval, 'error-interval', false),
    timeout: setTimeout(function() { showError(category, editor, interval, message); }, 1500),
    widget: null
  };
}

function showError(category, editor, interval, message) {
  var errorEl = createElement('.error', message);
  var line = editor.posFromIndex(interval.endIdx).line;
  errorMarks[category].widget = editor.addLineWidget(line, errorEl);
}

function useLocalStorage() {
  return typeof localStorage !== 'undefined' &&
         typeof Storage === 'function' &&
         localStorage instanceof Storage;
}

function setEditorValueFromLocalStorage(editor, key) {
  if (useLocalStorage()) {
    var contents = localStorage.getItem(key);
    if (contents != null) {
      editor.setValue(contents);
    }
  }
}

function hideBottomOverlay() {
  $('#bottomSection .overlay').style.width = 0;
}

function showBottomOverlay() {
  $('#bottomSection .overlay').style.width = '100%';
}

// Main
// ----

(function main() {
  var checkboxes = document.querySelectorAll('#options input[type=checkbox]');
  var refreshTimeout;
  var grammar;
  var grammarChanged = true;

  function triggerRefresh(delay) {
    showBottomOverlay();
    if (refreshTimeout) {
      clearTimeout(refreshTimeout);
    }
    refreshTimeout = setTimeout(refresh, delay || 0);
  }
  Array.prototype.forEach.call(checkboxes, function(cb) {
    cb.addEventListener('click', function(e) { triggerRefresh(); });
  });

  setEditorValueFromLocalStorage(inputEditor, 'input');
  setEditorValueFromLocalStorage(grammarEditor, 'grammar');

  inputEditor.on('change', function() { triggerRefresh(250); });
  grammarEditor.on('change', function() {
    grammarChanged = true;
    hideError('grammar', grammarEditor);
    triggerRefresh(250);
  });

  function refresh() {
    hideError('input', inputEditor);
    if (useLocalStorage()) {
      localStorage.setItem('input', inputEditor.getValue());
    }

    // Refresh the option values.
    for (var i = 0; i < checkboxes.length; ++i) {
      var checkbox = checkboxes[i];
      options[checkbox.name] = checkbox.checked;
    }

    if (grammarChanged) {
      grammarChanged = false;

      var grammarSrc = grammarEditor.getValue();
      if (useLocalStorage()) {
        localStorage.setItem('grammar', grammarSrc);
      }
      try {
        grammar = ohm.grammar(grammarSrc);
      } catch (e) {
        console.log(e);  // eslint-disable-line no-console

        var message = e.shortMessage ? e.shortMessage : e.message;
        setError('grammar', grammarEditor, e.interval, message);
        // If the grammar is unusable, prevent the input from being parsed.
        grammar = null;
        return;
      }
    }

    if (!grammar) {
      return;
    }
    hideBottomOverlay();
    $('#expandedInput').innerHTML = '';
    $('#parseResults').innerHTML = '';

    refreshParseTree(grammar, inputEditor.getValue());
  }
  refresh();
})();
<|endoftext|>


<commit_before>angular
  .module('StationCreator')
  .factory('StationCreatorService', StationCreatorService);

StationCreatorService.$inject = [
  '$log', '$http'
];

function StationCreatorService (
  $log, $http
) {
  /// StationCreatorService
  var service =
  {
    /// constants
    BASIS_TAB_INDEX      : 0,
    PLACE_TAB_INDEX      : 1,
    CATEGORIES_TAB_INDEX : 2,
    SETTINGS_TAB_INDEX   : 3,

    STATION_CODE_EXAMPLE : 'station-code',

    /// vars
    marker : {
      coords : null
    },
    markersAll : [],

    /// functions
    loadCategories       : loadCategories,
    loadStation          : loadStation,
    addStation           : addStation,
    saveStation          : saveStation,
    deleteStation        : deleteStation,
    cloneMyStation       : cloneMyStation,
    updateStationContent: updateStationContent
  };

  /// services

  function loadCategories (mobidulCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/GetCategories');
  }

  function loadStation (mobidulCode, stationCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/GetForCode/' + stationCode);
  }

  function addStation (mobidulCode, stationData) {
    return $http.post(cordovaUrl + '/' + mobidulCode + '/AddStation', stationData);
  }

  function saveStation (mobidulCode, stationCode, stationData) {
    return $http.post(cordovaUrl + '/' + mobidulCode + '/SaveStation/' + stationCode, stationData);
  }

  function updateStationContent (mobidulCode, stationCode, content){
    return $http.post(cordovaUrl + '/' + mobidulCode + '/UpdateContent/' + stationCode, { content: content });
  }

  function deleteStation (mobidulCode, stationCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/RemoveStationByCode/' + stationCode);
  }

  /**
   * This function calls the Server in order to clone the current Station. It also contains the ID of the new station.
   * @param mobidulCode Code of the Mobidul the station belongs to.
   * @param stationCode Code of the Station that will be duplicated.
   * @returns {*} Call of the Server
   */
  function cloneMyStation(mobidulCode, stationCode) {

    return $http.get(cordovaUrl + '/' + mobidulCode + '/cloneStation/' + stationCode)
      .success(function (response, status, headers, config) {
      return response;
    })
      .error(function (response, status, headers, config) {
        $log.error(response);
        $log.error(status);
      });
  }

  return service;
}
<commit_msg>Minor code revision<commit_after>angular
  .module('StationCreator')
  .factory('StationCreatorService', StationCreatorService);

StationCreatorService.$inject = [
  '$log', '$http'
];

function StationCreatorService (
  $log, $http
) {
  /// StationCreatorService
  var service =
  {
    /// constants
    BASIS_TAB_INDEX      : 0,
    PLACE_TAB_INDEX      : 1,
    CATEGORIES_TAB_INDEX : 2,
    SETTINGS_TAB_INDEX   : 3,

    STATION_CODE_EXAMPLE : 'station-code',

    /// vars
    marker : {
      coords : null
    },
    markersAll : [],

    /// functions
    loadCategories       : loadCategories,
    loadStation          : loadStation,
    addStation           : addStation,
    saveStation          : saveStation,
    deleteStation        : deleteStation,
    cloneMyStation       : cloneMyStation,
    updateStationContent : updateStationContent
  };

  /// services

  function loadCategories (mobidulCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/GetCategories');
  }

  function loadStation (mobidulCode, stationCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/GetForCode/' + stationCode);
  }

  function addStation (mobidulCode, stationData) {
    return $http.post(cordovaUrl + '/' + mobidulCode + '/AddStation', stationData);
  }

  function saveStation (mobidulCode, stationCode, stationData) {
    return $http.post(cordovaUrl + '/' + mobidulCode + '/SaveStation/' + stationCode, stationData);
  }

  function updateStationContent (mobidulCode, stationCode, content){
    return $http.post(cordovaUrl + '/' + mobidulCode + '/UpdateContent/' + stationCode, { content: content });
  }

  function deleteStation (mobidulCode, stationCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/RemoveStationByCode/' + stationCode);
  }

  /**
   * This function calls the Server in order to clone the current Station. It also contains the ID of the new station.
   * @param mobidulCode Code of the Mobidul the station belongs to.
   * @param stationCode Code of the Station that will be duplicated.
   * @returns {*} Call of the Server
   */
  function cloneMyStation(mobidulCode, stationCode) {
    return $http.get(cordovaUrl + '/' + mobidulCode + '/cloneStation/' + stationCode)
      .success(function (response, status, headers, config) {
      return response;
    })
    .error(function (response, status, headers, config) {
      $log.error(response);
      $log.error(status);
    });
  }

  return service;
}
<|endoftext|>


<commit_before>var EE = require('events').EventEmitter;
var inherits = require('inherits');

function PhrasePrompt(options) {
    if (!this instanceof PhrasePrompt) {
        return new PhrasePrompt(options);
    }
    // TODO: ick
    options = options || {};
    if (!options.scoreResult) throw new Error('missing scoreResult option');
    if (!options.generatePhrase) throw new Error('missing generatePhrase option');
    if (!options.complexity) throw new Error('missing complexity option');
    if (!options.input) throw new Error('missing input');
    if (!options.display) throw new Error('missing display');

    this.running = false;
    this.repromptDelay = options.repromptDelay || 100;
    this.scoreResult = options.scoreResult;
    this.displayTime = options.displayTime || 1000;
    this.inputTime = options.inputTime || 10000;
    this.input = options.input;
    this.displayElement = options.display;
    this.expected = '';
    this.inputing = null;
    this.generatePhrase = options.generatePhrase;
    this.complexity = options.complexity;

    this.input.on('data', this.onInput.bind(this));
    this.on('showdisplay', this.onDisplay.bind(this));
    this.on('settimeout', this.onSetTimeout.bind(this));
    this.on('showinput', this.onShowInput.bind(this));
}

inherits(PhrasePrompt, EE);

PhrasePrompt.prototype.prompt = function() {
    this.record = {
        elapsed: {},
        timeout: {}
    };
    var text = this.generatePhrase.apply(this, this.complexity.value);
    this.expected = text;
    this.display(text);
    this.setTimer();
    this.record.expected = this.expected;
    this.onInput('');
};

PhrasePrompt.prototype.display = function(text) {
    this.displayElement.innerHTML = text;
    this.input.element.value = '';
    this.input.element.size = text.length + 2;
    this.showDisplay(text);
    this.emit('display');
};

PhrasePrompt.prototype.showDisplay = function() {
    if (this.inputing !== false) {
        this.inputing = false;
        this.emit('showdisplay');
    }
};

PhrasePrompt.prototype.showInput = function() {
    this.clearTimer();
    if (this.inputing !== true) {
        this.inputing = true;
        this.emit('showinput');
        this.input.element.disabled = false;
        this.input.element.focus();
    }
    this.setTimer();
};

PhrasePrompt.prototype.setTimer = function() {
    this.clearTimer();
    if (this.inputing) {
        this.timer = setTimeout(function() {
            if (this.inputing) this.expireInput();
        }.bind(this), this.inputTime);
        this.emit('settimeout', 'input', this.inputTime);
    } else {
        this.timer = setTimeout(function() {
            if (!this.inputing) this.showInput();
        }.bind(this), this.displayTime);
        this.emit('settimeout', 'display', this.displayTime);
    }
};

PhrasePrompt.prototype.clearTimer = function() {
    if (this.timer) {
        clearTimeout(this.timer);
        delete this.timer;
    }
};

PhrasePrompt.prototype.expireInput = function() {
    this.clearTimer();
    this.input.element.disabled = true;
    this.finishRecord(true);
    if (this.record) {
        this.record.expired = true;
        this.emitRecord();
    }
    if (this.running) {
        this.reprompt();
    }
};

PhrasePrompt.prototype.start = function() {
    if (!this.running) {
        this.running = true;
        this.prompt();
    }
};

PhrasePrompt.prototype.stop = function() {
    if (this.running) {
        this.running = false;
        this.expireInput();
    }
};

PhrasePrompt.prototype.emitRecord = function() {
    if (this.record) {
        this.emit('result', this.record);
        this.record = null;
    }
};

PhrasePrompt.prototype.finishRecord = function(force) {
    if (!this.record) return;
    if (this.record.inputShownAt) {
        this.record.elapsed.input = Date.now() - this.record.inputShownAt;
    }
    this.record.forced = force;
    this.scoreResult(this.record, force);
};

PhrasePrompt.prototype.reprompt = function() {
    if (this.inputing) {
        this.input.element.disabled = true;
    }
    setTimeout(this.prompt.bind(this), this.repromptDelay);
};

PhrasePrompt.prototype.onSetTimeout = function(kind, time) {
    if (this.record) {
        this.record.timeout[kind] = time;
    }
};

PhrasePrompt.prototype.onDisplay = function() {
    if (this.record && !this.record.displayedAt) {
        this.record.displayedAt = Date.now();
    }
};

PhrasePrompt.prototype.onShowInput = function() {
    this.record.inputShownAt = Date.now();
    if (this.record.displayedAt) {
        if (!this.record.elapsed.display) {
            this.record.elapsed.display = this.record.inputShownAt - this.record.displayedAt;
        }
    }
};

PhrasePrompt.prototype.onInput = function(got, force) {
    if (this.record) {
        this.record.got = got;
        this.finishRecord(force);
        if (this.record.finished) {
            this.clearTimer();
            this.emitRecord();
            this.reprompt();
        }
    }
};

module.exports = PhrasePrompt;
<commit_msg>Drop record expired flag<commit_after>var EE = require('events').EventEmitter;
var inherits = require('inherits');

function PhrasePrompt(options) {
    if (!this instanceof PhrasePrompt) {
        return new PhrasePrompt(options);
    }
    // TODO: ick
    options = options || {};
    if (!options.scoreResult) throw new Error('missing scoreResult option');
    if (!options.generatePhrase) throw new Error('missing generatePhrase option');
    if (!options.complexity) throw new Error('missing complexity option');
    if (!options.input) throw new Error('missing input');
    if (!options.display) throw new Error('missing display');

    this.running = false;
    this.repromptDelay = options.repromptDelay || 100;
    this.scoreResult = options.scoreResult;
    this.displayTime = options.displayTime || 1000;
    this.inputTime = options.inputTime || 10000;
    this.input = options.input;
    this.displayElement = options.display;
    this.expected = '';
    this.inputing = null;
    this.generatePhrase = options.generatePhrase;
    this.complexity = options.complexity;

    this.input.on('data', this.onInput.bind(this));
    this.on('showdisplay', this.onDisplay.bind(this));
    this.on('settimeout', this.onSetTimeout.bind(this));
    this.on('showinput', this.onShowInput.bind(this));
}

inherits(PhrasePrompt, EE);

PhrasePrompt.prototype.prompt = function() {
    this.record = {
        elapsed: {},
        timeout: {}
    };
    var text = this.generatePhrase.apply(this, this.complexity.value);
    this.expected = text;
    this.display(text);
    this.setTimer();
    this.record.expected = this.expected;
    this.onInput('');
};

PhrasePrompt.prototype.display = function(text) {
    this.displayElement.innerHTML = text;
    this.input.element.value = '';
    this.input.element.size = text.length + 2;
    this.showDisplay(text);
    this.emit('display');
};

PhrasePrompt.prototype.showDisplay = function() {
    if (this.inputing !== false) {
        this.inputing = false;
        this.emit('showdisplay');
    }
};

PhrasePrompt.prototype.showInput = function() {
    this.clearTimer();
    if (this.inputing !== true) {
        this.inputing = true;
        this.emit('showinput');
        this.input.element.disabled = false;
        this.input.element.focus();
    }
    this.setTimer();
};

PhrasePrompt.prototype.setTimer = function() {
    this.clearTimer();
    if (this.inputing) {
        this.timer = setTimeout(function() {
            if (this.inputing) this.expireInput();
        }.bind(this), this.inputTime);
        this.emit('settimeout', 'input', this.inputTime);
    } else {
        this.timer = setTimeout(function() {
            if (!this.inputing) this.showInput();
        }.bind(this), this.displayTime);
        this.emit('settimeout', 'display', this.displayTime);
    }
};

PhrasePrompt.prototype.clearTimer = function() {
    if (this.timer) {
        clearTimeout(this.timer);
        delete this.timer;
    }
};

PhrasePrompt.prototype.expireInput = function() {
    this.clearTimer();
    this.input.element.disabled = true;
    this.finishRecord(true);
    if (this.record) {
        this.emitRecord();
    }
    if (this.running) {
        this.reprompt();
    }
};

PhrasePrompt.prototype.start = function() {
    if (!this.running) {
        this.running = true;
        this.prompt();
    }
};

PhrasePrompt.prototype.stop = function() {
    if (this.running) {
        this.running = false;
        this.expireInput();
    }
};

PhrasePrompt.prototype.emitRecord = function() {
    if (this.record) {
        this.emit('result', this.record);
        this.record = null;
    }
};

PhrasePrompt.prototype.finishRecord = function(force) {
    if (!this.record) return;
    if (this.record.inputShownAt) {
        this.record.elapsed.input = Date.now() - this.record.inputShownAt;
    }
    this.record.forced = force;
    this.scoreResult(this.record, force);
};

PhrasePrompt.prototype.reprompt = function() {
    if (this.inputing) {
        this.input.element.disabled = true;
    }
    setTimeout(this.prompt.bind(this), this.repromptDelay);
};

PhrasePrompt.prototype.onSetTimeout = function(kind, time) {
    if (this.record) {
        this.record.timeout[kind] = time;
    }
};

PhrasePrompt.prototype.onDisplay = function() {
    if (this.record && !this.record.displayedAt) {
        this.record.displayedAt = Date.now();
    }
};

PhrasePrompt.prototype.onShowInput = function() {
    this.record.inputShownAt = Date.now();
    if (this.record.displayedAt) {
        if (!this.record.elapsed.display) {
            this.record.elapsed.display = this.record.inputShownAt - this.record.displayedAt;
        }
    }
};

PhrasePrompt.prototype.onInput = function(got, force) {
    if (this.record) {
        this.record.got = got;
        this.finishRecord(force);
        if (this.record.finished) {
            this.clearTimer();
            this.emitRecord();
            this.reprompt();
        }
    }
};

module.exports = PhrasePrompt;
<|endoftext|>


<commit_before>import Ember from 'ember';
import LinkComponent from './link-to-component';
import ExternalLinkComponent from './link-to-external-component';
import emberRequire from './ext-require';

const EmberView = emberRequire('ember-views/views/view');
const RoutingService = emberRequire('ember-routing/services/routing');
const Engine = emberRequire('ember-application/system/engine');
const P = emberRequire('container/registry', 'privatize');
const topLevelViewTemplate = emberRequire('ember-htmlbars/templates/top-level-view');

const {
  OutletView,
  TextField,
  TextArea,
  Checkbox,
  ContainerDebugAdapter,
  ComponentLookup
} = Ember;

Engine.reopen({
  _initializersRan: false,

  ensureInitializers() {
    if (!this._initializersRan) {
      this.runInitializers();
      this._initializersRan = true;
    }
  },

  buildInstance(options) {
    this.ensureInitializers();
    return this._super(options);
  },

  buildRegistry() {
    let namespace = this;
    let registry = this._super(...arguments);

    if (!(this instanceof Ember.Application)) {
      registry.optionsForType('component', { singleton: false });
      registry.optionsForType('view', { singleton: false });
      registry.optionsForType('template', { instantiate: false });

      registry.register('application:main', namespace, { instantiate: false });

      registry.register('controller:basic', Ember.Controller, { instantiate: false });

      // registry.register('renderer:-dom', { create() { return new Renderer(new DOMHelper()); } });

      registry.injection('view', 'renderer', 'renderer:-dom');

      registry.register('template:-outlet', topLevelViewTemplate);
      registry.injection('route', '_topLevelViewTemplate', 'template:-outlet');
      registry.register('view:-outlet', OutletView);

      //registry.register('-view-registry:main', { create() { return {}; } });

      registry.injection('view', '_viewRegistry', '-view-registry:main');

      registry.register('view:toplevel', EmberView.extend());

      // registry.register('route:basic', Route, { instantiate: false });
      // registry.register('event_dispatcher:main', EventDispatcher);

      // registry.injection('router:main', 'namespace', 'application:main');
      registry.injection('view:-outlet', 'namespace', 'application:main');

      // registry.register('location:auto', AutoLocation);
      // registry.register('location:hash', HashLocation);
      // registry.register('location:history', HistoryLocation);
      // registry.register('location:none', NoneLocation);

      registry.injection('controller', 'target', 'router:main');
      registry.injection('controller', 'namespace', 'application:main');

      // registry.register('-bucket-cache:main', BucketCache);
      registry.injection('router', '_bucketCache', P`-bucket-cache:main`);
      registry.injection('route', '_bucketCache', P`-bucket-cache:main`);
      registry.injection('controller', '_bucketCache', P`-bucket-cache:main`);

      registry.injection('route', 'router', 'router:main');

      registry.register('component:-text-field', TextField);
      registry.register('component:-text-area', TextArea);
      registry.register('component:-checkbox', Checkbox);
      // registry.register('view:-legacy-each', LegacyEachView);
      registry.register('component:link-to', LinkComponent);
      registry.register('component:link-to-external', ExternalLinkComponent);

      // Register the routing service...
      registry.register('service:-routing', RoutingService);
      // Then inject the app router into it
      registry.injection('service:-routing', 'router', 'router:main');

      // DEBUGGING
      registry.register('resolver-for-debugging:main', registry.resolver, { instantiate: false });
      registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
      registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
      // Custom resolver authors may want to register their own ContainerDebugAdapter with this key

      registry.register('container-debug-adapter:main', ContainerDebugAdapter);

      registry.register('component-lookup:main', ComponentLookup);
    }

    return registry;
  }
});
<commit_msg>[Clean] Eliminate registrations moved upstream.<commit_after>import Ember from 'ember';
import EngineScopedLinkComponent from './link-to-component';
import ExternalLinkComponent from './link-to-external-component';
import emberRequire from './ext-require';

const Engine = emberRequire('ember-application/system/engine');

const {
  ComponentLookup
} = Ember;

Engine.reopen({
  _initializersRan: false,

  ensureInitializers() {
    if (!this._initializersRan) {
      this.runInitializers();
      this._initializersRan = true;
    }
  },

  buildInstance(options) {
    this.ensureInitializers();
    return this._super(options);
  },

  buildRegistry() {
    let registry = this._super(...arguments);

    if (!(this instanceof Ember.Application)) {
      registry.register('component:link-to', EngineScopedLinkComponent);
      registry.register('component:link-to-external', ExternalLinkComponent);
      registry.register('component-lookup:main', ComponentLookup);
    }

    return registry;
  }
});
<|endoftext|>