<commit_before>VISH.Quiz.Renderer = (function(V,$,undefined){

  var init = function(){

  }

  ////////////////////
  //renderer methods called from VISH.Renderer
  ///////////////////

  /**
   * Function to render a quiz inside an article (a slide)
   */
  var renderQuiz = function(quizType, element, zone_class, slide, zone){

    V.Debugging.log("V.Quiz.Renderes, quizType:" + quizType)
    switch(quizType){
      case "multiplechoice":
        return _renderMcQuestion(element, zone_class, slide, zone);

        break;
      case "mcquestion":
        return _renderMcQuestion(element, zone_class, slide);
        break;
      case "openQuestion":
        return _renderOpenquestion(element, template);
        break;
      case "truefalsequestion":
        return _renderTrueFalseQuestion(element, template);
        break;
      default:
        break;
    }
  };

  var _renderMcQuestion = function(element, zone_class, slide, zone){

      var ret = "
";
      ret += "
";
      ret += "

";
      ret += "

"+ element['question']+"
";
      ret += "<form class='mcquestion_form' action='"+element['posturl']+"' method='post'>";

      for(var i = 0; i<element['options'].length; i++){
        var next_index = String.fromCharCode("a".charCodeAt(0) + (i));
        if(VISH.Quiz.getQuizMode()=="answer"){
          ret += ""+next_index+") <input class='mc_radio' type='radio' name='mc_radio' value='"+next_index+"'</input>"+element['options'][i]+"";
        } else {
          ret += ""+next_index+") "+element['options'][i]+"";
        }
        ret += "

";
        ret += "";
      }
      ret += "<input type='hidden' value='"+ slide + "_"+ zone +"' name='zone' class='quiz_id' />";
      ret += "
";
      ret += "
";
      ret += "
";
      ret += "";
      ret += "
";
      ret += "
";
      //ret += "<input type='button' class='mcquestion_start_button' value='Start Quiz'/>";
      ret += "Start";
      ret += "
";
      ret += "</form>";
      ret += "
";
      return ret;
  };

  var _renderOpenquestion = function(element, template){
    var ret = "<form action='"+element['posturl']+"' method='post' style='text-align:center;'>";
    ret += "Name:  ";
    ret += "<textarea id='pupil_name' rows='1' cols='50' class='question_name_input' placeholder='Write your name here'></textarea>";
    ret += "
 Question: "+element['question']+"?
";

    ret += "Answer: ";
    ret += "<textarea id='question_answer' rows='5' cols='50' class='question_answer' placeholder='Write your answer here'></textarea>";

    ret += "<button type='button' class='question_button'>Send</button>";

    return ret;
  };

  /**
   * Function to render a True False Question choice question form inside an article (a slide)
   * TODO Include in the VISH.Quiz?? ... think and ask Kike about it
   */

  var _renderTrueFalseQuestion = function(element, template){
    var next_num=0;
    var answers = new Array();
    var ret = "
";

    ret += "
";
    ret += "<form class='truefalse_question_form' action='"+element['posturl']+"' method='post'>";
    ret+= "

True	False	 Question
";

    for(var i = 0; i<element['questions'].length; i++){
      //saving correct answers
      answers[i] =element['questions'][i]['answer'];
      ret +="
";
      ret +="";
      ret += "<input type='radio' name='tf_radio_"+(i+1)+"' value='true' />	";
      ret += "";
      ret += "<input type='radio' name='tf_radio_"+(i+1)+"' value='false'/>	";
      ret += ""+element['questions'][i]['text_question']+"?	";
      ret += "
";
    }

    ret += "
";
    ret += "<input type='button' class='tfquestion_button' value='Send'/>";
    ret += "</form>";
    ret += "
";

    trueFalseAnswers = answers;
    asnswers = [];
    VISH.Debugging.log("JSON object answer is: " +trueFalseAnswers);

    return ret;
  };

  return {
    init:                             init,
    renderQuiz:                       renderQuiz
  };

}) (VISH, jQuery);<commit_msg>Quiz: added startQuiz button<commit_after>VISH.Quiz.Renderer = (function(V,$,undefined){

  var init = function(){

  }

  ////////////////////
  //renderer methods called from VISH.Renderer
  ///////////////////

  /**
   * Function to render a quiz inside an article (a slide)
   */
  var renderQuiz = function(quizType, element, zone_class, slide, zone){

    V.Debugging.log("V.Quiz.Renderes, quizType:" + quizType)
    switch(quizType){
      case "multiplechoice":
        return _renderMcQuestion(element, zone_class, slide, zone);

        break;
      case "mcquestion":
        return _renderMcQuestion(element, zone_class, slide);
        break;
      case "openQuestion":
        return _renderOpenquestion(element, template);
        break;
      case "truefalsequestion":
        return _renderTrueFalseQuestion(element, template);
        break;
      default:
        break;
    }
  };

  var _renderMcQuestion = function(element, zone_class, slide, zone){

      var ret = "
";
      ret += "
";
      ret += "

";
      ret += "

"+ element['question']+"
";
      ret += "<form class='mcquestion_form' action='"+element['posturl']+"' method='post'>";

      for(var i = 0; i<element['options'].length; i++){
        var next_index = String.fromCharCode("a".charCodeAt(0) + (i));
        if(VISH.Quiz.getQuizMode()=="answer"){
          ret += ""+next_index+") <input class='mc_radio' type='radio' name='mc_radio' value='"+next_index+"'</input>"+element['options'][i]+"";
        } else {
          ret += ""+next_index+") "+element['options'][i]+"";
        }
        ret += "

";
        ret += "";
      }
      ret += "<input type='hidden' value='"+ slide + "_"+ zone +"' name='zone' class='quiz_id' />";
      ret += "
";
      ret += "
";
      ret += "
";
      ret += "";
      ret += "
";
      ret += "
";
      //ret += "<input type='button' class='mcquestion_start_button' value='Start Quiz'/>";
      ret += "<input type='button' class='mcquestion_start_button' value='Start Quiz'/>";
      ret += "
";
      ret += "</form>";
      ret += "
";
      return ret;
  };

  var _renderOpenquestion = function(element, template){
    var ret = "<form action='"+element['posturl']+"' method='post' style='text-align:center;'>";
    ret += "Name:  ";
    ret += "<textarea id='pupil_name' rows='1' cols='50' class='question_name_input' placeholder='Write your name here'></textarea>";
    ret += "
 Question: "+element['question']+"?
";

    ret += "Answer: ";
    ret += "<textarea id='question_answer' rows='5' cols='50' class='question_answer' placeholder='Write your answer here'></textarea>";

    ret += "<button type='button' class='question_button'>Send</button>";

    return ret;
  };

  /**
   * Function to render a True False Question choice question form inside an article (a slide)
   * TODO Include in the VISH.Quiz?? ... think and ask Kike about it
   */

  var _renderTrueFalseQuestion = function(element, template){
    var next_num=0;
    var answers = new Array();
    var ret = "
";

    ret += "
";
    ret += "<form class='truefalse_question_form' action='"+element['posturl']+"' method='post'>";
    ret+= "

True	False	 Question
";

    for(var i = 0; i<element['questions'].length; i++){
      //saving correct answers
      answers[i] =element['questions'][i]['answer'];
      ret +="
";
      ret +="";
      ret += "<input type='radio' name='tf_radio_"+(i+1)+"' value='true' />	";
      ret += "";
      ret += "<input type='radio' name='tf_radio_"+(i+1)+"' value='false'/>	";
      ret += ""+element['questions'][i]['text_question']+"?	";
      ret += "
";
    }

    ret += "
";
    ret += "<input type='button' class='tfquestion_button' value='Send'/>";
    ret += "</form>";
    ret += "
";

    trueFalseAnswers = answers;
    asnswers = [];
    VISH.Debugging.log("JSON object answer is: " +trueFalseAnswers);

    return ret;
  };

  return {
    init:                             init,
    renderQuiz:                       renderQuiz
  };

}) (VISH, jQuery);<|endoftext|>


<commit_before><commit_msg>color constant example<commit_after><|endoftext|>


<commit_before>module.exports = function(nettings){
    var INREC = {};
    INREC.cache = {};
    INREC.cache.users = [];
    INREC.cache.cards = [];
    INREC.receiver = {eventMap:{}};
    INREC.receiver.on = function(eventKey, action){
        INREC.receiver.eventMap[eventKey] = action;
    };

    // +++++++++++
    // +++++++++++
    // +++++++++++
    INREC.cacheSaver = { fs : require('fs') };
    INREC.cacheSaver.cacheDir = __dirname + "/../cache/" + nettings.projectKey;
    INREC.cacheSaver.cacheFilePath = INREC.cacheSaver.cacheDir + "/cache.json";

    INREC.cacheSaver.mkDir = function(dir){
        try {
            INREC.cacheSaver.fs.mkdirSync(dir);
        } catch(e){
            if(e.code !== "EEXIST"){
                console.log(e);
            }
        }
    };

    INREC.cacheSaver.saveCache = function(){
        console.log("_______Saving cache");
        INREC.cacheSaver.mkDir(INREC.cacheSaver.cacheDir);
        INREC.cacheSaver.fs.writeFileSync(INREC.cacheSaver.cacheFilePath, JSON.stringify(INREC.cache, 0, 4));
    };
    // +++++++++++
    // +++++++++++
    // +++++++++++

    INREC.cacheSaver.loadCache = function(){
        console.log("_______Loading cache");
        try{
            var filePath = INREC.cacheSaver.cacheFilePath;
            if(!INREC.cacheSaver.fs.existsSync(filePath)) {
                 INREC.cacheSaver.saveCache();
            }
            var contents = INREC.cacheSaver.fs.readFileSync(filePath).toString();
            INREC.cache = JSON.parse(contents);
        } catch(e) {
            console.log(e);
        }
    };

    INREC.pad = function(num, size) {
        var s = num+"";
        while (s.length < size) s = "0" + s;
        return s;
    }

    INREC.formatDate = function(date){
        var df = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear()
         + "  "+INREC.pad(date.getHours(), 2) + ":" + INREC.pad(date.getMinutes(), 2);
        return df;
    };

    INREC.handleEvent = function(eventKey, response) {
        var action = INREC.receiver.eventMap[eventKey];
        action && action(response);
    };

    INREC.findUserIndex = function(gitUser) {
        for(var i=0; i<INREC.cache.users.length; i++){
            if(INREC.cache.users[i].email==gitUser.email){
                return i;
            }
        }
        return -1;
    };

    INREC.findCardIndex = function(issueKey) {
        for(var i=0; i<INREC.cache.cards.length; i++){
            if(INREC.cache.cards[i].key==issueKey){
                return i;
            }
        }
        return -1;
    };

    INREC.receiver.on('update_feature_commit', function (response) {
        var issueKey = response.issueKey;
        var commitTime = (new Date().getTime());
        var userIndex = INREC.findUserIndex(response.gitUser);
        if(userIndex == -1) {
            INREC.cache.users.push({
                name : response.gitUser.name,
                email : response.gitUser.email,
                allIssues : []});
            userIndex = INREC.cache.users.length-1;
        }
        //
        var cardIndex = INREC.findCardIndex(issueKey);
        if(cardIndex == -1){
            INREC.cache.cards.push({
            });
            cardIndex = INREC.cache.cards.length-1;
        }
        //
        if(!INREC.cache.users[userIndex].commits){
            INREC.cache.users[userIndex].commits = [];
        }
        INREC.cache.users[userIndex].commits.push({time:commitTime, issueKey : issueKey});
        //
        if(!INREC.cache.cards[cardIndex].commits){
            INREC.cache.cards[cardIndex].commits = [];
        }
        INREC.cache.cards[cardIndex].commits.push({
            time : commitTime,
            issueKey : issueKey,
            user : {name : INREC.cache.users[userIndex].name, email : INREC.cache.users[userIndex].email}
        });
        INREC.cacheSaver.saveCache();
    });

    INREC.receiver.on('update_status', function (response) {
        var userIndex = INREC.findUserIndex(response.gitUser);
        if(userIndex == -1) {
            INREC.cache.users.push({
                name : response.gitUser.name,
                email : response.gitUser.email,
                allIssues : []});
            userIndex = INREC.cache.users.length-1;
        }
        INREC.cache.users[userIndex].status = {
            currentBranch : response.currentBranch,
            currentIssueKey : response.issueKey,
            status : response.data
        };
    });

    INREC.receiver.on('update_issue', function (response) {
        var userIndex = INREC.findUserIndex(response.gitUser);
        if(userIndex == -1) {
            INREC.cache.users.push({
                name : response.gitUser.name,
                email : response.gitUser.email,
                allIssues : []});
            userIndex = INREC.cache.users.length-1;
        }
        //
        var cardIndex = INREC.findCardIndex(response.key);
        if(cardIndex == -1){
            INREC.cache.cards.push({
            });
            cardIndex = INREC.cache.cards.length-1;
        }
        //
        INREC.cache.users[userIndex].issue = { active : true};
        //~
        var key = response.key;
        INREC.cache.users[userIndex].issue.key = response.key;
        INREC.cache.users[userIndex].issue.url = response.url;
        var fields = response.fields;
        if(fields){
            INREC.cache.users[userIndex].issue.cachedAge = fields.cachedAge || 0;
            INREC.cache.users[userIndex].issue.issuetype = fields.issuetype ? fields.issuetype.name || "" : "typeless";
            INREC.cache.users[userIndex].issue.status = fields.status ? fields.status.name || "" : "without any status";
            INREC.cache.users[userIndex].issue.assignee = fields.assignee ? fields.assignee.displayName || "" : "no one";
            INREC.cache.users[userIndex].issue.summary = fields.summary || "";
            INREC.cache.users[userIndex].issue.description = fields.description || "";
            INREC.cache.users[userIndex].issue.description =  INREC.cache.users[userIndex].issue.description.replace(/(?:\r\n|\r|\n)/g, '
');

            INREC.cache.users[userIndex].issue.issueTitle = "A '"+INREC.cache.users[userIndex].issue.issuetype+"'"
            + " issue that is '"+INREC.cache.users[userIndex].issue.status+"'"
            + " assigned to '"+INREC.cache.users[userIndex].issue.assignee+"'";
            //
            var comments = fields.comment.comments;
            INREC.cache.users[userIndex].issue.comments = [];
            for(var i=0; i<comments.length; i++) {
                var c = comments[i];
                var com = {
                    author : c.author.displayName,
                    date : {
                        createdFormatted : INREC.formatDate(new Date(c.created)),
                        updatedFormatted : INREC.formatDate(new Date(c.updated)),
                        created : c.created,
                        updated : c.updated,
                    },
                    concise : "    # author: "
                        + c.author.name  + " created: "
                        + c.created  + " updated: "+c.updated,
                    body : c.body
                };
                INREC.cache.users[userIndex].issue.comments.push(com);
            }
        }

        if(key) {
            var issueIndex = -1;
            for(var i=0; i<INREC.cache.users[userIndex].allIssues.length; i++) {
                if(INREC.cache.users[userIndex].allIssues[i].key == key){
                    issueIndex = i;
                } else{
                    INREC.cache.users[userIndex].allIssues[i].active = false;
                }
            }
            if(issueIndex==-1){
                 INREC.cache.users[userIndex].allIssues.push({});
                 issueIndex =  INREC.cache.users[userIndex].allIssues.length-1;
            }
            INREC.cache.users[userIndex].allIssues[issueIndex] = INREC.createPartialIssue(INREC.cache.users[userIndex].issue);
            INREC.cache.cards[cardIndex] = INREC.createPartialIssue(INREC.cache.users[userIndex].issue, INREC.cache.cards[cardIndex].authors);
            INREC.addAuthorToCard(cardIndex, response.gitUser);
        }

        //~
    });

    INREC.createPartialIssue = function(fullIssue, authors) {
        var partialIssue = {};
        partialIssue.summary = fullIssue.summary;
        partialIssue.assignee = fullIssue.assignee;
        partialIssue.description = fullIssue.description;
        partialIssue.issuetype = fullIssue.issuetype;
        partialIssue.status = fullIssue.status;
        partialIssue.issueTitle = fullIssue.issueTitle;
        partialIssue.key = fullIssue.key;
        partialIssue.comments = fullIssue.comments;
        partialIssue.authors = authors;
        return partialIssue;
    };

    INREC.addAuthorToCard = function(cardIndex, gitUser) {
        if(!INREC.cache.cards[cardIndex].authors) {
            INREC.cache.cards[cardIndex].authors = [];
        }

        var authors = INREC.cache.cards[cardIndex].authors;
        for(var i=0; i<authors.length; i++) {
            console.log(authors[i].email, gitUser.email);
            if(authors[i].email == gitUser.email){
                return;
            }
        }
        INREC.cache.cards[cardIndex].authors.push(gitUser);
    };
    return INREC;
}<commit_msg>NIT-10 authors not overwritten. smaller issues<commit_after>module.exports = function(nettings){
    var INREC = {};
    INREC.cache = {};
    INREC.cache.users = [];
    INREC.cache.cards = [];
    INREC.receiver = {eventMap:{}};
    INREC.receiver.on = function(eventKey, action){
        INREC.receiver.eventMap[eventKey] = action;
    };

    // +++++++++++
    // +++++++++++
    // +++++++++++
    INREC.cacheSaver = { fs : require('fs') };
    INREC.cacheSaver.cacheDir = __dirname + "/../cache/" + nettings.projectKey;
    INREC.cacheSaver.cacheFilePath = INREC.cacheSaver.cacheDir + "/cache.json";

    INREC.cacheSaver.mkDir = function(dir){
        try {
            INREC.cacheSaver.fs.mkdirSync(dir);
        } catch(e){
            if(e.code !== "EEXIST"){
                console.log(e);
            }
        }
    };

    INREC.cacheSaver.saveCache = function(){
        console.log("_______Saving cache");
        INREC.cacheSaver.mkDir(INREC.cacheSaver.cacheDir);
        INREC.cacheSaver.fs.writeFileSync(INREC.cacheSaver.cacheFilePath, JSON.stringify(INREC.cache, 0, 4));
    };
    // +++++++++++
    // +++++++++++
    // +++++++++++

    INREC.cacheSaver.loadCache = function(){
        console.log("_______Loading cache");
        try{
            var filePath = INREC.cacheSaver.cacheFilePath;
            if(!INREC.cacheSaver.fs.existsSync(filePath)) {
                 INREC.cacheSaver.saveCache();
            }
            var contents = INREC.cacheSaver.fs.readFileSync(filePath).toString();
            INREC.cache = JSON.parse(contents);
        } catch(e) {
            console.log(e);
        }
    };

    INREC.pad = function(num, size) {
        var s = num+"";
        while (s.length < size) s = "0" + s;
        return s;
    }

    INREC.formatDate = function(date){
        var df = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear()
         + "  "+INREC.pad(date.getHours(), 2) + ":" + INREC.pad(date.getMinutes(), 2);
        return df;
    };

    INREC.handleEvent = function(eventKey, response) {
        var action = INREC.receiver.eventMap[eventKey];
        action && action(response);
    };

    INREC.findUserIndex = function(gitUser) {
        for(var i=0; i<INREC.cache.users.length; i++){
            if(INREC.cache.users[i].email==gitUser.email){
                return i;
            }
        }
        return -1;
    };

    INREC.findCardIndex = function(issueKey) {
        for(var i=0; i<INREC.cache.cards.length; i++){
            if(INREC.cache.cards[i].key==issueKey){
                return i;
            }
        }
        return -1;
    };

    INREC.receiver.on('update_feature_commit', function (response) {
        var issueKey = response.issueKey;
        var commitTime = (new Date().getTime());
        var userIndex = INREC.findUserIndex(response.gitUser);
        if(userIndex == -1) {
            INREC.cache.users.push({
                name : response.gitUser.name,
                email : response.gitUser.email,
                allIssues : []});
            userIndex = INREC.cache.users.length-1;
        }
        //
        var cardIndex = INREC.findCardIndex(issueKey);
        if(cardIndex == -1){
            INREC.cache.cards.push({
            });
            cardIndex = INREC.cache.cards.length-1;
        }
        //
        if(!INREC.cache.users[userIndex].commits){
            INREC.cache.users[userIndex].commits = [];
        }
        INREC.cache.users[userIndex].commits.push({time:commitTime, issueKey : issueKey});
        //
        if(!INREC.cache.cards[cardIndex].commits){
            INREC.cache.cards[cardIndex].commits = [];
        }
        INREC.cache.cards[cardIndex].commits.push({
            time : commitTime,
            issueKey : issueKey,
            user : {name : INREC.cache.users[userIndex].name, email : INREC.cache.users[userIndex].email}
        });
        INREC.cacheSaver.saveCache();
    });

    INREC.receiver.on('update_status', function (response) {
        var userIndex = INREC.findUserIndex(response.gitUser);
        if(userIndex == -1) {
            INREC.cache.users.push({
                name : response.gitUser.name,
                email : response.gitUser.email,
                allIssues : []});
            userIndex = INREC.cache.users.length-1;
        }
        INREC.cache.users[userIndex].status = {
            currentBranch : response.currentBranch,
            currentIssueKey : response.issueKey,
            status : response.data
        };
    });

    INREC.receiver.on('update_issue', function (response) {
        var userIndex = INREC.findUserIndex(response.gitUser);
        if(userIndex == -1) {
            INREC.cache.users.push({
                name : response.gitUser.name,
                email : response.gitUser.email,
                allIssues : []});
            userIndex = INREC.cache.users.length-1;
        }
        //
        var cardIndex = INREC.findCardIndex(response.key);
        if(cardIndex == -1){
            INREC.cache.cards.push({
            });
            cardIndex = INREC.cache.cards.length-1;
        }
        //
        INREC.cache.users[userIndex].issue = { active : true};
        //~
        var key = response.key;
        INREC.cache.users[userIndex].issue.key = response.key;
        INREC.cache.users[userIndex].issue.url = response.url;
        var fields = response.fields;
        if(fields){
            INREC.cache.users[userIndex].issue.cachedAge = fields.cachedAge || 0;
            INREC.cache.users[userIndex].issue.issuetype = fields.issuetype ? fields.issuetype.name || "" : "typeless";
            INREC.cache.users[userIndex].issue.status = fields.status ? fields.status.name || "" : "without any status";
            INREC.cache.users[userIndex].issue.assignee = fields.assignee ? fields.assignee.displayName || "" : "no one";
            INREC.cache.users[userIndex].issue.summary = fields.summary || "";
            INREC.cache.users[userIndex].issue.description = fields.description || "";
            INREC.cache.users[userIndex].issue.description =  INREC.cache.users[userIndex].issue.description.replace(/(?:\r\n|\r|\n)/g, '
');

            INREC.cache.users[userIndex].issue.issueTitle = "A '"+INREC.cache.users[userIndex].issue.issuetype+"'"
            + " issue that is '"+INREC.cache.users[userIndex].issue.status+"'"
            + " assigned to '"+INREC.cache.users[userIndex].issue.assignee+"'";
            //
            var comments = fields.comment.comments;
            INREC.cache.users[userIndex].issue.comments = [];
            for(var i=0; i<comments.length; i++) {
                var c = comments[i];
                var com = {
                    author : c.author.displayName,
                    date : {
                        createdFormatted : INREC.formatDate(new Date(c.created)),
                        updatedFormatted : INREC.formatDate(new Date(c.updated)),
                        created : c.created,
                        updated : c.updated,
                    },
                    concise : "    # author: "
                        + c.author.name  + " created: "
                        + c.created  + " updated: "+c.updated,
                    body : c.body
                };
                INREC.cache.users[userIndex].issue.comments.push(com);
            }
        }

        if(key) {
            var issueIndex = -1;
            for(var i=0; i<INREC.cache.users[userIndex].allIssues.length; i++) {
                if(INREC.cache.users[userIndex].allIssues[i].key == key){
                    issueIndex = i;
                } else{
                    INREC.cache.users[userIndex].allIssues[i].active = false;
                }
            }
            if(issueIndex==-1){
                 INREC.cache.users[userIndex].allIssues.push({});
                 issueIndex =  INREC.cache.users[userIndex].allIssues.length-1;
            }
            INREC.cache.users[userIndex].allIssues[issueIndex] = INREC.createPartialIssue(INREC.cache.users[userIndex].issue);
            INREC.cache.cards[cardIndex] = INREC.createPartialIssue(INREC.cache.users[userIndex].issue, INREC.cache.cards[cardIndex].authors);
            INREC.addAuthorToCard(cardIndex, response.gitUser);
        }

        //~
    });

    INREC.createPartialIssue = function(fullIssue, authors) {
        var partialIssue = {};
        partialIssue.summary = fullIssue.summary;
        partialIssue.assignee = fullIssue.assignee;
        partialIssue.description = fullIssue.description;
        partialIssue.issuetype = fullIssue.issuetype;
        partialIssue.status = fullIssue.status;
        partialIssue.issueTitle = fullIssue.issueTitle;
        partialIssue.key = fullIssue.key;
        partialIssue.comments = fullIssue.comments;
        partialIssue.authors = authors;
        return partialIssue;
    };

    INREC.addAuthorToCard = function(cardIndex, gitUser) {
        if(!INREC.cache.cards[cardIndex].authors) {
            INREC.cache.cards[cardIndex].authors = [];
        }

        var authors = INREC.cache.cards[cardIndex].authors;
        for(var i=0; i<authors.length; i++) {
            if(authors[i].email == gitUser.email){
                return;
            }
        }
        INREC.cache.cards[cardIndex].authors.push(gitUser);
    };
    return INREC;
}<|endoftext|>


<commit_before>
connector_url = '{{connector_url|safe}}';
<commit_msg>remove safe<commit_after>
connector_url = '{{connector_url}}';
<|endoftext|>


<commit_before>/*
 * Lively 4 Text Editor
 * - based Ace editor
 * - simple load/save/navigate UI, that can be disabled to use elsewhere, e.g. container
 * - updates change indicator while when editting,loading, and saving
 */

import Morph from './Morph.js';
import moment from "src/external/moment.js";
import diff from 'src/external/diff-match-patch.js';

export default class Editor extends Morph {

  initialize() {
    var container = this.get(".container");
    lively.html.registerButtons(this);
    var input = this.get("#filename");
    $(input).keyup(event => {
      if (event.keyCode == 13) { // ENTER
        this.onFilenameEntered(input.value);
      }
    });
    container.dispatchEvent(new Event("initialized"));

    this.currentEditor().on('change', () => {
      this.onTextChanged();
    });
  }

  onTextChanged() {
    this.updateChangeIndicator();
  }

  updateChangeIndicator() {
    if (!this.lastText) return;
    var newText = this.currentEditor().getValue();

    if (newText != this.lastText) {
      this.get("#changeIndicator").style.backgroundColor = "rgb(220,30,30)";
      this.textChanged = true;
    } else {
      this.get("#changeIndicator").style.backgroundColor = "rgb(200,200,200)";
      this.textChanged = false;
    }
  }

  updateOtherEditors() {

  }

  onSaveButton() {
    this.saveFile();
  }

  onLoadButton() {
    this.loadFile();
  }

  onVersionsButton() {
    this.toggleVersions();
  }

  onLoadVersionButton() {
    this.loadFile(this.currentVersion());
  }

  onCloseVersionsButton() {
    this.get("#versionControl").style.display = "none";
  }

  currentVersion() {
    var selection = this.get("#versions").selection;
    if (selection) return selection.version;
  }

  onFilenameEntered() {
    this.loadFile();
  }

  getMountURL() {
    return "https://lively4/sys/fs/mount";
  }

  currentEditor() {
    return this.getSubmorph('juicy-ace-editor').editor;
  }

  getURL() {
    var filename = $(this.getSubmorph('#filename')).val();
    return new URL(filename);
  }

  setURL(urlString) {
    var url = new URL(urlString);
    this.getSubmorph("#filename").value = url.href;
  }

  setText(text) {
    this.lastText = text;
    this.updateChangeIndicator();
    this.currentEditor().setValue(text);
    this.currentEditor().resize();
    this.updateAceMode();
  }

  updateAceMode() {
    var url = this.getURL();
    var editorComp = this.getSubmorph("juicy-ace-editor");
    editorComp.changeModeForFile(url.pathname);
  }

  loadFile(version) {
    var url = this.getURL();
    console.log("load " + url);
    this.updateAceMode();

    fetch(url, {
      headers: {
        fileversion: version
      }
    }).then( response => {
      // remember the commit hash (or similar version information) if loaded resource
      this.lastVersion = response.headers.get("fileversion");
      lively.notify("loaded version " + this.lastVersion);
      return response.text();
    }).then((text) => {
        this.setText(text);
      },
      (err) => {
        lively.notify("Could not load file " + url +"\nMaybe next time you are more lucky?");
      });
  }

  saveFile() {
    var url = this.getURL();
    console.log("save " + url + "!");
    var data = this.currentEditor().getValue();
    var urlString = url.toString();
    if (urlString.match(/\/$/)) {
      return fetch(urlString, {method: 'MKCOL'});
    } else {
      return fetch(urlString, {
        method: 'PUT',
        body: data,
        headers: {
          lastversion:  this.lastVersion
        }
      }).then((response) => {
        console.log("edited file " + url + " written.");
        var newVersion = response.headers.get("fileversion");
        var conflictVersion = response.headers.get("conflictversion");
        if (conflictVersion) {
          return this.solveConflic(conflictVersion);
        }
        if (newVersion) {
          lively.notify("new version " + newVersion);
          this.lastVersion = newVersion;
        }
        lively.notify("saved file", url );
        this.lastText = data;
        this.updateChangeIndicator();
      }, (err) => {
         lively.notify("Could not save file" + url +"\nMaybe next time you are more lucky?");
         throw err;
      }); // don't catch here... so we can get the error later as needed...
    }
  }

  threeWayMerge(a,b,c) {
    var dmp = new diff.diff_match_patch();
    var diff1 = dmp.diff_main(a, b);
    var diff2 = dmp.diff_main(a, c);

    var patch1 = dmp.patch_make(diff1);
    var patch2 = dmp.patch_make(diff2);
    var merge = dmp.patch_apply(patch1.concat(patch2), a);
    // #TODO handle conflicts detected in merge
    return merge[0];
  }

  /*
   * solveConflict
   * use three-way-merge
   */
  async solveConflic(otherVersion) {
    lively.notify("Solve Conflict: " + otherVersion);
    var parentText = this.lastText; //
    var myText = this.currentEditor().getValue(); // data
    // load from conflict version
    var otherText = await fetch(this.getURL(), {
        headers: {fileversion: otherVersion}
      }).then( r => r.text());

    // #TODO do something when actual conflicts occure?
    var mergedText = this.threeWayMerge(parentText, myText, otherText);
    lively.notify("Merged: " + mergedText);
    this.setText(mergedText);
    this.lastVersion = otherVersion;
    this.saveFile();
  }

  hideToolbar() {
    this.getSubmorph("#toolbar").style.display = "none";
  }

  toggleVersions() {
    var versionControl = this.shadowRoot.querySelector("#versionControl");
    if (versionControl.style.display == "block") {
      versionControl.style.display = "none";
    } else {
      versionControl.style.display = "block";
      versionControl.querySelector("#versions").showVersions(this.getURL());
    }
  }

  livelyMigrate(obj) {
    this.setURL(obj.getURL());
    this.loadFile();
  }
}<commit_msg>AUTO-COMMIT templates/lively-editor.js<commit_after>/*
 * Lively 4 Text Editor
 * - based Ace editor
 * - simple load/save/navigate UI, that can be disabled to use elsewhere, e.g. container
 * - updates change indicator while when editting,loading, and saving
 */

import Morph from './Morph.js';
import moment from "src/external/moment.js";
import diff from 'src/external/diff-match-patch.js';

export default class Editor extends Morph {

  initialize() {
    var container = this.get(".container");
    lively.html.registerButtons(this);
    var input = this.get("#filename");
    $(input).keyup(event => {
      if (event.keyCode == 13) { // ENTER
        this.onFilenameEntered(input.value);
      }
    });
    container.dispatchEvent(new Event("initialized"));

    this.currentEditor().on('change', () => {
      this.onTextChanged();
    });
  }

  onTextChanged() {
    this.updateChangeIndicator();
  }

  updateChangeIndicator() {
    if (!this.lastText) return;
    var newText = this.currentEditor().getValue();

    if (newText != this.lastText) {
      this.get("#changeIndicator").style.backgroundColor = "rgb(220,30,30)";
      this.textChanged = true;
    } else {
      this.get("#changeIndicator").style.backgroundColor = "rgb(200,200,200)";
      this.textChanged = false;
    }
  }

  updateOtherEditors() {

    var editors = lively.array(document.querySelectorAll("lively-container::shadow lively-editor, lively-editor"))
    editors[2].textChanged

  }

  onSaveButton() {
    this.saveFile();
  }

  onLoadButton() {
    this.loadFile();
  }

  onVersionsButton() {
    this.toggleVersions();
  }

  onLoadVersionButton() {
    this.loadFile(this.currentVersion());
  }

  onCloseVersionsButton() {
    this.get("#versionControl").style.display = "none";
  }

  currentVersion() {
    var selection = this.get("#versions").selection;
    if (selection) return selection.version;
  }

  onFilenameEntered() {
    this.loadFile();
  }

  getMountURL() {
    return "https://lively4/sys/fs/mount";
  }

  currentEditor() {
    return this.getSubmorph('juicy-ace-editor').editor;
  }

  getURL() {
    var filename = $(this.getSubmorph('#filename')).val();
    return new URL(filename);
  }

  setURL(urlString) {
    var url = new URL(urlString);
    this.getSubmorph("#filename").value = url.href;
  }

  setText(text) {
    this.lastText = text;
    this.updateChangeIndicator();
    this.currentEditor().setValue(text);
    this.currentEditor().resize();
    this.updateAceMode();
  }

  updateAceMode() {
    var url = this.getURL();
    var editorComp = this.getSubmorph("juicy-ace-editor");
    editorComp.changeModeForFile(url.pathname);
  }

  loadFile(version) {
    var url = this.getURL();
    console.log("load " + url);
    this.updateAceMode();

    fetch(url, {
      headers: {
        fileversion: version
      }
    }).then( response => {
      // remember the commit hash (or similar version information) if loaded resource
      this.lastVersion = response.headers.get("fileversion");
      lively.notify("loaded version " + this.lastVersion);
      return response.text();
    }).then((text) => {
        this.setText(text);
      },
      (err) => {
        lively.notify("Could not load file " + url +"\nMaybe next time you are more lucky?");
      });
  }

  saveFile() {
    var url = this.getURL();
    console.log("save " + url + "!");
    var data = this.currentEditor().getValue();
    var urlString = url.toString();
    if (urlString.match(/\/$/)) {
      return fetch(urlString, {method: 'MKCOL'});
    } else {
      return fetch(urlString, {
        method: 'PUT',
        body: data,
        headers: {
          lastversion:  this.lastVersion
        }
      }).then((response) => {
        console.log("edited file " + url + " written.");
        var newVersion = response.headers.get("fileversion");
        var conflictVersion = response.headers.get("conflictversion");
        if (conflictVersion) {
          return this.solveConflic(conflictVersion);
        }
        if (newVersion) {
          lively.notify("new version " + newVersion);
          this.lastVersion = newVersion;
        }
        lively.notify("saved file", url );
        this.lastText = data;
        this.updateChangeIndicator();
        this.updateOtherEditors();
      }, (err) => {
         lively.notify("Could not save file" + url +"\nMaybe next time you are more lucky?");
         throw err;
      }); // don't catch here... so we can get the error later as needed...
    }
  }

  threeWayMerge(a,b,c) {
    var dmp = new diff.diff_match_patch();
    var diff1 = dmp.diff_main(a, b);
    var diff2 = dmp.diff_main(a, c);

    var patch1 = dmp.patch_make(diff1);
    var patch2 = dmp.patch_make(diff2);
    var merge = dmp.patch_apply(patch1.concat(patch2), a);
    // #TODO handle conflicts detected in merge
    return merge[0];
  }

  /*
   * solveConflict
   * use three-way-merge
   */
  async solveConflic(otherVersion) {
    lively.notify("Solve Conflict: " + otherVersion);
    var parentText = this.lastText; //
    var myText = this.currentEditor().getValue(); // data
    // load from conflict version
    var otherText = await fetch(this.getURL(), {
        headers: {fileversion: otherVersion}
      }).then( r => r.text());

    // #TODO do something when actual conflicts occure?
    var mergedText = this.threeWayMerge(parentText, myText, otherText);
    lively.notify("Merged: " + mergedText);
    this.setText(mergedText);
    this.lastVersion = otherVersion;
    this.saveFile();
  }

  hideToolbar() {
    this.getSubmorph("#toolbar").style.display = "none";
  }

  toggleVersions() {
    var versionControl = this.shadowRoot.querySelector("#versionControl");
    if (versionControl.style.display == "block") {
      versionControl.style.display = "none";
    } else {
      versionControl.style.display = "block";
      versionControl.querySelector("#versions").showVersions(this.getURL());
    }
  }

  livelyMigrate(obj) {
    this.setURL(obj.getURL());
    this.loadFile();
  }
}<|endoftext|>


<commit_before>function module(stdlib) {
    "use asm"
    function foo() {
        var abc;
    }
}
<commit_msg>adding a copyright notice<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function module(stdlib) {
    "use asm"
    function foo() {
        var abc;
    }
}
<|endoftext|>


<commit_before>var path  = require('path');
var spawn = require('child_process').spawn;

process.nextTick(run);

function installNpmModule(name, version, callback) {
  if (getPackageVersion(name) === version) {
    callback();
    return;
  }

  var spec  = name + '@' + version;
  var args  = ['install', '--silent', '--no-save', spec];
  var child = spawn('npm', args, {
    cwd   : path.join(__dirname, '..'),
    shell : true
  });

  child.stderr.resume();
  child.stdout.resume();

  child.on('exit', function (code) {
    var err = null;

    if (code !== 0) {
      err = new Error('npm install ' + spec + ' failed with exit code ' + code);
    }

    callback(err);
  });
}

function getNycVersion() {
  var nodeVersion = process.version.replace(/^v/, '').split('.')
    .map(function (s) { return Number(s); });

  if (nodeVersion[0] === 0 && nodeVersion[1] < 10) {
    return undefined;
  } else if (nodeVersion[0] < 4) {
    return '10.3.2';
  } else if (nodeVersion[0] < 6) {
    return '11.9.0';
  } else {
    return '13.1.0';
  }
}

function getPackageVersion(name) {
  try {
    return require(name + '/package').version;
  } catch (e) {
    return undefined;
  }
}

function run() {
  var args    = process.argv.slice(2);
  var cmd     = null;
  var divider = args.indexOf('--');
  var version = getNycVersion();

  if (divider !== -1) {
    cmd  = args.slice(divider + 1);
    args = args.slice(0, divider);
  }

  if (!version && args.indexOf('--nyc-optional') === -1) {
    console.error('nyc does not support current Node.js version');
    process.exit(1);
  } else if (version) {
    installNpmModule('nyc', version, function (err) {
      if (err) {
        console.error(err.message);
        process.exit(1);
      } else if (cmd) {
        runCmd('nyc', args.concat(cmd));
      }
    });
  } else if (cmd) {
    runCmd(cmd[0], cmd.slice(1));
  }
}

function runCmd(cmd, args) {
  var child = spawn(cmd, args, {
    cwd   : path.join(__dirname, '..'),
    shell : true
  });

  child.stderr.pipe(process.stderr, {end: false});
  child.stdout.pipe(process.stdout, {end: false});

  child.on('exit', function (code) {
    process.exit(code);
  });
}
<commit_msg>build: nyc@13.2.0<commit_after>var path  = require('path');
var spawn = require('child_process').spawn;

process.nextTick(run);

function installNpmModule(name, version, callback) {
  if (getPackageVersion(name) === version) {
    callback();
    return;
  }

  var spec  = name + '@' + version;
  var args  = ['install', '--silent', '--no-save', spec];
  var child = spawn('npm', args, {
    cwd   : path.join(__dirname, '..'),
    shell : true
  });

  child.stderr.resume();
  child.stdout.resume();

  child.on('exit', function (code) {
    var err = null;

    if (code !== 0) {
      err = new Error('npm install ' + spec + ' failed with exit code ' + code);
    }

    callback(err);
  });
}

function getNycVersion() {
  var nodeVersion = process.version.replace(/^v/, '').split('.')
    .map(function (s) { return Number(s); });

  if (nodeVersion[0] === 0 && nodeVersion[1] < 10) {
    return undefined;
  } else if (nodeVersion[0] < 4) {
    return '10.3.2';
  } else if (nodeVersion[0] < 6) {
    return '11.9.0';
  } else {
    return '13.2.0';
  }
}

function getPackageVersion(name) {
  try {
    return require(name + '/package').version;
  } catch (e) {
    return undefined;
  }
}

function run() {
  var args    = process.argv.slice(2);
  var cmd     = null;
  var divider = args.indexOf('--');
  var version = getNycVersion();

  if (divider !== -1) {
    cmd  = args.slice(divider + 1);
    args = args.slice(0, divider);
  }

  if (!version && args.indexOf('--nyc-optional') === -1) {
    console.error('nyc does not support current Node.js version');
    process.exit(1);
  } else if (version) {
    installNpmModule('nyc', version, function (err) {
      if (err) {
        console.error(err.message);
        process.exit(1);
      } else if (cmd) {
        runCmd('nyc', args.concat(cmd));
      }
    });
  } else if (cmd) {
    runCmd(cmd[0], cmd.slice(1));
  }
}

function runCmd(cmd, args) {
  var child = spawn(cmd, args, {
    cwd   : path.join(__dirname, '..'),
    shell : true
  });

  child.stderr.pipe(process.stderr, {end: false});
  child.stdout.pipe(process.stdout, {end: false});

  child.on('exit', function (code) {
    process.exit(code);
  });
}
<|endoftext|>


<commit_before>/*
 * prune.js - ilib tool to remove properties from lower-level json files
 * when the values of those lower-level properties match the parent.
 *
 * Copyright © 2014, JEDLSoft
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * This code is intended to be run under node.js
 */
var fs = require('fs');
var util = require('util');
var common = require('./common');

function usage() {
	util.print("Usage: prune.js [-h] [locale_data_dir]\n" +
		"Prune json files to remove extraneous properties.\n\n" +
		"-h or --help\n" +
		"  this help\n" +
		"locale_data_dir\n" +
		'  the top level of the ilib locale data directory. Default "."\n');
	process.exit(1);
}

localeDirName = process.argv[2] || ".";
util.print("locale dir: " + localeDirName + "\n");
fs.exists(localeDirName, function (exists) {
	if (!exists) {
		util.print("Could not access locale data directory " + localeDirName);
		usage();
	}
});

function walk(dir, locale) {
	var results = [];
	var list = fs.readdirSync(dir);
	var merged = {};
	list.forEach(function (file) {
		var path = dir + '/' + file;
		var stat = fs.statSync(path);
		if (stat && stat.isDirectory()) {
			walk(path, (locale && locale !== "und" && locale !== '.') ? locale + "-" + file : file);
		} else {
			var obj = {};
			if (path.match(/[a-z]+\.json/)) {
				try {
					var data = fs.readFileSync(path, 'utf8');
					if (data.length > 0) {
						obj = JSON.parse(data);
						merged = common.merge(merged, obj);
					}
				} catch (err) {
					util.print("File " + path + " is not readable or does not contain valid JSON.\n");
					util.print(err + "\n");
				}
			}
		}
	});

	var path = dir;
	if (!common.isEmpty(merged)) {
		if (merged.generated) {
			delete merged.generated;
		}
		merged.locale = locale;
		fs.writeFileSync(path + "/localeinfo.json", JSON.stringify(merged, true, 4), 'utf8');
		util.print(path + ": merged *.jf into localeinfo.json\n");
	} else {
		util.print(path + ": nothing to write\n");
	}

	return results;
}

walk(localeDirName, undefined);
<commit_msg>Checkpoint<commit_after>/*
 * prune.js - ilib tool to remove properties from lower-level json files
 * when the values of those lower-level properties match the parent.
 *
 * Copyright © 2014, JEDLSoft
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * This code is intended to be run under node.js
 */
var fs = require('fs');
var util = require('util');
var common = require('./common');
var path = require('path');

function usage() {
	util.print("Usage: prune.js [-h] [locale_data_dir]\n" +
		"Prune json files to remove extraneous properties.\n\n" +
		"-h or --help\n" +
		"  this help\n" +
		"locale_data_dir\n" +
		'  the top level of the ilib locale data directory. Default "."\n');
	process.exit(1);
}

localeDirName = process.argv[2] || ".";
util.print("locale dir: " + localeDirName + "\n");
if (!fs.existsSync(localeDirName)) {
	util.print("Could not access locale data directory " + localeDirName);
	usage();
}

function readJson(path) {
	if (!fs.existsSync(path)) {
		return undefined;
	}
	var data = fs.readFileSync(path);
	if (data.length > 0) {
		return JSON.parse(data);
	}
	return {};
}

var likelyLocaleFileName = path.join(localeDirName, "likelylocales.json");
var likelylocales = {};

var temp = readJson(likelyLocaleFileName);
if (temp) {
	for (var part in temp) {
		if (part && temp[part]) {
			likelylocale[part] = new common.Locale(temp[part]);
		}
	}
}

var fileTypes = [
	"address.json",
	"calendar.jf",
	"clock.jf",
	"countries.json",
	"ctrynames.json",
	"currency.jf",
	"currency.json",
	"dateformats.json",
	"delimiters.jf",
	"empty.jf",
	"firstdayofweek.jf",
	"langname.jf",
	"name.json",
	"nativecountries.json",
	"numfmt.jf",
	"papersizes.jf",
	"phoneres.json",
	"plurals.json",
	"scripts.jf",
	"sysres.json",
	"timezone.jf",
	"unitfmt.json",
	"units.jf"
];

function walk(dir, locale) {
	var results = [];
	var list = fs.readdirSync(dir);
	var merged = {};
	var thisloc = new common.Locale(locale);

	// special case -- und is the undetermined language, so leave it off
	var lookupSpec = (thisloc.getLanguage() === 'und') ? thisloc.getRegion() : thisloc.getSpec();

	fileTypes.forEach(function (type) {
		var json;
		var thispath = path.join(dir, type);
		if (!fs.existsSync(thispath)) {
			// try to find the base locale's version of the file and use that instead
			var loc;
			loc = likelylocales[lookupSpec];
			if (loc) {
				var filename = path.join(dir, loc.getLanguage(), loc.getRegion(), type);
				if (fs.existsSync(filename)) {
					json = readJson(filename);
				} else {
					filename = path.join(dir, loc.getLanguage(), loc.getScript(), loc.getRegion(), type);
					if (fs.existsSync(filename)) {
						json = readJson(filename);
					} else {
						filename = path.join(dir, loc.getLanguage(), loc.getScript(), type);
						if (fs.existsSync(filename)) {
							json = readJson(filename);
						}
					}
				}
			}
		}
	});

	list.forEach(function (file) {
		var thispath = dir + '/' + file;
		var stat = fs.statSync(thispath);
		if (stat && stat.isDirectory()) {
			walk(thispath, (locale && locale !== "und" && locale !== '.') ? locale + "-" + file : file);
		} else {
			var obj = {};
			if (fileTypes.indexOf(file) !== -1) {
				try {

				} catch (err) {
					util.print("File " + thispath + " is not readable or does not contain valid JSON.\n");
					util.print(err + "\n");
				}
			}
		}
	});

	var thispath = dir;
	if (!common.isEmpty(merged)) {
		if (merged.generated) {
			delete merged.generated;
		}
		merged.locale = locale;
		fs.writeFileSync(thispath + "/localeinfo.json", JSON.stringify(merged, true, 4), 'utf8');
		util.print(thispath + ": merged *.jf into localeinfo.json\n");
	} else {
		util.print(thispath + ": nothing to write\n");
	}

	return results;
}

walk(localeDirName, undefined);
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Maximum numer of lines to record in the debug log.
// Only the most recent <n> lines are displayed.
var MAX_DEBUG_LOG_SIZE = 1000;
var remoting = chrome.extension.getBackgroundPage().remoting;

// Message id so that we can identify (and ignore) message fade operations for
// old messages.  This starts at 1 and is incremented for each new message.
remoting.messageId = 1;

remoting.scaleToFit = false;

// Default to trying to sandboxed connections.
remoting.connectMethod = 'sandboxed';
remoting.httpXmppProxy =
    'https://chromoting-httpxmpp-oauth2-dev.corp.google.com';

// This executes a poll loop on the server for more Iq packets, and feeds them
// to the plugin.
function feedIq() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', remoting.httpXmppProxy + '/readIq?host_jid=' +
           encodeURIComponent(remoting.hostjid), true);
  xhr.withCredentials = true;
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        addToDebugLog('Receiving Iq: --' + xhr.responseText + '--');
        remoting.plugin.onIq(xhr.responseText);
      }
      if (xhr.status == 200 || xhr.status == 204) {
        window.setTimeout(feedIq, 0);
      } else {
        addToDebugLog('HttpXmpp gateway returned code: ' + xhr.status);
        remoting.plugin.disconnect();
        setClientStateMessage('Failed');
      }
    }
  }
  xhr.send(null);
}

function registerConnection() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', remoting.httpXmppProxy + '/newConnection', true);
  xhr.withCredentials = true;
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        addToDebugLog('Receiving Iq: --' + xhr.responseText + '--');
        var clientjid = xhr.responseText;

        remoting.plugin.sendIq = sendIq;
        remoting.plugin.connect(remoting.hostjid, clientjid,
                                remoting.accessCode);
        // TODO(ajwong): This should just be feedIq();
        window.setTimeout(feedIq, 1000);
      } else {
        addToDebugLog('FailedToConnect: --' + xhr.responseText +
                      '-- (status=' + xhr.status + ')');
        setClientStateMessage('Failed');
      }
    }
  }
  xhr.send('host_jid=' + encodeURIComponent(remoting.hostjid) +
           '&username=' + encodeURIComponent(remoting.username) +
           '&password=' + encodeURIComponent(remoting.oauth2.getAccessToken()));
  setClientStateMessage('Connecting');
}

function sendIq(msg) {
  addToDebugLog('Sending Iq: ' + msg);

  // Extract the top level fields of the Iq packet.
  // TODO(ajwong): Can the plugin just return these fields broken out.
  parser = new DOMParser();
  iqNode = parser.parseFromString(msg, 'text/xml').firstChild;
  id = iqNode.getAttribute('id');
  type = iqNode.getAttribute('type');
  to = iqNode.getAttribute('to');
  serializer = new XMLSerializer();
  payload_xml = serializer.serializeToString(iqNode.firstChild);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', remoting.httpXmppProxy + '/sendIq', true);
  xhr.withCredentials = true;
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('to=' + encodeURIComponent(to) +
           '&payload_xml=' + encodeURIComponent(payload_xml) +
           '&id=' + id + '&type=' + type +
           '&host_jid=' + encodeURIComponent(remoting.hostjid));
}

function init() {
  // Kick off the connection.
  var plugin = document.getElementById('remoting');

  remoting.plugin = plugin;

  // Only allow https connections to the httpXmppProxy.
  if (remoting.httpXmppProxy.search(/^ *https:\/\//) == -1) {
    addToDebugLog('Aborting. httpXmppProxy does not specify https protocol: ' +
                  remoting.httpXmppProxy);
    return;
  }

  // Setup the callback that the plugin will call when the connection status
  // has changes and the UI needs to be updated. It needs to be an object with
  // a 'callback' property that contains the callback function.
  plugin.connectionInfoUpdate = connectionInfoUpdateCallback;
  plugin.debugInfo = debugInfoCallback;
  plugin.desktopSizeUpdate = desktopSizeChanged;
  plugin.loginChallenge = loginChallengeCallback;

  addToDebugLog('Connect as user ' + remoting.username);

  // TODO(garykac): Clean exit if |connect| isn't a function.
  if (typeof plugin.connect === 'function') {
    if (remoting.connectMethod == 'sandboxed') {
      registerConnection();
    } else {
      plugin.connectUnsandboxed(remoting.hostjid, remoting.username,
                                remoting.xmppAuthToken, remoting.accessCode);
    }
  } else {
    addToDebugLog('ERROR: remoting plugin not loaded');
    setClientStateMessage('Plugin not loaded');
  }

}

function toggleDebugLog() {
  debugLog = document.getElementById('debug_log');
  toggleButton = document.getElementById('debug_log_toggle');

  if (!debugLog.style.display || debugLog.style.display == 'none') {
    debugLog.style.display = 'block';
    toggleButton.value = 'Hide Debug Log';
  } else {
    debugLog.style.display = 'none';
    toggleButton.value = 'Show Debug Log';
  }
}

function toggleScaleToFit() {
  remoting.scaleToFit = !remoting.scaleToFit;
  document.getElementById('scale_to_fit_toggle').value =
      remoting.scaleToFit ? 'No scaling' : 'Scale to fit';
  remoting.plugin.setScaleToFit(remoting.scaleToFit);
}

/**
 * This is the callback method that the plugin calls to request username and
 * password for logging into the remote host. For Me2Mom we are pre-authorized
 * so this is a no-op.
 */
function loginChallengeCallback() {
}

/**
 * This is a callback that gets called when the desktop size contained in the
 * the plugin has changed.
 */
function desktopSizeChanged() {
  var width = remoting.plugin.desktopWidth;
  var height = remoting.plugin.desktopHeight;

  addToDebugLog('desktop size changed: ' + width + 'x' + height);
  remoting.plugin.style.width = width + 'px';
  remoting.plugin.style.height = height + 'px';
}

/**
 * This is that callback that the plugin invokes to indicate that the
 * host/client connection status has changed.
 */
function connectionInfoUpdateCallback() {
  var status = remoting.plugin.status;
  var quality = remoting.plugin.quality;

  if (status == remoting.plugin.STATUS_UNKNOWN) {
    setClientStateMessage('');
  } else if (status == remoting.plugin.STATUS_CONNECTING) {
    setClientStateMessage('Connecting as ' + remoting.username);
  } else if (status == remoting.plugin.STATUS_INITIALIZING) {
    setClientStateMessageFade('Initializing connection');
  } else if (status == remoting.plugin.STATUS_CONNECTED) {
    desktopSizeChanged();
    setClientStateMessageFade('Connected', 1000);
    window.setTimeout(updateStatusBarStats, 1000);
  } else if (status == remoting.plugin.STATUS_CLOSED) {
    setClientStateMessage('Closed');
  } else if (status == remoting.plugin.STATUS_FAILED) {
    setClientStateMessage('Failed');
  }
}

/**
 * Show a client message that stays on the screeen until the state changes.
 *
 * @param {string} message The message to display.
 */
function setClientStateMessage(message) {
  // Increment message id to ignore any previous fadeout requests.
  remoting.messageId++;

  // Update the status message.
  var msg = document.getElementById('status_msg');
  msg.innerText = message;
  msg.style.opacity = 1;
  msg.style.display = '';
}

/**
 * Show a client message for the specified amount of time.
 *
 * @param {string} message The message to display.
 * @param {number} duration Milliseconds to show message before fading.
 */
function setClientStateMessageFade(message, duration) {
  setClientStateMessage(message);

  // Set message duration.
  window.setTimeout("fade('status_msg', " + remoting.messageId + ', ' +
                          '100, 10, 200)',
                    duration);
}

/**
 * Fade the specified element.
 * For example, to have element 'foo' fade away over 2 seconds, you could use
 * either:
 *   fade('foo', 100, 10, 200)
 *     - Start at 100%, decrease by 10% each time, wait 200ms between updates.
 *   fade('foo', 100, 5, 100)
 *     - Start at 100%, decrease by 5% each time, wait 100ms between updates.
 *
 * @param {string} name Name of element to fade.
 * @param {number} id The id of the message associated with this fade request.
 * @param {number} val The new opacity value (0-100) for this element.
 * @param {number} delta Amount to adjust the opacity each iteration.
 * @param {number} delay Delay (in ms) to wait between each update.
 */
function fade(name, id, val, delta, delay) {
  // Ignore the fade call if it does not apply to the current message.
  if (id != remoting.messageId) {
    return;
  }

  var e = document.getElementById(name);
  if (e) {
    var newVal = val - delta;
    if (newVal > 0) {
      // Decrease opacity and set timer for next fade event.
      e.style.opacity = newVal / 100;
      window.setTimeout("fade('status_msg', " + id + ', ' + newVal + ', ' +
                              delta + ', ' + delay + ')',
                        delay);
    } else {
      // Completely hide the text and stop fading.
      e.style.opacity = 0;
      e.style.display = 'none';
    }
  }
}

/**
 * This is that callback that the plugin invokes to indicate that there
 * is additional debug log info to display.
 */
function debugInfoCallback(msg) {
  addToDebugLog('plugin: ' + msg);
}

/**
 * Add the given message to the debug log.
 *
 * @param {string} message The debug info to add to the log.
 */
function addToDebugLog(message) {
  var debugLog = document.getElementById('debug_log');

  // Remove lines from top if we've hit our max log size.
  if (debugLog.childNodes.length == MAX_DEBUG_LOG_SIZE) {
    debugLog.removeChild(debugLog.firstChild);
  }

  // Add the new <p> to the end of the debug log.
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(message));
  debugLog.appendChild(p);

  // Scroll to bottom of div
  debugLog.scrollTop = debugLog.scrollHeight;
}

function updateStatusBarStats() {
  if (remoting.plugin.status != remoting.plugin.STATUS_CONNECTED)
    return;
  var videoBandwidth = remoting.plugin.videoBandwidth;
  var videoCaptureLatency = remoting.plugin.videoCaptureLatency;
  var videoEncodeLatency = remoting.plugin.videoEncodeLatency;
  var videoDecodeLatency = remoting.plugin.videoDecodeLatency;
  var videoRenderLatency = remoting.plugin.videoRenderLatency;

  setClientStateMessage(
      'Video stats: bandwidth: ' + videoBandwidth.toFixed(2) + 'Kbps' +
      ', Latency: capture: ' + videoCaptureLatency.toFixed(2) + 'ms' +
      ', encode: ' + videoEncodeLatency.toFixed(2) + 'ms' +
      ', decode: ' + videoDecodeLatency.toFixed(2) + 'ms' +
      ', render: ' + videoRenderLatency.toFixed(2) + 'ms');

  // Update the stats once per second.
  window.setTimeout('updateStatusBarStats()', 1000);
}
<commit_msg>Get remoting units working correctly.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Maximum numer of lines to record in the debug log.
// Only the most recent <n> lines are displayed.
var MAX_DEBUG_LOG_SIZE = 1000;
var remoting = chrome.extension.getBackgroundPage().remoting;

// Message id so that we can identify (and ignore) message fade operations for
// old messages.  This starts at 1 and is incremented for each new message.
remoting.messageId = 1;

remoting.scaleToFit = false;

// Default to trying to sandboxed connections.
remoting.connectMethod = 'sandboxed';
remoting.httpXmppProxy =
    'https://chromoting-httpxmpp-oauth2-dev.corp.google.com';

// This executes a poll loop on the server for more Iq packets, and feeds them
// to the plugin.
function feedIq() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', remoting.httpXmppProxy + '/readIq?host_jid=' +
           encodeURIComponent(remoting.hostjid), true);
  xhr.withCredentials = true;
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        addToDebugLog('Receiving Iq: --' + xhr.responseText + '--');
        remoting.plugin.onIq(xhr.responseText);
      }
      if (xhr.status == 200 || xhr.status == 204) {
        window.setTimeout(feedIq, 0);
      } else {
        addToDebugLog('HttpXmpp gateway returned code: ' + xhr.status);
        remoting.plugin.disconnect();
        setClientStateMessage('Failed');
      }
    }
  }
  xhr.send(null);
}

function registerConnection() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', remoting.httpXmppProxy + '/newConnection', true);
  xhr.withCredentials = true;
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        addToDebugLog('Receiving Iq: --' + xhr.responseText + '--');
        var clientjid = xhr.responseText;

        remoting.plugin.sendIq = sendIq;
        remoting.plugin.connect(remoting.hostjid, clientjid,
                                remoting.accessCode);
        // TODO(ajwong): This should just be feedIq();
        window.setTimeout(feedIq, 1000);
      } else {
        addToDebugLog('FailedToConnect: --' + xhr.responseText +
                      '-- (status=' + xhr.status + ')');
        setClientStateMessage('Failed');
      }
    }
  }
  xhr.send('host_jid=' + encodeURIComponent(remoting.hostjid) +
           '&username=' + encodeURIComponent(remoting.username) +
           '&password=' + encodeURIComponent(remoting.oauth2.getAccessToken()));
  setClientStateMessage('Connecting');
}

function sendIq(msg) {
  addToDebugLog('Sending Iq: ' + msg);

  // Extract the top level fields of the Iq packet.
  // TODO(ajwong): Can the plugin just return these fields broken out.
  parser = new DOMParser();
  iqNode = parser.parseFromString(msg, 'text/xml').firstChild;
  id = iqNode.getAttribute('id');
  type = iqNode.getAttribute('type');
  to = iqNode.getAttribute('to');
  serializer = new XMLSerializer();
  payload_xml = serializer.serializeToString(iqNode.firstChild);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', remoting.httpXmppProxy + '/sendIq', true);
  xhr.withCredentials = true;
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('to=' + encodeURIComponent(to) +
           '&payload_xml=' + encodeURIComponent(payload_xml) +
           '&id=' + id + '&type=' + type +
           '&host_jid=' + encodeURIComponent(remoting.hostjid));
}

function init() {
  // Kick off the connection.
  var plugin = document.getElementById('remoting');

  remoting.plugin = plugin;

  // Only allow https connections to the httpXmppProxy.
  if (remoting.httpXmppProxy.search(/^ *https:\/\//) == -1) {
    addToDebugLog('Aborting. httpXmppProxy does not specify https protocol: ' +
                  remoting.httpXmppProxy);
    return;
  }

  // Setup the callback that the plugin will call when the connection status
  // has changes and the UI needs to be updated. It needs to be an object with
  // a 'callback' property that contains the callback function.
  plugin.connectionInfoUpdate = connectionInfoUpdateCallback;
  plugin.debugInfo = debugInfoCallback;
  plugin.desktopSizeUpdate = desktopSizeChanged;
  plugin.loginChallenge = loginChallengeCallback;

  addToDebugLog('Connect as user ' + remoting.username);

  // TODO(garykac): Clean exit if |connect| isn't a function.
  if (typeof plugin.connect === 'function') {
    if (remoting.connectMethod == 'sandboxed') {
      registerConnection();
    } else {
      plugin.connectUnsandboxed(remoting.hostjid, remoting.username,
                                remoting.xmppAuthToken, remoting.accessCode);
    }
  } else {
    addToDebugLog('ERROR: remoting plugin not loaded');
    setClientStateMessage('Plugin not loaded');
  }

}

function toggleDebugLog() {
  debugLog = document.getElementById('debug_log');
  toggleButton = document.getElementById('debug_log_toggle');

  if (!debugLog.style.display || debugLog.style.display == 'none') {
    debugLog.style.display = 'block';
    toggleButton.value = 'Hide Debug Log';
  } else {
    debugLog.style.display = 'none';
    toggleButton.value = 'Show Debug Log';
  }
}

function toggleScaleToFit() {
  remoting.scaleToFit = !remoting.scaleToFit;
  document.getElementById('scale_to_fit_toggle').value =
      remoting.scaleToFit ? 'No scaling' : 'Scale to fit';
  remoting.plugin.setScaleToFit(remoting.scaleToFit);
}

/**
 * This is the callback method that the plugin calls to request username and
 * password for logging into the remote host. For Me2Mom we are pre-authorized
 * so this is a no-op.
 */
function loginChallengeCallback() {
}

/**
 * This is a callback that gets called when the desktop size contained in the
 * the plugin has changed.
 */
function desktopSizeChanged() {
  var width = remoting.plugin.desktopWidth;
  var height = remoting.plugin.desktopHeight;

  addToDebugLog('desktop size changed: ' + width + 'x' + height);
  remoting.plugin.style.width = width + 'px';
  remoting.plugin.style.height = height + 'px';
}

/**
 * This is that callback that the plugin invokes to indicate that the
 * host/client connection status has changed.
 */
function connectionInfoUpdateCallback() {
  var status = remoting.plugin.status;
  var quality = remoting.plugin.quality;

  if (status == remoting.plugin.STATUS_UNKNOWN) {
    setClientStateMessage('');
  } else if (status == remoting.plugin.STATUS_CONNECTING) {
    setClientStateMessage('Connecting as ' + remoting.username);
  } else if (status == remoting.plugin.STATUS_INITIALIZING) {
    setClientStateMessageFade('Initializing connection');
  } else if (status == remoting.plugin.STATUS_CONNECTED) {
    desktopSizeChanged();
    setClientStateMessageFade('Connected', 1000);
    window.setTimeout(updateStatusBarStats, 1000);
  } else if (status == remoting.plugin.STATUS_CLOSED) {
    setClientStateMessage('Closed');
  } else if (status == remoting.plugin.STATUS_FAILED) {
    setClientStateMessage('Failed');
  }
}

/**
 * Show a client message that stays on the screeen until the state changes.
 *
 * @param {string} message The message to display.
 */
function setClientStateMessage(message) {
  // Increment message id to ignore any previous fadeout requests.
  remoting.messageId++;

  // Update the status message.
  var msg = document.getElementById('status_msg');
  msg.innerText = message;
  msg.style.opacity = 1;
  msg.style.display = '';
}

/**
 * Show a client message for the specified amount of time.
 *
 * @param {string} message The message to display.
 * @param {number} duration Milliseconds to show message before fading.
 */
function setClientStateMessageFade(message, duration) {
  setClientStateMessage(message);

  // Set message duration.
  window.setTimeout("fade('status_msg', " + remoting.messageId + ', ' +
                          '100, 10, 200)',
                    duration);
}

/**
 * Fade the specified element.
 * For example, to have element 'foo' fade away over 2 seconds, you could use
 * either:
 *   fade('foo', 100, 10, 200)
 *     - Start at 100%, decrease by 10% each time, wait 200ms between updates.
 *   fade('foo', 100, 5, 100)
 *     - Start at 100%, decrease by 5% each time, wait 100ms between updates.
 *
 * @param {string} name Name of element to fade.
 * @param {number} id The id of the message associated with this fade request.
 * @param {number} val The new opacity value (0-100) for this element.
 * @param {number} delta Amount to adjust the opacity each iteration.
 * @param {number} delay Delay (in ms) to wait between each update.
 */
function fade(name, id, val, delta, delay) {
  // Ignore the fade call if it does not apply to the current message.
  if (id != remoting.messageId) {
    return;
  }

  var e = document.getElementById(name);
  if (e) {
    var newVal = val - delta;
    if (newVal > 0) {
      // Decrease opacity and set timer for next fade event.
      e.style.opacity = newVal / 100;
      window.setTimeout("fade('status_msg', " + id + ', ' + newVal + ', ' +
                              delta + ', ' + delay + ')',
                        delay);
    } else {
      // Completely hide the text and stop fading.
      e.style.opacity = 0;
      e.style.display = 'none';
    }
  }
}

/**
 * This is that callback that the plugin invokes to indicate that there
 * is additional debug log info to display.
 */
function debugInfoCallback(msg) {
  addToDebugLog('plugin: ' + msg);
}

/**
 * Add the given message to the debug log.
 *
 * @param {string} message The debug info to add to the log.
 */
function addToDebugLog(message) {
  var debugLog = document.getElementById('debug_log');

  // Remove lines from top if we've hit our max log size.
  if (debugLog.childNodes.length == MAX_DEBUG_LOG_SIZE) {
    debugLog.removeChild(debugLog.firstChild);
  }

  // Add the new <p> to the end of the debug log.
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(message));
  debugLog.appendChild(p);

  // Scroll to bottom of div
  debugLog.scrollTop = debugLog.scrollHeight;
}

function updateStatusBarStats() {
  if (remoting.plugin.status != remoting.plugin.STATUS_CONNECTED)
    return;
  var videoBandwidth = remoting.plugin.videoBandwidth;
  var videoCaptureLatency = remoting.plugin.videoCaptureLatency;
  var videoEncodeLatency = remoting.plugin.videoEncodeLatency;
  var videoDecodeLatency = remoting.plugin.videoDecodeLatency;
  var videoRenderLatency = remoting.plugin.videoRenderLatency;

  var units = '';
  if (videoBandwidth < 1024) {
    units = 'Bps';
  } else if (videoBandwidth < 1048576) {
    units = 'KBps';
    videoBandwidth = videoBandwidth / 1024;
  } else if (videoBandwidth < 1073741824) {
    units = 'MBps';
    videoBandwidth = videoBandwidth / 1048576;
  } else {
    units = 'GBps';
    videoBandwidth = videoBandwidth / 1073741824;
  }

  setClientStateMessage(
      'Video stats: bandwidth: ' + videoBandwidth.toFixed(2) + units +
      ', Latency: capture: ' + videoCaptureLatency.toFixed(2) + 'ms' +
      ', encode: ' + videoEncodeLatency.toFixed(2) + 'ms' +
      ', decode: ' + videoDecodeLatency.toFixed(2) + 'ms' +
      ', render: ' + videoRenderLatency.toFixed(2) + 'ms');

  // Update the stats once per second.
  window.setTimeout('updateStatusBarStats()', 1000);
}
<|endoftext|>


<commit_before>
var IMAGES = new Array(0);

var title = $('').attr('id', 'title')
                     .attr('href', "http://github.com/givanse/cr24Sauce")
                     .attr('target', '_blank')
                     .html('
cr24Sauce
');
IMAGES.push(title);

function hasURL(string) {
    var re = /(url\()(.*)(\))/;
    var array = re.exec(string);
    if(array)
        return array[2];

    return false;
}

function storeImage(url) {
    if(! url)
        return;

    var imgWrap = $('
').attr('class', 'imageWrap');

    var img = $('').attr('class', 'hiddenImage')
                         .attr('src', url)
                         .appendTo(imgWrap);

    var imageOverlay = $('
').attr('class', 'imageOverlay')
                                  .html('Size:
')
                                  .appendTo(imgWrap);

    var openLink = $('').attr('href', url)
                              .attr('target', '_blank')
                              .html('open')
                              .appendTo(imageOverlay);

    IMAGES.push(imgWrap);
}

function findDivImages(div) {
    if($(div).attr('class') == 'spaceball') /* Flickr mask. */
        return;

    var background = $(div).css('background');
    var url = hasURL(background);
    storeImage(url);
}

function findImgImages(img) {
    var url = $(img).attr('src');
    storeImage(url);
}

$(document).ready(function() {
    console.log('processing images');
    /* google.com */
    $('div').each(function(index, div) {
        findDivImages(div);
    });
    /* flickr.com */
    $('div#allsizes-photo img').each(function(index, img) {
        findImgImages(img);
    });

    var imagesPanel = $('
').attr('id', 'imagesPanel').html(IMAGES);
    $(document.body).append(imagesPanel);
});

/* EOF */
<commit_msg>show image size<commit_after>
var IMAGES = new Array(0);

var title = $('').attr('id', 'title')
                     .attr('href', "http://github.com/givanse/cr24Sauce")
                     .attr('target', '_blank')
                     .html('
cr24Sauce
');
IMAGES.push(title);

/******************************************************************************/

function getImageSize(url, imageOverlay) {
    var image = new Image();
    image.name = url;
    image.onload = function() {
            var size = this.width + 'x' + this.height;
            imageOverlay.append('
Size: ' + size);
        };
    image.src = url;
}

function backgroundHasURL(string) {
    var re = /(url\()(.*)(\))/;
    var array = re.exec(string);
    if(array) {
        var url = array[2];
        return url;
    }

    return false;
}

function storeImage(url) {
    if(! url)
        return;

    var imgWrap = $('
').attr('class', 'imageWrap');

    var img = $('').attr('class', 'hiddenImage')
                         .attr('src', url)
                         .appendTo(imgWrap);

    var imageOverlay = $('
').attr('class', 'imageOverlay')
                                  .appendTo(imgWrap);

    var openLink = $('').attr('href', url)
                              .attr('target', '_blank')
                              .html('open')
                              .appendTo(imageOverlay);

    getImageSize(url, imageOverlay);

    IMAGES.push(imgWrap);
}

function findDivImages(div) {
    if($(div).attr('class') == 'spaceball') /* Flickr mask. */
        return;

    var background = $(div).css('background');
    var url = backgroundHasURL(background);
    storeImage(url);
}

function findImgImages(img) {
    var url = $(img).attr('src');
    storeImage(url);
}

$(document).ready(function() {
    console.log('processing images');
    /* google.com */
    $('div').each(function(index, div) {
        findDivImages(div);
    });
    /* flickr.com */
    $('div#allsizes-photo img').each(function(index, img) {
        findImgImages(img);
    });

    var imagesPanel = $('
').attr('id', 'imagesPanel').html(IMAGES);
    $(document.body).append(imagesPanel);
});

/* EOF */
<|endoftext|>


<commit_before>$(function(){

    $("#bouncyBox").bouncyBoxRegister();

    $("#bounce").click(function(){

        $("#bouncyBox").html("This is a Bouncy Box example!");

        $("#bouncyBox").bouncyBox(500,function(){
            $(this).html("Click this box to dismiss...");
        });

    });

    $("#bouncyBox").click(function(){

        $(this).bouncyBoxDismiss(1000);

    });

});
<commit_msg>demo demo.js<commit_after>$(function(){
    $("#bouncyBox").bouncyBoxRegister();

    $("#bounce").click(function(){

        $("#bouncyBox").html("This is a Bouncy Box example!");

        $("#bouncyBox").bouncyBox(500,function(){
            $(this).html("Click this box to dismiss...");
        });
    });

    $("#bouncyBox").click(function(){

        $(this).bouncyBoxDismiss(1000);

    });

});
<|endoftext|>


<commit_before>/* global describe, it */
"use strict";

const path = require("path");
const webpack = require("../lib/webpack");

describe("NodeTemplatePlugin", () => {
	it("should compile and run a simple module", done => {
		webpack(
			{
				mode: "production",
				context: path.join(__dirname, "fixtures", "nodetest"),
				target: "node",
				output: {
					path: path.join(__dirname, "js", "NodeTemplatePlugin"),
					filename: "result.js",
					chunkFilename: "[hash].result.[id].js",
					library: "abc",
					libraryTarget: "commonjs"
				},
				entry: "./entry"
			},
			(err, stats) => {
				if (err) return err;
				expect(stats.hasErrors()).toBe(false);
				expect(stats.hasWarnings()).toBe(false);
				// eslint-disable-next-line node/no-missing-require
				const result = require("./js/NodeTemplatePlugin/result").abc;
				expect(result.nextTick).toBe(process.nextTick);
				expect(result.fs).toBe(require("fs"));
				result.loadChunk(456, chunk => {
					expect(chunk).toBe(123);
					result.loadChunk(567, chunk => {
						expect(chunk).toEqual({
							a: 1
						});
						done();
					});
				});
			}
		);
	});

	it("should compile and run a simple module in single mode", done => {
		webpack(
			{
				mode: "production",
				context: path.join(__dirname, "fixtures", "nodetest"),
				target: "node",
				output: {
					path: path.join(__dirname, "js", "NodeTemplatePluginSingle"),
					filename: "result2.js",
					chunkFilename: "[hash].result2.[id].js",
					library: "def",
					libraryTarget: "umd",
					auxiliaryComment: "test"
				},
				entry: "./entry",
				plugins: [
					new webpack.optimize.LimitChunkCountPlugin({
						maxChunks: 1
					})
				]
			},
			(err, stats) => {
				if (err) return err;
				expect(stats.hasErrors()).toBe(false);
				// eslint-disable-next-line node/no-missing-require
				const result = require("./js/NodeTemplatePluginSingle/result2");
				expect(result.nextTick).toBe(process.nextTick);
				expect(result.fs).toBe(require("fs"));
				const sameTick = true;
				result.loadChunk(456, chunk => {
					expect(chunk).toBe(123);
					expect(sameTick).toBe(true);
					result.loadChunk(567, chunk => {
						expect(chunk).toEqual({
							a: 1
						});
						done();
					});
				});
			}
		);
	});
});
<commit_msg>increase test timeout<commit_after>/* global describe, it */
"use strict";

const path = require("path");
const webpack = require("../lib/webpack");

describe("NodeTemplatePlugin", () => {
	jest.setTimeout(20000);
	it("should compile and run a simple module", done => {
		webpack(
			{
				mode: "production",
				context: path.join(__dirname, "fixtures", "nodetest"),
				target: "node",
				output: {
					path: path.join(__dirname, "js", "NodeTemplatePlugin"),
					filename: "result.js",
					chunkFilename: "[hash].result.[id].js",
					library: "abc",
					libraryTarget: "commonjs"
				},
				entry: "./entry"
			},
			(err, stats) => {
				if (err) return err;
				expect(stats.hasErrors()).toBe(false);
				expect(stats.hasWarnings()).toBe(false);
				// eslint-disable-next-line node/no-missing-require
				const result = require("./js/NodeTemplatePlugin/result").abc;
				expect(result.nextTick).toBe(process.nextTick);
				expect(result.fs).toBe(require("fs"));
				result.loadChunk(456, chunk => {
					expect(chunk).toBe(123);
					result.loadChunk(567, chunk => {
						expect(chunk).toEqual({
							a: 1
						});
						done();
					});
				});
			}
		);
	});

	it("should compile and run a simple module in single mode", done => {
		webpack(
			{
				mode: "production",
				context: path.join(__dirname, "fixtures", "nodetest"),
				target: "node",
				output: {
					path: path.join(__dirname, "js", "NodeTemplatePluginSingle"),
					filename: "result2.js",
					chunkFilename: "[hash].result2.[id].js",
					library: "def",
					libraryTarget: "umd",
					auxiliaryComment: "test"
				},
				entry: "./entry",
				plugins: [
					new webpack.optimize.LimitChunkCountPlugin({
						maxChunks: 1
					})
				]
			},
			(err, stats) => {
				if (err) return err;
				expect(stats.hasErrors()).toBe(false);
				// eslint-disable-next-line node/no-missing-require
				const result = require("./js/NodeTemplatePluginSingle/result2");
				expect(result.nextTick).toBe(process.nextTick);
				expect(result.fs).toBe(require("fs"));
				const sameTick = true;
				result.loadChunk(456, chunk => {
					expect(chunk).toBe(123);
					expect(sameTick).toBe(true);
					result.loadChunk(567, chunk => {
						expect(chunk).toEqual({
							a: 1
						});
						done();
					});
				});
			}
		);
	});
});
<|endoftext|>


<commit_before>const {desktopCapturer, screen, shell} = require('electron')

const fs = require('fs')
const os = require('os')
const path = require('path')

const screenshot = document.getElementById('screen-shot')
const screenshotMsg = document.getElementById('screenshot-path')

screenshot.addEventListener('click', (event) => {
  screenshotMsg.textContent = 'Gathering screens...'
  const thumbSize = determineScreenShotSize()
  let options = { types: ['screen'], thumbnailSize: thumbSize }

  desktopCapturer.getSources(options, (error, sources) => {
    if (error) return console.log(error)

    sources.forEach((source) => {
      if (source.name === 'Entire screen' || source.name === 'Screen 1') {
        const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')

        fs.writeFile(screenshotPath, source.thumbnail.toPNG(), (error) => {
          if (error) return console.log(error)
          shell.openExternal(`file://${screenshotPath}`)

          const message = `Saved screenshot to: ${screenshotPath}`
          screenshotMsg.textContent = message
        })
      }
    })
  })
})

function determineScreenShotSize () {
  const screenSize = screen.getPrimaryDisplay().workAreaSize
  const maxDimension = Math.max(screenSize.width, screenSize.height)
  return {
    width: maxDimension * window.devicePixelRatio,
    height: maxDimension * window.devicePixelRatio
  }
}
<commit_msg>fix: case error in desktop capturer demo (#447)<commit_after>const {desktopCapturer, screen, shell} = require('electron')

const fs = require('fs')
const os = require('os')
const path = require('path')

const screenshot = document.getElementById('screen-shot')
const screenshotMsg = document.getElementById('screenshot-path')

screenshot.addEventListener('click', (event) => {
  screenshotMsg.textContent = 'Gathering screens...'
  const thumbSize = determineScreenShotSize()
  let options = { types: ['screen'], thumbnailSize: thumbSize }

  desktopCapturer.getSources(options, (error, sources) => {
    if (error) return console.log(error)

    sources.forEach((source) => {
      if (source.name === 'Entire Screen' || source.name === 'Screen 1') {
        const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')

        fs.writeFile(screenshotPath, source.thumbnail.toPNG(), (error) => {
          if (error) return console.log(error)
          shell.openExternal(`file://${screenshotPath}`)

          const message = `Saved screenshot to: ${screenshotPath}`
          screenshotMsg.textContent = message
        })
      }
    })
  })
})

function determineScreenShotSize () {
  const screenSize = screen.getPrimaryDisplay().workAreaSize
  const maxDimension = Math.max(screenSize.width, screenSize.height)
  return {
    width: maxDimension * window.devicePixelRatio,
    height: maxDimension * window.devicePixelRatio
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { Panel, FormGroup, ControlLabel, Radio, Button } from 'react-bootstrap';
import AppointmentFormLocation from'./AppointmentFormLocation';
import MdLocationSearching from 'react-icons/lib/md/location-searching';

class AppointmentFormDirections extends Component {
  geolocation() {
    if ('geolocation' in navigator) {
      this.props.handleOriginChange(new google.maps.LatLng(position.coords.latitude, position.coords.longitude))
    } else {
      alert('Geolocation is not currently available')
    }
  }
  render() {
    return (
      <Panel header="Directions" bsStyle="danger">
        <FormGroup
          className='radio'>

I will travel by:

            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('DRIVING')}
                   inline>
              Driving
            </Radio>
            {' '}
            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('TRANSIT')}
                   inline>
              Public Transit
            </Radio>
            {' '}
            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('BICYCLING')}
                   inline>
              Bicycle
            </Radio>
            {' '}
            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('WALKING')}
                   inline>
              Walking
            </Radio>
        </FormGroup>
        <FormGroup controlId="origin">
          <ControlLabel>Start Location</ControlLabel>
          <AppointmentFormLocation
                updateDestination={this.props.handleOriginChange}
                address={this.props.address}
                placeholder='Start Location' />
        </FormGroup>
        <Button
          bsStyle='link'
          className='geolocation'
          onClick={()=> {this.geolocation}}>
          <MdLocationSearching /> Use Current Location
        </Button>
      </Panel>
    )
  }
}

export default AppointmentFormDirections;<commit_msg>Remove geolocation call<commit_after>import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { Panel, FormGroup, ControlLabel, Radio, Button } from 'react-bootstrap';
import AppointmentFormLocation from'./AppointmentFormLocation';
import MdLocationSearching from 'react-icons/lib/md/location-searching';

class AppointmentFormDirections extends Component {
  render() {
    return (
      <Panel header="Directions" bsStyle="danger">
        <FormGroup
          className='radio'>

I will travel by:

            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('DRIVING')}
                   inline>
              Driving
            </Radio>
            {' '}
            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('TRANSIT')}
                   inline>
              Public Transit
            </Radio>
            {' '}
            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('BICYCLING')}
                   inline>
              Bicycle
            </Radio>
            {' '}
            <Radio name="radioGroup"
                   onClick={() => this.props.travelMode('WALKING')}
                   inline>
              Walking
            </Radio>
        </FormGroup>
        <FormGroup controlId="origin">
          <ControlLabel>Start Location</ControlLabel>
          <AppointmentFormLocation
                updateDestination={this.props.handleOriginChange}
                address={this.props.address}
                placeholder='Start Location' />
        </FormGroup>
        <Button
          bsStyle='link'
          className='geolocation'>
          <MdLocationSearching /> Use Current Location
        </Button>
      </Panel>
    )
  }
}

export default AppointmentFormDirections;<|endoftext|>