<commit_before>/**
* Dashboard controller
* @namespace crowdsource.dashboard.controllers
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.dashboard.controllers')
    .controller('DashboardController', DashboardController);

  DashboardController.$inject = ['$window', '$location', '$scope', '$mdToast', 'Dashboard', '$filter', '$routeParams', 'RankingService'];

  /**
  * @namespace DashboardController
  */
  function DashboardController($window, $location, $scope, $mdToast, Dashboard, $filter, $routeParams, RankingService) {
      var self = this;
      self.toggleAll = toggleAll;
      self.toggle = toggle;
      self.isSelected = isSelected;
      self.selectedItems = [];
      self.getSavedTask = getSavedTask;
      self.dropSavedTasks = dropSavedTasks;

      getWorkerData();
      getRequesterData();

      //Just a simple example of how to get all tasks that are currently in progress
      //TODO display data in table

      function toggleAll() {
        if(!self.selectedItems.length) {
          angular.forEach(self.inProgressTaskWorkers, function(obj) {
            self.selectedItems.push(obj);
          });
          self.selectAll = true;
        } else {
          self.selectedItems = [];
          self.selectAll = false;
        }
      }

      function toggle(item) {
          var idx = self.selectedItems.indexOf(item);
          if (idx > -1) self.selectedItems.splice(idx, 1);
          else self.selectedItems.push(item);
      }
      function isSelected(item){
          return !(self.selectedItems.indexOf(item) < 0);
      }

      activate();
      function activate() {
        Dashboard.getTasksByStatus().then(
          function success(data) {
            self.inProgressTaskWorkers = data[0]['In Progress'];
            self.acceptedTaskWorkers = data[0]['Accepted'];
            self.rejectedTaskWorkers = data[0]['Rejected'];
            self.returnedTaskWorkers = data[0]['Returned'];
            processAccepted();
          },
          function error(data) {
            $mdToast.showSimple('Could not retrieve dashboard.')
          }).finally(function(){}
        );
      }

      function processAccepted() {
        self.acceptedModules = {};
        for(var i = 0; i < self.acceptedTaskWorkers.length; i++) {
          var module_id = self.acceptedTaskWorkers[i].module.id;
          if(module_id in self.acceptedModules) {
            self.acceptedModules[module_id].tasks_completed += 1;
          } else {
            self.acceptedModules[module_id] = {
              project: self.acceptedTaskWorkers[i].project_name,
              name: self.acceptedTaskWorkers[i].module.name,
              price: self.acceptedTaskWorkers[i].module.price,
              requester_alias: self.acceptedTaskWorkers[i].requester_alias,
              tasks_completed: 1,
              //assumes we pay all taskworkers at the same time which we will do for microsoft
              is_paid: self.acceptedTaskWorkers[i].is_paid ? 'yes': 'not yet'
            }
          }
        }
        for(var i=0; i < self.requesterRankings.length; i++) {

        }
        self.totalEarned = 0;
        angular.forEach(self.acceptedModules, function(obj) {
          if(obj.is_paid === "yes") self.totalEarned += obj.price * obj.tasks_completed;
        });
      }

      //TODO process data as html upon click of inprogress task and allow worker to finish/delete task
      //Reroute to task feed or just stay in dashboard???
      function getSavedTask() {
        if(self.selectedItems.length != 1) {
          $mdToast.showSimple('You can only return to 1 task at a time');
          return;
        }
        $location.path('/task/' + self.selectedItems[0].task + '/' + self.selectedItems[0].id);
      }

      function dropSavedTasks() {
        var request_data = {
          task_ids: []
        };
        angular.forEach(self.selectedItems, function(obj) {
            request_data.task_ids.push(obj.task);
        });
        Dashboard.dropSavedTasks(request_data).then(
            function success(response) {
                self.selectedItems = [];
                self.selectAll = false;
                activate();
            },
            function error(response) {
              $mdToast.showSimple('Drop tasks failed.')
            }
        ).finally(function () {});
      }

    function getWorkerData() {
      self.pendingRankings = [];
      RankingService.getWorkerRankings().then(
        function success (resp) {
          var data = resp[0];
          data = data.map(function (item) {
            item.reviewType = 'worker';
            return item;
          });
          self.pendingRankings = data;
        },
        function error (errResp) {
          var data = resp[0];
          $mdToast.showSimple('Could get worker rankings.');
        });
    }

    function getRequesterData() {
      self.requesterRankings = [];
      RankingService.getRequesterRankings().then(
        function success (resp) {
          var data = resp[0];
          data = data.map(function (item) {
            item.reviewType = 'requester';
            return item;
          });
          self.requesterRankings = data;
        },
        function error (errResp) {
          var data = resp[0];
          $mdToast.showSimple('Could get requester rankings.');
        });
    }

    function refreshData(reviewType) {
      if (reviewType === 'worker') {
        getRequesterData();
      } else {
        getWorkerData();
      }
    }

    self.handleRatingSubmit = function (rating, entry) {
      entry.current_rating = rating;
      if (entry.current_rating_id) {
        RankingService.updateRating(rating, entry).then(function success(resp) {
        }, function error (resp) {
          $mdToast.showSimple('Could not update rating.');
        }).finally(function () {
          refreshData(entry.reviewType);
        });
      } else {
        RankingService.submitRating(rating, entry).then(function success(resp) {
        }, function error (resp) {
          $mdToast.showSimple('Could not submit rating.')
        }).finally(function () {
          refreshData(entry.reviewType);
        });
      }

    }
  }
})();<commit_msg>don't get worker rankings on dashboard<commit_after>/**
* Dashboard controller
* @namespace crowdsource.dashboard.controllers
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.dashboard.controllers')
    .controller('DashboardController', DashboardController);

  DashboardController.$inject = ['$window', '$location', '$scope', '$mdToast', 'Dashboard', '$filter', '$routeParams', 'RankingService'];

  /**
  * @namespace DashboardController
  */
  function DashboardController($window, $location, $scope, $mdToast, Dashboard, $filter, $routeParams, RankingService) {
      var self = this;
      self.toggleAll = toggleAll;
      self.toggle = toggle;
      self.isSelected = isSelected;
      self.selectedItems = [];
      self.getSavedTask = getSavedTask;
      self.dropSavedTasks = dropSavedTasks;

//      getWorkerData();
      getRequesterData();

      //Just a simple example of how to get all tasks that are currently in progress
      //TODO display data in table

      function toggleAll() {
        if(!self.selectedItems.length) {
          angular.forEach(self.inProgressTaskWorkers, function(obj) {
            self.selectedItems.push(obj);
          });
          self.selectAll = true;
        } else {
          self.selectedItems = [];
          self.selectAll = false;
        }
      }

      function toggle(item) {
          var idx = self.selectedItems.indexOf(item);
          if (idx > -1) self.selectedItems.splice(idx, 1);
          else self.selectedItems.push(item);
      }
      function isSelected(item){
          return !(self.selectedItems.indexOf(item) < 0);
      }

      activate();
      function activate() {
        Dashboard.getTasksByStatus().then(
          function success(data) {
            self.inProgressTaskWorkers = data[0]['In Progress'];
            self.acceptedTaskWorkers = data[0]['Accepted'];
            self.rejectedTaskWorkers = data[0]['Rejected'];
            self.returnedTaskWorkers = data[0]['Returned'];
            processAccepted();
          },
          function error(data) {
            $mdToast.showSimple('Could not retrieve dashboard.')
          }).finally(function(){}
        );
      }

      function processAccepted() {
        self.acceptedModules = {};
        for(var i = 0; i < self.acceptedTaskWorkers.length; i++) {
          var module_id = self.acceptedTaskWorkers[i].module.id;
          if(module_id in self.acceptedModules) {
            self.acceptedModules[module_id].tasks_completed += 1;
          } else {
            self.acceptedModules[module_id] = {
              project: self.acceptedTaskWorkers[i].project_name,
              name: self.acceptedTaskWorkers[i].module.name,
              price: self.acceptedTaskWorkers[i].module.price,
              requester_alias: self.acceptedTaskWorkers[i].requester_alias,
              tasks_completed: 1,
              //assumes we pay all taskworkers at the same time which we will do for microsoft
              is_paid: self.acceptedTaskWorkers[i].is_paid ? 'yes': 'not yet'
            }
          }
        }
        for(var i=0; i < self.requesterRankings.length; i++) {

        }
        self.totalEarned = 0;
        angular.forEach(self.acceptedModules, function(obj) {
          if(obj.is_paid === "yes") self.totalEarned += obj.price * obj.tasks_completed;
        });
      }

      //TODO process data as html upon click of inprogress task and allow worker to finish/delete task
      //Reroute to task feed or just stay in dashboard???
      function getSavedTask() {
        if(self.selectedItems.length != 1) {
          $mdToast.showSimple('You can only return to 1 task at a time');
          return;
        }
        $location.path('/task/' + self.selectedItems[0].task + '/' + self.selectedItems[0].id);
      }

      function dropSavedTasks() {
        var request_data = {
          task_ids: []
        };
        angular.forEach(self.selectedItems, function(obj) {
            request_data.task_ids.push(obj.task);
        });
        Dashboard.dropSavedTasks(request_data).then(
            function success(response) {
                self.selectedItems = [];
                self.selectAll = false;
                activate();
            },
            function error(response) {
              $mdToast.showSimple('Drop tasks failed.')
            }
        ).finally(function () {});
      }

    function getWorkerData() {
      self.pendingRankings = [];
      RankingService.getWorkerRankings().then(
        function success (resp) {
          var data = resp[0];
          data = data.map(function (item) {
            item.reviewType = 'worker';
            return item;
          });
          self.pendingRankings = data;
        },
        function error (errResp) {
          var data = resp[0];
          $mdToast.showSimple('Could not get worker rankings.');
        });
    }

    function getRequesterData() {
      self.requesterRankings = [];
      RankingService.getRequesterRankings().then(
        function success (resp) {
          var data = resp[0];
          data = data.map(function (item) {
            item.reviewType = 'requester';
            return item;
          });
          self.requesterRankings = data;
        },
        function error (errResp) {
          var data = resp[0];
          $mdToast.showSimple('Could not get requester rankings.');
        });
    }

    function refreshData(reviewType) {
      if (reviewType === 'worker') {
        getRequesterData();
      } else {
        getWorkerData();
      }
    }

    self.handleRatingSubmit = function (rating, entry) {
      entry.current_rating = rating;
      if (entry.current_rating_id) {
        RankingService.updateRating(rating, entry).then(function success(resp) {
        }, function error (resp) {
          $mdToast.showSimple('Could not update rating.');
        }).finally(function () {
          refreshData(entry.reviewType);
        });
      } else {
        RankingService.submitRating(rating, entry).then(function success(resp) {
        }, function error (resp) {
          $mdToast.showSimple('Could not submit rating.')
        }).finally(function () {
          refreshData(entry.reviewType);
        });
      }

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


<commit_before>const express = require('express');
const rp = require('request-promise')
const Person = require('../models/Person')
const router = express.Router();

router.post('/', (req, res) => {
  const options = {
    method: 'POST',
    uri: 'http://api.kairos.com/recognize',
    headers: {
      'content-type': 'application/json',
      app_id: process.env.KAIROS_ID,
      app_key: process.env.KAIROS_KEY
    },
    body: {
      image: req.body.image,
      gallery_name: 'facedex'
    },
    json: true
  }
  rp(options)
    .then((APIresponse) => {
      const namesList = APIresponse.images.map(face => face.transaction.subject_id)
      console.log('namesList is: ' + namesList)
      const peopleList = namesList.map(name => {
        console.log('looking in db for: ' + name)
        return Person.findOne({ name })
        .lean()
      })
      return Promise.all(peopleList)
    })
    .then(people => res.send(people))
    .catch(err => res.status(400).send(err))
})

module.exports = router;
<commit_msg>New logic for recognize<commit_after>const express = require('express');
const rp = require('request-promise')
const Person = require('../models/Person')
const router = express.Router();

router.post('/', (req, res) => {
  const options = {
    method: 'POST',
    uri: 'http://api.kairos.com/recognize',
    headers: {
      'content-type': 'application/json',
      app_id: process.env.KAIROS_ID,
      app_key: process.env.KAIROS_KEY
    },
    body: {
      image: req.body.image,
      gallery_name: 'facedex'
    },
    json: true
  }
  rp(options)
    .then((APIresponse) => {
      if (APIresponse.Errors) {
        res.send({
          people: [],
          error: APIresponse.Errors[0].Message
        })
        return
      }

      const namesList = APIresponse.images.map(face => face.transaction.subject_id)
      console.log('namesList is: ' + namesList)
      const peopleList = namesList.map(name => {
        console.log('looking in db for: ' + name)
        return Person.findOne({ name }).lean()
      })
      return Promise.all(peopleList)
    })
    .then(people => res.send({people, error: null}))
    .catch(err => res.status(400).send(err))
})

module.exports = router;
<|endoftext|>


<commit_before>var CmsLess = ( function($) {

  var config = {
    contentPath: 'cms-less-content',
    destinationSelector: '#cms-less-destination',
    anchorDelimiter: '-',
    notFoundPageName: '404'
  }

  function loadContent(pageName) {
    beforePageLoad(pageName);
    $(config.destinationSelector).load(expandedContentPath(pageName), function(response, status) {
      var actualPageName;
      if(status == 'error') {
        $(config.destinationSelector).load(expandedContentPath(config.notFoundPageName));
        markPageAsIndexable(false);
        afterPageLoad(config.notFoundPageName);
      } else {
        markPageAsIndexable(true);
        afterPageLoad(pageName);
      }
    });
  }

  function markPageAsIndexable(indexable) {
    if(indexable) {
      $("head meta[name='robots']").remove();
    } else {
      $("head").append($("<meta name='robots' content='noindex' />"));
    }
  }

  function beforePageLoad(newPageName) {
    // scroll to the top
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  function afterPageLoad(newPageName) {
    // dispatch an event
    pageChangeEvent = new CustomEvent('cms-less-page-change', { 'detail': { pageName: newPageName }});
    document.dispatchEvent(pageChangeEvent);
  }

  function expandedContentPath(pageName) {
    return config.contentPath + "/" + pageName + ".html";
  }

  function loadContentFromHash() {
    var pageName = extractPageNameFromHash() || 'index';

    loadContent(pageName);
  }

  function extractPageNameFromHash(hash) {
    hash = hash || window.location.hash
    delimiterIndex = hash.lastIndexOf(config.anchorDelimiter);
    if(delimiterIndex > 0) {
      return hash.slice(1, delimiterIndex);
    } else {
      return hash.slice(1);
    }
  }

  function Init(options) {
    config = $.extend(config, options);
    // if the path has a query parameter, change it to a hash parameter
    if(window.location.href.match(/\?p=.+/)) {
      var pageName = window.location.href.match(/\?p=(.*)$/)[1].split("&")[0];
      window.location.href = "/#" + pageName;
    }

    loadContentFromHash();
    $(window).bind('hashchange', loadContentFromHash);

    // progressively enhance links
    $("a[data-cms-less-path]").each(function() {
      var link = $(this);
      link.attr("href", "#" + link.attr("data-cms-less-path"));
    });
  }

  return {
    Init : Init,
    PageName : extractPageNameFromHash
  };

} )( jQuery );
<commit_msg>use history.replaceState instead of redirecting ?p=page requests<commit_after>var CmsLess = ( function($) {

  var config = {
    contentPath: 'cms-less-content',
    destinationSelector: '#cms-less-destination',
    anchorDelimiter: '-',
    notFoundPageName: '404'
  }

  function loadContent(pageName) {
    beforePageLoad(pageName);
    $(config.destinationSelector).load(expandedContentPath(pageName), function(response, status) {
      var actualPageName;
      if(status == 'error') {
        $(config.destinationSelector).load(expandedContentPath(config.notFoundPageName));
        markPageAsIndexable(false);
        afterPageLoad(config.notFoundPageName);
      } else {
        markPageAsIndexable(true);
        afterPageLoad(pageName);
      }
    });
  }

  function markPageAsIndexable(indexable) {
    if(indexable) {
      $("head meta[name='robots']").remove();
    } else {
      $("head").append($("<meta name='robots' content='noindex' />"));
    }
  }

  function beforePageLoad(newPageName) {
    // scroll to the top
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  function afterPageLoad(newPageName) {
    // dispatch an event
    pageChangeEvent = new CustomEvent('cms-less-page-change', { 'detail': { pageName: newPageName }});
    document.dispatchEvent(pageChangeEvent);
  }

  function expandedContentPath(pageName) {
    return config.contentPath + "/" + pageName + ".html";
  }

  function loadContentFromHash() {
    var pageName = extractPageNameFromHash() || 'index';

    loadContent(pageName);
  }

  function extractPageNameFromHash(hash) {
    hash = hash || window.location.hash
    delimiterIndex = hash.lastIndexOf(config.anchorDelimiter);
    if(delimiterIndex > 0) {
      return hash.slice(1, delimiterIndex);
    } else {
      return hash.slice(1);
    }
  }

  function Init(options) {
    config = $.extend(config, options);
    // if the path has a query parameter, change it to a hash parameter
    if(window.location.href.match(/\?p=.+/)) {
      var pageName = window.location.href.match(/\?p=(.*)$/)[1].split("&")[0];
      window.history.replaceState(pageName, document.title, '/#' + pageName);
    }

    loadContentFromHash();
    $(window).bind('hashchange', loadContentFromHash);

    // progressively enhance links
    $("a[data-cms-less-path]").each(function() {
      var link = $(this);
      link.attr("href", "#" + link.attr("data-cms-less-path"));
    });
  }

  return {
    Init : Init,
    PageName : extractPageNameFromHash
  };

} )( jQuery );
<|endoftext|>


<commit_before>/*global emit: false, start: false, log: false, getRow: false, send: false,
  $: false*/

var utils = require('./utils'),
    forms = require('kanso/forms'),
    core = require('kanso/core'),
    templates = require('kanso/templates'),
    db = require('kanso/db'),
    flashmessages = require('kanso/flashmessages');

exports.addtype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + req.query.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            types = utils.appRequire(ddoc, 'kanso/types'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[req.query.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        form.validate(req.form);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('add_type.html', req, {
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: req.query.type,
                        description: type.description,
                        type_heading: utils.typeHeading(req.query.type),
                        form: form.toHTML(req)
                    });

                    content += widgets.scriptTagForInit('lib/forms', 'bind');
                    $('#content').html(content);

                    document.title = settings.name + ' - Types - ' + req.query.type;
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Added ' + resp.id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('add_type.html', req, {
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: req.query.type,
                description: type.description,
                type_heading: utils.typeHeading(req.query.type),
                form: form.toHTML(req)
            });

            content += widgets.scriptTagForInit('lib/forms', 'bind');
            $('#content').html(content);

            document.title = settings.name + ' - Types - ' + req.query.type;
        }
    });
};

exports.updatetype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + doc.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[doc.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        form.validate(req.form);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('edit_type.html', req, {
                        id: req.query.id,
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: doc.type,
                        type_heading: utils.typeHeading(doc.type),
                        form: form.toHTML(req)
                    });

                    content += widgets.scriptTagForInit('lib/forms', 'bind');
                    $('#content').html(content);

                    document.title = settings.name + ' - Types - ' + doc.type;
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Saved changes to ' + doc._id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('edit_type.html', req, {
                id: req.query.id,
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: doc.type,
                type_heading: utils.typeHeading(doc.type),
                form: form.toHTML(req)
            });

            content += widgets.scriptTagForInit('lib/forms', 'bind');
            $('#content').html(content);

            document.title = settings.name + ' - Types - ' + doc.type;
        }
    });
};

exports.deletetype = function (doc, req) {
    var baseURL = require('kanso/utils').getBaseURL();

    if (!req.client) {
        var loc = baseURL + '/' + req.query.app + '/types/' + doc.type;
        doc._deleted = true;
        flashmessages.addMessage(req, {
            type: 'success',
            message: 'Deleted ' + doc._id
        });
        return [doc, {code: 302, headers: {'Location': loc}}];
    }
    db.removeDoc(doc, function (err, resp) {
        if (err) {
            flashmessages.addMessage(req, {
                type: 'error',
                message: err.message || err.toString()
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'success',
                message: 'Deleted ' + doc._id
            });
        }
        core.setURL('GET', core.appPath(
            (req.form && req.form.next) ||
            ('/' + req.query.app + '/types/' + doc.type)
        ));
    });
};
<commit_msg>Adjust includes to require widgets module.<commit_after>/*global emit: false, start: false, log: false, getRow: false, send: false,
  $: false*/

var utils = require('./utils'),
    db = require('kanso/db'),
    forms = require('kanso/forms'),
    core = require('kanso/core'),
    templates = require('kanso/templates'),
    widgets = require('kanso/widgets'),
    flashmessages = require('kanso/flashmessages');

exports.addtype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + req.query.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            types = utils.appRequire(ddoc, 'kanso/types'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[req.query.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        form.validate(req.form);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('add_type.html', req, {
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: req.query.type,
                        description: type.description,
                        type_heading: utils.typeHeading(req.query.type),
                        form: form.toHTML(req)
                    });

                    content += widgets.scriptTagForInit('lib/forms', 'bind');
                    $('#content').html(content);

                    document.title = settings.name + ' - Types - ' + req.query.type;
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Added ' + resp.id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('add_type.html', req, {
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: req.query.type,
                description: type.description,
                type_heading: utils.typeHeading(req.query.type),
                form: form.toHTML(req)
            });

            content += widgets.scriptTagForInit('lib/forms', 'bind');
            $('#content').html(content);

            document.title = settings.name + ' - Types - ' + req.query.type;
        }
    });
};

exports.updatetype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + doc.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[doc.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        form.validate(req.form);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('edit_type.html', req, {
                        id: req.query.id,
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: doc.type,
                        type_heading: utils.typeHeading(doc.type),
                        form: form.toHTML(req)
                    });

                    content += widgets.scriptTagForInit('lib/forms', 'bind');
                    $('#content').html(content);

                    document.title = settings.name + ' - Types - ' + doc.type;
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Saved changes to ' + doc._id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('edit_type.html', req, {
                id: req.query.id,
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: doc.type,
                type_heading: utils.typeHeading(doc.type),
                form: form.toHTML(req)
            });

            content += widgets.scriptTagForInit('lib/forms', 'bind');
            $('#content').html(content);

            document.title = settings.name + ' - Types - ' + doc.type;
        }
    });
};

exports.deletetype = function (doc, req) {
    var baseURL = require('kanso/utils').getBaseURL();

    if (!req.client) {
        var loc = baseURL + '/' + req.query.app + '/types/' + doc.type;
        doc._deleted = true;
        flashmessages.addMessage(req, {
            type: 'success',
            message: 'Deleted ' + doc._id
        });
        return [doc, {code: 302, headers: {'Location': loc}}];
    }
    db.removeDoc(doc, function (err, resp) {
        if (err) {
            flashmessages.addMessage(req, {
                type: 'error',
                message: err.message || err.toString()
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'success',
                message: 'Deleted ' + doc._id
            });
        }
        core.setURL('GET', core.appPath(
            (req.form && req.form.next) ||
            ('/' + req.query.app + '/types/' + doc.type)
        ));
    });
};
<|endoftext|>


<commit_before>(function (window) {
  'use strict';

  var htmlEscapes = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    '\'': ''',
    '`': '`'
  };

  var escapeHtmlChar = function (chr) {
    return htmlEscapes[chr];
  };

  var reUnescapedHtml = /[&<>"'`]/g;
  var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source);

  var escape = function (string) {
    return (string && reHasUnescapedHtml.test(string))
      ? string.replace(reUnescapedHtml, escapeHtmlChar)
      : string;
  };

  /**
   * Sets up defaults for all the Template methods such as a default template
   *
   * @constructor
   */
  function Template() {
    this.defaultTemplate
      =	'
'
      +		'
{{title}}
'
      +   '
'
      +     '{{author}}'
      +     '{{written}}'
      +     'View'
      +     '{{readCount}}'
      +     ''
      +     '{{likeCount}}'
      +     ''
      +     '{{dislikeCount}}'
      +   '
'
      +	'
';
  }

  Template.prototype.show = function(data) {
    var i, l;
    var view = '';

    for (i = 0, l = data.length; i < l; i++) {
      var template = this.defaultTemplate;

      template = template.replace('{{id}}', data[i].pid);
      template = template.replace('{{title}}', escape(data[i].title));
      template = template.replace('{{author}}', escape(data[i].author));
      template = template.replace('{{written}}', escape(data[i].written));
      template = template.replace('{{readCount}}', escape(data[i].readCount));
      template = template.replace('{{likeCount}}', escape(data[i].likeCount));
      template = template.replace('{{dislikeCount}}', escape(data[i].dislikeCount));

      view = view + template;
    }

    return view;
  };

  // Export to window
  window.app = window.app || {};
  window.app.Template = Template;
})(window);
<commit_msg>Update post-page<commit_after>(function (window) {
  'use strict';

  var htmlEscapes = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    '\'': ''',
    '`': '`'
  };

  var escapeHtmlChar = function (chr) {
    return htmlEscapes[chr];
  };

  var reUnescapedHtml = /[&<>"'`]/g;
  var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source);

  var escape = function (string) {
    return (string && reHasUnescapedHtml.test(string))
      ? string.replace(reUnescapedHtml, escapeHtmlChar)
      : string;
  };

  /**
   * Sets up defaults for all the Template methods such as a default template
   *
   * @constructor
   */
  function Template() {
    this.defaultTemplate
      =	'
'
      +		''
      +		'
{{title}}
'
      +   '
'
      +     '{{author}}'
      +     '{{written}}'
      +     'View'
      +     '{{readCount}}'
      +     ''
      +     '{{likeCount}}'
      +     ''
      +     '{{dislikeCount}}'
      +   '
'
      +   ''
      +	'
';
  }

  Template.prototype.show = function(data) {
    var i, l;
    var view = '';

    for (i = 0, l = data.length; i < l; i++) {
      var template = this.defaultTemplate;

      template = template.replace(/{{id}}/gi, data[i].pid);
      template = template.replace('{{title}}', escape(data[i].title));
      template = template.replace('{{author}}', escape(data[i].author));
      template = template.replace('{{written}}', escape(data[i].written));
      template = template.replace('{{readCount}}', escape(data[i].readCount));
      template = template.replace('{{likeCount}}', escape(data[i].likeCount));
      template = template.replace('{{dislikeCount}}', escape(data[i].dislikeCount));

      view = view + template;
    }

    return view;
  };

  // Export to window
  window.app = window.app || {};
  window.app.Template = Template;
})(window);
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name ngInit
 * @restrict AC
 *
 * @description
 * The `ngInit` directive allows you to evaluate an expression in the
 * current scope.
 *
 *

 * The only appropriate use of `ngInit` is for aliasing special properties of
 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
 * should use {@link guide/controller controllers} rather than `ngInit`
 * to initialize values on a scope.
 *

 *

 * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
 * sure you have parenthesis for correct precedence:
 *

 *

 *

 *

 *
 * @priority 450
 *
 * @element ANY
 * @param {expression} ngInit {@link guide/expression Expression} to eval.
 *
 * @example
   <example>
     <file name="index.html">

          list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};

     </file>
     <file name="protractor.js" type="protractor">
       it('should alias index positions', function() {
         var elements = element.all(by.css('.example-init'));
         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
       });
     </file>
   </example>
 */
var ngInitDirective = ngDirective({
  priority: 450,
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    };
  }
});
<commit_msg>docs(ngInit): update example to use a module<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name ngInit
 * @restrict AC
 *
 * @description
 * The `ngInit` directive allows you to evaluate an expression in the
 * current scope.
 *
 *

 * The only appropriate use of `ngInit` is for aliasing special properties of
 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
 * should use {@link guide/controller controllers} rather than `ngInit`
 * to initialize values on a scope.
 *

 *

 * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
 * sure you have parenthesis for correct precedence:
 *

 *

 *

 *

 *
 * @priority 450
 *
 * @element ANY
 * @param {expression} ngInit {@link guide/expression Expression} to eval.
 *
 * @example
   <example module="initExample">
     <file name="index.html">

          list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};

     </file>
     <file name="protractor.js" type="protractor">
       it('should alias index positions', function() {
         var elements = element.all(by.css('.example-init'));
         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
       });
     </file>
   </example>
 */
var ngInitDirective = ngDirective({
  priority: 450,
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    };
  }
});
<|endoftext|>


<commit_before>/*
 Descripiton:The apis-asset-manager is used to retriew assets for api calls
 Filename: apis-asset-manager.js
 Created Date: 7/24/2014
 */
var putInStorage = function(options, asset, am, req, session) {
    var resourceFields = am.getAssetResources();
    var ref = require('utils').file;
    var storageModule = require('/modules/data/storage.js').storageModule();
    var storageConfig = require('/config/storage.json');
    var storageManager = new storageModule.StorageManager({
        context: 'storage',
        isCached: false,
        connectionInfo: {
            dataSource: storageConfig.dataSource
        }
    });
    var resource = {};
    var extension = '';
    var uuid;
    var key;
    //Get all of the files that have been sent in the request
    var files = request.getAllFiles();

    if(!files){
        log.warn('User has not provided any resources');
        return;
    }
    for (var index in resourceFields) {
        key = resourceFields[index];
        if (files[key]) {
            resource = {};
            resource.file = files[key];
            extension = ref.getExtension(files[key]);
            resource.contentType = ref.getMimeType(extension);
            uuid = storageManager.put(resource);
            asset.attributes[key] = uuid;
        }
    }
};
var putInOldResources=function(original,asset,am){
    var resourceFields = am.getAssetResources();
    var resourceField;
    for(var index in resourceFields){
        resourceField=resourceFields[index];

        //If the asset attribute value is null then use the old resource
        if(asset.attributes[resourceField]==''){
            asset.attributes[resourceField]=original.attributes[resourceField];
        }
    }
};
var createAsset = function(options, req, res, session) {
    var asset = require('rxt').asset;
    var am = asset.createUserAssetManager(session, options.type);
    var assetReq = req.getAllParameters('UTF-8');
    var asset = am.importAssetFromHttpRequest(assetReq);
    putInStorage(options, asset, am, req, session);
    try {
        am.create(asset);
    } catch (e) {
        log.error('Asset of type: ' + options.type + ' was not created due to ' + e);
        res.sendError(500, 'Failed to create asset of type: ' + options.type);
        return;
    }
    var isLcAttached = am.attachLifecycle(asset);
    //Check if the lifecycle was attached
    if (isLcAttached) {
        var synched = am.synchAsset(asset);
        if (synched) {
            am.invokeDefaultLcAction(asset);
        } else {
            log.warn('Failed to invoke default action as the asset could not be synched.')
        }
    }
};
var updateAsset = function(options, req, res, session) {
    var asset = require('rxt').asset;
    var am = asset.createUserAssetManager(session, options.type);
    var assetReq = req.getAllParameters('UTF-8');
    var asset = am.importAssetFromHttpRequest(assetReq);
    asset.id = options.id;
    putInStorage(options, asset, am, req, session);
    log.info('Asset after storing resources');
    log.info(asset);
    var original=am.get(options.id);
    log.info('After replacing with old resources');
    putInOldResources(original, asset,am);
    log.info(asset);
    //If the user has not uploaded any new resources then use the old resources

    //am.update(asset);
};
var fieldExpansion = function(options, req, res, session) {
    var fields = options.fields;
    var artifacts = options.assets;
    var extendedAssetTemplate = {};
    for (var val in fields) {
        var key = fields[val];
        var value = '';
        extendedAssetTemplate[key] = value;
    }
    var newArtifactTemplateString = stringify(extendedAssetTemplate);
    var modifiedArtifacts = [];
    for (var j in artifacts) {
        var artifactObject = parse(newArtifactTemplateString);
        for (var i in extendedAssetTemplate) {
            artifactObject[i] = artifacts[j].attributes[i];
        }
        modifiedArtifacts.push(artifactObject);
    }
    print(modifiedArtifacts);
    return;
};
var listAssets = function(options, req, res, session) {
    var assetManager = asset.createUserAssetManager(session, options.type);
    var sort = (request.getParameter("sort") || '');
    var sortOrder = DEFAULT_PAGIN.sortOrder;
    if (sort) {
        var order = sort.charAt(0);
        if (order == '+' || order == ' ') {
            sortOrder = 'asc';
            sort = sort.slice(1);
        } else if (order == '-') {
            sortOrder = 'desc';
            sort = sort.slice(1);
        } else {
            sortOrder = DEFAULT_PAGIN.sortOrder;
        }
    }
    var sortBy = (sort || DEFAULT_PAGIN.sortBy);
    var count = (request.getParameter("count") || DEFAULT_PAGIN.count);
    var start = (request.getParameter("start") || DEFAULT_PAGIN.start);
    var paginationLimit = (request.getParameter("paginationLimit") || DEFAULT_PAGIN.paginationLimit);
    var paging = {
        'start': start,
        'count': count,
        'sortOrder': sortOrder,
        'sortBy': sortBy,
        'paginationLimit': paginationLimit
    };
    var q = (request.getParameter("q") || '');
    try {
        if (q) {
            var qString = '{' + q + '}';
            var query = parse(qString);
            //print(query);
            var assets = assetManager.search(query, paging); //doesnt work properly
        } else {
            //print(paging);
            var assets = assetManager.list(paging);
        }
        var expansionFields = (request.getParameter('fields') || '');
        if (expansionFields) {
            options.fields = expansionFields.split(',');
            options.assets = assets;
            fieldExpansion(options, req, res, session);
            //return;
        } else {
            print(assets);
            return assets;
        }
    } catch (e) {
        res.sendError(400, "Your request is malformed");
        log.error(e);
    }
};
var getAsset = function(options, req, res, session) {
    var assetManager = asset.createUserAssetManager(session, options.type);
    try {
        var retrievedAsset = assetManager.get(options.id);
        if (!retrievedAsset) {
            print({
                error: "no matching asset found"
            });
            res.sendError(400, "no matching asset found");
            return;
        } else {
            var expansionFields = (request.getParameter('fields') || '');
            if (expansionFields) {
                options.fields = expansionFields.split(',');
                var assets = [];
                assets.push(retrievedAsset);
                options.assets = assets;
                fieldExpansion(options, req, res, session);
            } else {
                print(retrievedAsset);
                return retrievedAsset;
            }
        }
    } catch (e) {
        res.sendError(400, "No matching asset found");
        log.error(e);
    }
};<commit_msg>Enabled support for update methods<commit_after>/*
 Descripiton:The apis-asset-manager is used to retriew assets for api calls
 Filename: apis-asset-manager.js
 Created Date: 7/24/2014
 */
var putInStorage = function(options, asset, am, req, session) {
    var resourceFields = am.getAssetResources();
    var ref = require('utils').file;
    var storageModule = require('/modules/data/storage.js').storageModule();
    var storageConfig = require('/config/storage.json');
    var storageManager = new storageModule.StorageManager({
        context: 'storage',
        isCached: false,
        connectionInfo: {
            dataSource: storageConfig.dataSource
        }
    });
    var resource = {};
    var extension = '';
    var uuid;
    var key;
    //Get all of the files that have been sent in the request
    var files = request.getAllFiles();

    if(!files){
        log.warn('User has not provided any resources');
        return;
    }
    for (var index in resourceFields) {
        key = resourceFields[index];
        if (files[key]) {
            resource = {};
            resource.file = files[key];
            extension = ref.getExtension(files[key]);
            resource.contentType = ref.getMimeType(extension);
            uuid = storageManager.put(resource);
            asset.attributes[key] = uuid;
        }
    }
};
var putInOldResources=function(original,asset,am){
    var resourceFields = am.getAssetResources();
    var resourceField;
    for(var index in resourceFields){
        resourceField=resourceFields[index];

        //If the asset attribute value is null then use the old resource
        if(asset.attributes[resourceField]==''){
            asset.attributes[resourceField]=original.attributes[resourceField];
        }
    }
};
var createAsset = function(options, req, res, session) {
    var asset = require('rxt').asset;
    var am = asset.createUserAssetManager(session, options.type);
    var assetReq = req.getAllParameters('UTF-8');
    var asset = am.importAssetFromHttpRequest(assetReq);
    putInStorage(options, asset, am, req, session);
    try {
        am.create(asset);
    } catch (e) {
        log.error('Asset of type: ' + options.type + ' was not created due to ' + e);
        res.sendError(500, 'Failed to create asset of type: ' + options.type);
        return;
    }
    var isLcAttached = am.attachLifecycle(asset);
    //Check if the lifecycle was attached
    if (isLcAttached) {
        var synched = am.synchAsset(asset);
        if (synched) {
            am.invokeDefaultLcAction(asset);
        } else {
            log.warn('Failed to invoke default action as the asset could not be synched.')
        }
    }
};
var updateAsset = function(options, req, res, session) {
    var asset = require('rxt').asset;
    var am = asset.createUserAssetManager(session, options.type);
    var assetReq = req.getAllParameters('UTF-8');
    var asset = am.importAssetFromHttpRequest(assetReq);
    asset.id = options.id;
    putInStorage(options, asset, am, req, session);
    var original=am.get(options.id);
    putInOldResources(original, asset,am);
    //If the user has not uploaded any new resources then use the old resources
    am.update(asset);
};
var fieldExpansion = function(options, req, res, session) {
    var fields = options.fields;
    var artifacts = options.assets;
    var extendedAssetTemplate = {};
    for (var val in fields) {
        var key = fields[val];
        var value = '';
        extendedAssetTemplate[key] = value;
    }
    var newArtifactTemplateString = stringify(extendedAssetTemplate);
    var modifiedArtifacts = [];
    for (var j in artifacts) {
        var artifactObject = parse(newArtifactTemplateString);
        for (var i in extendedAssetTemplate) {
            artifactObject[i] = artifacts[j].attributes[i];
        }
        modifiedArtifacts.push(artifactObject);
    }
    print(modifiedArtifacts);
    return;
};
var listAssets = function(options, req, res, session) {
    var assetManager = asset.createUserAssetManager(session, options.type);
    var sort = (request.getParameter("sort") || '');
    var sortOrder = DEFAULT_PAGIN.sortOrder;
    if (sort) {
        var order = sort.charAt(0);
        if (order == '+' || order == ' ') {
            sortOrder = 'asc';
            sort = sort.slice(1);
        } else if (order == '-') {
            sortOrder = 'desc';
            sort = sort.slice(1);
        } else {
            sortOrder = DEFAULT_PAGIN.sortOrder;
        }
    }
    var sortBy = (sort || DEFAULT_PAGIN.sortBy);
    var count = (request.getParameter("count") || DEFAULT_PAGIN.count);
    var start = (request.getParameter("start") || DEFAULT_PAGIN.start);
    var paginationLimit = (request.getParameter("paginationLimit") || DEFAULT_PAGIN.paginationLimit);
    var paging = {
        'start': start,
        'count': count,
        'sortOrder': sortOrder,
        'sortBy': sortBy,
        'paginationLimit': paginationLimit
    };
    var q = (request.getParameter("q") || '');
    try {
        if (q) {
            var qString = '{' + q + '}';
            var query = parse(qString);
            //print(query);
            var assets = assetManager.search(query, paging); //doesnt work properly
        } else {
            //print(paging);
            var assets = assetManager.list(paging);
        }
        var expansionFields = (request.getParameter('fields') || '');
        if (expansionFields) {
            options.fields = expansionFields.split(',');
            options.assets = assets;
            fieldExpansion(options, req, res, session);
            //return;
        } else {
            print(assets);
            return assets;
        }
    } catch (e) {
        res.sendError(400, "Your request is malformed");
        log.error(e);
    }
};
var getAsset = function(options, req, res, session) {
    var assetManager = asset.createUserAssetManager(session, options.type);
    try {
        var retrievedAsset = assetManager.get(options.id);
        if (!retrievedAsset) {
            print({
                error: "no matching asset found"
            });
            res.sendError(400, "no matching asset found");
            return;
        } else {
            var expansionFields = (request.getParameter('fields') || '');
            if (expansionFields) {
                options.fields = expansionFields.split(',');
                var assets = [];
                assets.push(retrievedAsset);
                options.assets = assets;
                fieldExpansion(options, req, res, session);
            } else {
                print(retrievedAsset);
                return retrievedAsset;
            }
        }
    } catch (e) {
        res.sendError(400, "No matching asset found");
        log.error(e);
    }
};<|endoftext|>


<commit_before>/**
 * Module Name: Github
 * Description: Retrieves interesting Github information
 */
var request = require('request'),
    _ = require('underscore')._,
    exec = require('child_process').exec;

var github = function(dbot) {
    var commands = {
        '~repocount': function(event) {
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
                if(response.statusCode == "200") {
                    var result = JSON.parse(body);
                    event.reply(dbot.t("repocount",{"user": event.params[1], "count": result.length}));
                } else {
                    event.reply(dbot.t("usernotfound"));
               }
           });
        },
        '~repo': function(event) {
            var repo = event.params[1];
            if (typeof repo == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                if (data["fork"] == true) {
                   event.reply(dbot.t("forkedrepo",data));
                } else {
                    event.reply(dbot.t("unforkedrepo",data));
                }
                // TODO: move this shizz into an api call
                var longurl = "http://github.com/" + repo;
                request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                    event.reply(dbot.t('location')+" "+response.headers["location"]);
                });
            });
        },
        '~gstatus': function(event) {
            var reqUrl = "https://status.github.com/api/last-message.json";
            request(reqUrl, function(error,response,body){
                var data = JSON.parse(body);
                event.reply(dbot.t("status"+data["status"]));
                event.reply(data["body"]);
            });
        },
        '~milestone': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var reqUrl = "https://api.github.com/repos/";
            reqUrl += repo + "/milestones";

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                for (var section in data) {
                    var milestone = data[section];
                    if (milestone["title"] == event.params[1]){
                        var str = "Milestone " + milestone["title"];
                        var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]);
                        progress = Math.round(progress*100);
                        var bar = "[";
                        for (var i = 10; i < 100; i += 10) {
                            if  ((progress/i) > 1) {
                                bar += "█";
                            } else {
                                bar += " ";
                            }
                        }
                        bar += "]";
                        str += " is " + bar + progress + "% complete";

                        var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"];
                        request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                            event.reply(response.headers["location"]);
                        });
                        event.reply(str);
                        break;
                    }
                }
           });
        },
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        },
        '~issue': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var issue = event.params[1];
            if (isNaN(event.params[1])){
                repo = event.params[1];
                issue = event.params[2];
            }

            var reqUrl = "https://api.github.com/repos/" + repo + "/issues/" + issue;
            request(reqUrl, function(error,response, body) {
                if (response.statusCode == "200") {
                    var data = JSON.parse(body);
                    if (data["pull_request"]["html_url"] != null){
                        console.log(data["pull_request"]["html_url"]);
                        data["pull_request"] = " with code";
                    } else {
                        data["pull_request"] = "";
                    }
                    if (data["state"]=="open") {
                        data["state"] = "\u000303" + data["state"];
                    } else {
                        data["state"] = "\u000304" + data["state"];
                    }
                    //for (label in data["labels"]){
                    //    data["label"] = data["label"] + " " + label["name"];
                    //}
                    event.reply(dbot.t("issue",data));
                    event.reply(data["html_url"]);
                } else {
                    event.reply(dbot.t("issuenotfound"));
                }
            });
       },
       '~commits': function(event) {
            exec("git rev-list --all | wc -l", function(error, stdout, stderr) {
                stdout = stdout.trim();
                request("http://numbersapi.com/" + stdout + "?fragment&default=XXX", function(error, response, body){
                    if (body != "XXX"){
                        event.reply(dbot.t("commitcountfun",{"fact": body, "count": stdout}));
                    } else {
                        // nothing fun about the number, let's try the year
                        request("http://numbersapi.com/" + stdout + "/year?fragment&default=XXX", function(error, response, body){
                            if (body != "XXX"){
                                event.reply(dbot.t("commitcountyear",{"fact": body, "count": stdout}));
                            } else {
                                event.reply(dbot.t("commitcountboring",{"count": stdout}));
                            }
                        });
                    }
               });
            });
        }
    };
    this.commands = commands;

    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new github(dbot);
};
<commit_msg>Add tag functionality to ~issue<commit_after>/**
 * Module Name: Github
 * Description: Retrieves interesting Github information
 */
var request = require('request'),
    _ = require('underscore')._,
    exec = require('child_process').exec;

var github = function(dbot) {
    var commands = {
        '~repocount': function(event) {
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
                if(response.statusCode == "200") {
                    var result = JSON.parse(body);
                    event.reply(dbot.t("repocount",{"user": event.params[1], "count": result.length}));
                } else {
                    event.reply(dbot.t("usernotfound"));
               }
           });
        },
        '~repo': function(event) {
            var repo = event.params[1];
            if (typeof repo == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                if (data["fork"] == true) {
                   event.reply(dbot.t("forkedrepo",data));
                } else {
                    event.reply(dbot.t("unforkedrepo",data));
                }
                // TODO: move this shizz into an api call
                var longurl = "http://github.com/" + repo;
                request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                    event.reply(dbot.t('location')+" "+response.headers["location"]);
                });
            });
        },
        '~gstatus': function(event) {
            var reqUrl = "https://status.github.com/api/last-message.json";
            request(reqUrl, function(error,response,body){
                var data = JSON.parse(body);
                event.reply(dbot.t("status"+data["status"]));
                event.reply(data["body"]);
            });
        },
        '~milestone': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var reqUrl = "https://api.github.com/repos/";
            reqUrl += repo + "/milestones";

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                for (var section in data) {
                    var milestone = data[section];
                    if (milestone["title"] == event.params[1]){
                        var str = "Milestone " + milestone["title"];
                        var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]);
                        progress = Math.round(progress*100);
                        var bar = "[";
                        for (var i = 10; i < 100; i += 10) {
                            if  ((progress/i) > 1) {
                                bar += "█";
                            } else {
                                bar += " ";
                            }
                        }
                        bar += "]";
                        str += " is " + bar + progress + "% complete";

                        var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"];
                        request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                            event.reply(response.headers["location"]);
                        });
                        event.reply(str);
                        break;
                    }
                }
           });
        },
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        },
        '~issue': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var issue = event.params[1];
            if (isNaN(event.params[1])){
                repo = event.params[1];
                issue = event.params[2];
            }

            var reqUrl = "https://api.github.com/repos/" + repo + "/issues/" + issue;
            request(reqUrl, function(error,response, body) {
                if (response.statusCode == "200") {
                    var data = JSON.parse(body);
                    if (data["pull_request"]["html_url"] != null){
                        console.log(data["pull_request"]["html_url"]);
                        data["pull_request"] = " with code";
                    } else {
                        data["pull_request"] = "";
                    }
                    if (data["state"]=="open") {
                        data["state"] = "\u000303" + data["state"];
                    } else {
                        data["state"] = "\u000304" + data["state"];
                    }
                    var labels = "";
                    for (var i=0; i < data["labels"].length; i++) { // for-in doesn't like me
                        var color = "\u0003" + (parseInt(data["labels"][i]["color"],16) % 15);
                        labels += " " + color + data["labels"][i]["name"];
                    }
                    data["label"] = labels;
                    event.reply(dbot.t("issue",data));
                    event.reply(data["html_url"]);
                } else {
                    event.reply(dbot.t("issuenotfound"));
                }
            });
       },
       '~commits': function(event) {
            exec("git rev-list --all | wc -l", function(error, stdout, stderr) {
                stdout = stdout.trim();
                request("http://numbersapi.com/" + stdout + "?fragment&default=XXX", function(error, response, body){
                    if (body != "XXX"){
                        event.reply(dbot.t("commitcountfun",{"fact": body, "count": stdout}));
                    } else {
                        // nothing fun about the number, let's try the year
                        request("http://numbersapi.com/" + stdout + "/year?fragment&default=XXX", function(error, response, body){
                            if (body != "XXX"){
                                event.reply(dbot.t("commitcountyear",{"fact": body, "count": stdout}));
                            } else {
                                event.reply(dbot.t("commitcountboring",{"count": stdout}));
                            }
                        });
                    }
               });
            });
        }
    };
    this.commands = commands;

    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new github(dbot);
};
<|endoftext|>


<commit_before>var rulesUtil = require('../lib/rules-util');
var config = require('../lib/config');

module.exports = function(req, res) {
	var data = rulesUtil.getHostsData();
	data.fontSize = rulesUtil.getProperty('fontSize');
	data.showLineNumbers = rulesUtil.getProperty('showLineNumbers');
	data.theme = rulesUtil.getProperty('theme');
	data.version = config.version;

	res.json({
		rules: data,
		values: {
			fontSize: rulesUtil.getProperty('valuesFontSize'),
			theme: rulesUtil.getProperty('valuesTheme'),
			showLineNumbers: rulesUtil.getProperty('valuesShowLineNumbers'),
			values: rulesUtil.getValue()
		}
	});
};<commit_msg>https<commit_after>var rulesUtil = require('../lib/rules-util');
var config = require('../lib/config');

module.exports = function(req, res) {
	var data = rulesUtil.getHostsData();
	data.fontSize = rulesUtil.getProperty('fontSize');
	data.showLineNumbers = rulesUtil.getProperty('showLineNumbers');
	data.theme = rulesUtil.getProperty('theme');
	data.version = config.version;

	res.json({
		rules: data,
		values: {
			fontSize: rulesUtil.getProperty('valuesFontSize'),
			theme: rulesUtil.getProperty('valuesTheme'),
			showLineNumbers: rulesUtil.getProperty('valuesShowLineNumbers'),
			values: rulesUtil.getValue()
		},
		https: rulesUtil.getInterceptRuleList
	});
};<|endoftext|>


<commit_before>/*
Name:         europeana.js
Description:  Unofficial node.js module for the Europeana API
Author:       Franklin van de Meent - https://frankl.in
Source:       https://github.com/fvdm/nodejs-europeana
Feedback:     https://github.com/fvdm/nodejs-europeana/issues
License:      Public Domain / Unlicense (see UNLICENSE file)
              (https://github.com/fvdm/nodejs-europeana/raw/master/UNLICENSE)
*/

var http = require ('httpreq');

var settings = {
  apikey: null,
  timeout: 5000
};

// errors
// http://www.europeana.eu/portal/api-working-with-api.html#Error-Codes

var errors = {
  400: 'The request sent by the client was syntactically incorrect',
  401: 'Authentication credentials were missing or authentication failed.',
  404: 'The requested record was not found.',
  429: 'The request could be served because the application has reached its usage limit.',
  500: 'Internal Server Error. Something has gone wrong, please report to us.'
};

/**
 * Make and call back error
 *
 * @callback callback
 * @param message {string} - Error.message
 * @param err {mixed} - Error.error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err) {}`
 * @returns {void}
 */

function doError (message, err, res, callback) {
  var error = new Error (message);

  error.code = res.statusCode;
  error.error = err || errors [res.statusCode] || null;
  error.data = res.body;
  callback (error);
}

/**
 * Process response
 *
 * @callback callback
 * @param err {Error, null} - httpreq error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpResponse (err, res, callback) {
  var data = res && res.body;
  var error = null;
  var html;

  // client failed
  if (err) {
    doError ('request failed', err, res, callback);
    return;
  }

  // parse response
  try {
    data = JSON.parse (data);
  } catch (reason) {
    // weird API error
    if (data.match (/
HTTP Status /)) {
      html = data.replace (/.*description<\/b> (.+)<\/u><\/p>.*/, '$1');
      doError ('API error', html, res, callback);
    } else {
      doError ('invalid response', reason, res, callback);
    }
    return;
  }

  if (data.apikey) {
    delete data.apikey;
  }

  // API error
  if (!data.success && data.error) {
    doError ('API error', data.error, res, callback);
    return;
  }

  if (res.statusCode >= 300) {
    doError ('API error', null, res, callback);
    return;
  }

  // all good
  callback (null, data);
}

/**
 * Communicate with API
 *
 * @callback callback
 * @param path {string} - Method path between `/v2/` and `.json`
 * @param fields {object} - Method parameters
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpRequest (path, fields, callback) {
  var options = {
    method: 'GET',
    url: 'https://www.europeana.eu/api/v2/' + path + '.json',
    parameters: fields,
    timeout: settings.timeout,
    headers: {
      'User-Agent': 'europeana.js'
    }
  };

  if (typeof fields === 'function') {
    callback = fields;
    options.parameters = {};
  }

  // Request

  // check API key
  if (!settings.apikey) {
    callback (new Error ('apikey missing'));
    return;
  }

  options.parameters.wskey = settings.apikey;

  function doResponse (err, res) {
    httpResponse (err, res, callback);
  }

  http.doRequest (options, doResponse);
}

/**
 * Module interface
 *
 * @param [apikey] {string} - Your Europeana API key
 * @param [timeout = 5000] {number} - Request wait timeout in ms
 * @returns httpRequest {function}
 */

function setup (apikey, timeout) {
  settings.apikey = apikey || null;
  settings.timeout = timeout || settings.timeout;
  return httpRequest;
}

module.exports = setup;
<commit_msg>Refactor(cleanup): Remove unused var<commit_after>/*
Name:         europeana.js
Description:  Unofficial node.js module for the Europeana API
Author:       Franklin van de Meent - https://frankl.in
Source:       https://github.com/fvdm/nodejs-europeana
Feedback:     https://github.com/fvdm/nodejs-europeana/issues
License:      Public Domain / Unlicense (see UNLICENSE file)
              (https://github.com/fvdm/nodejs-europeana/raw/master/UNLICENSE)
*/

var http = require ('httpreq');

var settings = {
  apikey: null,
  timeout: 5000
};

// errors
// http://www.europeana.eu/portal/api-working-with-api.html#Error-Codes

var errors = {
  400: 'The request sent by the client was syntactically incorrect',
  401: 'Authentication credentials were missing or authentication failed.',
  404: 'The requested record was not found.',
  429: 'The request could be served because the application has reached its usage limit.',
  500: 'Internal Server Error. Something has gone wrong, please report to us.'
};

/**
 * Make and call back error
 *
 * @callback callback
 * @param message {string} - Error.message
 * @param err {mixed} - Error.error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err) {}`
 * @returns {void}
 */

function doError (message, err, res, callback) {
  var error = new Error (message);

  error.code = res.statusCode;
  error.error = err || errors [res.statusCode] || null;
  error.data = res.body;
  callback (error);
}

/**
 * Process response
 *
 * @callback callback
 * @param err {Error, null} - httpreq error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpResponse (err, res, callback) {
  var data = res && res.body;
  var html;

  // client failed
  if (err) {
    doError ('request failed', err, res, callback);
    return;
  }

  // parse response
  try {
    data = JSON.parse (data);
  } catch (reason) {
    // weird API error
    if (data.match (/
HTTP Status /)) {
      html = data.replace (/.*description<\/b> (.+)<\/u><\/p>.*/, '$1');
      doError ('API error', html, res, callback);
    } else {
      doError ('invalid response', reason, res, callback);
    }
    return;
  }

  if (data.apikey) {
    delete data.apikey;
  }

  // API error
  if (!data.success && data.error) {
    doError ('API error', data.error, res, callback);
    return;
  }

  if (res.statusCode >= 300) {
    doError ('API error', null, res, callback);
    return;
  }

  // all good
  callback (null, data);
}

/**
 * Communicate with API
 *
 * @callback callback
 * @param path {string} - Method path between `/v2/` and `.json`
 * @param fields {object} - Method parameters
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpRequest (path, fields, callback) {
  var options = {
    method: 'GET',
    url: 'https://www.europeana.eu/api/v2/' + path + '.json',
    parameters: fields,
    timeout: settings.timeout,
    headers: {
      'User-Agent': 'europeana.js'
    }
  };

  if (typeof fields === 'function') {
    callback = fields;
    options.parameters = {};
  }

  // Request

  // check API key
  if (!settings.apikey) {
    callback (new Error ('apikey missing'));
    return;
  }

  options.parameters.wskey = settings.apikey;

  function doResponse (err, res) {
    httpResponse (err, res, callback);
  }

  http.doRequest (options, doResponse);
}

/**
 * Module interface
 *
 * @param [apikey] {string} - Your Europeana API key
 * @param [timeout = 5000] {number} - Request wait timeout in ms
 * @returns httpRequest {function}
 */

function setup (apikey, timeout) {
  settings.apikey = apikey || null;
  settings.timeout = timeout || settings.timeout;
  return httpRequest;
}

module.exports = setup;
<|endoftext|>


<commit_before>var models = require('../../models');
var async = require('async');

module.exports = function (req, res) {
    res.render('my_account_new.ejs', {
        layout: false,
        title: "פרופיל שלי",
        logged: req.isAuthenticated(),
        user: req.user,                 // logged user
        url: req.url,
        avatar:req.session.avatar_url
    });
};
<commit_msg>my_account<commit_after>var models = require('../../models');
var async = require('async');

module.exports = function (req, res) {
    res.render('my_account.ejs', {
        layout: false,
        title: "פרופיל שלי",
        logged: req.isAuthenticated(),
        user: req.user,                 // logged user
        url: req.url,
        avatar:req.session.avatar_url
    });
};
<|endoftext|>


<commit_before>var rootDir = process.env.NODE_ENV === 'production' ? '/home/deploy/current' : process.cwd();
var timerService = require(rootDir + '/server/services/timer');
var sessionService = require(rootDir + '/server/services/session');

var self = module.exports = {
	users: sessionService.getQueue,
	speaker: null,
	attachSocketLayer: function(socketLayer) {
		// attach scope to this file
		io = socketLayer;

		io.sockets.on('connection', function(socket) {

			console.log('\nSocket.io connection established...'.green);

			// send chat message
			socket.on('sendChatMessage', function(data) {
				socket.broadcast.emit('sendChatMessageToAll', data);
				// chats.create(data.user, data.gameId, data.message, function(data) {
				// 	console.log('Chat message saved to DB');
				// });
			});

			socket.on('message', function (message) {
				console.log('Got message: ', message);
				socket.broadcast.emit('message', message);
			});

			socket.on('join', function (data) {
				// //join specific room (channel)
				// socket.join(data.room);
				// var numClients = io.sockets.clients(data.room).length;

				//add to queue
				sessionService.pushUser(data.id, data.id, function(session){
					// update the vote count on the front-end
					console.log(session.queue);
					self.users = session.queue;
				});

				//if there is no current speaker && queue is long enough make speaker and start
				if(!self.speaker && self.users.length > 1) {
					self.speaker = {
						id: self.users[0],
						ready: false
					};
					socket.broadcast.emit('startSpeaker', self.speaker.id);
				} else if(self.speaker && self.speaker.ready) {
					socket.emit('getSpeakerStream', self.speaker.id);
				}

				// io.sockets.in(data.room).emit('newUser', {numUsers: numClients, id: data.id});
				var newUser = {
					queue: self.users,
					id: data.id
				};

				//broadcast out new users to add to client queues
				socket.broadcast.emit('newUser', newUser);
				socket.emit('newUser', newUser);

				socket.on('disconnect', function () {
					console.log('disconnected: ', data.id);
					//remove user from queue
					for(var i = 0; i < self.users.length; i++) {
						if(self.users[i] === data.id) {
							var firstHalf = self.users.slice(0,i),
								secondHalf = self.users.slice(i+1, self.users.length);
							self.users = firstHalf.concat(secondHalf);
							break;
						}
					}
					//if someone leaves while its their turn
					if(self.speaker.id === data.id) {
						self.speaker.id = self.users[0];
						self.speaker.ready = false;
						socket.broadcast.emit('startSpeaker', self.speaker.id);
					} else if(self.users.length < 1) {
						self.speaker = null;
					}
					socket.broadcast.emit('userLeft', data.id);
				});
			});

			socket.on('readyToSpeak', function(speaker, avatar) {
				timerService.startTimer(function() {
					console.log('stop');
					socket.emit('stopSpeaker', self.speaker.id);
				});
				if(self.speaker.id === speaker) {
					self.speaker.ready = true;
					socket.broadcast.emit('getSpeakerStream', self.speaker.id, avatar);
				}
			});

			socket.on('doneSpeaking', function(speaker) {
				console.log('done speaking');
				if(self.speaker.id === speaker) {
					//update queue and move current to end
					// self.users.shift();
					sessionService.popUser(data.userid, self.users.shift(), function(session){
						// update the queue on the front-end
						console.log(session.queue);
					});
					// self.users.push(speaker);
					sessionService.pushuser(data.userid, speaker, function(session){
						// update the queue on the front-end
						console.log(session.queue);
					});
					self.speaker.id = self.users[0];
					self.speaker.ready = false;
					//start new speaker
					console.log('startNewSpeaker');
					setTimeout(function() {
						socket.broadcast.emit('startSpeaker', self.speaker.id);
					}, 4000);
				}
			});

			socket.on('broadcast', function (data) {
				console.log(data);
			});

			socket.on('participate', function(data) {
				io.sockets.in(data.room).emit('message', data);
			});

			socket.on('shareStream', function(data) {
				io.sockets.in(data.room).emit('shareStream', data);
			});

			socket.on('initSession', function(data) {
				//console.log(data)
				sessionService.createSession(data.userid, function(session){
					// console.log(session.votes);
				});
			});

			socket.on('upVoteUser', function(data) {
				// console.log(data);
				sessionService.upvote(data.userid, function(session){
					// update the vote count on the front-end
					// console.log(session.votes);
				});
			});

			socket.on('downVoteUser', function(data) {
				console.log(data);
				sessionService.downvote(data.userid, function(session){
					// update the vote count on the front-end
					console.log(session.votes);
				});
			});

			socket.on('pushUser', function(data) {
				console.log(data);
				sessionService.pushuser(data.userid, data.pushed, function(session){
					// update the vote count on the front-end
					console.log(session.queue);
				});
			});

			socket.on('popUser', function(data) {
				console.log(data);
				sessionService.popUser(data.userid, data.popped, function(session){
					// update the vote count on the front-end
					console.log(session.queue);
				});
			});

		});
	}

};

// console.log(timerService, 'timerService');
// timerService.startTimer(function() {

// 	console.log('emit!');

// });
// setTimeout(function() { timerService.addTime(5); }, 1000);

//console.log(voteService, 'voteService');
<commit_msg>detecting speaker and setting session accordingly<commit_after>var rootDir = process.env.NODE_ENV === 'production' ? '/home/deploy/current' : process.cwd();
var timerService = require(rootDir + '/server/services/timer');
var sessionService = require(rootDir + '/server/services/session');

var self = module.exports = {
	users: sessionService.getQueue,
	speaker: null,
	attachSocketLayer: function(socketLayer) {
		// attach scope to this file
		io = socketLayer;

		io.sockets.on('connection', function(socket) {

			console.log('\nSocket.io connection established...'.green);

			// send chat message
			socket.on('sendChatMessage', function(data) {
				socket.broadcast.emit('sendChatMessageToAll', data);
				// chats.create(data.user, data.gameId, data.message, function(data) {
				// 	console.log('Chat message saved to DB');
				// });
			});

			socket.on('message', function (message) {
				console.log('Got message: ', message);
				socket.broadcast.emit('message', message);
			});

			socket.on('join', function (data) {
				// //join specific room (channel)
				// socket.join(data.room);
				// var numClients = io.sockets.clients(data.room).length;

				if(!self.speaker){
					self.speaker = {
						id: data.id,
						ready: false
					};
				}
				//add to queue
				sessionService.pushUser(self.speaker.id, data.id, function(session){
					// update the vote count on the front-end
					console.log(session.queue);
					self.users = session.queue;
				});

				//if there is no current speaker && queue is long enough make speaker and start
				if(self.users.length > 1) {
					socket.broadcast.emit('startSpeaker', self.speaker.id);
				} else if(self.speaker && self.speaker.ready) {
					socket.emit('getSpeakerStream', self.speaker.id);
				}

				// io.sockets.in(data.room).emit('newUser', {numUsers: numClients, id: data.id});
				var newUser = {
					queue: self.users,
					id: data.id
				};

				//broadcast out new users to add to client queues
				socket.broadcast.emit('newUser', newUser);
				socket.emit('newUser', newUser);

				socket.on('disconnect', function () {
					console.log('disconnected: ', data.id);
					//remove user from queue
					for(var i = 0; i < self.users.length; i++) {
						if(self.users[i] === data.id) {
							var firstHalf = self.users.slice(0,i),
								secondHalf = self.users.slice(i+1, self.users.length);
							self.users = firstHalf.concat(secondHalf);
							break;
						}
					}
					//if someone leaves while its their turn
					if(self.speaker.id === data.id) {
						self.speaker.id = self.users[0];
						self.speaker.ready = false;
						socket.broadcast.emit('startSpeaker', self.speaker.id);
					} else if(self.users.length < 1) {
						self.speaker = null;
					}
					socket.broadcast.emit('userLeft', data.id);
				});
			});

			socket.on('readyToSpeak', function(speaker, avatar) {
				timerService.startTimer(function() {
					console.log('stop');
					socket.emit('stopSpeaker', self.speaker.id);
				});
				if(self.speaker.id === speaker) {
					self.speaker.ready = true;
					socket.broadcast.emit('getSpeakerStream', self.speaker.id, avatar);
				}
			});

			socket.on('doneSpeaking', function(speaker) {
				console.log('done speaking');
				if(self.speaker.id === speaker) {
					//update queue and move current to end
					// self.users.shift();
					sessionService.popUser(speaker, self.users.shift(), function(session){
						// update the queue on the front-end
						console.log(session.queue);
					});
					// self.users.push(speaker);
					sessionService.pushuser(speaker, speaker, function(session){
						// update the queue on the front-end
						console.log(session.queue);
					});
					self.speaker.id = self.users[0];
					self.speaker.ready = false;
					//start new speaker
					console.log('startNewSpeaker');
					setTimeout(function() {
						socket.broadcast.emit('startSpeaker', self.speaker.id);
					}, 4000);
				}
			});

			socket.on('broadcast', function (data) {
				console.log(data);
			});

			socket.on('participate', function(data) {
				io.sockets.in(data.room).emit('message', data);
			});

			socket.on('shareStream', function(data) {
				io.sockets.in(data.room).emit('shareStream', data);
			});

			socket.on('initSession', function(data) {
				//console.log(data)
				sessionService.createSession(data.userid, function(session){
					// console.log(session.votes);
				});
			});

			socket.on('upVoteUser', function(data) {
				// console.log(data);
				sessionService.upvote(data.userid, function(session){
					// update the vote count on the front-end
					// console.log(session.votes);
				});
			});

			socket.on('downVoteUser', function(data) {
				console.log(data);
				sessionService.downvote(data.userid, function(session){
					// update the vote count on the front-end
					console.log(session.votes);
				});
			});

			socket.on('pushUser', function(data) {
				console.log(data);
				sessionService.pushuser(data.userid, data.pushed, function(session){
					// update the vote count on the front-end
					console.log(session.queue);
				});
			});

			socket.on('popUser', function(data) {
				console.log(data);
				sessionService.popUser(data.userid, data.popped, function(session){
					// update the vote count on the front-end
					console.log(session.queue);
				});
			});

		});
	}

};

// console.log(timerService, 'timerService');
// timerService.startTimer(function() {

// 	console.log('emit!');

// });
// setTimeout(function() { timerService.addTime(5); }, 1000);

//console.log(voteService, 'voteService');
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { greyDark, grey } from 'shared/styles/colors';

const DayTick = ({
  x, y, width, height, payload: { value },
}) => value ? (
  <g>
    <text
      width={width}
      height={height}
      x={x}
      y={y}
      dx={0}
      dy={-10}
      textAnchor="middle"
      fill={greyDark}
      fontSize=".85rem"
    >
      {value}
    </text>
    {/* manually render a reference line */}
    <line
      x1={x}
      y1={y - 6}
      x2={x}
      y2={y + 2}
      stroke={grey}
      strokeWidth={1.5}
      fill="none"
    />
  </g>
) : null;

/* eslint-disable react/require-default-props */
DayTick.propTypes = {
  x: PropTypes.number,
  y: PropTypes.number,
  width: PropTypes.number,
  height: PropTypes.number,
  payload: PropTypes.object,
};

export default DayTick;
<commit_msg>refactor(UpcomingReviewsChart): remove day reference line<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { greyDark } from 'shared/styles/colors';

const DayTick = ({
  x, y, width, height, payload: { value },
}) =>
  value ? (
    <g>
      <text
        width={width}
        height={height}
        x={x}
        y={y}
        dx={0}
        dy={-10}
        textAnchor="middle"
        fill={greyDark}
        fontSize=".85rem"
      >
        {value}
      </text>
    </g>
  ) : null;

/* eslint-disable react/require-default-props */
DayTick.propTypes = {
  x: PropTypes.number,
  y: PropTypes.number,
  width: PropTypes.number,
  height: PropTypes.number,
  payload: PropTypes.object,
};

export default DayTick;
<|endoftext|>