<commit_before>"use strict";

var Client     = require("../lib/client");
var Transports = require("../lib/transports");
var Service    = require("../lib/service");
var s          = require("ht-schema");

var number     = 10;
var multiplyBy = 5;

// Make sure you pass the same instance
// of Transports.Local to both Service
// and Client or else this won"t work!
var mathTransport = new Transports.Local();

var mathService = new Service(mathTransport, {logger : console.log});

mathService.on("multiply", s.Object({
    number: s.Number(),
    by:     s.Number()
}), function(data, callback, logger) {
    logger(data);
    callback(null, data.number * data.by);
});

var client = new Client({
    "math": mathTransport
});

// If ALL of your services specified
// use local transports, you do not need
// to call connect here either.
client.connect(function(err) {

    if(err) {
        console.error("There was an error connecting to services:");
        console.error(err);
        process.exit(1);
    }

    client.call("math", "multiply", {
        number: number,
        by:     multiplyBy
    }, function(err, response) {

        if(err) {
            console.error("An error occured multiplying your number!");
            console.error(err);
            process.exit(1);
        }

        console.log("%d * %d = %d", number, multiplyBy, response);

    });

});
<commit_msg>remove depencency injection from old example [ci skip]<commit_after>"use strict";

var Client     = require("../lib/client");
var Transports = require("../lib/transports");
var Service    = require("../lib/service");
var s          = require("ht-schema");

var number     = 10;
var multiplyBy = 5;

// Make sure you pass the same instance
// of Transports.Local to both Service
// and Client or else this won"t work!
var mathTransport = new Transports.Local();

var mathService = new Service(mathTransport);

mathService.on("multiply", s.Object({
    number: s.Number(),
    by:     s.Number()
}), function(data, callback) {
    callback(null, data.number * data.by);
});

var client = new Client({
    "math": mathTransport
});

// If ALL of your services specified
// use local transports, you do not need
// to call connect here either.
client.connect(function(err) {

    if(err) {
        console.error("There was an error connecting to services:");
        console.error(err);
        process.exit(1);
    }

    client.call("math", "multiply", {
        number: number,
        by:     multiplyBy
    }, function(err, response) {

        if(err) {
            console.error("An error occured multiplying your number!");
            console.error(err);
            process.exit(1);
        }

        console.log("%d * %d = %d", number, multiplyBy, response);

    });

});
<|endoftext|>


<commit_before>var main = function() {
  $('.pubfilter').change(function() {
    var selectedPub = $(this).val();
    filterPublishers(selectedPub);
  });
  $('#select_info').hide();
  $('#title_sort').hide();
  $('#pub_sort').click(function() {sortByPublisher();});
  $('#title_sort').click(function() {sortByTitle();});
  $('#fade').click(function() {hideInfo();});
}

$(document).ready(main);

function revealInfo(image) {
  hideInfo();
  $('#fade').css('height', $(window).height());
  $('#fade').show();
  var infoPanel = $(image).parent().find('.about');
  infoPanel.show();
  infoPanel.css({margin:$(document).scrollTop()+100+'px 0 0 '+($(window).width() / 2 - infoPanel.width() / 2)+'px'});
  if(infoPanel.find('tab_set')) {
    $('.tab_content').hide();
    $(infoPanel.find('.tab_content')[0]).show();
    $(infoPanel.find('.tab_button')[0]).addClass('selected');
  }
}

function hideInfo() {
  $('.about').hide();
  $('#fade').hide();
}

function showTab(tab) {
  $('.tab_content').hide();
  $('#' + tab).show();
  $('.tab_button').removeClass('selected');
  $('#btn_' + tab).addClass('selected');
}

function filterPublishers(publisher) {
  hideInfo();
  if(publisher === 'Show All') {
    $('#books').children().show();
    $('#sort').show();
    $('#select_info').hide();
  } else {
    $('#books').children().hide();
    var matchingBooks = $("article p[itemprop='publisher']:contains(" + publisher +")").parent().parent().parent().parent();
    var numberFound = matchingBooks.length;

    $('#sort').hide();
    matchingBooks.show();
    if(numberFound === 1) {
      var bookStr = "book";
    } else {
      var bookStr = "books";
    }
    $('#select_info').html('Found ' + matchingBooks.length + ' ' + bookStr + ' for ' + publisher + '');
    $('#select_info').show();
  }
}

function sortByPublisher() {
  hideInfo();
  $('article').sortElements(function(a, b){
    pub_a = $(a).find('p[itemprop="publisher"]')[0].textContent.trim();
    title_a = $(a).find('h2')[0].textContent.trim();
    sort_key_a = pub_a.trim() + "__" + title_a.trim().replace(/^(The )|(A )/, "");

    pub_b = $(b).find('p[itemprop="publisher"]')[0].textContent.trim();
    title_b = $(b).find('h2')[0].textContent.trim();
    sort_key_b = pub_b.trim() + "__" + title_b.trim().replace(/^(The )|(A )/, "");

    return sort_key_a.toLowerCase().localeCompare(sort_key_b.toLowerCase());
  });
  $('#pub_sort').hide();
  $('#title_sort').show();
}

function sortByTitle() {
  hideInfo();
  $('article').sortElements(function(a, b){
    title_a = $(a).find('h2')[0].textContent.trim();
    sort_key_a = title_a.trim().replace(/^(The )|(A )/, "");

    title_b = $(b).find('h2')[0].textContent.trim();
    sort_key_b = title_b.trim().replace(/^(The )|(A )/, "");

    return sort_key_a.toLowerCase().localeCompare(sort_key_b.toLowerCase());
  });
  $('#title_sort').hide();
  $('#pub_sort').show();
}<commit_msg>Simplify filter function<commit_after>var main = function() {
  $('.pubfilter').change(function() {
    var selectedPub = $(this).val();
    filterPublishers(selectedPub);
  });
  $('#select_info').hide();
  $('#title_sort').hide();
  $('#pub_sort').click(function() {sortByPublisher();});
  $('#title_sort').click(function() {sortByTitle();});
  $('#fade').click(function() {hideInfo();});
}

$(document).ready(main);

function revealInfo(image) {
  hideInfo();
  $('#fade').css('height', $(window).height());
  $('#fade').show();
  var infoPanel = $(image).parent().find('.about');
  infoPanel.show();
  infoPanel.css({margin:$(document).scrollTop()+100+'px 0 0 '+($(window).width() / 2 - infoPanel.width() / 2)+'px'});
  if(infoPanel.find('tab_set')) {
    $('.tab_content').hide();
    $(infoPanel.find('.tab_content')[0]).show();
    $(infoPanel.find('.tab_button')[0]).addClass('selected');
  }
}

function hideInfo() {
  $('.about').hide();
  $('#fade').hide();
}

function showTab(tab) {
  $('.tab_content').hide();
  $('#' + tab).show();
  $('.tab_button').removeClass('selected');
  $('#btn_' + tab).addClass('selected');
}

function filterPublishers(publisher) {
  hideInfo();
  if(publisher === 'Show All') {
    $('#books').children().show();
    $('#sort').show();
    $('#select_info').hide();
  } else {
    $('#books').children().hide();
    var matchingBooks = $("article p[itemprop='publisher']:contains(" + publisher +")").closest("article");
    var numberFound = matchingBooks.length;

    $('#sort').hide();
    matchingBooks.show();
    if(numberFound === 1) {
      var bookStr = "book";
    } else {
      var bookStr = "books";
    }
    $('#select_info').html('Found ' + matchingBooks.length + ' ' + bookStr + ' for ' + publisher + '');
    $('#select_info').show();
  }
}

function sortByPublisher() {
  hideInfo();
  $('article').sortElements(function(a, b){
    pub_a = $(a).find('p[itemprop="publisher"]')[0].textContent.trim();
    title_a = $(a).find('h2')[0].textContent.trim();
    sort_key_a = pub_a.trim() + "__" + title_a.trim().replace(/^(The )|(A )/, "");

    pub_b = $(b).find('p[itemprop="publisher"]')[0].textContent.trim();
    title_b = $(b).find('h2')[0].textContent.trim();
    sort_key_b = pub_b.trim() + "__" + title_b.trim().replace(/^(The )|(A )/, "");

    return sort_key_a.toLowerCase().localeCompare(sort_key_b.toLowerCase());
  });
  $('#pub_sort').hide();
  $('#title_sort').show();
}

function sortByTitle() {
  hideInfo();
  $('article').sortElements(function(a, b){
    title_a = $(a).find('h2')[0].textContent.trim();
    sort_key_a = title_a.trim().replace(/^(The )|(A )/, "");

    title_b = $(b).find('h2')[0].textContent.trim();
    sort_key_b = title_b.trim().replace(/^(The )|(A )/, "");

    return sort_key_a.toLowerCase().localeCompare(sort_key_b.toLowerCase());
  });
  $('#title_sort').hide();
  $('#pub_sort').show();
}<|endoftext|>


<commit_before>export {
  SpectraProcessor // from 'https://www.lactame.com/lib/spectra-processor/0.19.4/spectra-processor.js';
} from 'http://localhost:9898/cheminfo-js/spectra-processor/dist/spectra-processor.js';
<commit_msg>chore: update spectra-processor to 0.19.4<commit_after>export {
  SpectraProcessor
} from 'https://www.lactame.com/lib/spectra-processor/0.19.4/spectra-processor.js';
// from 'http://localhost:9898/cheminfo-js/spectra-processor/dist/spectra-processor.js';
<|endoftext|>


<commit_before>$(document).ready(function(){
     $("#related").click(function(){
        $.post("http://localhost:8080/",
        {
          'action': 'my_action',
          'related': "true"
          'individual': 0,//update code for Id
        },
        function(){
        });
        //alert("post sent");
    });
   $("#unrelated").click(function(){
        $.post("http://localhost:8080/",
        {
          'action': 'my_action',
          'related': "false"
          'individual': 0,//update code for Id
        },
        function(){
        });
    });
});
<commit_msg>Fix javascript syntax error<commit_after>$(document).ready(function(){
     $("#related").click(function(){
        $.post("http://localhost:8080/",//Change localhost for wordpress site
        {
          'action': 'my_action',
          'related': "true",
          'individual': 0,//update code for Id
        },
        function(){
        });
        //alert("post sent");
    });
   $("#unrelated").click(function(){
        $.post("http://localhost:8080/",//Change localhost for wordpress site
        {
          'action': 'my_action',
          'related': "false",
          'individual': 0,//update code for Id
        },
        function(){
        });
    });
});
<|endoftext|>


<commit_before>var Block=require("block");

function GAME(type){
    this.stage=document.getElementById(type+"Stage");
    this.scoreBox=document.getElementById(type+"Score");
    this.nameBox=document.getElementById(type+"Name");
    this.control=type;

    //初始化
    this.init=function(){
        if(arguments[0]) {
            this.ws=arguments[0];
            this.setNameBox(arguments[0].userName)
        }
        this.clearStage();
        this.score=0;
        this.map=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]; //2048地图阵列
        this.blkArr=[];         //存储方块的数组
        this.maxNum=0;          //方块数
        this.score=0;           //分数初始化
        this.isKeyDown=0;       //记录键盘是否按下
        this.isMove=0;          //记录是否有移动
        this.moveNum=0;         //记录同时移动的操作数量，当有滑块仍在移动时禁止操作
        this.beginPos=[];       //方块记录队列，用于记录未渲染但已生成的方块
        if(this.control=="self"){
            this.rand();
            this.rand();
            this.rand();
            window.onkeydown = function (event) {
                if (that.isKeyDown) return;
                if(that.moveNum>=1) return;
                var e = event || window.event;
                if (e && e.keyCode>=37 && e.keyCode<=40) {
                    that.isKeyDown = 1;
                    that.slide(e.keyCode);
                    that.moveNum++;
                }
            };
            window.onkeyup = function () {
                that.isKeyDown = 0;
            };
        }
        var that=this;
        setInterval(function(){
            that.scoreBox.innerHTML=that.score;
        },10)
    };

    //渲染beginPos队列中的成员方块
    this.createBlock=function(){
        while(this.beginPos.length){
            var blk=new Block(),
                pos=this.beginPos.shift(),
                x=pos.x, y=pos.y;
            this.blkArr.push(blk);
            blk.create(x,y,this.stage);
            blk.setNumber(pos.num);
            this.map[y][x]=blk;
        }
    };

    //随机生成方块插入队列中，等待渲染
    this.rand=function(){
        var x, y;
        var newNum = Math.random() <= 0.6 ? 2 : 4;  //4的概率稍小
        x = Math.floor(Math.random() * 4);
        y = Math.floor(Math.random() * 4);
        while (this.map[y][x] != 0 || x == 4 || y == 4) {
            x = Math.floor(Math.random() * 4);
            y = Math.floor(Math.random() * 4);
        }
        this.beginPos.push({x:x,y:y,num:newNum});
        this.map[y][x]=1;
    };

    //设置顶端名字
    this.setNameBox=function(name){
        this.nameBox.innerHTML=name;
    };

    //方块合并
    this.merge=function(prevBlock,currBlock){
        var prev=prevBlock.block.innerHTML;
        var curr=currBlock.block.innerHTML;
        //console.log(prev,curr);
        if(prev==curr){
            if(!this.isMove) this.isMove=1;
            var prevx=prevBlock.x,
                prevy=prevBlock.y;
            prevBlock.position(currBlock.x,currBlock.y);
            currBlock.setNumber(curr * 2);
            prevBlock.block.style.zIndex=-1;
            this.map[prevy][prevx]=0;
            this.score+=curr*2;
            var that=this;
            setTimeout(function(){
                that.stage.removeChild(prevBlock.block);
                delete prevBlock;
            },300);
            return true;
        }
        return false;
    };

    //方块移动
    this.slide=function(keycode){
        var i, j, k, curr;
        if(keycode==37){//Left
            for(i=0;i<4;i++){
                k=0;
                for(j=0;j<3;j++){//所有块先移动
                    if(this.map[i][j]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[i][k]==0 && k++);
                        if(k==4) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
                for(j=0;j<3;j++){//相邻等值块合并
                    if(this.map[i][j]!=0 && this.map[i][j+1]!=0) {
                        if(this.merge(this.map[i][j + 1], this.map[i][j])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j+1;
                            while(k<4){
                                if(this.map[i][k]!=0){
                                    this.map[i][k].position(curr,i);
                                    this.map[i][curr++]=this.map[i][k];
                                    this.map[i][k]=0;
                                }
                                k++;
                            }
                        }
                    }
                }
                k=0;
                for(j=0;j<3;j++){//消除合并后可能产生的空块
                    if(this.map[i][j]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[i][k]==0 && k++);
                        if(k==4) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
            }
        }
        if(keycode==38){//Top
            for(i=0;i<4;i++){
                k=0;
                for(j=0;j<3;j++){//所有块先移动
                    if(this.map[j][i]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[k][i]==0 && k++);
                        if(k==4) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
                for(j=0;j<3;j++){//相邻等值块合并
                    if(this.map[j][i]!=0 && this.map[j+1][i]!=0) {
                        if(this.merge(this.map[j+1][i], this.map[j][i])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j+1;
                            while(k<4){
                                if(this.map[k][i]!=0){
                                    this.map[k][i].position(i,curr);
                                    this.map[curr++][i]=this.map[k][i];
                                    this.map[k][i]=0;
                                }
                                k++;
                            }
                        }
                    }
                }
                k=0;
                for(j=0;j<3;j++){//消除合并后可能产生的空块
                    if(this.map[j][i]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[k][i]==0 && k++);
                        if(k==4) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
            }
        }
        if(keycode==39){//Right
            for(i=0;i<4;i++){
                k=3;
                for(j=3;j>=1;j--){//所有块先移动
                    if(this.map[i][j]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[i][k]==0 && k--);
                        if(k==-1) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
                for(j=3;j>=1;j--){//相邻等值块合并
                    if(this.map[i][j]!=0 && this.map[i][j-1]!=0) {
                        if(this.merge(this.map[i][j - 1], this.map[i][j])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j-1;
                            while(k>=0){
                                if(this.map[i][k]!=0){
                                    this.map[i][k].position(curr,i);
                                    this.map[i][curr--]=this.map[i][k];
                                    this.map[i][k]=0;
                                }
                                k--;
                            }
                        }
                    }
                }
                k=3;
                for(j=3;j>=1;j--){//消除合并后可能产生的空块
                    if(this.map[i][j]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[i][k]==0 && k--);
                        if(k==-1) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
            }
        }
        if(keycode==40){//Down
            for(i=0;i<4;i++){
                k=3;
                for(j=3;j>=1;j--){//所有块先移动
                    if(this.map[j][i]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[k][i]==0 && k--);
                        if(k==-1) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
                for(j=3;j>=1;j--){//相邻等值块合并
                    if(this.map[j][i]!=0 && this.map[j-1][i]!=0) {
                        if(this.merge(this.map[j-1][i], this.map[j][i])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j-1;
                            while(k>=0){
                                if(this.map[k][i]!=0){
                                    this.map[k][i].position(i,curr);
                                    this.map[curr--][i]=this.map[k][i];
                                    this.map[k][i]=0;
                                }
                                k--;
                            }
                        }
                    }
                }
                k=3;
                for(j=3;j>=1;j--){//消除合并后可能产生的空块
                    if(this.map[j][i]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[k][i]==0 && k--);
                        if(k==-1) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
            }
        }
        if(this.control=="self") this.selfCheck(keycode);
    };

    this.selfCheck=function(keycode){   //己方检查游戏是否结束并生成新方块
        var that=this,info, i,j;
        setTimeout(function () {
            var numOfBlock = 0;
            for (i = 0; i < 4; i++) {
                for (j = 0; j < 4; j++) {
                    if (that.map[i][j] != 0){
                        numOfBlock++;
                        if(that.map[i][j].block.innerHTML>that.maxNum){
                            that.maxNum=that.map[i][j].block.innerHTML
                        }
                    }
                }
            }
            //console.log(numOfBlock)
            if (numOfBlock == 16 && !that.isMove) {
                alert("游戏结束,您的分数为["+that.score+"].");
                info={
                    code:-2,
                    user:that.ws.userName,
                    roomId:that.ws.roomId,
                    token:that.ws.token,
                    score:that.score
                };
                that.ws.send(JSON.stringify(info));
            }
            else {
                that.isMove=0;
                that.moveNum--;
                that.rand();
                info = {
                    code: 2,
                    user:that.ws.userName,
                    roomId:that.ws.roomId,
                    token:that.ws.token,
                    actionCode: keycode,
                    nwPos:that.beginPos[0]
                };
                that.ws.send(JSON.stringify(info));     //将新方块的位置发给对手
                that.createBlock();
            }
        }, 250)
    };

    this.comHandle=function(queue){      //对方2048处理指令队列
        var order;
        while(queue.length){
            order=queue.shift();
            this.beginPos.push(order.nwPos);
            this.slide(order.actionCode);
            this.createBlock();
        }
    };

    this.clearStage=function(){
        while(this.stage.hasChildNodes()){
            this.stage.removeChild(this.stage.firstChild);
        }
    }
}

module.exports=GAME;
<commit_msg>modify codes line<commit_after>var Block=require("block");

function GAME(type){
    this.stage=document.getElementById(type+"Stage");
    this.scoreBox=document.getElementById(type+"Score");
    this.nameBox=document.getElementById(type+"Name");
    this.control=type;

    //初始化
    this.init=function(){
        if(arguments[0]) {
            this.ws=arguments[0];
            this.setNameBox(arguments[0].userName)
        }
        this.clearStage();
        this.score=0;
        this.map=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]; //2048地图阵列
        this.blkArr=[];         //存储方块的数组
        this.maxNum=0;          //方块数
        this.score=0;           //分数初始化
        this.isKeyDown=0;       //记录键盘是否按下
        this.isMove=0;          //记录是否有移动
        this.moveNum=0;         //记录同时移动的操作数量，当有滑块仍在移动时禁止操作
        this.beginPos=[];       //方块记录队列，用于记录未渲染但已生成的方块
		var that=this;
        if(this.control=="self"){
            this.rand();
            this.rand();
            this.rand();
            window.onkeydown = function (event) {
                if (that.isKeyDown) return;
                if(that.moveNum>=1) return;
                var e = event || window.event;
                if (e && e.keyCode>=37 && e.keyCode<=40) {
                    that.isKeyDown = 1;
                    that.slide(e.keyCode);
                    that.moveNum++;
                }
            };
            window.onkeyup = function () {
                that.isKeyDown = 0;
            };
        }
        setInterval(function(){
            that.scoreBox.innerHTML=that.score;
        },10)
    };

    //渲染beginPos队列中的成员方块
    this.createBlock=function(){
        while(this.beginPos.length){
            var blk=new Block(),
                pos=this.beginPos.shift(),
                x=pos.x, y=pos.y;
            this.blkArr.push(blk);
            blk.create(x,y,this.stage);
            blk.setNumber(pos.num);
            this.map[y][x]=blk;
        }
    };

    //随机生成方块插入队列中，等待渲染
    this.rand=function(){
        var x, y;
        var newNum = Math.random() <= 0.6 ? 2 : 4;  //4的概率稍小
        x = Math.floor(Math.random() * 4);
        y = Math.floor(Math.random() * 4);
        while (this.map[y][x] != 0 || x == 4 || y == 4) {
            x = Math.floor(Math.random() * 4);
            y = Math.floor(Math.random() * 4);
        }
        this.beginPos.push({x:x,y:y,num:newNum});
        this.map[y][x]=1;
    };

    //设置顶端名字
    this.setNameBox=function(name){
        this.nameBox.innerHTML=name;
    };

    //方块合并
    this.merge=function(prevBlock,currBlock){
        var prev=prevBlock.block.innerHTML;
        var curr=currBlock.block.innerHTML;
        //console.log(prev,curr);
        if(prev==curr){
            if(!this.isMove) this.isMove=1;
            var prevx=prevBlock.x,
                prevy=prevBlock.y;
            prevBlock.position(currBlock.x,currBlock.y);
            currBlock.setNumber(curr * 2);
            prevBlock.block.style.zIndex=-1;
            this.map[prevy][prevx]=0;
            this.score+=curr*2;
            var that=this;
            setTimeout(function(){
                that.stage.removeChild(prevBlock.block);
                delete prevBlock;
            },300);
            return true;
        }
        return false;
    };

    //方块移动
    this.slide=function(keycode){
        var i, j, k, curr;
        if(keycode==37){//Left
            for(i=0;i<4;i++){
                k=0;
                for(j=0;j<3;j++){//所有块先移动
                    if(this.map[i][j]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[i][k]==0 && k++);
                        if(k==4) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
                for(j=0;j<3;j++){//相邻等值块合并
                    if(this.map[i][j]!=0 && this.map[i][j+1]!=0) {
                        if(this.merge(this.map[i][j + 1], this.map[i][j])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j+1;
                            while(k<4){
                                if(this.map[i][k]!=0){
                                    this.map[i][k].position(curr,i);
                                    this.map[i][curr++]=this.map[i][k];
                                    this.map[i][k]=0;
                                }
                                k++;
                            }
                        }
                    }
                }
                k=0;
                for(j=0;j<3;j++){//消除合并后可能产生的空块
                    if(this.map[i][j]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[i][k]==0 && k++);
                        if(k==4) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
            }
        }
        if(keycode==38){//Top
            for(i=0;i<4;i++){
                k=0;
                for(j=0;j<3;j++){//所有块先移动
                    if(this.map[j][i]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[k][i]==0 && k++);
                        if(k==4) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
                for(j=0;j<3;j++){//相邻等值块合并
                    if(this.map[j][i]!=0 && this.map[j+1][i]!=0) {
                        if(this.merge(this.map[j+1][i], this.map[j][i])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j+1;
                            while(k<4){
                                if(this.map[k][i]!=0){
                                    this.map[k][i].position(i,curr);
                                    this.map[curr++][i]=this.map[k][i];
                                    this.map[k][i]=0;
                                }
                                k++;
                            }
                        }
                    }
                }
                k=0;
                for(j=0;j<3;j++){//消除合并后可能产生的空块
                    if(this.map[j][i]==0){
                        if(k==0) k=j+1;
                        while(k<4 && this.map[k][i]==0 && k++);
                        if(k==4) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
            }
        }
        if(keycode==39){//Right
            for(i=0;i<4;i++){
                k=3;
                for(j=3;j>=1;j--){//所有块先移动
                    if(this.map[i][j]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[i][k]==0 && k--);
                        if(k==-1) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
                for(j=3;j>=1;j--){//相邻等值块合并
                    if(this.map[i][j]!=0 && this.map[i][j-1]!=0) {
                        if(this.merge(this.map[i][j - 1], this.map[i][j])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j-1;
                            while(k>=0){
                                if(this.map[i][k]!=0){
                                    this.map[i][k].position(curr,i);
                                    this.map[i][curr--]=this.map[i][k];
                                    this.map[i][k]=0;
                                }
                                k--;
                            }
                        }
                    }
                }
                k=3;
                for(j=3;j>=1;j--){//消除合并后可能产生的空块
                    if(this.map[i][j]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[i][k]==0 && k--);
                        if(k==-1) break;
                        this.map[i][k].position(j,i);
                        this.map[i][j]=this.map[i][k];
                        this.map[i][k]=0;
                    }
                }
            }
        }
        if(keycode==40){//Down
            for(i=0;i<4;i++){
                k=3;
                for(j=3;j>=1;j--){//所有块先移动
                    if(this.map[j][i]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[k][i]==0 && k--);
                        if(k==-1) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
                for(j=3;j>=1;j--){//相邻等值块合并
                    if(this.map[j][i]!=0 && this.map[j-1][i]!=0) {
                        if(this.merge(this.map[j-1][i], this.map[j][i])){
                            //防止相邻两两合并时方块无动画消失
                            curr=k=j-1;
                            while(k>=0){
                                if(this.map[k][i]!=0){
                                    this.map[k][i].position(i,curr);
                                    this.map[curr--][i]=this.map[k][i];
                                    this.map[k][i]=0;
                                }
                                k--;
                            }
                        }
                    }
                }
                k=3;
                for(j=3;j>=1;j--){//消除合并后可能产生的空块
                    if(this.map[j][i]==0){
                        if(k==3) k=j-1;
                        while(k>=0 && this.map[k][i]==0 && k--);
                        if(k==-1) break;
                        this.map[k][i].position(i,j);
                        this.map[j][i]=this.map[k][i];
                        this.map[k][i]=0;
                    }
                }
            }
        }
        if(this.control=="self") this.selfCheck(keycode);
    };

    this.selfCheck=function(keycode){   //己方检查游戏是否结束并生成新方块
        var that=this,info, i,j;
        setTimeout(function () {
            var numOfBlock = 0;
            for (i = 0; i < 4; i++) {
                for (j = 0; j < 4; j++) {
                    if (that.map[i][j] != 0){
                        numOfBlock++;
                        if(that.map[i][j].block.innerHTML>that.maxNum){
                            that.maxNum=that.map[i][j].block.innerHTML
                        }
                    }
                }
            }
            //console.log(numOfBlock)
            if (numOfBlock == 16 && !that.isMove) {
                alert("游戏结束,您的分数为["+that.score+"].");
                info={
                    code:-2,
                    user:that.ws.userName,
                    roomId:that.ws.roomId,
                    token:that.ws.token,
                    score:that.score
                };
                that.ws.send(JSON.stringify(info));
            }
            else {
                that.isMove=0;
                that.moveNum--;
                that.rand();
                info = {
                    code: 2,
                    user:that.ws.userName,
                    roomId:that.ws.roomId,
                    token:that.ws.token,
                    actionCode: keycode,
                    nwPos:that.beginPos[0]
                };
                that.ws.send(JSON.stringify(info));     //将新方块的位置发给对手
                that.createBlock();
            }
        }, 250)
    };

    this.comHandle=function(queue){      //对方2048处理指令队列
        var order;
        while(queue.length){
            order=queue.shift();
            this.beginPos.push(order.nwPos);
            this.slide(order.actionCode);
            this.createBlock();
        }
    };

    this.clearStage=function(){
        while(this.stage.hasChildNodes()){
            this.stage.removeChild(this.stage.firstChild);
        }
    }
}

module.exports=GAME;
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
     watch: {
      less: {
        files: ['./less/**/*.less'],
        tasks: ['less']
      }
    },
    less: {
      compile: {
        files: {
          './css/app.css': './less/app.less'
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task.
  grunt.registerTask('default', ['watch']);

};
<commit_msg>add default grunt tasks<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
     watch: {
      less: {
        files: [ 'less/**/*.less' ],
        tasks: [ 'less' ]
      }
    },
    less: {
      compile: {
        files: {
          './css/app.css': './less/app.less'
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task.
  grunt.registerTask('default', ['less', 'watch']);

};
<|endoftext|>


<commit_before>var keyshop = angular.module('keyshop', ['ui.bootstrap']);

keyshop.controller('ModalLogin', function ($scope, $modal) {
    $scope.openLogin = function() {

        $scope.data = {
            placeholders: {
                modalTitle: 'Anmelden',
                modalSend:  'Anmelden'
            },
            inputs: new Array(
                {
                    type: 'email',
                    name: 'email',
                    icon: 'fa-at',
                    placeholder: 'E-Mail Adresse'
                },
                {
                    type: 'password',
                    name: 'password',
                    icon: 'fa-key',
                    placeholder: 'Passwort'
                }
            )
        };
        $scope.open();
    };

    $scope.openRegister = function() {
        $scope.data = {
            placeholders: {
                modalTitle: 'Registrieren',
                modalSend:  'Registrieren'
            },
            inputs: new Array(
                {
                    type: 'email',
                    name: 'email',
                    icon: 'fa-at',
                    placeholder: 'E-Mail Adresse wählen'
                },
                {
                    type: 'password',
                    name: 'password',
                    icon: 'fa-key',
                    placeholder: 'Passwort erstellen'
                },
                {
                    type: 'password',
                    name: 'password',
                    icon: 'fa-repeat',
                    placeholder: 'Passwort bestätigen'
                }
            )
        };
        $scope.open();
    };

    $scope.open = function () {
        var modalInstance = $modal.open({
            templateUrl: 'modalUser.html',
            controller: 'ModalLoginInstance',
            resolve: {
                data: function () {
                    return $scope.data;
                }
            }
        });
    };
});

keyshop.controller('ModalLoginInstance', function ($scope, $modalInstance, data, Auth) {
    $scope.modalTitle = data.placeholders.modalTitle;
    $scope.modalSend  = data.placeholders.modalSend;
    $scope.inputs     = data.inputs;

    $scope.send = function () {
        $scope.loading = true;
        Auth.login($scope.loginData)
            .success(function(data) {
                if (data.success) {
                    window.location.reload();
                } else {
                    $scope.error = true;
                    $scope.feedback = {
                        title: "Error",
                        message: "Ajax not yet implemented"
                    };
                }
                $scope.loading = false;
            })
            .error(function(data) {
                $scope.error = true;
                console.log('error');
                console.log(data);
                $scope.feedback = {
                    title: "Server Error",
                    message: "watch console"
                };
                $scope.loading = false;
            });
    };

    $scope.cancel = function () {
        $modalInstance.close();
    };
});

keyshop.controller('KeyshopProducts', function ($scope) {
    $scope.products = $.parseJSON(ks.homeProducts);
}).directive('ksProduct', function() {
    return {
        restrict: 'E',
        templateUrl: '/assets/directives/ks-product.html'
    };
});<commit_msg>service not loaded<commit_after>var keyshop = angular.module('keyshop', ['ui.bootstrap', 'authService']);

keyshop.controller('ModalLogin', function ($scope, $modal) {
    $scope.openLogin = function() {

        $scope.data = {
            placeholders: {
                modalTitle: 'Anmelden',
                modalSend:  'Anmelden'
            },
            inputs: new Array(
                {
                    type: 'email',
                    name: 'email',
                    icon: 'fa-at',
                    placeholder: 'E-Mail Adresse'
                },
                {
                    type: 'password',
                    name: 'password',
                    icon: 'fa-key',
                    placeholder: 'Passwort'
                }
            )
        };
        $scope.open();
    };

    $scope.openRegister = function() {
        $scope.data = {
            placeholders: {
                modalTitle: 'Registrieren',
                modalSend:  'Registrieren'
            },
            inputs: new Array(
                {
                    type: 'email',
                    name: 'email',
                    icon: 'fa-at',
                    placeholder: 'E-Mail Adresse wählen'
                },
                {
                    type: 'password',
                    name: 'password',
                    icon: 'fa-key',
                    placeholder: 'Passwort erstellen'
                },
                {
                    type: 'password',
                    name: 'password',
                    icon: 'fa-repeat',
                    placeholder: 'Passwort bestätigen'
                }
            )
        };
        $scope.open();
    };

    $scope.open = function () {
        var modalInstance = $modal.open({
            templateUrl: 'modalUser.html',
            controller: 'ModalLoginInstance',
            resolve: {
                data: function () {
                    return $scope.data;
                }
            }
        });
    };
});

keyshop.controller('ModalLoginInstance', function ($scope, $modalInstance, data, Auth) {
    $scope.modalTitle = data.placeholders.modalTitle;
    $scope.modalSend  = data.placeholders.modalSend;
    $scope.inputs     = data.inputs;

    $scope.send = function () {
        $scope.loading = true;
        Auth.login($scope.loginData)
            .success(function(data) {
                if (data.success) {
                    window.location.reload();
                } else {
                    $scope.error = true;
                    $scope.feedback = {
                        title: "Error",
                        message: "Ajax not yet implemented"
                    };
                }
                $scope.loading = false;
            })
            .error(function(data) {
                $scope.error = true;
                console.log('error');
                console.log(data);
                $scope.feedback = {
                    title: "Server Error",
                    message: "watch console"
                };
                $scope.loading = false;
            });
    };

    $scope.cancel = function () {
        $modalInstance.close();
    };
});

keyshop.controller('KeyshopProducts', function ($scope) {
    $scope.products = $.parseJSON(ks.homeProducts);
}).directive('ksProduct', function() {
    return {
        restrict: 'E',
        templateUrl: '/assets/directives/ks-product.html'
    };
});<|endoftext|>


<commit_before>import './editable_node_selector.html';
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import './x_editable_node_selector.js';
import './x_editable_node_selector.css';

/**
 * Template Helpers
 */
Template.EditableNodeSelector.helpers({});

/**
 * Template Event Handlers
 */
Template.EditableNodeSelector.events({});

/**
 * Template Created
 */
Template.EditableNodeSelector.created = function () {

};

/**
 * Template Rendered
 */
Template.EditableNodeSelector.rendered = function () {
  var instance = Template.instance();

  instance.$(".editable").editable({
    type            : "nodeSelector",
    mode            : instance.data.mode || "popup",
    placement       : instance.data.placement || "auto",
    value           : instance.data.value,
    projectVersionId: instance.data.projectVersionId,
    parentInstance  : instance,
    highlight       : false,
    display() {
    },
    success(response, newValue) {
      console.log("EditableNodeSelector edited: ", newValue);
      var editedElement = this;
      $(editedElement).trigger("edited", [ newValue ]);
      setTimeout(function () {
        $(editedElement).removeClass('editable-unsaved');
      }, 10);
    }
  });

  // this event listener needs to be registered directly
  instance.$(".editable").on("hidden", function () {
    console.log("EditableNodeSelector .editable hidden: ", instance.searchView);
    if (instance.searchView) {
      setTimeout(function () {
        Blaze.remove(instance.searchView);
      }, 100);
    }
  });

  instance.autorun(function () {
    var data = Template.currentData();
    console.log("EditableNodeSelector autorun setting value: ", data.value);
    instance.$(".editable").editable("setValue", data.value);
  });
};

/**
 * Template Destroyed
 */
Template.EditableNodeSelector.destroyed = function () {

};
<commit_msg>EditableNodeSelector will throw an error if it's not given the projectVersionId<commit_after>import './editable_node_selector.html';
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import './x_editable_node_selector.js';
import './x_editable_node_selector.css';

/**
 * Template Helpers
 */
Template.EditableNodeSelector.helpers({});

/**
 * Template Event Handlers
 */
Template.EditableNodeSelector.events({});

/**
 * Template Created
 */
Template.EditableNodeSelector.created = function () {

};

/**
 * Template Rendered
 */
Template.EditableNodeSelector.rendered = function () {
  var instance = Template.instance();

  console.log("EditableNodeSelector context:", instance.data);

  // Make sure there's a project version id
  if(!instance.data.projectVersionId){
    throw new Meteor.Error('Null project version id:', instance.data);
  }

  instance.$(".editable").editable({
    type            : "nodeSelector",
    mode            : instance.data.mode || "popup",
    placement       : instance.data.placement || "auto",
    value           : instance.data.value,
    projectVersionId: instance.data.projectVersionId,
    parentInstance  : instance,
    highlight       : false,
    display() {
    },
    success(response, newValue) {
      console.log("EditableNodeSelector edited: ", newValue);
      var editedElement = this;
      $(editedElement).trigger("edited", [ newValue ]);
      setTimeout(function () {
        $(editedElement).removeClass('editable-unsaved');
      }, 10);
    }
  });

  // this event listener needs to be registered directly
  instance.$(".editable").on("hidden", function () {
    console.log("EditableNodeSelector .editable hidden: ", instance.searchView);
    if (instance.searchView) {
      setTimeout(function () {
        Blaze.remove(instance.searchView);
      }, 100);
    }
  });

  instance.autorun(function () {
    var data = Template.currentData();
    console.log("EditableNodeSelector autorun setting value: ", data.value);
    instance.$(".editable").editable("setValue", data.value);
  });
};

/**
 * Template Destroyed
 */
Template.EditableNodeSelector.destroyed = function () {

};
<|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// Support for Node 0.10
// See https://github.com/webpack/css-loader/issues/144
require('es6-promise').polyfill();

var fs = require('fs');
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var helpers = require('jupyterlab/scripts/extension_helpers');
var shimmer = require('./shim-maker');

// Get the CodeMirror files to create external bundle.
var CodeMirrorFiles = helpers.CODEMIRROR_FILES;
CodeMirrorFiles.push('codemirror/lib/codemirror.js');

// Create the Phosphor and JupyterLab shims.
// First make sure the build folder exists.
try {
  fs.mkdirSync('./build')
} catch(err) {
  if (err.code !== 'EEXIST') {
    throw e;
  }
}
fs.writeFileSync('./build/phosphor-shim.js', shimmer('phosphor', 'lib'));
var jlabShim = shimmer('jupyterlab', 'lib', /.*index\.js$/);
fs.writeFileSync('./build/jupyterlab-shim.js', jlabShim);

var loaders = [
  { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
  { test: /\.json$/, loader: 'json-loader' },
  { test: /\.html$/, loader: 'file-loader' },
  // jquery-ui loads some images
  { test: /\.(jpg|png|gif)$/, loader: 'file-loader' },
  // required to load font-awesome
  { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
  { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
  { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' },
  { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml' },
]

module.exports = [
// Application bundles
{
  entry: {
    'main': './index.js',
    'jupyterlab': './build/jupyterlab-shim.js',
    'CodeMirror': CodeMirrorFiles,
    'vendor': helpers.VENDOR_FILES
  },
  output: {
    path: __dirname + '/build',
    filename: '[name].bundle.js',
    publicPath: './',
    library: '[name]'
  },
  node: {
    fs: 'empty'
  },
  debug: true,
  bail: true,
  devtool: 'source-map',
  module: {
    loaders: loaders
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "jupyterlab",
      filename: "jupyterlab.bundle.js",
      chunks: ['main']
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      filename: "vendor.bundle.js"
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: "CodeMirror",
      filename: "CodeMirror.bundle.js",
      chunks: ['jupyterlab']
    }),
    new ExtractTextPlugin("[name].css")
  ],
  externals: helpers.BASE_EXTERNALS
},
// Jupyter-js-services bundle
{
    entry: 'jupyter-js-services',
    output: {
        filename: 'services.bundle.js',
        path: './build',
        library: ['jupyter', 'services'],
    },
    module: {
      loaders: loaders
    },
    bail: true,
    devtool: 'source-map',
    externals: helpers.phosphorExternals
},
// Phosphor bundle
{
    entry: './build/phosphor-shim.js',
    output: {
        filename: 'phosphor.bundle.js',
        path: './build',
        library: 'phosphor',
    },
    bail: true,
    devtool: 'source-map'
}
]
<commit_msg>Clean up webpack config to use separate builds<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// Support for Node 0.10
// See https://github.com/webpack/css-loader/issues/144
require('es6-promise').polyfill();

var fs = require('fs');
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var helpers = require('jupyterlab/scripts/extension_helpers');
var shimmer = require('./shim-maker');

// Get the CodeMirror files to create external bundle.
var CodeMirrorFiles = helpers.CODEMIRROR_FILES;
CodeMirrorFiles.push('codemirror/lib/codemirror.js');

// Create the Phosphor and JupyterLab shims.
// First make sure the build folder exists.
try {
  fs.mkdirSync('./build')
} catch(err) {
  if (err.code !== 'EEXIST') {
    throw e;
  }
}
fs.writeFileSync('./build/phosphor-shim.js', shimmer('phosphor'));
fs.writeFileSync('./build/jupyterlab-shim.js', shimmer('jupyterlab'));

var loaders = [
  { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
  { test: /\.json$/, loader: 'json-loader' },
  { test: /\.html$/, loader: 'file-loader' },
  // jquery-ui loads some images
  { test: /\.(jpg|png|gif)$/, loader: 'file-loader' },
  // required to load font-awesome
  { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
  { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
  { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' },
  { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml' },
]

module.exports = [
// Application bundles
{
  entry: {
    'main': './index.js',
    'vendor': helpers.VENDOR_FILES
  },
  output: {
    path: './build',
    filename: '[name].bundle.js',
    publicPath: './',
    library: '[name]'
  },
  node: {
    fs: 'empty'
  },
  debug: true,
  bail: true,
  devtool: 'source-map',
  module: {
    loaders: loaders
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      filename: "vendor.bundle.js"
    }),
    new ExtractTextPlugin("[name].css")
  ],
  externals: helpers.DEFAULT_EXTERNALS
},
// JupyterLab bundle
{
  entry: './build/jupyterlab-shim.js',
  output: {
      filename: 'lab.bundle.js',
      path: './build',
      publicPath: './',
      library: ['jupyter', 'lab'],
  },
  module: {
    loaders: loaders
  },
  plugins: [
    new ExtractTextPlugin("lab.css")
  ],
  bail: true,
  devtool: 'source-map',
  externals: helpers.BASE_EXTERNALS
},
// CodeMirror bundle
{
  entry: {
    'codemirror': CodeMirrorFiles
  },
  output: {
      filename: 'codemirror.bundle.js',
      path: './build',
      publicPath: './',
      library: ['jupyter', 'CodeMirror'],
  },
  module: {
    loaders: loaders
  },
  plugins: [
    new ExtractTextPlugin("codemirror.css")
  ],
  bail: true,
  devtool: 'source-map'
},
// Jupyter-js-services bundle
{
  entry: 'jupyter-js-services',
  output: {
      filename: 'services.bundle.js',
      path: './build',
      publicPath: './',
      library: ['jupyter', 'services'],
  },
  module: {
    loaders: loaders
  },
  bail: true,
  devtool: 'source-map',
  externals: helpers.phosphorExternals
},
// Phosphor bundle
{
  entry: './build/phosphor-shim.js',
  output: {
      filename: 'phosphor.bundle.js',
      path: './build',
      publicPath: './',
      library: ['jupyter', 'phosphor']
  },
  bail: true,
  devtool: 'source-map'
}
]
<|endoftext|>


<commit_before><commit_msg>added delay to handle validations. Filtered cases for tree and notInput components<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';
import config from '../config/environment';

export default Ember.Component.extend({
    session: Ember.inject.service(),
    store: Ember.inject.service(),
    lastInput: undefined,
	inputObserver: function() {
        if (this.get("lastInput") === this.get("module.evaluation.points")) {
            return;
        }
        var points = this.get("module.evaluation.points");
        if (isFinite(points) && isFinite(this.get("lastInput"))) {
		  this.sendAction("dirty");
          this.set("module.evaluation.corrected_by", this.get("session.current_user.id"));
        }
        if(points > 10) {
            this.set("module.evaluation.points", 10);
        }
        if(points < 0) {
            this.set("module.evaluation.points", 0);
        }
        this.set("lastInput", this.get("module.evaluation.points"));
	}.observes("module.evaluation.points"),
    actions: {
        all: function() {
            var self = this;
            this.get('session').authorize('authorizer:oauth2', function(header, content) {
                var request = new XMLHttpRequest();
                request.open("GET", config.API_LOC + "/admin/subm/eval/" + self.get("module.evaluation.eval_id"), true);
                request.responseType = "blob";
                request.setRequestHeader(header, content);
                request.onload = function() {
                    if (this.status === 200) {
                        var file = window.URL.createObjectURL(this.response);
                        var a = document.createElement("a");
                        a.href = file;
                        a.download = this.response.name || ("oprava" + self.get("module.evaluation.eval_id") + ".zip");
                        document.body.appendChild(a);
                        a.click();
                        window.onfocus = function() {
                            document.body.removeChild(a);
                        };
                    }
                };
                request.send();
            });
        },
        log: function() {
            this.set("show_log", !this.get("show_log"));
        }
    },
});
<commit_msg>MehMeh<commit_after>import Ember from 'ember';
import config from '../config/environment';

export default Ember.Component.extend({
    session: Ember.inject.service(),
    store: Ember.inject.service(),
    lastInput: undefined,
	inputObserver: function() {
        if (this.get("lastInput") === this.get("module.evaluation.points")) {
            return;
        }
        var points = this.get("module.evaluation.points");
        if (isFinite(points) && isFinite(this.get("lastInput"))) {
		  this.sendAction("dirty");
          var self = this;
          this.get("store").find("user", this.get("session.current_user.id")).then(function(p) {
            self.set("module.evaluation.corrected_by", p);
          });
        }
        if(points > 10) {
            this.set("module.evaluation.points", 10);
        }
        if(points < 0) {
            this.set("module.evaluation.points", 0);
        }
        this.set("lastInput", this.get("module.evaluation.points"));
	}.observes("module.evaluation.points"),
    actions: {
        all: function() {
            var self = this;
            this.get('session').authorize('authorizer:oauth2', function(header, content) {
                var request = new XMLHttpRequest();
                request.open("GET", config.API_LOC + "/admin/subm/eval/" + self.get("module.evaluation.eval_id"), true);
                request.responseType = "blob";
                request.setRequestHeader(header, content);
                request.onload = function() {
                    if (this.status === 200) {
                        var file = window.URL.createObjectURL(this.response);
                        var a = document.createElement("a");
                        a.href = file;
                        a.download = this.response.name || ("oprava" + self.get("module.evaluation.eval_id") + ".zip");
                        document.body.appendChild(a);
                        a.click();
                        window.onfocus = function() {
                            document.body.removeChild(a);
                        };
                    }
                };
                request.send();
            });
        },
        log: function() {
            this.set("show_log", !this.get("show_log"));
        }
    },
});
<|endoftext|>


<commit_before>/**********************************************************************************
	Class: Application

	A global instance of this class named SAPPHIRE.application manages the basic functions of a JavaScript Application,
	such as page management and the startup sequence.  Some of these functions will be called automatically using
	JavaScript snippets inserted when the application was built, see <Application>. Other functions will be called from
	within your	specific application.

	Extends:
		<Eventer>

	See Also:
		<PageManager>, <Eventer>
*/

Package('Sapphire', {
	Application : new Class({

		Extends : Sapphire.Eventer,

	/**********************************************************************************'
		Constructor: initialize

		Called at javascript load, the DOM will not be ready.
	*/
		initialize : function()
		{
			this.parent();
			this.pages = new Sapphire.PageManager(true);
			this.dialogs = new Sapphire.PageManager(false);
			this.panels = $H({});

			this.startPage = '';
			this.started = false;

			this.views = $H({});
			this.controllers = $H({});
			this.models = $H({});
			this.services = $H({});
		},

	/**********************************************************************************'
		Method: addPage

		The builder will insert a JavaScript snippet to call this function for every
		page that has been added.

		Parameters:
			spec    - the specification of a page
	*/
		addPage : function(spec)
		{
			this.pages.addPage(spec);
		},

	/**********************************************************************************'
		Method: dialog

		The builder will insert a JavaScript snippet to call this function for every
		dialog that has been added. Dialogs are modal windows designed to pop up over pages.
		You can have more than one dialog open at any time.

		Parameters:
			spec    - the specification for the dialog
	*/
		addDialog : function(spec)
		{
			this.dialogs.addPage(spec);
		},

		addPanel : function(name, spec)
		{
			if (!this.panels.has(name)) this.panels[name] = new Sapphire.PageManager(true);
			this.panels[name].addPage(spec);
		},

	/**********************************************************************************'
		Method: showPage

		Call this method to hide the current page and show a new one. If the current page
		has not been maked as dontPrune, then it will be removed from the DOM. Before the
		page has been removed, any hide events will be fired. The show events will fired
		once the page has been added back into the DOM.

		Parameters:
			name    - the name of the page
			...     - Any arguments passed after name will be passed to any listeners for
					  this page
	*/
		showPage : function(name)
		{
		 	var passed = Array.prototype.slice.call(arguments, 1);
			this.pages.showPage(name, passed);
			this.hasShownPage = true;
		},

	/**********************************************************************************'
		Method: showPanel

		Call this method to hide the current page and show a new one. If the current page
		has not been maked as dontPrune, then it will be removed from the DOM. Before the
		page has been removed, any hide events will be fired. The show events will fired
		once the page has been added back into the DOM.

		Parameters:
			name    - the name of the page
			...     - Any arguments passed after name will be passed to any listeners for
					  this page
	*/
		showPanel : function(set, name)
		{
		 	var passed = Array.prototype.slice.call(arguments, 1);
			this.panels[set].showPage(name, passed);
		},

		setPanelContainer : function(name, selector)
		{
			this.panels[name].setContainer(selector);
		},

		resetPanels : function(name)
		{
			this.panels[name].reset();
		},

		firePanelEvent : function(event, name)
		{
		 	var passed = Array.prototype.slice.call(arguments, 2);
			this.panels[name].fireArgs(event, passed);
		},

	/**********************************************************************************'
		Method: getCurrentPage

		Call this method to get the name of the current page.

		Returns:
			The page name as a string
	*/
		getCurrentPage : function()
		{
			return this.pages.currentPage;
		},

	/**********************************************************************************'
		Method: showDialog

		Call this method to show a dialog. Any dialogs already shown will remain shown.
		Show events will be fired once the dialog has been added back into the DOM.

		Parameters:
			name    - the name of the dialog
			...     - Any arguments passed after name will be passed to any listeners for
					  this dialog
	*/
		showDialog : function(name)
		{
		    var passed = Array.prototype.slice.call(arguments, 1);
			var deferred = Q.defer();
			passed.unshift(deferred);

			this.dialogs.showPage(name, passed);

			return deferred.promise;
		},

	/**********************************************************************************'
		Method: hideDialog

		Call this method to hide a dialog. This method must be called for all dialogs shown

		Parameters:
			name    - the name of the page
			...     - Any arguments passed after name will be passed to any listeners for
					  this page
	*/
		hideDialog : function(name)
		{
			this.dialogs.hidePage(name);
		},

	/**********************************************************************************'
		Method: setStartPage

		Call this method during application startup to set the first dialog to show

		Parameters:
			name    - the name of the page
	*/
		setStartPage : function(name)
		{
			this.startPage = name;
		},

		checkReady : function()
		{
			this.readyWaiting--;
			console.log('checkReady', this.readyWaiting);
			if (this.readyWaiting == 0) this.ready();
		},

		ready : function()
		{
			console.log('ready');
			this.pages.setContainer($('#pages'));
			this.dialogs.setContainer($('#dialogs'));

			this.fire('ready');

			if (this.startPage && !this.hasShownPage) this.showPage(this.startPage);
		},

	/**********************************************************************************'
		Method: start

		Call this method after the dom is ready to start the application start up sequence. The
		Application object on the server side will insert a call to this automatically.

		When this method is called:
			- if set, the default page will be shown
	*/
		start : function()
		{
			if (this.started) return;
			this.started = true;

			this.readyWaiting = this.getEventCount('start');
			console.log('start: this.readyWaiting');
			if (this.readyWaiting == 0) this.ready.delay(1, this);

			this.fire('start', this.checkReady.bind(this));
		},

		listenPageEvent : function(event, which, callback)
		{
			if (which) this.pages.listenPageEvent(event, which, callback)
			else this.pages.listenGlobalEvent(event, callback);
		},

		listenDialogEvent : function(event, which, callback)
		{
			if (which) this.dialogs.listenPageEvent(event, which, callback)
			else this.dialogs.listenGlobalEvent(event, callback);
		},

		listenPanelEvent : function(event, set, which, callback)
		{
			if (!set)
			{
				var panels = $H(this.panels);
				panels.each(function(set)
				{
					if (which) set.listenPageEvent(event, which, callback)
					else set.listenGlobalEvent(event, callback);
				}, this);
				return;
			}
			if (which) this.panels[set].listenPageEvent(event, which, callback)
			else this.panels[set].listenGlobalEvent(event, callback);
		},

	/**********************************************************************************'
		Method: setPageEffects

		Call this method to register callbacks for adding animations when a page is shown or hidden.

		Parameters:
			show      - the <showEffect> function to call when a page is shown
			hide      - the <hideEffect> function to call when a page is hidden

	 	See Also:
			<showEffect>, <hideEffect>
	*/
		setPageEffects : function (show, hide)
		{
			this.pages.setEffects(show, hide);
		},

	/**********************************************************************************'
		Method: setDialogEffects

		Call this method to register callbacks for adding animations when a dialog is shown or hidden.

		Parameters:
			show      - the <showEffect> function to call when a dialog is shown
			hide      - the <hideEffect> function to call when a dialogis hidden

	 	See Also:
			<showEffect>, <hideEffect>
	*/
		setDialogEffects : function (show, hide)
		{
			this.dialogs.setEffects(show, hide);
		},

		setPanelEffects : function (name, show, hide)
		{
			this.panels[name].setEffects(show, hide);
		},

		registerController : function(name, controller)
		{
			this.controllers[name] = controller;
		},

		registerView : function(name, view)
		{
			this.views[name] = view;
		},

		registerService : function(name, service)
		{
			this.services[name] = service;
		},

		registerModel : function(name, service)
		{
			this.models[name] = service;
		},

		getController : function(name)
		{
			return this.controllers[name];
		},

		getModel : function(name)
		{
			return this.models[name];
		},

		getView : function(name)
		{
			return this.views[name];
		}
	})
});

SAPPHIRE.application = new Sapphire.Application();

//===========================================================================================
// Group: Callbacks
//===========================================================================================
/**********************************************************************************'
	Function: showEffect

	When you call <setPageEffects> or <setDialogEffects> your showEffect
	callback should look like this.

	> showEffect: function(oldPage, newPage, callback)

	Parameters:
		oldPage		- the jQuery selector for the page being hidden
		newPage     - the JQuery selector of the page or dialog being shown
		callback    - a function to call when the effect has finished

*/

/**********************************************************************************'
	Function: hideEffect

	When you call <setPageEffects> or <setDialogEffects> your showEffect
	callback should look like this.

	> hideEffect: function(node, callback)

	Parameters:
		node        - the JQuery selector of the page or dialog being shown
		callback    - a function to call when the effect has finished
*/

<commit_msg>- removed some logs<commit_after>/**********************************************************************************
	Class: Application

	A global instance of this class named SAPPHIRE.application manages the basic functions of a JavaScript Application,
	such as page management and the startup sequence.  Some of these functions will be called automatically using
	JavaScript snippets inserted when the application was built, see <Application>. Other functions will be called from
	within your	specific application.

	Extends:
		<Eventer>

	See Also:
		<PageManager>, <Eventer>
*/

Package('Sapphire', {
	Application : new Class({

		Extends : Sapphire.Eventer,

	/**********************************************************************************'
		Constructor: initialize

		Called at javascript load, the DOM will not be ready.
	*/
		initialize : function()
		{
			this.parent();
			this.pages = new Sapphire.PageManager(true);
			this.dialogs = new Sapphire.PageManager(false);
			this.panels = $H({});

			this.startPage = '';
			this.started = false;

			this.views = $H({});
			this.controllers = $H({});
			this.models = $H({});
			this.services = $H({});
		},

	/**********************************************************************************'
		Method: addPage

		The builder will insert a JavaScript snippet to call this function for every
		page that has been added.

		Parameters:
			spec    - the specification of a page
	*/
		addPage : function(spec)
		{
			this.pages.addPage(spec);
		},

	/**********************************************************************************'
		Method: dialog

		The builder will insert a JavaScript snippet to call this function for every
		dialog that has been added. Dialogs are modal windows designed to pop up over pages.
		You can have more than one dialog open at any time.

		Parameters:
			spec    - the specification for the dialog
	*/
		addDialog : function(spec)
		{
			this.dialogs.addPage(spec);
		},

		addPanel : function(name, spec)
		{
			if (!this.panels.has(name)) this.panels[name] = new Sapphire.PageManager(true);
			this.panels[name].addPage(spec);
		},

	/**********************************************************************************'
		Method: showPage

		Call this method to hide the current page and show a new one. If the current page
		has not been maked as dontPrune, then it will be removed from the DOM. Before the
		page has been removed, any hide events will be fired. The show events will fired
		once the page has been added back into the DOM.

		Parameters:
			name    - the name of the page
			...     - Any arguments passed after name will be passed to any listeners for
					  this page
	*/
		showPage : function(name)
		{
		 	var passed = Array.prototype.slice.call(arguments, 1);
			this.pages.showPage(name, passed);
			this.hasShownPage = true;
		},

	/**********************************************************************************'
		Method: showPanel

		Call this method to hide the current page and show a new one. If the current page
		has not been maked as dontPrune, then it will be removed from the DOM. Before the
		page has been removed, any hide events will be fired. The show events will fired
		once the page has been added back into the DOM.

		Parameters:
			name    - the name of the page
			...     - Any arguments passed after name will be passed to any listeners for
					  this page
	*/
		showPanel : function(set, name)
		{
		 	var passed = Array.prototype.slice.call(arguments, 1);
			this.panels[set].showPage(name, passed);
		},

		setPanelContainer : function(name, selector)
		{
			this.panels[name].setContainer(selector);
		},

		resetPanels : function(name)
		{
			this.panels[name].reset();
		},

		firePanelEvent : function(event, name)
		{
		 	var passed = Array.prototype.slice.call(arguments, 2);
			this.panels[name].fireArgs(event, passed);
		},

	/**********************************************************************************'
		Method: getCurrentPage

		Call this method to get the name of the current page.

		Returns:
			The page name as a string
	*/
		getCurrentPage : function()
		{
			return this.pages.currentPage;
		},

	/**********************************************************************************'
		Method: showDialog

		Call this method to show a dialog. Any dialogs already shown will remain shown.
		Show events will be fired once the dialog has been added back into the DOM.

		Parameters:
			name    - the name of the dialog
			...     - Any arguments passed after name will be passed to any listeners for
					  this dialog
	*/
		showDialog : function(name)
		{
		    var passed = Array.prototype.slice.call(arguments, 1);
			var deferred = Q.defer();
			passed.unshift(deferred);

			this.dialogs.showPage(name, passed);

			return deferred.promise;
		},

	/**********************************************************************************'
		Method: hideDialog

		Call this method to hide a dialog. This method must be called for all dialogs shown

		Parameters:
			name    - the name of the page
			...     - Any arguments passed after name will be passed to any listeners for
					  this page
	*/
		hideDialog : function(name)
		{
			this.dialogs.hidePage(name);
		},

	/**********************************************************************************'
		Method: setStartPage

		Call this method during application startup to set the first dialog to show

		Parameters:
			name    - the name of the page
	*/
		setStartPage : function(name)
		{
			this.startPage = name;
		},

		checkReady : function()
		{
			this.readyWaiting--;
			if (this.readyWaiting == 0) this.ready();
		},

		ready : function()
		{
			this.pages.setContainer($('#pages'));
			this.dialogs.setContainer($('#dialogs'));

			this.fire('ready');

			if (this.startPage && !this.hasShownPage) this.showPage(this.startPage);
		},

	/**********************************************************************************'
		Method: start

		Call this method after the dom is ready to start the application start up sequence. The
		Application object on the server side will insert a call to this automatically.

		When this method is called:
			- if set, the default page will be shown
	*/
		start : function()
		{
			if (this.started) return;
			this.started = true;

			this.readyWaiting = this.getEventCount('start');
			if (this.readyWaiting == 0) this.ready.delay(1, this);

			this.fire('start', this.checkReady.bind(this));
		},

		listenPageEvent : function(event, which, callback)
		{
			if (which) this.pages.listenPageEvent(event, which, callback)
			else this.pages.listenGlobalEvent(event, callback);
		},

		listenDialogEvent : function(event, which, callback)
		{
			if (which) this.dialogs.listenPageEvent(event, which, callback)
			else this.dialogs.listenGlobalEvent(event, callback);
		},

		listenPanelEvent : function(event, set, which, callback)
		{
			if (!set)
			{
				var panels = $H(this.panels);
				panels.each(function(set)
				{
					if (which) set.listenPageEvent(event, which, callback)
					else set.listenGlobalEvent(event, callback);
				}, this);
				return;
			}
			if (which) this.panels[set].listenPageEvent(event, which, callback)
			else this.panels[set].listenGlobalEvent(event, callback);
		},

	/**********************************************************************************'
		Method: setPageEffects

		Call this method to register callbacks for adding animations when a page is shown or hidden.

		Parameters:
			show      - the <showEffect> function to call when a page is shown
			hide      - the <hideEffect> function to call when a page is hidden

	 	See Also:
			<showEffect>, <hideEffect>
	*/
		setPageEffects : function (show, hide)
		{
			this.pages.setEffects(show, hide);
		},

	/**********************************************************************************'
		Method: setDialogEffects

		Call this method to register callbacks for adding animations when a dialog is shown or hidden.

		Parameters:
			show      - the <showEffect> function to call when a dialog is shown
			hide      - the <hideEffect> function to call when a dialogis hidden

	 	See Also:
			<showEffect>, <hideEffect>
	*/
		setDialogEffects : function (show, hide)
		{
			this.dialogs.setEffects(show, hide);
		},

		setPanelEffects : function (name, show, hide)
		{
			this.panels[name].setEffects(show, hide);
		},

		registerController : function(name, controller)
		{
			this.controllers[name] = controller;
		},

		registerView : function(name, view)
		{
			this.views[name] = view;
		},

		registerService : function(name, service)
		{
			this.services[name] = service;
		},

		registerModel : function(name, service)
		{
			this.models[name] = service;
		},

		getController : function(name)
		{
			return this.controllers[name];
		},

		getModel : function(name)
		{
			return this.models[name];
		},

		getView : function(name)
		{
			return this.views[name];
		}
	})
});

SAPPHIRE.application = new Sapphire.Application();

//===========================================================================================
// Group: Callbacks
//===========================================================================================
/**********************************************************************************'
	Function: showEffect

	When you call <setPageEffects> or <setDialogEffects> your showEffect
	callback should look like this.

	> showEffect: function(oldPage, newPage, callback)

	Parameters:
		oldPage		- the jQuery selector for the page being hidden
		newPage     - the JQuery selector of the page or dialog being shown
		callback    - a function to call when the effect has finished

*/

/**********************************************************************************'
	Function: hideEffect

	When you call <setPageEffects> or <setDialogEffects> your showEffect
	callback should look like this.

	> hideEffect: function(node, callback)

	Parameters:
		node        - the JQuery selector of the page or dialog being shown
		callback    - a function to call when the effect has finished
*/

<|endoftext|>


<commit_before>/* ************************************************************************ */
/*

*/
var React = require('react');

var Calculations  = require( './panels/Calculations.js');
var Fermentables  = require( './panels/Fermentables.js');
var Hops  = require( './panels/Hops.js');
var helper  = require( '../utils/helpers');

var RecipeCreate = React.createClass({

    componentDidMount: function() {
        // Get initial recipe.
        console.log('Main getRecipe : function () {');
        helper.newRecipe().then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    getInitialState: function() {
        console.log('Main getInitialState: function () {');
        return {
            recipe: {}
        };
    },

    addNewHop: function(data) {
        console.log('RecipeCreate addNewHop  () {');
        var nstr = Date.now().toString()
        var idStr = 'FFFFFFFFFFF' + nstr;
        idStr = idStr.slice(idStr.length - 24, idStr.length);
        this.state.recipe.hops.push({ _id: idStr, name: data, lbs: "", ozs: "", alphaAcid: "", minutes: "" });
        this.forceUpdate();
    },

    addNewFermentable: function(data) {
        console.log('RecipeCreate addNewFermentable  () {');
        var nstr = Date.now().toString()
        var idStr = 'FFFFFFFFFFF' + nstr;
        idStr = idStr.slice(idStr.length - 24, idStr.length);
        this.state.recipe.fermentables.push({ _id: idStr, name: data, lbs: "", ozs: "" });
        this.forceUpdate();
    },

    deleteHop: function(hopId) {
        console.log('RecipeCreate deleteHop  () {');
        // if it is not in the database
        var i = 0;
        // untilwe find the hop we want to delete
        for (i = 0; i < this.state.recipe.hops.length; i++) {
            if (this.state.recipe.hops[i]._id === hopId) {
                // hops already in database have _id ObjectIds
                // hops only added locally have _id begin with F's
                if (hopId.startsWith('FFFFFFFF')) {
                    this.state.recipe.hops.splice(i, 1);
                } else {
                    this.state.recipe.hops[i].removed = 'true';
                }
                // hop has either been deleted or property removed added and set to true
                break;
            }
        }
        this.forceUpdate();
    },

    deleteFermentable: function(fermentableId) {
        console.log('RecipeCreate deleteFermentable  () {');
        // if it is not in the database
        var i = 0;
        // until we find the fermentable we want to delete
        for (i = 0; i < this.state.recipe.fermentables.length; i++) {
            if (this.state.recipe.fermentables[i]._id === fermentableId) {
                // fermentables already in database have _id ObjectIds
                // fermentables only added locally have _id begin with F's
                if (fermentableId.startsWith('FFFFFFFF')) {
                    this.state.recipe.fermentables.splice(i, 1);
                } else {
                    this.state.recipe.fermentables[i].removed = 'true';
                }
                // fermentable has either been deleted or property removed added and set to true
                break;
            }
        }
        this.forceUpdate();
    },

    getRecipe: function(recipeId) {
        console.log('RecipeCreate getRecipe  () {');
        helper.getRecipe(recipeId).then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    saveRecipe: function() {
        console.log('RecipeCreate saveRecipe  () {');
        helper.updateRecipe(this.state.recipe).then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    newRecipe: function() {
        console.log('RecipeCreate newRecipe  () {');
        helper.newRecipe().then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    deleteRecipe: function() {
        console.log('RecipeCreate deleteRecipe  () {');
        helper.deleteRecipe(this.state.recipe).then(function(response) {
            console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    saveToJSON: function() {
        console.log('RecipeCreate saveToJSON  () {');
        helper.saveToJSON(this.state.recipe).then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    calculationChange: function(varName, val) {
        console.log('RecipeCreate calculationChange  () {');
        console.log('varName:' + varName + ' val:' + val);

        if (varName === 'recipeName') {
            this.state.recipe.recipeName = val;
        } else if (varName === 'brewDate') {
            this.state.recipe.brewDate = val;
        } else if (varName === 'batchSize') {
            this.state.recipe.batchSize = val;
            // only the batchsize can change the calculations
        } else if (varName === 'style') {
            this.state.recipe.style = val;
        }
        // We can later add code to nnly update the CalculationsPanel
        // We do not need to udate the Hops and Fermentables PAnel
        this.forceUpdate();
    },

    fermentableChange: function(fermObjId, varName, val) {
        console.log('RecipeCreate fermentableChange  () {');
        for (var i = 0; i < this.state.recipe.fermentables.length; i++) {
            console.log('inloop:' + this.state.recipe.fermentables[i]._id)
            if (this.state.recipe.fermentables[i]._id === fermObjId) {
                if (varName === 'ozs') {
                    this.state.recipe.fermentables[i].ozs = val;
                } else if (varName === 'lbs') {
                    this.state.recipe.fermentables[i].lbs = val;
                } else if (varName === 'name') {
                    this.state.recipe.fermentables[i].name = val;
                }
                break;
            }
        }
        this.forceUpdate();
    },

    hopChange: function(hopObjId, varName, val) {
        console.log('RecipeCreate hopChange  () {');
        for (var i = 0; i < this.state.recipe.hops.length; i++) {
            console.log('inloop:' + this.state.recipe.hops[i]._id)
            if (this.state.recipe.hops[i]._id === hopObjId) {
                if (varName === 'ozs') {
                    this.state.recipe.hops[i].ozs = val;
                } else if (varName === 'lbs') {
                    this.state.recipe.hops[i].lbs = val;
                } else if (varName === 'minutes') {
                    this.state.recipe.hops[i].minutes = val;
                } else if (varName === 'alphaAcid') {
                    this.state.recipe.hops[i].alphaAcid = val;
                } else if (varName === 'name') {
                    this.state.recipe.hops[i].name = val;
                }
                break;
            }
        }
        //this.renderCalculationsPanel();
        this.forceUpdate();
    },

    render: function() {
        return (

                        <Calculations recipe={this.state.recipe} calculationChange={this.calculationChange} saveRecipe={this.saveRecipe}/>

                        <Hops hopChange={this.hopChange} addNewHop={this.addNewHop} deleteHop={this.deleteHop} hops={this.state.recipe.hops}/>

                        <Fermentables fermentableChange={this.fermentableChange} addNewFermentable={this.addNewFermentable} deleteFermentable={ this.deleteFermentable} fermentables={this.state.recipe.fermentables}/>

        );
    }

});

module.exports = RecipeCreate;

<commit_msg>changed ingredient panel to be stacked and collapsible<commit_after>/* ************************************************************************ */
/*

*/
var React = require('react');

var Calculations  = require( './panels/Calculations.js');
var Fermentables  = require( './panels/Fermentables.js');
var Hops  = require( './panels/Hops.js');
var helper  = require( '../utils/helpers');

var RecipeCreate = React.createClass({

    componentDidMount: function() {
        // Get initial recipe.
        console.log('Main getRecipe : function () {');
        helper.newRecipe().then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    getInitialState: function() {
        console.log('Main getInitialState: function () {');
        return {
            recipe: {}
        };
    },

    addNewHop: function(data) {
        console.log('RecipeCreate addNewHop  () {');
        var nstr = Date.now().toString()
        var idStr = 'FFFFFFFFFFF' + nstr;
        idStr = idStr.slice(idStr.length - 24, idStr.length);
        this.state.recipe.hops.push({ _id: idStr, name: data, lbs: "", ozs: "", alphaAcid: "", minutes: "" });
        this.forceUpdate();
    },

    addNewFermentable: function(data) {
        console.log('RecipeCreate addNewFermentable  () {');
        var nstr = Date.now().toString()
        var idStr = 'FFFFFFFFFFF' + nstr;
        idStr = idStr.slice(idStr.length - 24, idStr.length);
        this.state.recipe.fermentables.push({ _id: idStr, name: data, lbs: "", ozs: "" });
        this.forceUpdate();
    },

    deleteHop: function(hopId) {
        console.log('RecipeCreate deleteHop  () {');
        // if it is not in the database
        var i = 0;
        // untilwe find the hop we want to delete
        for (i = 0; i < this.state.recipe.hops.length; i++) {
            if (this.state.recipe.hops[i]._id === hopId) {
                // hops already in database have _id ObjectIds
                // hops only added locally have _id begin with F's
                if (hopId.startsWith('FFFFFFFF')) {
                    this.state.recipe.hops.splice(i, 1);
                } else {
                    this.state.recipe.hops[i].removed = 'true';
                }
                // hop has either been deleted or property removed added and set to true
                break;
            }
        }
        this.forceUpdate();
    },

    deleteFermentable: function(fermentableId) {
        console.log('RecipeCreate deleteFermentable  () {');
        // if it is not in the database
        var i = 0;
        // until we find the fermentable we want to delete
        for (i = 0; i < this.state.recipe.fermentables.length; i++) {
            if (this.state.recipe.fermentables[i]._id === fermentableId) {
                // fermentables already in database have _id ObjectIds
                // fermentables only added locally have _id begin with F's
                if (fermentableId.startsWith('FFFFFFFF')) {
                    this.state.recipe.fermentables.splice(i, 1);
                } else {
                    this.state.recipe.fermentables[i].removed = 'true';
                }
                // fermentable has either been deleted or property removed added and set to true
                break;
            }
        }
        this.forceUpdate();
    },

    getRecipe: function(recipeId) {
        console.log('RecipeCreate getRecipe  () {');
        helper.getRecipe(recipeId).then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    saveRecipe: function() {
        console.log('RecipeCreate saveRecipe  () {');
        helper.updateRecipe(this.state.recipe).then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    newRecipe: function() {
        console.log('RecipeCreate newRecipe  () {');
        helper.newRecipe().then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    deleteRecipe: function() {
        console.log('RecipeCreate deleteRecipe  () {');
        helper.deleteRecipe(this.state.recipe).then(function(response) {
            console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    saveToJSON: function() {
        console.log('RecipeCreate saveToJSON  () {');
        helper.saveToJSON(this.state.recipe).then(function(response) {
            //console.log(response);
            this.setState({
                recipe: response.data
            });
        }.bind(this));
    },

    calculationChange: function(varName, val) {
        console.log('RecipeCreate calculationChange  () {');
        console.log('varName:' + varName + ' val:' + val);

        if (varName === 'recipeName') {
            this.state.recipe.recipeName = val;
        } else if (varName === 'brewDate') {
            this.state.recipe.brewDate = val;
        } else if (varName === 'batchSize') {
            this.state.recipe.batchSize = val;
            // only the batchsize can change the calculations
        } else if (varName === 'style') {
            this.state.recipe.style = val;
        }
        // We can later add code to nnly update the CalculationsPanel
        // We do not need to udate the Hops and Fermentables PAnel
        this.forceUpdate();
    },

    fermentableChange: function(fermObjId, varName, val) {
        console.log('RecipeCreate fermentableChange  () {');
        for (var i = 0; i < this.state.recipe.fermentables.length; i++) {
            console.log('inloop:' + this.state.recipe.fermentables[i]._id)
            if (this.state.recipe.fermentables[i]._id === fermObjId) {
                if (varName === 'ozs') {
                    this.state.recipe.fermentables[i].ozs = val;
                } else if (varName === 'lbs') {
                    this.state.recipe.fermentables[i].lbs = val;
                } else if (varName === 'name') {
                    this.state.recipe.fermentables[i].name = val;
                }
                break;
            }
        }
        this.forceUpdate();
    },

    hopChange: function(hopObjId, varName, val) {
        console.log('RecipeCreate hopChange  () {');
        for (var i = 0; i < this.state.recipe.hops.length; i++) {
            console.log('inloop:' + this.state.recipe.hops[i]._id)
            if (this.state.recipe.hops[i]._id === hopObjId) {
                if (varName === 'ozs') {
                    this.state.recipe.hops[i].ozs = val;
                } else if (varName === 'lbs') {
                    this.state.recipe.hops[i].lbs = val;
                } else if (varName === 'minutes') {
                    this.state.recipe.hops[i].minutes = val;
                } else if (varName === 'alphaAcid') {
                    this.state.recipe.hops[i].alphaAcid = val;
                } else if (varName === 'name') {
                    this.state.recipe.hops[i].name = val;
                }
                break;
            }
        }
        //this.renderCalculationsPanel();
        this.forceUpdate();
    },

    render: function() {
        return (

                        <Calculations recipe={this.state.recipe} calculationChange={this.calculationChange} saveRecipe={this.saveRecipe}/>

                        <Hops hopChange={this.hopChange} addNewHop={this.addNewHop} deleteHop={this.deleteHop} hops={this.state.recipe.hops}/>

                        <Fermentables fermentableChange={this.fermentableChange} addNewFermentable={this.addNewFermentable} deleteFermentable={ this.deleteFermentable} fermentables={this.state.recipe.fermentables}/>

        );
    }

});

module.exports = RecipeCreate;

<|endoftext|>