<commit_before>"use strict";

var Config = {
  supportsHistory : !!(window.history && history.pushState),
  inMaintenanceMode : false,

  treeName: 'mozilla-central',
  hgBaseURL: "https://hg.mozilla.org/",
  hgURL: "https://hg.mozilla.org/mozilla-central/",
  hgRevURL: "https://hg.mozilla.org/mozilla-central/rev/",
  hgPushlogURL: "https://hg.mozilla.org/mozilla-central/pushloghtml?changeset=",
  showBugURL: "https://bugzilla.mozilla.org/show_bug.cgi?id=",

  // Here be dragons
  versionRE: /^mozilla\d+$/i,
  csetInputRE: /^(tip|[\da-f]{12,40})$/i,
  csetIDRE: /\b([\da-f]{12,40})\b/ig,
  leaveOpenRE: /(?:leave|keep)(?:-|\s+)open/i,
  bugNumRE: /\b(\d{4,7})\b/g,
  strictBugNumRE: /^(\d{4,7})$/,
  mergeRE: /\bmerg(ed?|ing)\b/i,
  backoutRE: /back(ing|ed)?\s*out/i,
  backoutOtherBugRE: /^Bug\s+\d{4,7}.*back(ing|ed)?\s*out.*bug\s+\d{4,7}/i,
  revertRE: /^revert(ing)?/i,
  partialRevertRE: /(?:from|in)(?:\s+(?:rev(?:ision)?|c(?:hange)?set))?\s+([\da-f]{12,40})/i,
  partialTestRE: /test\s+for/i,
  revertRangeRE: /revert(?:ing)?\s+(?:\S+\s+)?to(?:\s+(?:rev(?:ision)?|c(?:hange)set))?\s+([\da-f]{12,40})/i,
  csetRangeRE: /\b([\da-f]{12,40})\s*(?:to|:|-|through)\s*([\da-f]{12,40})/i,
  hgRevRE: /https?:\/\/hg.mozilla.org\/mozilla-central\/rev\//ig,
  hgRevFullRE: /https?:\/\/hg.mozilla.org\/mozilla-central\/rev\/[\da-f]{12}/ig,
  hgPushlogRE: /https?:\/\/hg.mozilla.org\/mozilla-central\/pushloghtml\?changeset=/ig,
  emailRE: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,   // I'm not looking for RFC 822 compliance here!

  // The many ways bug numbers are specified
  bugRE1: /b(?:ug)?=(\d{4,7})\b/i,                       // e.g. b=XXXXXX
  bugRE2: /^fix(?:es)?\s*(?:for\s*)?(\d{4,7})\b/i,                         // Fix is sometimes used as a synonym for bug
  bugRE3: /to\s+fix\s+bug\s+(\d{4,7})/i,
  bugRE4: /\((\d{4,7}), r=/i,                          // e.g. JS-team style (XXXXXX, r=foo)
  bugRE5: /but\s*(\d{4,7})/i,                          // The typo but XXXXXX happens quite often
  bugRE6: /\bb(?:u?g(?:zilla)?)?:?\s*#?(\d{4,7})\b/i,  // The catchall
  bugRE7: /^(\d{4,7})\b/i,                              // e.g. XXXXXX,

  repoMergeRE: "\\s+(&|and|with|<->|<>|-?->|(in|on)?to)\\s+",

  mcSynonyms: ["mozilla-central", "central", "m-c", "mc", "mozilla central"],

  rewriteTrees: {
    "thunderbird-trunk": "comm-central",
    "thunderbird-beta": "comm-beta",
    "thunderbird-esr91": "comm-esr91",
    "thunderbird-esr102": "comm-esr102",
  },

  treeInfo: {
    "mozilla-central": {
      repo: "mozilla-central",
      trackedTree: true,
      synonyms: ["mozilla-central", "central", "m-c", "mc", "mozilla central"]
    },
    "autoland": {
      repo: "integration/autoland",
      trackedTree: false,
      synonyms: ["autoland"]
    },
    "mozilla-beta": {
      repo: "releases/mozilla-beta",
      trackedTree: true,
      synonyms: ["releases/mozilla-beta", "mozilla-beta"]
    },
    "mozilla-release": {
      repo: "releases/mozilla-release",
      trackedTree: true,
      synonyms: ["releases/mozilla-release", "mozilla-release"]
    },
    "mozilla-esr91": {
      repo: "releases/mozilla-esr91",
      trackedTree: true,
      synonyms: ["esr91", "releases/mozilla-esr91", "mozilla-esr91"]
    },
    "mozilla-esr102": {
      repo: "releases/mozilla-esr102",
      trackedTree: true,
      synonyms: ["esr102", "releases/mozilla-esr102", "mozilla-esr102"]
    },
    "ash": {
      repo: "projects/ash",
      trackedTree: false,
      synonyms: ["ash", "projects/ash"]
    },
    "birch": {
      repo: "projects/birch",
      trackedTree: false,
      synonyms: ["birch", "projects/birch"]
    },
    "cedar": {
      repo: "projects/cedar",
      trackedTree: false,
      synonyms: ["projects/cedar", "cedar"]
    },
    "cypress": {
      repo: "projects/cypress",
      trackedTree: false,
      synonyms: ["projects/cypress", "cypress"]
    },
    "date": {
      repo: "projects/date",
      trackedTree: false,
      synonyms: ["projects/date", "date"]
    },
    "elm": {
      repo: "projects/elm",
      trackedTree: false,
      synonyms: ["projects/elm", "elm"]
    },
    "fig": {
      repo: "projects/fig",
      trackedTree: false,
      synonyms: ["projects/fig", "fig"]
    },
    "graphics": {
      repo: "projects/graphics",
      trackedTree: false,
      synonyms: ["projects/graphics", "graphics"]
    },
    "holly": {
      repo: "projects/holly",
      trackedTree: false,
      synonyms: ["projects/holly", "holly"]
    },
    "jamun": {
      repo: "projects/jamun",
      trackedTree: false,
      synonyms: ["projects/jamun", "jamun"]
    },
    "larch": {
      repo: "projects/larch",
      trackedTree: false,
      synonyms: ["projects/larch", "larch"]
    },
    "maple": {
      repo: "projects/maple",
      trackedTree: false,
      synonyms: ["projects/maple", "maple"]
    },
    "oak": {
      repo: "projects/oak",
      trackedTree: false,
      synonyms: ["projects/oak", "oak"]
    },
    "pine": {
      repo: "projects/pine",
      trackedTree: false,
      synonyms: ["projects/pine", "pine"]
    },
    "comm-central": {
      repo: "comm-central",
      trackedTree: true,
      synonyms: ["comm-central", "c-c"]
    },
    "comm-beta": {
      repo: "releases/comm-beta",
      trackedTree: true,
      synonyms: ["releases/comm-beta", "comm-beta"]
    },
    "comm-esr91": {
      repo: "releases/comm-esr91",
      trackedTree: true,
      synonyms: ["releases/comm-esr91", "comm-esr91"]
    },
    "comm-esr102": {
      repo: "releases/comm-esr102",
      trackedTree: true,
      synonyms: ["releases/comm-esr102", "comm-esr102"]
    },
  }
};

Config.bugNumberREs = [Config.bugRE1, Config.bugRE2, Config.bugRE3,
                       Config.bugRE4, Config.bugRE5, Config.bugRE6, Config.bugRE7];

(function () {
  var base = Config.hgBaseURL;
  for (var treeName in Config.treeInfo) {
    var repo = Config.treeInfo[treeName].repo;
    Config.treeInfo[treeName]['hgURL'] = base + repo + '/';
    Config.treeInfo[treeName]['hgRevURL'] = base + repo + '/rev/';
    Config.treeInfo[treeName]['hgPushlogURL'] = base + repo + '/pushloghtml?changeset=';
    Config.treeInfo[treeName]['hgRevRE'] = new RegExp('https?:\/\/hg.mozilla.org\/' + repo + '\/rev\/', 'ig');
    Config.treeInfo[treeName]['hgRevFullRE'] = new RegExp('https?:\/\/hg.mozilla.org\/' + repo + '\/rev\/[\\da-f]{12}', 'ig');
    Config.treeInfo[treeName]['hgPushlogRE'] = new RegExp('https?:\/\/hg.mozilla.org\/' + repo + '\/pushloghtml\\?changeset=', 'ig');
  }
})();

// Detect input type="email" support
$(document).ready(function() {
  Config.needsValidation = $('#username').prop('type') != 'email';
});
<commit_msg>Bug 1798497 - Add ci-config to bugherder<commit_after>"use strict";

var Config = {
  supportsHistory : !!(window.history && history.pushState),
  inMaintenanceMode : false,

  treeName: 'mozilla-central',
  hgBaseURL: "https://hg.mozilla.org/",
  hgURL: "https://hg.mozilla.org/mozilla-central/",
  hgRevURL: "https://hg.mozilla.org/mozilla-central/rev/",
  hgPushlogURL: "https://hg.mozilla.org/mozilla-central/pushloghtml?changeset=",
  showBugURL: "https://bugzilla.mozilla.org/show_bug.cgi?id=",

  // Here be dragons
  versionRE: /^mozilla\d+$/i,
  csetInputRE: /^(tip|[\da-f]{12,40})$/i,
  csetIDRE: /\b([\da-f]{12,40})\b/ig,
  leaveOpenRE: /(?:leave|keep)(?:-|\s+)open/i,
  bugNumRE: /\b(\d{4,7})\b/g,
  strictBugNumRE: /^(\d{4,7})$/,
  mergeRE: /\bmerg(ed?|ing)\b/i,
  backoutRE: /back(ing|ed)?\s*out/i,
  backoutOtherBugRE: /^Bug\s+\d{4,7}.*back(ing|ed)?\s*out.*bug\s+\d{4,7}/i,
  revertRE: /^revert(ing)?/i,
  partialRevertRE: /(?:from|in)(?:\s+(?:rev(?:ision)?|c(?:hange)?set))?\s+([\da-f]{12,40})/i,
  partialTestRE: /test\s+for/i,
  revertRangeRE: /revert(?:ing)?\s+(?:\S+\s+)?to(?:\s+(?:rev(?:ision)?|c(?:hange)set))?\s+([\da-f]{12,40})/i,
  csetRangeRE: /\b([\da-f]{12,40})\s*(?:to|:|-|through)\s*([\da-f]{12,40})/i,
  hgRevRE: /https?:\/\/hg.mozilla.org\/mozilla-central\/rev\//ig,
  hgRevFullRE: /https?:\/\/hg.mozilla.org\/mozilla-central\/rev\/[\da-f]{12}/ig,
  hgPushlogRE: /https?:\/\/hg.mozilla.org\/mozilla-central\/pushloghtml\?changeset=/ig,
  emailRE: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,   // I'm not looking for RFC 822 compliance here!

  // The many ways bug numbers are specified
  bugRE1: /b(?:ug)?=(\d{4,7})\b/i,                       // e.g. b=XXXXXX
  bugRE2: /^fix(?:es)?\s*(?:for\s*)?(\d{4,7})\b/i,                         // Fix is sometimes used as a synonym for bug
  bugRE3: /to\s+fix\s+bug\s+(\d{4,7})/i,
  bugRE4: /\((\d{4,7}), r=/i,                          // e.g. JS-team style (XXXXXX, r=foo)
  bugRE5: /but\s*(\d{4,7})/i,                          // The typo but XXXXXX happens quite often
  bugRE6: /\bb(?:u?g(?:zilla)?)?:?\s*#?(\d{4,7})\b/i,  // The catchall
  bugRE7: /^(\d{4,7})\b/i,                              // e.g. XXXXXX,

  repoMergeRE: "\\s+(&|and|with|<->|<>|-?->|(in|on)?to)\\s+",

  mcSynonyms: ["mozilla-central", "central", "m-c", "mc", "mozilla central"],

  rewriteTrees: {
    "thunderbird-trunk": "comm-central",
    "thunderbird-beta": "comm-beta",
    "thunderbird-esr91": "comm-esr91",
    "thunderbird-esr102": "comm-esr102",
  },

  treeInfo: {
    "mozilla-central": {
      repo: "mozilla-central",
      trackedTree: true,
      synonyms: ["mozilla-central", "central", "m-c", "mc", "mozilla central"]
    },
    "autoland": {
      repo: "integration/autoland",
      trackedTree: false,
      synonyms: ["autoland"]
    },
    "mozilla-beta": {
      repo: "releases/mozilla-beta",
      trackedTree: true,
      synonyms: ["releases/mozilla-beta", "mozilla-beta"]
    },
    "mozilla-release": {
      repo: "releases/mozilla-release",
      trackedTree: true,
      synonyms: ["releases/mozilla-release", "mozilla-release"]
    },
    "mozilla-esr91": {
      repo: "releases/mozilla-esr91",
      trackedTree: true,
      synonyms: ["esr91", "releases/mozilla-esr91", "mozilla-esr91"]
    },
    "mozilla-esr102": {
      repo: "releases/mozilla-esr102",
      trackedTree: true,
      synonyms: ["esr102", "releases/mozilla-esr102", "mozilla-esr102"]
    },
    "ash": {
      repo: "projects/ash",
      trackedTree: false,
      synonyms: ["ash", "projects/ash"]
    },
    "birch": {
      repo: "projects/birch",
      trackedTree: false,
      synonyms: ["birch", "projects/birch"]
    },
    "cedar": {
      repo: "projects/cedar",
      trackedTree: false,
      synonyms: ["projects/cedar", "cedar"]
    },
    "cypress": {
      repo: "projects/cypress",
      trackedTree: false,
      synonyms: ["projects/cypress", "cypress"]
    },
    "date": {
      repo: "projects/date",
      trackedTree: false,
      synonyms: ["projects/date", "date"]
    },
    "elm": {
      repo: "projects/elm",
      trackedTree: false,
      synonyms: ["projects/elm", "elm"]
    },
    "fig": {
      repo: "projects/fig",
      trackedTree: false,
      synonyms: ["projects/fig", "fig"]
    },
    "graphics": {
      repo: "projects/graphics",
      trackedTree: false,
      synonyms: ["projects/graphics", "graphics"]
    },
    "holly": {
      repo: "projects/holly",
      trackedTree: false,
      synonyms: ["projects/holly", "holly"]
    },
    "jamun": {
      repo: "projects/jamun",
      trackedTree: false,
      synonyms: ["projects/jamun", "jamun"]
    },
    "larch": {
      repo: "projects/larch",
      trackedTree: false,
      synonyms: ["projects/larch", "larch"]
    },
    "maple": {
      repo: "projects/maple",
      trackedTree: false,
      synonyms: ["projects/maple", "maple"]
    },
    "oak": {
      repo: "projects/oak",
      trackedTree: false,
      synonyms: ["projects/oak", "oak"]
    },
    "pine": {
      repo: "projects/pine",
      trackedTree: false,
      synonyms: ["projects/pine", "pine"]
    },
    "comm-central": {
      repo: "comm-central",
      trackedTree: true,
      synonyms: ["comm-central", "c-c"]
    },
    "comm-beta": {
      repo: "releases/comm-beta",
      trackedTree: true,
      synonyms: ["releases/comm-beta", "comm-beta"]
    },
    "comm-esr91": {
      repo: "releases/comm-esr91",
      trackedTree: true,
      synonyms: ["releases/comm-esr91", "comm-esr91"]
    },
    "comm-esr102": {
      repo: "releases/comm-esr102",
      trackedTree: true,
      synonyms: ["releases/comm-esr102", "comm-esr102"]
    },
    "ci-configuration": {
      repo: "ci/ci-configuration",
      trackedTree: false
    },
  }
};

Config.bugNumberREs = [Config.bugRE1, Config.bugRE2, Config.bugRE3,
                       Config.bugRE4, Config.bugRE5, Config.bugRE6, Config.bugRE7];

(function () {
  var base = Config.hgBaseURL;
  for (var treeName in Config.treeInfo) {
    var repo = Config.treeInfo[treeName].repo;
    Config.treeInfo[treeName]['hgURL'] = base + repo + '/';
    Config.treeInfo[treeName]['hgRevURL'] = base + repo + '/rev/';
    Config.treeInfo[treeName]['hgPushlogURL'] = base + repo + '/pushloghtml?changeset=';
    Config.treeInfo[treeName]['hgRevRE'] = new RegExp('https?:\/\/hg.mozilla.org\/' + repo + '\/rev\/', 'ig');
    Config.treeInfo[treeName]['hgRevFullRE'] = new RegExp('https?:\/\/hg.mozilla.org\/' + repo + '\/rev\/[\\da-f]{12}', 'ig');
    Config.treeInfo[treeName]['hgPushlogRE'] = new RegExp('https?:\/\/hg.mozilla.org\/' + repo + '\/pushloghtml\\?changeset=', 'ig');
  }
})();

// Detect input type="email" support
$(document).ready(function() {
  Config.needsValidation = $('#username').prop('type') != 'email';
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2.md',
  name: 'CheckBox',
  extends: 'foam.u2.CheckBox',

  css: `
    ^ {
      padding: 0px !important;

      -webkit-appearance: none;
      border-radius: 2px;
      border: solid 2px #5a5a5a;
      box-sizing: border-box;
      display: inline-block;
      fill: rgba(0, 0, 0, 0);

      height: 18px;
      width: 18px;

      opacity: 1;

      transition: background-color 140ms, border-color 140ms;
    }

    ^:checked {
      background-color: #093649;
      border-color: #093649;
      fill: white;
    }

    ^:checked:after {
      content: url(data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2048%2048%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2215%22%20height%3D%2215%22%20version%3D%221.1%22%3E%0A%20%20%20%3Cpath%20fill%3D%22white%22%20stroke-width%3D%223%22%20d%3D%22M18%2032.34L9.66%2024l-2.83%202.83L18%2038l24-24-2.83-2.83z%22/%3E%0A%3C/svg%3E);
    }

    ^:focus {
      outline:0;
    }

    ^label {
      margin-top: 9px;
      position: absolute;
    }
   `
});
<commit_msg>Show the cursor in pointer mode when hovering on a checkbox<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2.md',
  name: 'CheckBox',
  extends: 'foam.u2.CheckBox',

  css: `
    ^ {
      padding: 0px !important;

      -webkit-appearance: none;
      border-radius: 2px;
      border: solid 2px #5a5a5a;
      box-sizing: border-box;
      display: inline-block;
      fill: rgba(0, 0, 0, 0);

      height: 18px;
      width: 18px;

      opacity: 1;

      transition: background-color 140ms, border-color 140ms;
    }

    ^:hover {
      cursor: pointer;
    }

    ^:checked {
      background-color: #093649;
      border-color: #093649;
      fill: white;
    }

    ^:checked:after {
      content: url(data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2048%2048%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2215%22%20height%3D%2215%22%20version%3D%221.1%22%3E%0A%20%20%20%3Cpath%20fill%3D%22white%22%20stroke-width%3D%223%22%20d%3D%22M18%2032.34L9.66%2024l-2.83%202.83L18%2038l24-24-2.83-2.83z%22/%3E%0A%3C/svg%3E);
    }

    ^:focus {
      outline:0;
    }

    ^label {
      margin-top: 9px;
      position: absolute;
    }
   `
});
<|endoftext|>


<commit_before>angular.module('codeview', ['ui.router', 'firebase', 'ui.ace'])

.config(function($stateProvider, $locationProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('code', {
    url: '/code/:type',
    templateUrl: 'templates/code.html',
    controller: 'CodeCtrl'
  });

  $urlRouterProvider.otherwise('/');
})

.controller('HomeCtrl', function($scope) {
  $scope.test = 'asdf';
  // Closes the sidebar menu
  $("#menu-close").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Opens the sidebar menu
  $("#menu-toggle").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Scrolls to the selected menu item on the page
  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });
})

.controller('CodeCtrl', function($scope, $stateParams, Room, $http) {
  var coder = $scope.coder = mycoder = (($stateParams.type || 'code') === 'code');

  $scope.langace = 'javascript';

  $scope.aceOpts = {
    theme: 'monokai',
    mode: 'javascript',
    rendererOptions: {
      fontSize: 16
    },
    onLoad: function(e) {
      e.$blockScrolling = Infinity;
    }
  };

  $scope.$watch('data', function() {
    $scope.aceOpts.mode = $scope.data.lang.split('/')[0];
  });

  $scope.code = '// Enter code here \n';
  $scope.code2 = '// Interviewer comments\n';
  $scope.data = {};
  var room = Room('test');
  room.$loaded().then(function() {
    $scope.data = room;
    $scope.code = room.code;
    $scope.code2 = room.code2;
  });
  room.$bindTo($scope, 'data');

  if (coder) {
    // Allow editing code
    $scope.$watch('code', function() {
      if ($scope.code) {
        $scope.data.code = $scope.code;
      }
    });
    $scope.$watch('data', function() {
      $scope.code2 = $scope.data.code2;
    });
  } else {
    // Only read code
    $scope.$watch('data', function() {
      $scope.code = $scope.data.code;
    });
    $scope.$watch('code2', function() {
      if ($scope.code2) {
        $scope.data.code2 = $scope.code2;
      }
    });
  }

  execute = function(code) {
    $http.post('/execute', {
      code: code,
      lang: $scope.data.lang.id
    }).
    success(function(data, status, headers, config) {
      console.log(data);
    }).
    error(function(data, status, headers, config) {
      console.log(data);
    });
  }

  $scope.execute1 = function() {
    console.log($scope.code);
    execute($scope.code);
  }

  $scope.execute2 = function() {
    execute($scope.code2);
  }

  $scope.langs = [];
  $http.get('/langs').then(function(data) {
    $scope.langs = data.data;
  });
})

.factory('Room', function($firebase) {
  return function(room) {
    var ref = new Firebase("https://codeview1.firebaseio.com/rooms/").child(room);
    return $firebase(ref).$asObject();
  }
});
<commit_msg>fixed font<commit_after>angular.module('codeview', ['ui.router', 'firebase', 'ui.ace'])

.config(function($stateProvider, $locationProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('code', {
    url: '/code/:type',
    templateUrl: 'templates/code.html',
    controller: 'CodeCtrl'
  });

  $urlRouterProvider.otherwise('/');
})

.controller('HomeCtrl', function($scope) {
  $scope.test = 'asdf';
  // Closes the sidebar menu
  $("#menu-close").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Opens the sidebar menu
  $("#menu-toggle").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Scrolls to the selected menu item on the page
  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });
})

.controller('CodeCtrl', function($scope, $stateParams, Room, $http) {
  var coder = $scope.coder = mycoder = (($stateParams.type || 'code') === 'code');

  $scope.langace = 'javascript';

  $scope.aceOpts = {
    theme: 'monokai',
    mode: 'javascript',
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(e) {
      e.$blockScrolling = Infinity;
    }
  };

  $scope.$watch('data', function() {
    $scope.aceOpts.mode = $scope.data.lang.split('/')[0];
  });

  $scope.code = '// Enter code here \n';
  $scope.code2 = '// Interviewer comments\n';
  $scope.data = {};
  var room = Room('test');
  room.$loaded().then(function() {
    $scope.data = room;
    $scope.code = room.code;
    $scope.code2 = room.code2;
  });
  room.$bindTo($scope, 'data');

  if (coder) {
    // Allow editing code
    $scope.$watch('code', function() {
      if ($scope.code) {
        $scope.data.code = $scope.code;
      }
    });
    $scope.$watch('data', function() {
      $scope.code2 = $scope.data.code2;
    });
  } else {
    // Only read code
    $scope.$watch('data', function() {
      $scope.code = $scope.data.code;
    });
    $scope.$watch('code2', function() {
      if ($scope.code2) {
        $scope.data.code2 = $scope.code2;
      }
    });
  }

  execute = function(code) {
    $http.post('/execute', {
      code: code,
      lang: $scope.data.lang.id
    }).
    success(function(data, status, headers, config) {
      console.log(data);
    }).
    error(function(data, status, headers, config) {
      console.log(data);
    });
  }

  $scope.execute1 = function() {
    console.log($scope.code);
    execute($scope.code);
  }

  $scope.execute2 = function() {
    execute($scope.code2);
  }

  $scope.langs = [];
  $http.get('/langs').then(function(data) {
    $scope.langs = data.data;
  });
})

.factory('Room', function($firebase) {
  return function(room) {
    var ref = new Firebase("https://codeview1.firebaseio.com/rooms/").child(room);
    return $firebase(ref).$asObject();
  }
});
<|endoftext|>


<commit_before>var app = angular.module("sampleApp", ["firebase"]);
app.controller("SampleCtrl", function($scope, $firebaseArray, $firebaseAuth, $http) {
  var auth = $firebaseAuth();

  // This code runs whenever the user logs in
  $scope.logIn = function login(){
    auth.$signInWithPopup("google").then(function(firebaseUser) {
      console.log("Signed in as:", firebaseUser.user.displayName);
    }).catch(function(error) {
      console.log("Authentication failed: ", error);
    });
  };

  // This code runs whenever the user changes authentication states
  // e.g. whevenever the user logs in or logs out
  // this is where we put most of our logic so that we don't duplicate
  // the same things in the login and the logout code
  auth.$onAuthStateChanged(function(firebaseUser){
    // firebaseUser will be null if not logged in
    if(firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function(idToken){
        $http({
          method: 'GET',
          url: '/privateData',
          headers: {
            id_token: idToken
          }
        }).then(function(response){
          $scope.secretData = response.data;
        });
      });
    }else{
      console.log('Not logged in.');
      $scope.secretData = "Log in to get some secret data."
    }

  });

  // This code runs when the user logs out
  $scope.logOut = function(){
    auth.$signOut().then(function(){
      console.log('Logging the user out!');
    });
  };
});
<commit_msg>Making login function anonymous<commit_after>var app = angular.module("sampleApp", ["firebase"]);
app.controller("SampleCtrl", function($scope, $firebaseArray, $firebaseAuth, $http) {
  var auth = $firebaseAuth();

  // This code runs whenever the user logs in
  $scope.logIn = function(){
    auth.$signInWithPopup("google").then(function(firebaseUser) {
      console.log("Signed in as:", firebaseUser.user.displayName);
    }).catch(function(error) {
      console.log("Authentication failed: ", error);
    });
  };

  // This code runs whenever the user changes authentication states
  // e.g. whevenever the user logs in or logs out
  // this is where we put most of our logic so that we don't duplicate
  // the same things in the login and the logout code
  auth.$onAuthStateChanged(function(firebaseUser){
    // firebaseUser will be null if not logged in
    if(firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function(idToken){
        $http({
          method: 'GET',
          url: '/privateData',
          headers: {
            id_token: idToken
          }
        }).then(function(response){
          $scope.secretData = response.data;
        });
      });
    }else{
      console.log('Not logged in.');
      $scope.secretData = "Log in to get some secret data."
    }

  });

  // This code runs when the user logs out
  $scope.logOut = function(){
    auth.$signOut().then(function(){
      console.log('Logging the user out!');
    });
  };
});
<|endoftext|>


<commit_before>function something()
	{
		alert('Hello');
	}<commit_msg>Add x variable to app.js<commit_after>var x = 1;

function something()
	{
		alert(x);
		x = x + 1;
	}<|endoftext|>


<commit_before>jQuery(document).ready(function ($) {
	var content = $('#content');

    var WS_SERVER = 'ws://localhost:4080';

    var url = window.location.href;
        if (url.indexOf("localhost") < 0) {
        WS_SERVER = 'wss://glacial-wildwood-7266.herokuapp.com';
    }

    var ws = new WebSocket(WS_SERVER);

	ws.onopen = function () {
		console.log('Connected');
	};

	$('#btnChat').click(function () {
		var message = $('#input').val();
		console.log(message);
		ws.send(message);
        sendWebPush(subscription);
	});

	ws.onmessage = function (msg) {
		console.log('Received message from server: ' + msg.data);
		addMessage(msg.data);
	}

	function addMessage(message) {
		content.prepend('
' + message + '
');
	}
});
<commit_msg>Push Msg Working1 Fix<commit_after>jQuery(document).ready(function ($) {
	var content = $('#content');

    var WS_SERVER = 'ws://localhost:4080';

    var url = window.location.href;
        if (url.indexOf("localhost") < 0) {
        WS_SERVER = 'wss://glacial-wildwood-7266.herokuapp.com';
    }

    var ws = new WebSocket(WS_SERVER);

	ws.onopen = function () {
		console.log('Connected');
	};

	$('#btnChat').click(function () {
		var message = $('#input').val();
		console.log(message);
		ws.send(message);
        sendWebPush();
	});

	ws.onmessage = function (msg) {
		console.log('Received message from server: ' + msg.data);
		addMessage(msg.data);
	}

	function addMessage(message) {
		content.prepend('
' + message + '
');
	}
});
<|endoftext|>


<commit_before>var app = angular.module('LO07-publi', ['ui.router', 'auth-module', 'angular.filter', 'naif.base64', 'publi-module', 'routes-module'])

app.run(function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

//Filtre spécial pour afficher une taille de façon user-friendly
app.filter('bytes', function() {
    return function(bytes) {
        if (isNaN(parseFloat(bytes)) || !isFinite(bytes) || bytes == 0) return '0';
        var units = {1: 'Kio', 2: 'Mio', 3: 'Gio', 4: 'Tio'},
            measure, floor, precision;
        if (bytes > 1099511627775) {
            measure = 4;
        } else if (bytes > 1048575999 && bytes <= 1099511627775) {
            measure = 3;
        } else if (bytes > 1024000 && bytes <= 1048575999) {
            measure = 2;
        } else if (bytes <= 1024000) {
            measure = 1;
        }
        floor = Math.floor(bytes / Math.pow(1024, measure)).toString().length;
        if (floor > 3) {
            precision = 0
        } else {
            precision = 3 - floor;
        }
        return (bytes / Math.pow(1024, measure)).toFixed(precision) + units[measure];
    }
});

app.filter('unique', function() {
   return function(collection, keyname) {
      var output = [],
          keys = [];

      angular.forEach(collection, function(item) {
          var key = item[keyname];
          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});

app.controller('Home', [
    '$scope',
    '$state',
    'publi',
    function($scope, $state, publi){
        $scope.hasPublis = true;

        publi.getAll(function(response){
            if(response.success){
                $scope.publis = response.content;
                if(response.content.length === 0){
                    $scope.hasPublis = false;
                }
            } else {
                $scope.hasPublis = false;
                $scope.errors = response.error;
            }
        });
}]);

app.controller('NavBar', [
    '$scope',
    '$state',
    '$rootScope',
    'auth',
    function($scope, $state, $rootScope, auth){
        $rootScope.$on('$stateChangeStart',
            function(event, toState, toParams, fromState, fromParams, options){
            auth.currentUser(function(status){
                $scope.loggedIn = status.success;
                if(status.success){
                    $scope.username = status.username;
                    $rootScope.id = status.id;
                    $scope.isAdmin = (status.admin === 1);
                }else{
                    $scope.username = null;
                }
            });
        });

        $scope.goProfile = function(){
            $state.go('profile', {id: $rootScope.id});
        };

        $scope.goPublish = function(){
            $state.go('publish');
        };

        $scope.goHome = function(){
            $state.go('home');
        };

        $scope.login = function(){
            $state.go('login');
        };

        $scope.register = function(){
            $state.go('register');
        };

        $scope.logout = function(){
            auth.logout(function(status){
                $scope.loggedIn = !status.success;
                $scope.isAdmin = !status.success;
                $state.go('home');
            });
        };

        $scope.goRecherche = function(){
            $state.go('recherche');
        };

        $scope.goAdmin = function(){
            $state.go('admin');
        };
}]);

app.controller('Register', [
    '$scope',
    '$http',
    '$state',
    'auth',
    function($scope, $http, $state, auth){

        $scope.equipes = ["CREIDD", "ERA", "GAMMA3", "LASMIS", "LM2S", "LNIO", "LOSI", "Tech-CICO"];

        $scope.annuler = function(){
            $state.go("home");
        };

        $scope.register = function(){
            if(!$scope.user.prenom || !$scope.user.nom || !$scope.user.username || !$scope.user.password
                || !$scope.user.organisation || !$scope.user.equipe){
                $scope.errors = "Le formulaire d'inscription n'est pas complet !";
                return;
            }

            auth.register($scope.user, function(result){
                $scope.errors = status.error;
                if(result.success){
                    $state.go('home');
                }
            });
        };
}]);

app.controller('Login',[
    '$scope',
    '$http',
    '$state',
    'auth',
    function($scope, $http, $state, auth){

        $scope.login_info = {};

        $scope.annuler = function(){
            $state.go("home");
        };

        $scope.login = function(login_info){
            $scope.errors = "";

            if(!$scope.login_info.username || !$scope.login_info.password){
                $scope.errors = "Le formulaire de connexion n'est pas complet !";
                return;
            }

            auth.login($scope.login_info, function(result){
                $scope.errors = result.error;
                if(result.success){
                    $state.go('home');
                }
            });
        };
}]);

app.controller('Publish', [
    '$scope',
    '$state',
    '$http',
    '$rootScope',
    'publi',
    'auth',
    function($scope, $state, $http, $rootScope, publi, auth){
        $scope.statuts = ["Soumis", "En révision", "Publié"];
        $scope.categories = ['RI', 'CI', 'RF', 'CF', 'OS', 'TD', 'BV', 'AP'];
        $scope.publi = {};
        $scope.publi.auteurs = [];
        $scope.auteur = {};
        $scope.auteurs= [];
        $scope.journaux = [];
        $scope.conferences = [];

        publi.getAuteurs(function(status){
            if(status.success){
                $scope.auteurs = status.content;
            } else if(status.message != "empty"){
                $scope.errors = status.error;
            }
        });

        publi.getJournaux(function(status){
            if(status.success){
                $scope.journaux = status.content;
            } else if(status.message != "empty"){
                $scope.errors = status.error;
            }
        });

        publi.getConferences(function(status){
            if(status.success){
                $scope.conferences = status.content;
            } else if(status.message != "empty"){
                $scope.errors = status.error;
            }
        });

        $scope.associateAuteur = function(){
            for(var i = 0; i < $scope.auteurs.length; i++){
                if($scope.auteurs[i].nom == $scope.auteur.nom){
                    $scope.auteur.prenom = $scope.auteurs[i].prenom;
                    $scope.auteur.organisation = $scope.auteurs[i].organisation;
                    $scope.auteur.equipe = $scope.auteurs[i].equipe;
                    return;
                }
            }
        };

        $scope.associateJournal = function(){
            for(var i = 0; i < $scope.journaux.length; i++){
                if($scope.journaux[i].titre == $scope.publi.journal_titre){
                    $scope.publi.journal_editeur = $scope.journaux[i].editeur;
                }
            }
        };

        $scope.associateConf = function(){
            for(var i = 0; i < $scope.conferences.length; i++){
                if($scope.conferences[i].nom == $scope.publi.conference_nom){
                    $scope.publi.conference_lieu = $scope.conferences[i].lieu;
                    $scope.publi.conference_date = $scope.conferences[i].date_conference;
                }
            }
        };

        $scope.addAuteur = function(){
          $scope.publi.auteurs.push({
            prenom : $scope.auteur.prenom,
            nom : $scope.auteur.nom,
            organisation : $scope.auteur.organisation,
            equipe : $scope.auteur.equipe
          });
        };

        $scope.removeAuteur = function(index){
          $scope.publi.auteurs.splice(index, 1);
        };

        $scope.publish = function(){
            if($scope.publi.titre.length && $scope.publi.statut.length
                && $scope.publi.categorie.length && $scope.publi.annee_publication.toString().length){
                var publication = angular.copy( $scope.publi );

                if($scope.isAuteur){
                    publication.auteurs.push({ id: $rootScope.id} );
                }
                publi.post(publication, function(status){
                    if(status.success){
                        $state.go("publi", {id: status.id});
                    }
                    else{
                        $scope.errors = status.error;
                    }
                });
            }
        };
}]);

app.controller('Publi', [
    '$scope',
    '$stateParams',
    'publi',
    function($scope, $stateParams, publi){
        $scope.hasJournal = false;
        $scope.hasConference = false;

        $scope.download = function(){
            window.open("download/" + $scope.publi.id, '_blank');
        }

        publi.get($stateParams.id, function(response){
            if(response.success){
                $scope.publi = response.content;
                if(response.content.journal_titre != null){
                    $scope.hasJournal = true;
                }
                if(response.content.conference_nom != null){
                    $scope.hasConference = true;
                }
            } else {
                $scope.errors = response.error;
            }
        })
}]);

app.controller('Profile', [
    '$scope',
    '$stateParams',
    'publi',
    function($scope, $stateParams, publi){
        $scope.hasPublis = false;
        $scope.coAuteurs = [];

        publi.getAuteur($stateParams.id, function(response){
            if(response.success){
                $scope.auteur = response.auteur[0];
                if(response.publis.length){
                    $scope.publis = response.publis;
                    $scope.hasPublis = true;

                    //Récupération des co-auteurs
                    for(var i = 0; i < $scope.publis.length; i++){
                        publi.get($scope.publis[i].id, function(response){
                            if(response.success){
                                for(var j = 0; j < response.content.auteurs.length; j++){
                                    if(response.content.auteurs[j].id != $stateParams.id){
                                        $scope.coAuteurs.push(response.content.auteurs[j]);
                                    }
                                }
                            } else {
                                $scope.errors = response.error;
                            }
                        });
                    }

                } else {
                    $scope.hasPublis = false;
                }
            }
            else if(response.message != "empty"){
                $scope.errors = response.error;
            }
        });

        $scope.countCoPublis = function(id){
            var result = 0;
            for(var i = 0; i<$scope.coAuteurs.length; i++){
                if($scope.coAuteurs[i].id == id){
                    result++
                }
            }
            return result;
        };
}]);

app.controller('Recherche', [
    '$scope',
    'publi',
    function($scope, publi){
        $scope.hasPublis = false;

        //constructeur des fields
        function f(l, v){
            return({label: l, value: v});
        }

        $scope.fields = [f("Id", "p.id"), f("Titre", "p.titre"), f("Description", "p.description"), f("Statut", "p.statut"),
                f("Année de publication", "p.annee_publication"), f("Titre du journal", "journal_titre"), f("Editeur du journal", "journal_editeur"),
                f("Nom de la conférence", "conference_nom")];

        $scope.search = function(){
            publi.search($scope.params, function(response){
                if(response.success){
                    if(response.content.length){
                        $scope.hasPublis = true;
                        $scope.publis = response.content;
                    }
                    else{
                        $scope.hasPublis = false;
                    }
                }
                else{
                    $scope.hasPublis = false;
                    $scope.errors = status.error;
                }
            });
        };
}]);

/**
 * Directive pour afficher une liste de publications
 *
 * Paramètres :
 * - liste = la variable contenant une liste des publications à afficher
 */
app.directive('projetListePublications', function(){
    return {
        restrict: 'E',
        scope: {
            liste: '=liste',
            groupBy: '@groupBy',
            orderBy: '@orderBy'
        },
        templateUrl: 'public/templates/directives/listepublications.html',
        controller: function($scope){
            $scope.groupBy = angular.isDefined($scope.groupBy) ? $scope.groupBy : 'categorie';
            $scope.orderBy = angular.isDefined($scope.orderBy) ? $scope.orderBy : '-annee_publication';
        }
    };
});
<commit_msg>Correction de l'affichage du bouton "Administration"<commit_after>var app = angular.module('LO07-publi', ['ui.router', 'auth-module', 'angular.filter', 'naif.base64', 'publi-module', 'routes-module'])

app.run(function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

//Filtre spécial pour afficher une taille de façon user-friendly
app.filter('bytes', function() {
    return function(bytes) {
        if (isNaN(parseFloat(bytes)) || !isFinite(bytes) || bytes == 0) return '0';
        var units = {1: 'Kio', 2: 'Mio', 3: 'Gio', 4: 'Tio'},
            measure, floor, precision;
        if (bytes > 1099511627775) {
            measure = 4;
        } else if (bytes > 1048575999 && bytes <= 1099511627775) {
            measure = 3;
        } else if (bytes > 1024000 && bytes <= 1048575999) {
            measure = 2;
        } else if (bytes <= 1024000) {
            measure = 1;
        }
        floor = Math.floor(bytes / Math.pow(1024, measure)).toString().length;
        if (floor > 3) {
            precision = 0
        } else {
            precision = 3 - floor;
        }
        return (bytes / Math.pow(1024, measure)).toFixed(precision) + units[measure];
    }
});

app.filter('unique', function() {
   return function(collection, keyname) {
      var output = [],
          keys = [];

      angular.forEach(collection, function(item) {
          var key = item[keyname];
          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});

app.controller('Home', [
    '$scope',
    '$state',
    'publi',
    function($scope, $state, publi){
        $scope.hasPublis = true;

        publi.getAll(function(response){
            if(response.success){
                $scope.publis = response.content;
                if(response.content.length === 0){
                    $scope.hasPublis = false;
                }
            } else {
                $scope.hasPublis = false;
                $scope.errors = response.error;
            }
        });
}]);

app.controller('NavBar', [
    '$scope',
    '$state',
    '$rootScope',
    'auth',
    function($scope, $state, $rootScope, auth){
        $rootScope.$on('$stateChangeStart',
            function(event, toState, toParams, fromState, fromParams, options){
            auth.currentUser(function(status){
                $scope.loggedIn = status.success;
                if(status.success){
                    $scope.username = status.username;
                    $rootScope.id = status.id;
                    $scope.isAdmin = (status.admin == 1);
                }else{
                    $scope.username = null;
                }
            });
        });

        $scope.goProfile = function(){
            $state.go('profile', {id: $rootScope.id});
        };

        $scope.goPublish = function(){
            $state.go('publish');
        };

        $scope.goHome = function(){
            $state.go('home');
        };

        $scope.login = function(){
            $state.go('login');
        };

        $scope.register = function(){
            $state.go('register');
        };

        $scope.logout = function(){
            auth.logout(function(status){
                $scope.loggedIn = !status.success;
                $scope.isAdmin = false;
                $state.go('home');
            });
        };

        $scope.goRecherche = function(){
            $state.go('recherche');
        };

        $scope.goAdmin = function(){
            $state.go('admin');
        };
}]);

app.controller('Register', [
    '$scope',
    '$http',
    '$state',
    'auth',
    function($scope, $http, $state, auth){

        $scope.equipes = ["CREIDD", "ERA", "GAMMA3", "LASMIS", "LM2S", "LNIO", "LOSI", "Tech-CICO"];

        $scope.annuler = function(){
            $state.go("home");
        };

        $scope.register = function(){
            if(!$scope.user.prenom || !$scope.user.nom || !$scope.user.username || !$scope.user.password
                || !$scope.user.organisation || !$scope.user.equipe){
                $scope.errors = "Le formulaire d'inscription n'est pas complet !";
                return;
            }

            auth.register($scope.user, function(result){
                $scope.errors = status.error;
                if(result.success){
                    $state.go('home');
                }
            });
        };
}]);

app.controller('Login',[
    '$scope',
    '$http',
    '$state',
    'auth',
    function($scope, $http, $state, auth){

        $scope.login_info = {};

        $scope.annuler = function(){
            $state.go("home");
        };

        $scope.login = function(login_info){
            $scope.errors = "";

            if(!$scope.login_info.username || !$scope.login_info.password){
                $scope.errors = "Le formulaire de connexion n'est pas complet !";
                return;
            }

            auth.login($scope.login_info, function(result){
                $scope.errors = result.error;
                if(result.success){
                    $state.go('home');
                }
            });
        };
}]);

app.controller('Publish', [
    '$scope',
    '$state',
    '$http',
    '$rootScope',
    'publi',
    'auth',
    function($scope, $state, $http, $rootScope, publi, auth){
        $scope.statuts = ["Soumis", "En révision", "Publié"];
        $scope.categories = ['RI', 'CI', 'RF', 'CF', 'OS', 'TD', 'BV', 'AP'];
        $scope.publi = {};
        $scope.publi.auteurs = [];
        $scope.auteur = {};
        $scope.auteurs= [];
        $scope.journaux = [];
        $scope.conferences = [];

        publi.getAuteurs(function(status){
            if(status.success){
                $scope.auteurs = status.content;
            } else if(status.message != "empty"){
                $scope.errors = status.error;
            }
        });

        publi.getJournaux(function(status){
            if(status.success){
                $scope.journaux = status.content;
            } else if(status.message != "empty"){
                $scope.errors = status.error;
            }
        });

        publi.getConferences(function(status){
            if(status.success){
                $scope.conferences = status.content;
            } else if(status.message != "empty"){
                $scope.errors = status.error;
            }
        });

        $scope.associateAuteur = function(){
            for(var i = 0; i < $scope.auteurs.length; i++){
                if($scope.auteurs[i].nom == $scope.auteur.nom){
                    $scope.auteur.prenom = $scope.auteurs[i].prenom;
                    $scope.auteur.organisation = $scope.auteurs[i].organisation;
                    $scope.auteur.equipe = $scope.auteurs[i].equipe;
                    return;
                }
            }
        };

        $scope.associateJournal = function(){
            for(var i = 0; i < $scope.journaux.length; i++){
                if($scope.journaux[i].titre == $scope.publi.journal_titre){
                    $scope.publi.journal_editeur = $scope.journaux[i].editeur;
                }
            }
        };

        $scope.associateConf = function(){
            for(var i = 0; i < $scope.conferences.length; i++){
                if($scope.conferences[i].nom == $scope.publi.conference_nom){
                    $scope.publi.conference_lieu = $scope.conferences[i].lieu;
                    $scope.publi.conference_date = $scope.conferences[i].date_conference;
                }
            }
        };

        $scope.addAuteur = function(){
          $scope.publi.auteurs.push({
            prenom : $scope.auteur.prenom,
            nom : $scope.auteur.nom,
            organisation : $scope.auteur.organisation,
            equipe : $scope.auteur.equipe
          });
        };

        $scope.removeAuteur = function(index){
          $scope.publi.auteurs.splice(index, 1);
        };

        $scope.publish = function(){
            if($scope.publi.titre.length && $scope.publi.statut.length
                && $scope.publi.categorie.length && $scope.publi.annee_publication.toString().length){
                var publication = angular.copy( $scope.publi );

                if($scope.isAuteur){
                    publication.auteurs.push({ id: $rootScope.id} );
                }
                publi.post(publication, function(status){
                    if(status.success){
                        $state.go("publi", {id: status.id});
                    }
                    else{
                        $scope.errors = status.error;
                    }
                });
            }
        };
}]);

app.controller('Publi', [
    '$scope',
    '$stateParams',
    'publi',
    function($scope, $stateParams, publi){
        $scope.hasJournal = false;
        $scope.hasConference = false;

        $scope.download = function(){
            window.open("download/" + $scope.publi.id, '_blank');
        }

        publi.get($stateParams.id, function(response){
            if(response.success){
                $scope.publi = response.content;
                if(response.content.journal_titre != null){
                    $scope.hasJournal = true;
                }
                if(response.content.conference_nom != null){
                    $scope.hasConference = true;
                }
            } else {
                $scope.errors = response.error;
            }
        })
}]);

app.controller('Profile', [
    '$scope',
    '$stateParams',
    'publi',
    function($scope, $stateParams, publi){
        $scope.hasPublis = false;
        $scope.coAuteurs = [];

        publi.getAuteur($stateParams.id, function(response){
            if(response.success){
                $scope.auteur = response.auteur[0];
                if(response.publis.length){
                    $scope.publis = response.publis;
                    $scope.hasPublis = true;

                    //Récupération des co-auteurs
                    for(var i = 0; i < $scope.publis.length; i++){
                        publi.get($scope.publis[i].id, function(response){
                            if(response.success){
                                for(var j = 0; j < response.content.auteurs.length; j++){
                                    if(response.content.auteurs[j].id != $stateParams.id){
                                        $scope.coAuteurs.push(response.content.auteurs[j]);
                                    }
                                }
                            } else {
                                $scope.errors = response.error;
                            }
                        });
                    }

                } else {
                    $scope.hasPublis = false;
                }
            }
            else if(response.message != "empty"){
                $scope.errors = response.error;
            }
        });

        $scope.countCoPublis = function(id){
            var result = 0;
            for(var i = 0; i<$scope.coAuteurs.length; i++){
                if($scope.coAuteurs[i].id == id){
                    result++
                }
            }
            return result;
        };
}]);

app.controller('Recherche', [
    '$scope',
    'publi',
    function($scope, publi){
        $scope.hasPublis = false;

        //constructeur des fields
        function f(l, v){
            return({label: l, value: v});
        }

        $scope.fields = [f("Id", "p.id"), f("Titre", "p.titre"), f("Description", "p.description"), f("Statut", "p.statut"),
                f("Année de publication", "p.annee_publication"), f("Titre du journal", "journal_titre"), f("Editeur du journal", "journal_editeur"),
                f("Nom de la conférence", "conference_nom")];

        $scope.search = function(){
            publi.search($scope.params, function(response){
                if(response.success){
                    if(response.content.length){
                        $scope.hasPublis = true;
                        $scope.publis = response.content;
                    }
                    else{
                        $scope.hasPublis = false;
                    }
                }
                else{
                    $scope.hasPublis = false;
                    $scope.errors = status.error;
                }
            });
        };
}]);

/**
 * Directive pour afficher une liste de publications
 *
 * Paramètres :
 * - liste = la variable contenant une liste des publications à afficher
 */
app.directive('projetListePublications', function(){
    return {
        restrict: 'E',
        scope: {
            liste: '=liste',
            groupBy: '@groupBy',
            orderBy: '@orderBy'
        },
        templateUrl: 'public/templates/directives/listepublications.html',
        controller: function($scope){
            $scope.groupBy = angular.isDefined($scope.groupBy) ? $scope.groupBy : 'categorie';
            $scope.orderBy = angular.isDefined($scope.orderBy) ? $scope.orderBy : '-annee_publication';
        }
    };
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        jPlug Loader
// @namespace   github.com/Juici/jPlug
// @author      Juici
// @version     0.1.0

// @downloadURL https://juici.github.io/jPlug/jplug.user.js

// @include     https://plug.dj/*
// @include     https://*.plug.dj/*

// @exclude     https://plug.dj/_/*
// @exclude     https://plug.dj/@/*
// @exclude     https://plug.dj/ba
// @exclude     https://plug.dj/plot
// @exclude     https://plug.dj/press
// @exclude     https://plug.dj/partners
// @exclude     https://plug.dj/team
// @exclude     https://plug.dj/about
// @exclude     https://plug.dj/jobs
// @exclude     https://plug.dj/purchase
// @exclude     https://plug.dj/subscribe
// @exclude     https://*.plug.dj/_/*
// @exclude     https://*.plug.dj/@/*
// @exclude     https://*.plug.dj/ba
// @exclude     https://*.plug.dj/plot
// @exclude     https://*.plug.dj/press
// @exclude     https://*.plug.dj/partners
// @exclude     https://*.plug.dj/team
// @exclude     https://*.plug.dj/about
// @exclude     https://*.plug.dj/jobs
// @exclude     https://*.plug.dj/purchase
// @exclude     https://*.plug.dj/subscribe

// @grant       none
// ==/UserScript==

(function ($) {
  const loader = {
    hook: function () {
      if (typeof API !== 'undefined' && API.enabled) {
        this.load();
      } else {
        setTimeout(() => loader.hook(), 500);
      }
    },
    load: function () {
      console.log('[jPlug] autoload enabled');
      API.chatLog('jPlug autoload enabled');
      $.getScript('https://juici.github.io/jPlug/jplug.js').fail((e) => console.error(`[jPlug] autoload failed: ${e}`));
    }
  };
  loader.hook();
})(window.jQuery);
<commit_msg>maybe now<commit_after>// ==UserScript==
// @name        jPlug Loader
// @namespace   github.com/Juici/jPlug
// @author      Juici
// @version     0.1.0

// @downloadURL https://juici.github.io/jPlug/jplug.user.js

// @include     https://plug.dj/*
// @include     https://*.plug.dj/*

// @exclude     https://plug.dj/_/*
// @exclude     https://plug.dj/@/*
// @exclude     https://plug.dj/ba
// @exclude     https://plug.dj/plot
// @exclude     https://plug.dj/press
// @exclude     https://plug.dj/partners
// @exclude     https://plug.dj/team
// @exclude     https://plug.dj/about
// @exclude     https://plug.dj/jobs
// @exclude     https://plug.dj/purchase
// @exclude     https://plug.dj/subscribe
// @exclude     https://*.plug.dj/_/*
// @exclude     https://*.plug.dj/@/*
// @exclude     https://*.plug.dj/ba
// @exclude     https://*.plug.dj/plot
// @exclude     https://*.plug.dj/press
// @exclude     https://*.plug.dj/partners
// @exclude     https://*.plug.dj/team
// @exclude     https://*.plug.dj/about
// @exclude     https://*.plug.dj/jobs
// @exclude     https://*.plug.dj/purchase
// @exclude     https://*.plug.dj/subscribe

// @grant       none
// ==/UserScript==

(function ($) {
  const loader = {
    hook: function () {
      if (typeof API !== 'undefined' && API.enabled) {
        loader.load();
      } else {
        setTimeout(() => loader.hook(), 500);
      }
    },
    load: function () {
      console.log('[jPlug] autoload enabled');
      API.chatLog('jPlug autoload enabled');
      $.getScript('https://juici.github.io/jPlug/jplug.js').fail((e) => console.error(`[jPlug] autoload failed: ${e}`));
    }
  };
  loader.hook();
})(window.jQuery);
<|endoftext|>


<commit_before>var clusterpost = require("clusterpost-lib");
var path = require('path');
var argv = require('minimist')(process.argv.slice(2));
var stringArgv = require('string-argv');
var Converter=require("csvtojson").Converter;
var fs=require('fs');
var _=require('underscore');
var Promise = require('bluebird');

const getConfigFile = function (env, base_directory) {
  try {
    // Try to load the user's personal configuration file
    var conf = path.join(base_directory, 'conf.my.' + env + '.json');
    return require(conf);
  } catch (e) {
    // Else, read the default configuration file
    return require(base_directory + '/conf.' + env + '.json');
  }
};

var env = process.env.NODE_ENV;
if(!env) throw "Please set NODE_ENV variable.";

var conf = getConfigFile(env, process.cwd());

var remotefs = conf.uri + '/dataprovider-fs/';

var parameters = [];
var inputs = [];

parameters.push({
    "flag": "",
    "name": String(argv._[0])
});

var addJobInputs = function(jobinput){
    var jobin = path.basename(jobinput);

    if(jobinput[0] == "/"){
        jobinput = jobinput.slice(1);//remove the slash at the start
    }

    inputs.push({
        "name": jobin,
        "remote" : {
            "uri" : remotefs + jobinput
        }
    });
}

try{
    var m = argv["m"];

    if(!m){
        console.error("Please check ants documentation for parameter '-m'");
        process.exit(1);
    }

    var parseMparameter = function(m){

        try{
            var marray = m.substring(m.lastIndexOf("[")+1,m.lastIndexOf("]")).split(",");
            var fixedimagepath = marray[0];
            var fixedimagefilename = path.basename(fixedimagepath);
            var movingimagepath = marray[1];
            var movingimagefilename = path.basename(movingimagepath);
        }catch(e){
            console.error("parseParam", argv);
            throw e + " " + m;
        }

        if(fixedimagefilename && movingimagefilename){
            if(fixedimagefilename === movingimagefilename){
                fixedimagefilename = "0_" + fixedimagefilename;
                movingimagefilename = "1_" + movingimagefilename;
            }

            marray[0] = fixedimagefilename;
            marray[1] = movingimagefilename;

            var mm = m.substring(0, m.lastIndexOf("[")) + JSON.stringify(marray).replace(/"/g, '');

            parameters.push({
                "flag": "-m",
                "name": mm
            });

            var input = _.find(inputs, function(input){
                if(remotefs + fixedimagepath === input.remote.uri){
                    return true;
                }
                return false;
            });

            if(!input){
                if(fixedimagepath[0] == "/"){
                    fixedimagepath = fixedimagepath.slice(1);//remove the slash at the start
                }
                inputs.push({
                    "name": fixedimagefilename,
                    "remote" : {
                        "uri" : remotefs + fixedimagepath
                    }
                });
            }

            var input = _.find(inputs, function(input){
                if(remotefs + movingimagepath === input.remote.uri){
                    return true;
                }
                return false;
            });

            if(!input){
                if(movingimagepath[0] == "/"){
                    movingimagepath = movingimagepath.slice(1);//remove the slash at the start
                }
                inputs.push({
                    "name": movingimagefilename,
                    "remote" : {
                        "uri" : remotefs + movingimagepath
                    }
                });
            }

        }else{
            throw 'Could not parse "-m ' + m + '"';
        }
    }

    if(_.isArray(m)){
        _.each(m, parseMparameter);
    }else{
        parseMparameter(m);
    }

}catch(e){
    console.error(e);
    process.exit(1);
}

var x = argv["x"];

if(x){
    addJobInputs(x);

    var xx = path.basename(x);

    parameters.push({
        "flag": "-x",
        "name": xx
    });
}

var jobinputs = argv["jobinputs"];

if(jobinputs){
    if(_.isArray(jobinputs)){
        _.each(jobinputs, addJobInputs);
    }else{
        addJobInputs(jobinputs);
    }
}

var outname = argv["o"];
if(!outname){
    console.error("Please check ants documentation for parameter '-o'");
    process.exit(1);
}
//Parse all the rest of parameters that are specific to ANTS
_.each(argv, function(val, key){
    if(key !== "x" && key !== "m" && key !== "_" && key !== "outputdir" && key !== "jobname" && key !== "jobparameters" && key !== "$0" && key !== "useremail" && key !== "executionserver"){
        var flag = "-";

        if(key.length > 1){
            flag += "-";
        }

        parameters.push({
            "flag": flag+key,
            "name": String(val)
        });
    }
});

var jobparameters;
if(argv["jobparameters"]){
    jobparameters = _.compact(_.map(require('minimist')(stringArgv(argv["jobparameters"])), function(param, key){
        if(key !== "_"){
            var flag = "-";

            if(key.length > 1){
                flag += "-";
            }

            return {
                flag: flag + key,
                name: String(param)
            }
        }
    }));
}

var outputdir = argv["outputdir"];
if(!outputdir){
    console.error("Please set output directory '-outputdir <outputdir>'");
    process.exit(1);
}

var jobname = argv["jobname"];

var getcsvfile = function(filename){
  return new Promise(function(resolve, reject){
    var fileStream=fs.createReadStream(filename);
    //new converter instance
    var csvConverter=new Converter({constructResult:true});

    //end_parsed will be emitted once parsing finished
    csvConverter.on("end_parsed",function(jsonObj){
      resolve(jsonObj);
    });

    fileStream.pipe(csvConverter);
  })
}

clusterpost.setClusterPostServer(conf.uri);

var agentoptions = {
	rejectUnauthorized: false
}

clusterpost.setAgentOptions(agentoptions);

var prom;
try{
    var token = fs.readFileSync(".token");
    clusterpost.setUserToken(token);
    prom = Promise.resolve(token);
}catch(e){

    prom = clusterpost.getUsernamePassword(function(user){
        return clusterpost.userLogin(user);
    })
    .then(function(token){
        fs.writeFileSync(".token", token.token);
        return token;
    });
}

var useremail = "juanprietob@gmail.com";

if(argv["useremail"]){
    useremail = argv["useremail"];
}

var executionserver = "localhost";

if(argv["executionserver"]){
    executionserver = argv["executionserver"];
}

prom
.then(function(res){

    var job = {
        "executable": "ANTS",
        "parameters": parameters,
        "inputs": inputs,
        "outputs": [
            {
                "type": "file",
                "name": "stdout.out"
            },
            {
                "type": "file",
                "name": "stderr.err"
            }
        ],
        "type": "job",
        "userEmail": useremail
    };

    job.executionserver = executionserver;

    job.inputs = inputs;

    job.outputs.push({
        type: "file",
        name: outname + "Affine.txt"
    });
    job.outputs.push({
        type: "file",
        name: outname + "Warp.nii.gz"
    });
    job.outputs.push({
        type: "file",
        name: outname + "InverseWarp.nii.gz"
    });

    job.outputdir = outputdir;

    if(jobname){
        job.name = jobname;
    }

    if(jobparameters){
        job.jobparameters = jobparameters;
    }

    return clusterpost.createDocument(job)
    .then(function(res){
        var jobid = res.id;
        return clusterpost.executeJob(jobid)
        .then(function(res){
            console.log(jobid);
            return res;
        })
        .catch(function(res){
            console.error(res);
            return res;
        });
    });
})
.then(function(){
    process.exit(0);
})
.catch(console.error)
<commit_msg>ENH: Improve mechanism to check for token and ask for email, password.<commit_after>var clusterpost = require("clusterpost-lib");
var path = require('path');
var argv = require('minimist')(process.argv.slice(2));
var stringArgv = require('string-argv');
var Converter=require("csvtojson").Converter;
var fs=require('fs');
var _=require('underscore');
var Promise = require('bluebird');

const getConfigFile = function (env, base_directory) {
  try {
    // Try to load the user's personal configuration file
    var conf = path.join(base_directory, 'conf.my.' + env + '.json');
    return require(conf);
  } catch (e) {
    // Else, read the default configuration file
    return require(base_directory + '/conf.' + env + '.json');
  }
};

var env = process.env.NODE_ENV;
if(!env) throw "Please set NODE_ENV variable.";

var conf = getConfigFile(env, process.cwd());

var remotefs = conf.uri + '/dataprovider-fs/';

var parameters = [];
var inputs = [];

parameters.push({
    "flag": "",
    "name": String(argv._[0])
});

var addJobInputs = function(jobinput){
    var jobin = path.basename(jobinput);

    if(jobinput[0] == "/"){
        jobinput = jobinput.slice(1);//remove the slash at the start
    }

    inputs.push({
        "name": jobin,
        "remote" : {
            "uri" : remotefs + jobinput
        }
    });
}

try{
    var m = argv["m"];

    if(!m){
        console.error("Please check ants documentation for parameter '-m'");
        process.exit(1);
    }

    var parseMparameter = function(m){

        try{
            var marray = m.substring(m.lastIndexOf("[")+1,m.lastIndexOf("]")).split(",");
            var fixedimagepath = marray[0];
            var fixedimagefilename = path.basename(fixedimagepath);
            var movingimagepath = marray[1];
            var movingimagefilename = path.basename(movingimagepath);
        }catch(e){
            console.error("parseParam", argv);
            throw e + " " + m;
        }

        if(fixedimagefilename && movingimagefilename){
            if(fixedimagefilename === movingimagefilename){
                fixedimagefilename = "0_" + fixedimagefilename;
                movingimagefilename = "1_" + movingimagefilename;
            }

            marray[0] = fixedimagefilename;
            marray[1] = movingimagefilename;

            var mm = m.substring(0, m.lastIndexOf("[")) + JSON.stringify(marray).replace(/"/g, '');

            parameters.push({
                "flag": "-m",
                "name": mm
            });

            var input = _.find(inputs, function(input){
                if(remotefs + fixedimagepath === input.remote.uri){
                    return true;
                }
                return false;
            });

            if(!input){
                if(fixedimagepath[0] == "/"){
                    fixedimagepath = fixedimagepath.slice(1);//remove the slash at the start
                }
                inputs.push({
                    "name": fixedimagefilename,
                    "remote" : {
                        "uri" : remotefs + fixedimagepath
                    }
                });
            }

            var input = _.find(inputs, function(input){
                if(remotefs + movingimagepath === input.remote.uri){
                    return true;
                }
                return false;
            });

            if(!input){
                if(movingimagepath[0] == "/"){
                    movingimagepath = movingimagepath.slice(1);//remove the slash at the start
                }
                inputs.push({
                    "name": movingimagefilename,
                    "remote" : {
                        "uri" : remotefs + movingimagepath
                    }
                });
            }

        }else{
            throw 'Could not parse "-m ' + m + '"';
        }
    }

    if(_.isArray(m)){
        _.each(m, parseMparameter);
    }else{
        parseMparameter(m);
    }

}catch(e){
    console.error(e);
    process.exit(1);
}

var x = argv["x"];

if(x){
    addJobInputs(x);

    var xx = path.basename(x);

    parameters.push({
        "flag": "-x",
        "name": xx
    });
}

var jobinputs = argv["jobinputs"];

if(jobinputs){
    if(_.isArray(jobinputs)){
        _.each(jobinputs, addJobInputs);
    }else{
        addJobInputs(jobinputs);
    }
}

var outname = argv["o"];
if(!outname){
    console.error("Please check ants documentation for parameter '-o'");
    process.exit(1);
}
//Parse all the rest of parameters that are specific to ANTS
_.each(argv, function(val, key){
    if(key !== "x" && key !== "m" && key !== "_" && key !== "outputdir" && key !== "jobname" && key !== "jobparameters" && key !== "$0" && key !== "useremail" && key !== "executionserver"){
        var flag = "-";

        if(key.length > 1){
            flag += "-";
        }

        parameters.push({
            "flag": flag+key,
            "name": String(val)
        });
    }
});

var jobparameters;
if(argv["jobparameters"]){
    jobparameters = _.compact(_.map(require('minimist')(stringArgv(argv["jobparameters"])), function(param, key){
        if(key !== "_"){
            var flag = "-";

            if(key.length > 1){
                flag += "-";
            }

            return {
                flag: flag + key,
                name: String(param)
            }
        }
    }));
}

var outputdir = argv["outputdir"];
if(!outputdir){
    console.error("Please set output directory '-outputdir <outputdir>'");
    process.exit(1);
}

var jobname = argv["jobname"];

var getcsvfile = function(filename){
  return new Promise(function(resolve, reject){
    var fileStream=fs.createReadStream(filename);
    //new converter instance
    var csvConverter=new Converter({constructResult:true});

    //end_parsed will be emitted once parsing finished
    csvConverter.on("end_parsed",function(jsonObj){
      resolve(jsonObj);
    });

    fileStream.pipe(csvConverter);
  })
}

var userLogin = function(){
    return clusterpost.getUsernamePassword(function(user){
        return clusterpost.userLogin(user)
        .then(function(token){
            fs.writeFileSync(".token", JSON.stringify(token));
            return user;
        });;
    });
}

clusterpost.setClusterPostServer(conf.uri);

var agentoptions = {
	rejectUnauthorized: false
}

clusterpost.setAgentOptions(agentoptions);

var prom;
try{
    var token = JSON.parse(fs.readFileSync(".token"));
    clusterpost.setUserToken(token);
    prom = clusterpost.getUser()
    .catch(function(err){
        return userLogin();
    });
}catch(e){
    prom = userLogin();
}

var useremail = "";

prom
.then(function(res){

    if(argv["useremail"]){
        useremail = argv["useremail"];
    }else{
        useremail = res.email;
    }

    if(argv["executionserver"]){
        serverprom = Promise.resolve(argv["executionserver"]);
    }else{
        serverprom = clusterpost.getExecutionServers()
        .then(function(servers){
            console.log("Selecting first server by default");
            if(servers.length > 0){
                return servers[0].name
            }else{
                return Promise.reject("No servers configured");
            }
        })
    }

    return serverprom
    .then(function(executionserver){
        var job = {
            "executable": "ANTS",
            "parameters": parameters,
            "inputs": inputs,
            "outputs": [
                {
                    "type": "file",
                    "name": "stdout.out"
                },
                {
                    "type": "file",
                    "name": "stderr.err"
                }
            ],
            "type": "job",
            "userEmail": useremail
        };

        job.executionserver = executionserver;

        job.inputs = inputs;

        job.outputs.push({
            type: "file",
            name: outname + "Affine.txt"
        });
        job.outputs.push({
            type: "file",
            name: outname + "Warp.nii.gz"
        });
        job.outputs.push({
            type: "file",
            name: outname + "InverseWarp.nii.gz"
        });

        job.outputdir = outputdir;

        if(jobname){
            job.name = jobname;
        }

        if(jobparameters){
            job.jobparameters = jobparameters;
        }

        return clusterpost.createDocument(job)
        .then(function(res){
            var jobid = res.id;
            return clusterpost.executeJob(jobid)
            .then(function(res){
                console.log(jobid);
                return res;
            })
            .catch(function(res){
                console.error(res);
                return res;
            });
        });
    });

})
.then(function(){
    process.exit(0);
})
.catch(console.error)
<|endoftext|>


<commit_before>import curryN from './internal/_curryN.js';

/**
 * Takes a binary function `f`, a unary function `g`, and two values.
 * Applies `g` to each value, then applies the result of each to `f`.
 *
 * Also known as the P combinator.
 *
 * @func
 * @memberOf R
 * @since v0.28.0
 * @category Function
 * @sig ((a, a) -> b) -> (c -> a) -> c -> c -> b
 * @param {Function} f a binary function
 * @param {Function} g a unary function
 * @param {any} a any value
 * @param {any} b any value
 * @return {any} The result of `f`
 * @example
 *
 *      const eqBy = R.on((a, b) => a === b);
 *      eqBy(R.prop('a'), {b:0, a:1}, {a:1}) //=> true;
 *
 *      const containsInsensitive = R.on(R.contains, R.toLower);
 *      containsInsensitive('o', 'FOO'); //=> true
 * @symb R.on(f, g, a, b) = f(g(a), g(b))
 */
var on = curryN(4, [], function on(f, g, a, b) {
  return f(g(a), g(b));
});
export default on;
<commit_msg>Update on.js<commit_after>import curryN from './internal/_curryN.js';

/**
 * Takes a binary function `f`, a unary function `g`, and two values.
 * Applies `g` to each value, then applies the result of each to `f`.
 *
 * Also known as the P combinator.
 *
 * @func
 * @memberOf R
 * @since v0.28.0
 * @category Function
 * @sig ((a, a) -> b) -> (c -> a) -> c -> c -> b
 * @param {Function} f a binary function
 * @param {Function} g a unary function
 * @param {any} a any value
 * @param {any} b any value
 * @return {any} The result of `f`
 * @example
 *
 *      const eqBy = R.on((a, b) => a === b);
 *      eqBy(R.prop('a'), {b:0, a:1}, {a:1}) //=> true;
 *
 *      const containsInsensitive = R.on(R.includes, R.toLower);
 *      containsInsensitive('o', 'FOO'); //=> true
 * @symb R.on(f, g, a, b) = f(g(a), g(b))
 */
var on = curryN(4, [], function on(f, g, a, b) {
  return f(g(a), g(b));
});
export default on;
<|endoftext|>


<commit_before>/*Copyright 2012 Google Inc. All Rights Reserved.

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.*/

/**
 * @fileoverview Description of this file.
 * @author ctiller@google.com (Craig Tiller)
 */

var http = require('http')
var assert = require('assert')
var fs = require('fs')

var host = null;
var port = null;
var SERVERID = null;
var DEBUG = true;
var INDENT_JSON = DEBUG ? 4: null;

exports.DEBUG = DEBUG
exports.INDENT_JSON = INDENT_JSON

var pairing_key = JSON.parse(fs.readFileSync(__dirname + '/../shared/pairing-key.json')).key
exports.pairing_key = pairing_key

// exponential backoff knobs
var check_connection_delay_s = .1;
var check_connection_delay_s_max = 300;
var check_connection_delay_s_ok = 30;

function get(path, cb) {
  var caller = get.caller.name;
  var options = {
    host: host,
    port: port,
    path: path
  };
  var result = "";
  var donecb = false;
  function callback(arg) {
    if (!donecb) cb(arg);
    donecb = true;
  }
  url = 'http://' + options.host + ':' + options.port + (options.path[0] == '/' ? '' : '/') + options.path;
  // console.log(caller + ': GET ' + url);
  http.get(options, function(res) {
    if (res.statusCode != 200) {
      console.log(caller + ': GET ' + url + ' -> HTTP status code ' + res.statusCode);
      callback(null);
      return;
    }
    res.on('data', function(chunk) {
      result += chunk;
    });
    res.on('end', function() {
      console.log(caller + ': GET', url, '->', result);
      callback(result);
    });
    res.on('close', function() {
      callback(null);
    });
  }).on('error', function(e) {
    console.log(caller + ': GET ' + url + ' -> FAILED due to ' + e);
    callback(null);
  })
}

function post(path, contents, cb) {
  var caller = post.caller = call ? post.caller.caller.name : post.caller.name;
  var options = {
    host: host,
    port: port,
    path: path,
    method: 'POST',
    headers: {
      'Content-Length': contents.length
    }
  };
  var result = "";
  var donecb = false;
  function callback(arg) {
    if (!donecb) cb(arg);
    donecb = true;
  }
  url = 'http://' + options.host + ':' + options.port + (options.path[0] == '/' ? '' : '/') + options.path;
  // console.log(caller + ': POST ' + url);
  var req = http.request(options, function(res) {
    if (res.statusCode != 200) {
      console.log(caller + ': POST ' + url + ' -> HTTP status code ' + res.statusCode + ':\n' + res);
      callback(null);
      return;
    }
    res.on('data', function(chunk) {
      result += chunk;
    });
    res.on('end', function() {
      console.log(caller + ':', contents, '->', url, '->', result);
      callback(result);
    });
    res.on('close', function() {
      callback(null);
    });
  });
  req.on('error', function(e) {
    console.log(caller + ': POST ' + url + ' -> FAILED due to ' + e);
    callback(null);
  });
  req.write(contents);
  req.end();
}

function call(path, args, callback) {
  post(path, JSON.stringify(args, undefined, INDENT_JSON), function(r) {
    var result = null;
    try {
      if (r) {
        result = JSON.parse(r);
      } else {
        result = {
          success: false,
          exception: 'POST FAILED'
        };
      }
    } catch (e) {
      result = {
        success: false,
        exception: e
      };
    }
    assert.ok(result);
    callback(result);
  });
}

function checkConnectionSoon(controller_port, delay_s) {
  check_connection_delay_s = delay_s;
  console.log('Will check connection again in', delay_s, 'seconds');
  setTimeout(function() { checkConnection(controller_port); }, delay_s * 1000);
}

function checkConnection(controller_port) {
  console.log(checkConnection.name + '()');
  var info = {
    controller_port: controller_port,
    serverid: SERVERID,
    pairing_key: pairing_key,
  };
  uri = '/register-controller';
  call(uri, info, function(r) {
    if (!r || !r.success || r.backend != 'matcher') {
      console.log(checkConnection.name, 'FAILED', r);
      // use exponential backoff + fuzz factor
      var delay_s = Math.min(check_connection_delay_s_max, check_connection_delay_s * 2 + Math.ceil(Math.random() * 5));
      checkConnectionSoon(controller_port, delay_s);
      return;
    }
    console.log(checkConnection.name, 'SUCCESS', info, '->', uri, '->', r);
    checkConnectionSoon(controller_port, check_connection_delay_s_ok);
  });
}

function updateGameState(controller_port, game_state) {
  var info = {
    controller_port: controller_port,
    serverid: SERVERID,
    game_state: game_state,
  };
  uri = '/update-game-state';
  call(uri, info, function(r) {
    if (!r || !r.success || r.backend != 'matcher') {
      console.log('UNEXPECTED RESPONSE', r);
    }
  });
}
exports.updateGameState = updateGameState;

function reportGameOver(instance_id, stats) {
  var info = {
    name: instance_id,
    serverid: SERVERID,
    counts: stats.counts,
    logs: stats.logs,
  };
  uri = '/game-over';
  call(uri, info, function(r) {
    if (!r || !r.success || r.backend != 'matcher') {
      console.log('UNEXPECTED RESPONSE', r);
    }
  });
}
exports.reportGameOver = reportGameOver

function connect(h, p, controller_port, serverid) {
  assert.ok(!host);
  assert.ok(!port);
  assert.ok(h);
  assert.ok(p);
  host = h;
  port = p;
  SERVERID = serverid
  checkConnection(controller_port);
}
exports.connect = connect;

<commit_msg>remove redundant logging<commit_after>/*Copyright 2012 Google Inc. All Rights Reserved.

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.*/

/**
 * @fileoverview Description of this file.
 * @author ctiller@google.com (Craig Tiller)
 */

var http = require('http')
var assert = require('assert')
var fs = require('fs')

var host = null;
var port = null;
var SERVERID = null;
var DEBUG = true;
var INDENT_JSON = DEBUG ? 4: null;

exports.DEBUG = DEBUG
exports.INDENT_JSON = INDENT_JSON

var pairing_key = JSON.parse(fs.readFileSync(__dirname + '/../shared/pairing-key.json')).key
exports.pairing_key = pairing_key

// exponential backoff knobs
var check_connection_delay_s = .1;
var check_connection_delay_s_max = 300;
var check_connection_delay_s_ok = 30;

function get(path, cb) {
  var caller = get.caller.name;
  var options = {
    host: host,
    port: port,
    path: path
  };
  var result = "";
  var donecb = false;
  function callback(arg) {
    if (!donecb) cb(arg);
    donecb = true;
  }
  url = 'http://' + options.host + ':' + options.port + (options.path[0] == '/' ? '' : '/') + options.path;
  // console.log(caller + ': GET ' + url);
  http.get(options, function(res) {
    if (res.statusCode != 200) {
      console.log(caller + ': GET ' + url + ' -> HTTP status code ' + res.statusCode);
      callback(null);
      return;
    }
    res.on('data', function(chunk) {
      result += chunk;
    });
    res.on('end', function() {
      console.log(caller + ': GET', url, '->', result);
      callback(result);
    });
    res.on('close', function() {
      callback(null);
    });
  }).on('error', function(e) {
    console.log(caller + ': GET ' + url + ' -> FAILED due to ' + e);
    callback(null);
  })
}

function post(path, contents, cb) {
  var caller = post.caller = call ? post.caller.caller.name : post.caller.name;
  var options = {
    host: host,
    port: port,
    path: path,
    method: 'POST',
    headers: {
      'Content-Length': contents.length
    }
  };
  var result = "";
  var donecb = false;
  function callback(arg) {
    if (!donecb) cb(arg);
    donecb = true;
  }
  url = 'http://' + options.host + ':' + options.port + (options.path[0] == '/' ? '' : '/') + options.path;
  // console.log(caller + ': POST ' + url);
  var req = http.request(options, function(res) {
    if (res.statusCode != 200) {
      console.log(caller + ': POST ' + url + ' -> HTTP status code ' + res.statusCode + ':\n' + res);
      callback(null);
      return;
    }
    res.on('data', function(chunk) {
      result += chunk;
    });
    res.on('end', function() {
      console.log(caller + ':', contents, '->', url, '->', result);
      callback(result);
    });
    res.on('close', function() {
      callback(null);
    });
  });
  req.on('error', function(e) {
    console.log(caller + ': POST ' + url + ' -> FAILED due to ' + e);
    callback(null);
  });
  req.write(contents);
  req.end();
}

function call(path, args, callback) {
  post(path, JSON.stringify(args, undefined, INDENT_JSON), function(r) {
    var result = null;
    try {
      if (r) {
        result = JSON.parse(r);
      } else {
        result = {
          success: false,
          exception: 'POST FAILED'
        };
      }
    } catch (e) {
      result = {
        success: false,
        exception: e
      };
    }
    assert.ok(result);
    callback(result);
  });
}

function checkConnectionSoon(controller_port, delay_s) {
  check_connection_delay_s = delay_s;
  console.log('Will call', checkConnection.name, 'again in', delay_s, 'seconds');
  setTimeout(function() { checkConnection(controller_port); }, delay_s * 1000);
}

function checkConnection(controller_port) {
  var info = {
    controller_port: controller_port,
    serverid: SERVERID,
    pairing_key: pairing_key,
  };
  uri = '/register-controller';
  call(uri, info, function(r) {
    if (!r || !r.success || r.backend != 'matcher') {
      // use exponential backoff + fuzz factor
      var delay_s = Math.min(check_connection_delay_s_max, check_connection_delay_s * 2 + Math.ceil(Math.random() * 5));
      checkConnectionSoon(controller_port, delay_s);
      return;
    }
    checkConnectionSoon(controller_port, check_connection_delay_s_ok);
  });
}

function updateGameState(controller_port, game_state) {
  var info = {
    controller_port: controller_port,
    serverid: SERVERID,
    game_state: game_state,
  };
  uri = '/update-game-state';
  call(uri, info, function(r) {
    if (!r || !r.success || r.backend != 'matcher') {
      console.log('UNEXPECTED RESPONSE', r);
    }
  });
}
exports.updateGameState = updateGameState;

function reportGameOver(instance_id, stats) {
  var info = {
    name: instance_id,
    serverid: SERVERID,
    counts: stats.counts,
    logs: stats.logs,
  };
  uri = '/game-over';
  call(uri, info, function(r) {
    if (!r || !r.success || r.backend != 'matcher') {
      console.log('UNEXPECTED RESPONSE', r);
    }
  });
}
exports.reportGameOver = reportGameOver

function connect(h, p, controller_port, serverid) {
  assert.ok(!host);
  assert.ok(!port);
  assert.ok(h);
  assert.ok(p);
  host = h;
  port = p;
  SERVERID = serverid
  checkConnection(controller_port);
}
exports.connect = connect;

<|endoftext|>


<commit_before>function something()
{
    var x = window.localStorage.getItem('aaa');

    window.localStorage.setItem('aaa', 555);

    alert(x);
}<commit_msg>keep x var in localStorage<commit_after>function something()
{
    var x = window.localStorage.getItem('aaa');
    x = x * 1 + 1;

    window.localStorage.setItem('aaa', x);

    alert(x);
}<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import classes from 'dom-helpers/class'
import getWidth from 'dom-helpers/query/width'
import scrollbarSize from 'dom-helpers/util/scrollbarSize'

import localizer from './localizer'
import message from './utils/messages'
import dates from './utils/dates'
import { navigate } from './utils/constants'
import { accessor as get } from './utils/accessors'
import { accessor, dateFormat, dateRangeFormat } from './utils/propTypes'
import { inRange } from './utils/eventLevels'
import { isSelected } from './utils/selection'

class Agenda extends React.Component {
  static propTypes = {
    events: PropTypes.array,
    date: PropTypes.instanceOf(Date),
    length: PropTypes.number.isRequired,
    titleAccessor: accessor.isRequired,
    tooltipAccessor: accessor.isRequired,
    allDayAccessor: accessor.isRequired,
    startAccessor: accessor.isRequired,
    endAccessor: accessor.isRequired,
    eventPropGetter: PropTypes.func,
    selected: PropTypes.object,

    agendaDateFormat: dateFormat,
    agendaTimeFormat: dateFormat,
    agendaTimeRangeFormat: dateRangeFormat,
    culture: PropTypes.string,

    components: PropTypes.object.isRequired,
    messages: PropTypes.shape({
      date: PropTypes.string,
      time: PropTypes.string,
    }),
  }

  static defaultProps = {
    length: 30,
  }

  componentDidMount() {
    this._adjustHeader()
  }

  componentDidUpdate() {
    this._adjustHeader()
  }

  render() {
    let { length, date, events, startAccessor } = this.props
    let messages = message(this.props.messages)
    let end = dates.add(date, length, 'day')

    let range = dates.range(date, end, 'day')

    events = events.filter(event => inRange(event, date, end, this.props))

    events.sort((a, b) => +get(a, startAccessor) - +get(b, startAccessor))

    return (

                {messages.date}

                {messages.time}

              {messages.event}

              {range.map((day, idx) => this.renderDay(day, events, idx))}

    )
  }

  renderDay = (day, events, dayKey) => {
    let {
      culture,
      components,
      titleAccessor,
      agendaDateFormat,
      eventPropGetter,
      startAccessor,
      endAccessor,
      selected,
    } = this.props

    let EventComponent = components.event
    let DateComponent = components.date

    events = events.filter(e => inRange(e, day, day, this.props))

    return events.map((event, idx) => {
      const { className, style } = eventPropGetter
        ? eventPropGetter(
            event,
            get(event, startAccessor),
            get(event, endAccessor),
            isSelected(event, selected)
          )
        : {}
      let dateLabel =
        idx === 0 && localizer.format(day, agendaDateFormat, culture)
      let first =
        idx === 0 ? (

            {DateComponent ? (
              <DateComponent day={day} label={dateLabel} />
            ) : (
              dateLabel
            )}

        ) : (
          false
        )

      let title = get(event, titleAccessor)

      return (

          {first}

            {this.timeRangeLabel(day, event)}

            {EventComponent ? (
              <EventComponent event={event} title={title} />
            ) : (
              title
            )}

      )
    }, [])
  }

  timeRangeLabel = (day, event) => {
    let {
      endAccessor,
      startAccessor,
      allDayAccessor,
      culture,
      messages,
      components,
    } = this.props

    let labelClass = '',
      TimeComponent = components.time,
      label = message(messages).allDay

    let start = get(event, startAccessor)
    let end = get(event, endAccessor)

    if (!get(event, allDayAccessor)) {
      if (dates.eq(start, end, 'day')) {
        label = localizer.format(
          { start, end },
          this.props.agendaTimeRangeFormat,
          culture
        )
      } else if (dates.eq(day, start, 'day')) {
        label = localizer.format(start, this.props.agendaTimeFormat, culture)
      } else if (dates.eq(day, end, 'day')) {
        label = localizer.format(end, this.props.agendaTimeFormat, culture)
      }
    }

    if (dates.gt(day, start, 'day')) labelClass = 'rbc-continues-prior'
    if (dates.lt(day, end, 'day')) labelClass += ' rbc-continues-after'

    return (

        {TimeComponent ? (
          <TimeComponent event={event} day={day} label={label} />
        ) : (
          label
        )}

    )
  }

  _adjustHeader = () => {
    let header = this.refs.header
    let firstRow = this.refs.tbody.firstChild

    if (!firstRow) return

    let isOverflowing =
      this.refs.content.scrollHeight > this.refs.content.clientHeight
    let widths = this._widths || []

    this._widths = [
      getWidth(firstRow.children[0]),
      getWidth(firstRow.children[1]),
    ]

    if (widths[0] !== this._widths[0] || widths[1] !== this._widths[1]) {
      this.refs.dateCol.style.width = this._widths[0] + 'px'
      this.refs.timeCol.style.width = this._widths[1] + 'px'
    }

    if (isOverflowing) {
      classes.addClass(header, 'rbc-header-overflowing')
      header.style.marginRight = scrollbarSize() + 'px'
    } else {
      classes.removeClass(header, 'rbc-header-overflowing')
    }
  }
}

Agenda.range = (start, { length = Agenda.defaultProps.length }) => {
  let end = dates.add(start, length, 'day')
  return { start, end }
}

Agenda.navigate = (date, action, { length = Agenda.defaultProps.length }) => {
  switch (action) {
    case navigate.PREVIOUS:
      return dates.add(date, -length, 'day')

    case navigate.NEXT:
      return dates.add(date, length, 'day')

    default:
      return date
  }
}

Agenda.title = (
  start,
  { length = Agenda.defaultProps.length, formats, culture }
) => {
  let end = dates.add(start, length, 'day')
  return localizer.format({ start, end }, formats.agendaHeaderFormat, culture)
}

export default Agenda
<commit_msg>Fixed determining events for a given day, regardless of current time (#850)<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import classes from 'dom-helpers/class'
import getWidth from 'dom-helpers/query/width'
import scrollbarSize from 'dom-helpers/util/scrollbarSize'

import localizer from './localizer'
import message from './utils/messages'
import dates from './utils/dates'
import { navigate } from './utils/constants'
import { accessor as get } from './utils/accessors'
import { accessor, dateFormat, dateRangeFormat } from './utils/propTypes'
import { inRange } from './utils/eventLevels'
import { isSelected } from './utils/selection'

class Agenda extends React.Component {
  static propTypes = {
    events: PropTypes.array,
    date: PropTypes.instanceOf(Date),
    length: PropTypes.number.isRequired,
    titleAccessor: accessor.isRequired,
    tooltipAccessor: accessor.isRequired,
    allDayAccessor: accessor.isRequired,
    startAccessor: accessor.isRequired,
    endAccessor: accessor.isRequired,
    eventPropGetter: PropTypes.func,
    selected: PropTypes.object,

    agendaDateFormat: dateFormat,
    agendaTimeFormat: dateFormat,
    agendaTimeRangeFormat: dateRangeFormat,
    culture: PropTypes.string,

    components: PropTypes.object.isRequired,
    messages: PropTypes.shape({
      date: PropTypes.string,
      time: PropTypes.string,
    }),
  }

  static defaultProps = {
    length: 30,
  }

  componentDidMount() {
    this._adjustHeader()
  }

  componentDidUpdate() {
    this._adjustHeader()
  }

  render() {
    let { length, date, events, startAccessor } = this.props
    let messages = message(this.props.messages)
    let end = dates.add(date, length, 'day')

    let range = dates.range(date, end, 'day')

    events = events.filter(event => inRange(event, date, end, this.props))

    events.sort((a, b) => +get(a, startAccessor) - +get(b, startAccessor))

    return (

                {messages.date}

                {messages.time}

              {messages.event}

              {range.map((day, idx) => this.renderDay(day, events, idx))}

    )
  }

  renderDay = (day, events, dayKey) => {
    let {
      culture,
      components,
      titleAccessor,
      agendaDateFormat,
      eventPropGetter,
      startAccessor,
      endAccessor,
      selected,
    } = this.props

    let EventComponent = components.event
    let DateComponent = components.date

    events = events.filter(e =>
      inRange(e, dates.startOf(day, 'day'), dates.endOf(day, 'day'), this.props)
    )

    return events.map((event, idx) => {
      const { className, style } = eventPropGetter
        ? eventPropGetter(
            event,
            get(event, startAccessor),
            get(event, endAccessor),
            isSelected(event, selected)
          )
        : {}
      let dateLabel =
        idx === 0 && localizer.format(day, agendaDateFormat, culture)
      let first =
        idx === 0 ? (

            {DateComponent ? (
              <DateComponent day={day} label={dateLabel} />
            ) : (
              dateLabel
            )}

        ) : (
          false
        )

      let title = get(event, titleAccessor)

      return (

          {first}

            {this.timeRangeLabel(day, event)}

            {EventComponent ? (
              <EventComponent event={event} title={title} />
            ) : (
              title
            )}

      )
    }, [])
  }

  timeRangeLabel = (day, event) => {
    let {
      endAccessor,
      startAccessor,
      allDayAccessor,
      culture,
      messages,
      components,
    } = this.props

    let labelClass = '',
      TimeComponent = components.time,
      label = message(messages).allDay

    let start = get(event, startAccessor)
    let end = get(event, endAccessor)

    if (!get(event, allDayAccessor)) {
      if (dates.eq(start, end, 'day')) {
        label = localizer.format(
          { start, end },
          this.props.agendaTimeRangeFormat,
          culture
        )
      } else if (dates.eq(day, start, 'day')) {
        label = localizer.format(start, this.props.agendaTimeFormat, culture)
      } else if (dates.eq(day, end, 'day')) {
        label = localizer.format(end, this.props.agendaTimeFormat, culture)
      }
    }

    if (dates.gt(day, start, 'day')) labelClass = 'rbc-continues-prior'
    if (dates.lt(day, end, 'day')) labelClass += ' rbc-continues-after'

    return (

        {TimeComponent ? (
          <TimeComponent event={event} day={day} label={label} />
        ) : (
          label
        )}

    )
  }

  _adjustHeader = () => {
    let header = this.refs.header
    let firstRow = this.refs.tbody.firstChild

    if (!firstRow) return

    let isOverflowing =
      this.refs.content.scrollHeight > this.refs.content.clientHeight
    let widths = this._widths || []

    this._widths = [
      getWidth(firstRow.children[0]),
      getWidth(firstRow.children[1]),
    ]

    if (widths[0] !== this._widths[0] || widths[1] !== this._widths[1]) {
      this.refs.dateCol.style.width = this._widths[0] + 'px'
      this.refs.timeCol.style.width = this._widths[1] + 'px'
    }

    if (isOverflowing) {
      classes.addClass(header, 'rbc-header-overflowing')
      header.style.marginRight = scrollbarSize() + 'px'
    } else {
      classes.removeClass(header, 'rbc-header-overflowing')
    }
  }
}

Agenda.range = (start, { length = Agenda.defaultProps.length }) => {
  let end = dates.add(start, length, 'day')
  return { start, end }
}

Agenda.navigate = (date, action, { length = Agenda.defaultProps.length }) => {
  switch (action) {
    case navigate.PREVIOUS:
      return dates.add(date, -length, 'day')

    case navigate.NEXT:
      return dates.add(date, length, 'day')

    default:
      return date
  }
}

Agenda.title = (
  start,
  { length = Agenda.defaultProps.length, formats, culture }
) => {
  let end = dates.add(start, length, 'day')
  return localizer.format({ start, end }, formats.agendaHeaderFormat, culture)
}

export default Agenda
<|endoftext|>