<commit_before>/* Copyright IBM Corp. 2014
 *
 * 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.
 */

'use strict';

var router = require('express').Router(),
  mongoose = require('mongoose'),
  fs       = require('fs'),
  Q        = require('q'),
  Profile  = mongoose.model('Profile'),
  User     = mongoose.model('User'),
  logger   = require('../../config/logger');

/**
 * Render the celebrity list
*/
router.get('/secret', function(req,res) {
  Profile.find({},function(err,profiles){
    if (err)
      res.render('celebrities',{error: err});
    else
      res.render('celebrities',{profiles: profiles});
  });
});

/**
 * Render the celebrity list
*/
router.get('/secret/users', function(req,res) {
  User.find({},function(err,profiles){
    if (err)
      res.render('celebrities',{error: err});
    else
      res.render('celebrities',{profiles: profiles});
  });
});

var getUserId = function(text) {
  return text.replace('.json','');
};

var jsonProfiles = function(text) {
  return text.indexOf('.json', text.length - '.json'.length) !== -1;
};

/**
 * Validate twitter usernames
*/
router.get('/secret/syncdb', function (req, res) {
  logger.info('update celebrity database');
  var removeAll = Q.nfbind(Profile.remove.bind(Profile)),
    getFiles = Q.denodeify(fs.readdir),
    getUsers = Q.denodeify(req.twit.getUsers.bind(req.twit)),
    getFile = Q.denodeify(fs.readFile);

  removeAll({})
  .then(function() {
    return getFiles('./profiles');
  })
  .then(function(files){
    if (!files || files.length === 0)
      return;

    var user_ids = files.filter(jsonProfiles).map(getUserId),
      count = Math.ceil(user_ids.length / 100),
      promises = [];

    for (var i = 0; i < count; i++) {
      var ids = user_ids.slice(0,100);
      user_ids = user_ids.slice(Math.min(100, user_ids.length));
      promises.push(getUsers({user_id:ids.join(',')}));
    }
    return Q.all(promises);
  })
  .then(function(usersArray){
    var users = [];
    usersArray.forEach(function(_users){
      users = users.concat(_users);
    });

    logger.info(users.length);
      return Q.all(users.map(function(u){
        getFile('./profiles/'+u.id+'.json')
        .then(function(profileJson) {
          u.profile = profileJson;
          return Profile.create(u).exec();
        });
      }));
  })
  .then(function(){
    res.redirect('/celebrities/secret');
  })
  .fail(function (error) {
    logger.error(error);
    res.render('celebrities',{error:error});
  });
});

module.exports = router;
<commit_msg>Update celebrities.js<commit_after>/* Copyright IBM Corp. 2014
 *
 * 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.
 */

'use strict';

var router = require('express').Router(),
  mongoose = require('mongoose'),
  fs       = require('fs'),
  Q        = require('q'),
  Profile  = mongoose.model('Profile'),
  User     = mongoose.model('User'),
  logger   = require('../../config/logger');

/**
 * Render the celebrity list
*/
router.get('/', function(req,res) {
  Profile.find({},function(err,profiles){
    if (err)
      res.render('celebrities',{error: err});
    else
      res.render('celebrities',{profiles: profiles});
  });
});

/**
 * Render the celebrity list
*/
router.get('/users', function(req,res) {
  User.find({},function(err,profiles){
    if (err)
      res.render('celebrities',{error: err});
    else
      res.render('celebrities',{profiles: profiles});
  });
});

var getUserId = function(text) {
  return text.replace('.json','');
};

var jsonProfiles = function(text) {
  return text.indexOf('.json', text.length - '.json'.length) !== -1;
};

/**
 * Validate twitter usernames
*/
router.get('/syncdb', function (req, res) {
  logger.info('update celebrity database');
  var removeAll = Q.nfbind(Profile.remove.bind(Profile)),
    getFiles = Q.denodeify(fs.readdir),
    getUsers = Q.denodeify(req.twit.getUsers.bind(req.twit)),
    getFile = Q.denodeify(fs.readFile);

  removeAll({})
  .then(function() {
    return getFiles('./profiles');
  })
  .then(function(files){
    if (!files || files.length === 0)
      return;

    var user_ids = files.filter(jsonProfiles).map(getUserId),
      count = Math.ceil(user_ids.length / 100),
      promises = [];

    for (var i = 0; i < count; i++) {
      var ids = user_ids.slice(0,100);
      user_ids = user_ids.slice(Math.min(100, user_ids.length));
      promises.push(getUsers({user_id:ids.join(',')}));
    }
    return Q.all(promises);
  })
  .then(function(usersArray){
    var users = [];
    usersArray.forEach(function(_users){
      users = users.concat(_users);
    });

    logger.info(users.length);
      return Q.all(users.map(function(u){
        getFile('./profiles/'+u.id+'.json')
        .then(function(profileJson) {
          u.profile = profileJson;
          return Profile.create(u).exec();
        });
      }));
  })
  .then(function(){
    res.redirect('/celebrities');
  })
  .fail(function (error) {
    logger.error(error);
    res.render('celebrities',{error:error});
  });
});

module.exports = router;
<|endoftext|>


<commit_before>(function(Editor, markdownit, WebUploader){
    // Set default options
    var md = new markdownit();

    md.set({
      html:         false,        // Enable HTML tags in source
      xhtmlOut:     false,        // Use '/' to close single tags (
)
      breaks:       true,        // Convert '\n' in paragraphs into

      langPrefix:   'language-',  // CSS language prefix for fenced blocks
      linkify:      false,        // Autoconvert URL-like text to links
      typographer:  false,        // Enable smartypants and other sweet transforms
    });

    window.markdowniter = md;

    var toolbar = Editor.toolbar;

    var replaceTool = function(name, callback){
        for(var i=0, len=toolbar.length; i<len; i++){
            var v = toolbar[i];
            if(typeof(v) !== 'string' && v.name === name){
                v.action = callback;
                break;
            }
        }
    };

    var $body = $('body');

    //添加连接工具
    var ToolLink = function(){
        var self = this;
        this.$win = $([
            '
',
                '
',
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>',
                    '
添加连接
',
                '
',
                '
',
                    '<form class="form-horizontal">',
                        '
',
                            '标题',
                            '
',
                                '<input type="text" name="title" placeholder="Title">',
                            '
',
                        '
',
                        '
',
                            '连接',
                            '
',
                                '<input type="text" name="link" value="http://" placeholder="Link">',
                            '
',
                        '
',
                    '</form>',
                '
',
                '
',
                    '<button class="btn btn-primary" role="save">确定</button>',
                '
',
            '
'
        ].join('')).appendTo($body);

        this.$win.on('click', '[role=save]', function(){
            self.$win.find('form').submit();
        }).on('submit', 'form', function(){
            var $el = $(this);
            var title = $el.find('[name=title]').val();
            var link = $el.find('[name=link]').val();

            self.$win.modal('hide');
            self.editor.push(' ['+ title +']('+ link +')');

            $el.find('[name=title]').val('');
            $el.find('[name=link]').val('http://');

            return false;
        });
    };

    ToolLink.prototype.bind = function(editor){
        this.editor = editor;
        this.$win.modal('show');
    };

    //图片上传工具
    var ToolImage = function(){
        var self = this;
        this.$win = $([
            '
',
                '
',
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>',
                    '
图片
',
                '
',
                '
',
                    '
',
                        '
上传图片
',
                        '',
                        '

',
                    '
',
                '
',
            '
'
        ].join('')).appendTo($body);

        this.$upload = this.$win.find('.upload-img').css({
            height: 50,
            padding: '60px 0',
            textAlign: 'center',
            border: '4px dashed#ddd'
        });

        this.$uploadBtn = this.$upload.find('.button').css({
            width: 86,
            height: 40,
            margin: '0 auto'
        });

        this.$uploadTip = this.$upload.find('.tip').hide();

        this.file = false;
        var _csrf = $('[name=_csrf]').val();

        this.uploader = WebUploader.create({
            swf: '/public/libs/webuploader/Uploader.swf',
            server: '/upload?_csrf=' + _csrf,
            pick: this.$uploadBtn[0],
            paste: document.body,
            dnd: this.$upload[0],
            auto: true,
            fileSingleSizeLimit: 2 * 1024 * 1024,
            //sendAsBinary: true,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });

        this.uploader.on('beforeFileQueued', function(file){
            if(self.file !== false || !self.editor){
                return false;
            }
            self.showFile(file);
        });

        this.uploader.on('uploadProgress', function(file, percentage){
            // console.log(percentage);
            self.showProgress(file, percentage * 100);
        });

        this.uploader.on('uploadSuccess', function(file, res){
            if(res.success){
                self.$win.modal('hide');
                self.editor.push(' !['+ file.name +']('+ res.url +')');
            }
            else{
                self.removeFile();
                self.showError(res.msg || '服务器走神了，上传失败');
            }
        });

        this.uploader.on('uploadComplete', function(file){
            self.uploader.removeFile(file);
            self.removeFile();
        });

        this.uploader.on('error', function(type){
            self.removeFile();
            switch(type){
                case 'Q_EXCEED_SIZE_LIMIT':
                case 'F_EXCEED_SIZE':
                    self.showError('文件太大了, 不能超过2M');
                    break;
                case 'Q_TYPE_DENIED':
                    self.showError('只能上传图片');
                    break;
                default:
                    self.showError('发生未知错误');
            }
        });

        this.uploader.on('uploadError', function(){
            self.removeFile();
            self.showError('服务器走神了，上传失败');
        });
    };

    ToolImage.prototype.removeFile = function(){
        //var self = this;
        this.file = false;
        this.$uploadBtn.show();
        this.$uploadTip.hide();
    };

    ToolImage.prototype.showFile = function(file){
        //var self = this;
        this.file = file;
        this.$uploadBtn.hide();
        this.$uploadTip.html('正在上传: ' + file.name).show();
        this.hideError();
    };

    ToolImage.prototype.showError = function(error){
        this.$upload.find('.alert-error').html(error).show();
    };

    ToolImage.prototype.hideError = function(error){
        this.$upload.find('.alert-error').hide();
    };

    ToolImage.prototype.showProgress = function(file, percentage){
        this.$uploadTip
            .html('正在上传: ' + file.name + ' ' + percentage + '%')
            .show();
    };

    ToolImage.prototype.bind = function(editor){
        this.editor = editor;
        this.$win.modal('show');
    };

    var toolImage = new ToolImage();
    var toolLink = new ToolLink();

    replaceTool('image', function(editor){
        toolImage.bind(editor);
    });
    replaceTool('link', function(editor){
        toolLink.bind(editor);
    });

    //当编辑器取得焦点时，绑定 toolImage；
    var createToolbar = Editor.prototype.createToolbar;
    Editor.prototype.createToolbar = function(items){
        createToolbar.call(this, items);
        var self = this;
        $(self.codemirror.display.input).on('focus', function(){
            toolImage.editor = self;
        });
    };

    //追加内容
    Editor.prototype.push = function(txt){
        var cm = this.codemirror;
        var line = cm.lastLine();
        cm.setLine(line, cm.getLine(line) + txt);
    };
})(window.Editor, window.markdownit, window.WebUploader);
<commit_msg>上传图片后不要空格<commit_after>(function(Editor, markdownit, WebUploader){
    // Set default options
    var md = new markdownit();

    md.set({
      html:         false,        // Enable HTML tags in source
      xhtmlOut:     false,        // Use '/' to close single tags (
)
      breaks:       true,        // Convert '\n' in paragraphs into

      langPrefix:   'language-',  // CSS language prefix for fenced blocks
      linkify:      false,        // Autoconvert URL-like text to links
      typographer:  false,        // Enable smartypants and other sweet transforms
    });

    window.markdowniter = md;

    var toolbar = Editor.toolbar;

    var replaceTool = function(name, callback){
        for(var i=0, len=toolbar.length; i<len; i++){
            var v = toolbar[i];
            if(typeof(v) !== 'string' && v.name === name){
                v.action = callback;
                break;
            }
        }
    };

    var $body = $('body');

    //添加连接工具
    var ToolLink = function(){
        var self = this;
        this.$win = $([
            '
',
                '
',
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>',
                    '
添加连接
',
                '
',
                '
',
                    '<form class="form-horizontal">',
                        '
',
                            '标题',
                            '
',
                                '<input type="text" name="title" placeholder="Title">',
                            '
',
                        '
',
                        '
',
                            '连接',
                            '
',
                                '<input type="text" name="link" value="http://" placeholder="Link">',
                            '
',
                        '
',
                    '</form>',
                '
',
                '
',
                    '<button class="btn btn-primary" role="save">确定</button>',
                '
',
            '
'
        ].join('')).appendTo($body);

        this.$win.on('click', '[role=save]', function(){
            self.$win.find('form').submit();
        }).on('submit', 'form', function(){
            var $el = $(this);
            var title = $el.find('[name=title]').val();
            var link = $el.find('[name=link]').val();

            self.$win.modal('hide');
            self.editor.push(' ['+ title +']('+ link +')');

            $el.find('[name=title]').val('');
            $el.find('[name=link]').val('http://');

            return false;
        });
    };

    ToolLink.prototype.bind = function(editor){
        this.editor = editor;
        this.$win.modal('show');
    };

    //图片上传工具
    var ToolImage = function(){
        var self = this;
        this.$win = $([
            '
',
                '
',
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>',
                    '
图片
',
                '
',
                '
',
                    '
',
                        '
上传图片
',
                        '',
                        '

',
                    '
',
                '
',
            '
'
        ].join('')).appendTo($body);

        this.$upload = this.$win.find('.upload-img').css({
            height: 50,
            padding: '60px 0',
            textAlign: 'center',
            border: '4px dashed#ddd'
        });

        this.$uploadBtn = this.$upload.find('.button').css({
            width: 86,
            height: 40,
            margin: '0 auto'
        });

        this.$uploadTip = this.$upload.find('.tip').hide();

        this.file = false;
        var _csrf = $('[name=_csrf]').val();

        this.uploader = WebUploader.create({
            swf: '/public/libs/webuploader/Uploader.swf',
            server: '/upload?_csrf=' + _csrf,
            pick: this.$uploadBtn[0],
            paste: document.body,
            dnd: this.$upload[0],
            auto: true,
            fileSingleSizeLimit: 2 * 1024 * 1024,
            //sendAsBinary: true,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });

        this.uploader.on('beforeFileQueued', function(file){
            if(self.file !== false || !self.editor){
                return false;
            }
            self.showFile(file);
        });

        this.uploader.on('uploadProgress', function(file, percentage){
            // console.log(percentage);
            self.showProgress(file, percentage * 100);
        });

        this.uploader.on('uploadSuccess', function(file, res){
            if(res.success){
                self.$win.modal('hide');
                self.editor.push('!['+ file.name +']('+ res.url +')');
            }
            else{
                self.removeFile();
                self.showError(res.msg || '服务器走神了，上传失败');
            }
        });

        this.uploader.on('uploadComplete', function(file){
            self.uploader.removeFile(file);
            self.removeFile();
        });

        this.uploader.on('error', function(type){
            self.removeFile();
            switch(type){
                case 'Q_EXCEED_SIZE_LIMIT':
                case 'F_EXCEED_SIZE':
                    self.showError('文件太大了, 不能超过2M');
                    break;
                case 'Q_TYPE_DENIED':
                    self.showError('只能上传图片');
                    break;
                default:
                    self.showError('发生未知错误');
            }
        });

        this.uploader.on('uploadError', function(){
            self.removeFile();
            self.showError('服务器走神了，上传失败');
        });
    };

    ToolImage.prototype.removeFile = function(){
        //var self = this;
        this.file = false;
        this.$uploadBtn.show();
        this.$uploadTip.hide();
    };

    ToolImage.prototype.showFile = function(file){
        //var self = this;
        this.file = file;
        this.$uploadBtn.hide();
        this.$uploadTip.html('正在上传: ' + file.name).show();
        this.hideError();
    };

    ToolImage.prototype.showError = function(error){
        this.$upload.find('.alert-error').html(error).show();
    };

    ToolImage.prototype.hideError = function(error){
        this.$upload.find('.alert-error').hide();
    };

    ToolImage.prototype.showProgress = function(file, percentage){
        this.$uploadTip
            .html('正在上传: ' + file.name + ' ' + percentage + '%')
            .show();
    };

    ToolImage.prototype.bind = function(editor){
        this.editor = editor;
        this.$win.modal('show');
    };

    var toolImage = new ToolImage();
    var toolLink = new ToolLink();

    replaceTool('image', function(editor){
        toolImage.bind(editor);
    });
    replaceTool('link', function(editor){
        toolLink.bind(editor);
    });

    //当编辑器取得焦点时，绑定 toolImage；
    var createToolbar = Editor.prototype.createToolbar;
    Editor.prototype.createToolbar = function(items){
        createToolbar.call(this, items);
        var self = this;
        $(self.codemirror.display.input).on('focus', function(){
            toolImage.editor = self;
        });
    };

    //追加内容
    Editor.prototype.push = function(txt){
        var cm = this.codemirror;
        var line = cm.lastLine();
        cm.setLine(line, cm.getLine(line) + txt);
    };
})(window.Editor, window.markdownit, window.WebUploader);
<|endoftext|>


<commit_before>import Ember from 'ember';
const { inject: { service }, Route } = Ember;

export default Route.extend({
  headData: service(),
  model() {
    // return this.store.findAll('github-repo');

    // Use static data for now, since EmberFire gives Fastboot Errors
    return [
      {
        'name': 'Ember 3D Nav',
        'repo': 'ember-3d-nav',
        'stars': 9
      },
      {
        'name': 'Ember Drop',
        'repo': 'ember-drop',
        'stars': 4
      },
      {
        'name': 'Ember Flatpickr',
        'repo': 'ember-flatpickr',
        'stars': 16
      },
      {
        'name': 'Ember Math Helpers',
        'repo': 'ember-math-helpers',
        'stars': 12
      },
      {
        'name': 'Ember Newton Cradle Loader',
        'repo': 'ember-newton-cradle-loader',
        'stars': 0
      },
      {
        'name': 'Ember Shepherd',
        'repo': 'ember-shepherd',
        'stars': 62
      },
      {
        'name': 'Ember Typewriter',
        'repo': 'ember-typewriter',
        'stars': 0
      },
      {
        'name': 'Ember Vivus',
        'repo': 'ember-vivus',
        'stars': 0
      },
      {
        'name': 'Ember X-Editable',
        'repo': 'ember-x-editable',
        'stars': 13
      }
    ];
  },
  afterModel() {
    return this.get('headData').setProperties({
      title: 'Ship Shape - Open Source',
      description: 'We have created several Ember addons and collaborated extensively with the Ember community.',
      type: 'website',
      url: 'https://shipshape.io/portfolio'
    });
  }
});
<commit_msg>Update stars<commit_after>import Ember from 'ember';
const { inject: { service }, Route } = Ember;

export default Route.extend({
  headData: service(),
  model() {
    // return this.store.findAll('github-repo');

    // Use static data for now, since EmberFire gives Fastboot Errors
    return [
      {
        'name': 'Ember 3D Nav',
        'repo': 'ember-3d-nav',
        'stars': 10
      },
      {
        'name': 'Ember Drop',
        'repo': 'ember-drop',
        'stars': 4
      },
      {
        'name': 'Ember Flatpickr',
        'repo': 'ember-flatpickr',
        'stars': 16
      },
      {
        'name': 'Ember Math Helpers',
        'repo': 'ember-math-helpers',
        'stars': 17
      },
      {
        'name': 'Ember Newton Cradle Loader',
        'repo': 'ember-newton-cradle-loader',
        'stars': 0
      },
      {
        'name': 'Ember Shepherd',
        'repo': 'ember-shepherd',
        'stars': 66
      },
      {
        'name': 'Ember Typewriter',
        'repo': 'ember-typewriter',
        'stars': 0
      },
      {
        'name': 'Ember Vivus',
        'repo': 'ember-vivus',
        'stars': 0
      },
      {
        'name': 'Ember X-Editable',
        'repo': 'ember-x-editable',
        'stars': 13
      }
    ];
  },
  afterModel() {
    return this.get('headData').setProperties({
      title: 'Ship Shape - Open Source',
      description: 'We have created several Ember addons and collaborated extensively with the Ember community.',
      type: 'website',
      url: 'https://shipshape.io/portfolio'
    });
  }
});
<|endoftext|>


<commit_before>define(['lib/knockout', 'scripts/Book', 'scripts/Link', 'scripts/Skill', 'scripts/Utils'],
  function (ko, Book, Link, Skill, Utils) {
    'use strict';
    window.jiathis_config = {
      url: window.location.href,
      summary: '快来试试。',
      title: '我是 Level 1 Web Developer #Web技能树#',
      showClose: true,
      shortUrl: true,
      hideMore: false
    };

    var TalentTree = function (_e) {
      var e = _e || {};
      var self = this;

      var asciiOffset = 96;
      var hashDelimeter = '_';

      var numPortraits = 1;

      //Mega skill list population
      self.skills = ko.observableArray(ko.utils.arrayMap(e.skills, function (item) {
        return new Skill(item);
      }));

      //Wire up dependency references
      function handleDependencies() {
        ko.utils.arrayForEach(e.skills, function (item) {
          if (item.dependsOn) {
            var dependent = Utils.getSkillById(self.skills(), item.id);
            ko.utils.arrayForEach(item.dependsOn, function (dependencyId) {
              var dependency = Utils.getSkillById(self.skills(), dependencyId);
              dependent.dependencies.push(dependency);
              dependency.dependents.push(dependent);
            });
          }
        });
      }

      handleDependencies();

      //Avatar properties
      self.avatarName = ko.observable('Name');
      //level = total of all points spent
      self.level = ko.computed(function () {
        var totalSkillPoints = 0;
        ko.utils.arrayForEach(self.skills(), function (skill) {
          totalSkillPoints += skill.points();
        });
        var totalLevel = totalSkillPoints + 1;
        window.jiathis_config.title = '@phodal 我是Level ' + totalLevel + ' Web Developer #Web技能树#';
        return totalLevel;
      });
      self.noPointsSpent = ko.computed(function () {
        return !Boolean(ko.utils.arrayFirst(self.skills(), function (skill) {
          return (skill.points() > 0);
        }));
      });
      self.stats = ko.computed(function () {
        var totals = {
          '魅力': 9,
          '灵巧': 9,
          '坚韧': 9,
          '智力': 9,
          '力量': 9,
          '智慧': 9
        };
        //get all the skill name/value pairs and add/create them, using the stat name as the index
        ko.utils.arrayForEach(self.skills(), function (skill) {
          var p = skill.points();
          if (p > 0) {
            ko.utils.arrayForEach(skill.stats, function (stat) {
              var total = totals[stat.title] || 0;
              total += stat.value * p; //multiply the stat value by the points spent on the skill
              totals[stat.title] = total;
            });
          }
        });
        //Translate into a view-friendly array
        var result = [];
        for (var statName in totals) {
          result.push({
            title: statName,
            value: totals[statName]
          });
        }
        return result;
      });
      //String of unique characteristics, comma delimeted
      self.talentSummary = ko.computed(function () {
        var a = [];
        ko.utils.arrayForEach(self.skills(), function (skill) {
          if (skill.hasPoints()) {
            a = a.concat(skill.talents);
          }
        });
        window.jiathis_config.summary = '我获得的称号有: ' + a.join(', ');
        return a.join(', ');
      });
      //Portrait stuff
      self.portrait = ko.observable(Math.ceil(Math.random() * numPortraits));
      self.portraitURL = ko.computed(function () {
        if(self.avatarName() !== 'Name') {
          return 'https://avatars.githubusercontent.com/' + self.avatarName();
        } else{
          return 'app/images/portraits/portrait-' + self.portrait() + '.jpg';
        }
      });
      self.choosePreviousPortrait = function () {
        var n = self.portrait() - 1;
        if (n < 1) {
          n = numPortraits;
        }
        self.portrait(n);
      };
      self.chooseNextPortrait = function () {
        var n = self.portrait() + 1;
        if (n > numPortraits) {
          n = 1;
        }
        self.portrait(n);
      };

      //Utility functions
      self.newbMode = function () {
        ko.utils.arrayForEach(self.skills(), function (skill) {
          skill.points(0);
        });
      };

      //Hash functions
      self.hash = ko.computed(function () {
        var a = [];
        //compile a flat list of skill ids and values
        ko.utils.arrayForEach(self.skills(), function (skill) {
          if (skill.hasPoints()) {
            a.push(String.fromCharCode(skill.id + asciiOffset)); //convert skill id to letter of the alphabet
            if (skill.hasMultiplePoints()) {
              a.push(skill.points());
            } //only include points if they are > 1
          }
        });
        return ['', a.join(''), self.portrait(), self.avatarName()].join(hashDelimeter);
      });

      //update the address bar when the hash changes
      //Update the skill tree based on a new hash
      self.updateLastHash = function (hash) {
        if (hash) {
          self.newbMode();

          var hashParts = hash.split(hashDelimeter);
          if (hashParts[2]) {
            self.portrait(Number(hashParts[2]));
          } //use the segment after the second delimeter as the portrait index
          if (hashParts[3]) {
            self.avatarName(hashParts[3]);
          } //use the segment after the third delimeter as the avatar name

          var skills_hash = hashParts[1]; //use the segment after the first delimeter as the skill hash

          var pairs = Utils.getSkillsByHash(skills_hash, self.skills(), asciiOffset);
          //cycle through the whole list, adding points where possible, until the list is depleted
          var pointsWereAllocated = true; //flag
          var handlePair = function (pair) {
            if (!pair.wasAllocated && pair.skill.canAddPoints()) { //only add points once, and only where possible
              pair.skill.points(Math.min(pair.skill.maxPoints, pair.points)); //don't add more points than allowed
              pair.wasAllocated = true; //don't add this one again
              pointsWereAllocated = true;
            }
          };
          while (pointsWereAllocated) {
            pointsWereAllocated = false; //assume the list is depleted by default
            ko.utils.arrayForEach(pairs, handlePair);
          }

          do_update_hash = true;
        }
      };

      //update the address bar when the hash changes
      function useLastHash() {
        self.updateLastHash(lastHash);
      }

      function updateHash(s) {
        window.location.hash = s || newHash;
        window.jiathis_config.url = window.location.href;
      }

      var lastHash, usehash_timeout, newHash, update_hash_timeout, do_update_hash = true;
      self.useHash = function (hash) {
        lastHash = hash;
        clearTimeout(usehash_timeout);
        usehash_timeout = setTimeout(useLastHash, 50);
      };

      self.hash.subscribe(function (newValue) {
        if (do_update_hash) {
          newHash = newValue;
          clearTimeout(update_hash_timeout);
          update_hash_timeout = setTimeout(updateHash, 50);
        }
      });

      window.onhashchange = function () {
        self.useHash(window.location.hash.substr(1));
      };

      var current_hash = window.location.hash.substr(1);
      self.useHash(current_hash);

      self.clear = function () {
        window.location = '';
      };
      self.noAvatarName = ko.computed(function () {
        return !Boolean(self.avatarName() !== 'Name');
      });
      self.canShare = ko.computed(function () {
        return Boolean(self.avatarName() !== 'Name');
      });
    };

    return TalentTree;
  });
<commit_msg>move jiathis config to handle hash<commit_after>define(['lib/knockout', 'scripts/Book', 'scripts/Link', 'scripts/Skill', 'scripts/Utils'],
  function (ko, Book, Link, Skill, Utils) {
    'use strict';
    window.jiathis_config = {
      url: window.location.href,
      summary: '快来试试。',
      title: '我是 Level 1 Web Developer #Web技能树#',
      showClose: true,
      shortUrl: true,
      hideMore: false
    };

    var TalentTree = function (_e) {
      var e = _e || {};
      var self = this;

      var asciiOffset = 96;
      var hashDelimeter = '_';

      var numPortraits = 1;

      //Mega skill list population
      self.skills = ko.observableArray(ko.utils.arrayMap(e.skills, function (item) {
        return new Skill(item);
      }));

      //Wire up dependency references
      function handleDependencies() {
        ko.utils.arrayForEach(e.skills, function (item) {
          if (item.dependsOn) {
            var dependent = Utils.getSkillById(self.skills(), item.id);
            ko.utils.arrayForEach(item.dependsOn, function (dependencyId) {
              var dependency = Utils.getSkillById(self.skills(), dependencyId);
              dependent.dependencies.push(dependency);
              dependency.dependents.push(dependent);
            });
          }
        });
      }

      handleDependencies();

      //Avatar properties
      self.avatarName = ko.observable('Name');
      //level = total of all points spent
      self.level = ko.computed(function () {
        var totalSkillPoints = 0;
        ko.utils.arrayForEach(self.skills(), function (skill) {
          totalSkillPoints += skill.points();
        });
        var totalLevel = totalSkillPoints + 1;
        window.jiathis_config.title = '@phodal 我是Level ' + totalLevel + ' Web Developer #Web技能树#';
        return totalLevel;
      });
      self.noPointsSpent = ko.computed(function () {
        return !Boolean(ko.utils.arrayFirst(self.skills(), function (skill) {
          return (skill.points() > 0);
        }));
      });
      self.stats = ko.computed(function () {
        var totals = {
          '魅力': 9,
          '灵巧': 9,
          '坚韧': 9,
          '智力': 9,
          '力量': 9,
          '智慧': 9
        };
        //get all the skill name/value pairs and add/create them, using the stat name as the index
        ko.utils.arrayForEach(self.skills(), function (skill) {
          var p = skill.points();
          if (p > 0) {
            ko.utils.arrayForEach(skill.stats, function (stat) {
              var total = totals[stat.title] || 0;
              total += stat.value * p; //multiply the stat value by the points spent on the skill
              totals[stat.title] = total;
            });
          }
        });
        //Translate into a view-friendly array
        var result = [];
        for (var statName in totals) {
          result.push({
            title: statName,
            value: totals[statName]
          });
        }
        return result;
      });
      //String of unique characteristics, comma delimeted
      self.talentSummary = ko.computed(function () {
        var a = [];
        ko.utils.arrayForEach(self.skills(), function (skill) {
          if (skill.hasPoints()) {
            a = a.concat(skill.talents);
          }
        });
        window.jiathis_config.summary = '我获得的称号有: ' + a.join(', ');
        return a.join(', ');
      });
      //Portrait stuff
      self.portrait = ko.observable(Math.ceil(Math.random() * numPortraits));
      self.portraitURL = ko.computed(function () {
        if(self.avatarName() !== 'Name') {
          return 'https://avatars.githubusercontent.com/' + self.avatarName();
        } else{
          return 'app/images/portraits/portrait-' + self.portrait() + '.jpg';
        }
      });
      self.choosePreviousPortrait = function () {
        var n = self.portrait() - 1;
        if (n < 1) {
          n = numPortraits;
        }
        self.portrait(n);
      };
      self.chooseNextPortrait = function () {
        var n = self.portrait() + 1;
        if (n > numPortraits) {
          n = 1;
        }
        self.portrait(n);
      };

      //Utility functions
      self.newbMode = function () {
        ko.utils.arrayForEach(self.skills(), function (skill) {
          skill.points(0);
        });
      };

      //Hash functions
      self.hash = ko.computed(function () {
        var a = [];
        //compile a flat list of skill ids and values
        ko.utils.arrayForEach(self.skills(), function (skill) {
          if (skill.hasPoints()) {
            a.push(String.fromCharCode(skill.id + asciiOffset)); //convert skill id to letter of the alphabet
            if (skill.hasMultiplePoints()) {
              a.push(skill.points());
            } //only include points if they are > 1
          }
        });
        window.jiathis_config.url = window.location.href;
        return ['', a.join(''), self.portrait(), self.avatarName()].join(hashDelimeter);
      });

      //update the address bar when the hash changes
      //Update the skill tree based on a new hash
      self.updateLastHash = function (hash) {
        if (!hash) {
          return;
        } else {
          self.newbMode();

          var hashParts = hash.split(hashDelimeter);
          if (hashParts[2]) {
            self.portrait(Number(hashParts[2]));
          } //use the segment after the second delimeter as the portrait index
          if (hashParts[3]) {
            self.avatarName(hashParts[3]);
          } //use the segment after the third delimeter as the avatar name

          var skills_hash = hashParts[1]; //use the segment after the first delimeter as the skill hash

          var pairs = Utils.getSkillsByHash(skills_hash, self.skills(), asciiOffset);
          //cycle through the whole list, adding points where possible, until the list is depleted
          var pointsWereAllocated = true; //flag
          var handlePair = function (pair) {
            if (!pair.wasAllocated && pair.skill.canAddPoints()) { //only add points once, and only where possible
              pair.skill.points(Math.min(pair.skill.maxPoints, pair.points)); //don't add more points than allowed
              pair.wasAllocated = true; //don't add this one again
              pointsWereAllocated = true;
            }
          };
          while (pointsWereAllocated) {
            pointsWereAllocated = false; //assume the list is depleted by default
            ko.utils.arrayForEach(pairs, handlePair);
          }

          do_update_hash = true;
        }
      };

      //update the address bar when the hash changes
      function useLastHash() {
        self.updateLastHash(lastHash);
      }

      function updateHash(s) {
        window.location.hash = s || newHash;
      }

      var lastHash, usehash_timeout, newHash, update_hash_timeout, do_update_hash = true;
      self.useHash = function (hash) {
        lastHash = hash;
        clearTimeout(usehash_timeout);
        usehash_timeout = setTimeout(useLastHash, 50);
      };

      self.hash.subscribe(function (newValue) {
        if (do_update_hash) {
          newHash = newValue;
          clearTimeout(update_hash_timeout);
          update_hash_timeout = setTimeout(updateHash, 50);
        }
      });

      window.onhashchange = function () {
        self.useHash(window.location.hash.substr(1));
      };

      var current_hash = window.location.hash.substr(1);
      self.useHash(current_hash);

      self.clear = function () {
        window.location = '';
      };
      self.noAvatarName = ko.computed(function () {
        return !Boolean(self.avatarName() !== 'Name');
      });
      self.canShare = ko.computed(function () {
        return Boolean(self.avatarName() !== 'Name');
      });
    };

    return TalentTree;
  });
<|endoftext|>


<commit_before>angular.module('xoWebApp').directive('stopEvent', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            console.log(attr);
            element.bind(attr.stopEvent, function (e) {
                e.stopPropagation();
            });
        }
    };
});<commit_msg>oops remove a useless console log in custom directive<commit_after>angular.module('xoWebApp').directive('stopEvent', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind(attr.stopEvent, function (e) {
                e.stopPropagation();
            });
        }
    };
});<|endoftext|>


<commit_before>var fs = require('fs');
var cl_template = require('./client.js');
var game_template = require('./../Game/game.js');
var Clients = [];
var Games = [];
var NamedClients = [];
var SciNames;
var io;

fs.readFile(__dirname + '/scientist-names.json','utf8', function(err, data)
{
	if (err)
	{
		console.Error("Cannot load JSON file for scientist-names");
		return;
	}
	SciNames = JSON.parse(data);
});

exports.init = function(ioContext)
{
	io = ioContext;
};

function request(socket, data)
{
	if ( 'undefined' == typeof socket )
	{
		return;
	}

	var res = null;
	if ( 'undefined' == typeof data || 'undefined' == typeof data.cmd )
	{
		res = {
			approved: false,
			data: "Error invaild request",
			id: data.id
		};
	}

	else
	{
		var clientContext = Clients[socket.id];
		if (clientContext.isPlaying)
			return;

		switch ( data.cmd )
		{
			//Create Game
			case 'C':
				res = createGame(clientContext, data.id);
				break;

			//Leave Game
			case 'L':
				res = leaveGame(clientContext, data.id);
				break;

			//Join Game
			case 'J':
				res = joinGame(clientContext, data.data, data.id);
				break;

			//Set Ready
			case 'R':
				res = setReady(clientContext, data.id);
				break;

			//Set Wait
			case 'W':
				res = setWait(clientContext, data.id);
				break;

			//Set Name
			case 'N':
				res = setName(clientContext, data.data, data.id);
				break;

			case 'I':
				res = lobbyInit(clientContext, data.id);
			break;

			default:
				res = {
					approved: false,
					data: "Error cannot determine command",
					id: data.id
				};
				break;
		}
	}
	socket.emit( 'lobby', res );
}

// Helper for adding clients to the lobby.
// Should be done on connect
exports.AddClient = function(socket)
{
	Clients[socket.id] = new cl_template.CreateClient(socket);

	socket.on('lobby', function(data)
	{
		request(socket, data);
	});

	socket.on('disconnect', function()
	{
		onDisconnect(socket);
	});
};

exports.GetClients = function()
{
	return Clients;
};

function createGame(clientContext, reqId)
{
	//Check if the player is already in a game
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot create a game if you are in a game"

		};
	}

	//Check if the play has a name
	if('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot create a game. client name is invaild",
			id: reqId
		};
	}

	var game = game_template.CreateGame(clientContext);

	Games[game.gameName] = game;

	pushGameCreated(game);
	pushPlayerUpdate(clientContext);

	var ret = {};
	ret.approved = true;
	ret.id = reqId;
	ret.data = {};
	ret.data.players = [];
	var player = {
		name: clientContext.name,
		state: clientContext.isReady
	};
	ret.data.players.push(player);
	return ret;
}

function leaveGame(clientContext, reqId)
{
	if(clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot leave a game if you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot leave game. client name is invaild",
			id: reqId
		};
	}

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	var isGameDeleted = gameContext.leaveGame(clientContext);
	if (isGameDeleted === true)
	{
		pushGameClosed(game);
		delete Games[game.gameName];
	}
	else
	{
		pushGameUpdated(game);
	}

	pushPlayerUpdate(clientContext);
	return{
		approved: true,
		id: reqId
	};
}

function joinGame(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot join a game if you are in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return{
			approved: false,
			data: "Cannot join a game if you do not have a name",
			id: reqId
		};
	}

	var gameContext = Games[data];

	if ('undefined' == typeof gameContext)
	{
		return{
			approved: false,
			data: "You dun fucked up"
		};
	}

	if (gameContext.joinGame(clientContext) === true)
	{
		clientContext.isInGame = true;
		clientContext.gameId = gameContext.gameId;

		pushGameUpdated(gameContext);

		return {
			approved: true,
			id: reqId
		};
	}
	else
		return{
			approved: false,
			data: "Game is either full or dosent exist anymore",
			id: reqId
		};
}

function setReady(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot ready whne you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot ready if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === true)
	{
		return {
			approved: false,
			data: "Cannot ready if you are already ready",
			id: reqId
		};
	}

	clientContext.isReady = true;

	var gameContext = {};

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setWait(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return {
			approved: false,
			data: "Must be in a game to be waiting",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot wait if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === false)
	{
		return {
			approved: false,
			data: "Cannot wait if you are already waiting",
			id: reqId
		};
	}

	clientContext.isReady = false;

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setName(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot change your name if you are in a game",
			id: reqId
		};
	}

	var isPlayerCreated = false;

	if (clientContext.name !== "")
	{
		if ('undefined' != typeof NamedClients[clientContext.name])
			delete NamedClients[clientContext.name];

	}
	else
	{
		isPlayerCreated = true;
	}

	//Change the name
	if (data === '')
	{

		var name;
		do
		{
			var potentialName = SciNames[Math.floor(Math.random()*SciNames.length)];

			if ('undefined' == typeof NamedClients[potentialName])
			{
				name = potentialName;
				break;
			}

		} while (true);

		clientContext.name = name;
		NamedClients[name] = clientContext;

		if(isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return{
			approved: true,
			data: name,
			id: reqId
		};
	}

	else
	{

		if ('undefined' != typeof NamedClients[data])
		{
			return {
				approved:false,
				data: "Name is already taken",
				id: reqId
			};
		}

		clientContext.name = data;
		NamedClients[data] = clientContext;

		if (isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return {
			approved: true,
			data: data,
			id: reqId
		};
	}
}

function lobbyInit(clientContext, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "something very bad happened to the client state. contact help fast",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "get the lobby if you do not have a name",
			id: reqId
		};
	}
	var ret = {};
	ret.approved = true;
	ret.data = {};
	ret.data.players = [];

	for (var key in NamedClients)
	{
		if(NamedClients.hasOwnProperty(key))
		{
			var player = {};
			player.name = NamedClients[key].name;
			player.state = (NamedClients[key].isInGame ? 'Playing' : 'Available');
			ret.data.players.push(player);
		}
	}

	ret.data.games = [];

	for (key in Games)
	{
		if(Games.hasOwnProperty(key))
		{
			var game = {};
			game.players = [];
			for (var j = 0; j < Games[key].players.length; j++)
			{
				var gamePlayer = {};
				gamePlayer.name = Games[key].players[j].name;
				gamePlayer.ready = Games[key].players[j].isReady;
				game.players.push(gamePlayer);
			}
			ret.data.games.push(game);
		}
	}

	ret.id = reqId;
	clientContext.isInitalized = true;
	pushPlayerCreated(clientContext);
	return ret;
}

function onDisconnect(socket)
{
	var client = Clients[socket.id];
	pushPlayerDisconnect(client);
	var name = client.name;

	if (client.isInGame === true)
	{
		var gameContext;

		for (var key in Games)
		{
			if (Games.hasOwnProperty(key))
			{
				if (Games[key].id === client.gameId)
				{
					gameContext0 = Games[key];
				}
			}
		}
		if('undefined' != typeof gameContext)
		{
			var isGameDeleted = gameContext.leaveGame(client);
			if (isGameDeleted === true)
			{
				pushGameClosed(game);
				delete Games[game.gameName];
			}
			else
			{
				pushGameUpdated(game);
			}
		}

	}

	delete Clients[socket.id];
	delete NamedClients[name];
}

function pushPlayerCreated(clientContext)
{

	var req = {
		cmd: "PC",
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerDisconnect(clientContext)
{
	var req = {
		cmd: 'PR',
		data: clientContext.name
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerUpdate(clientContext)
{
	var req = {
		cmd: 'PU',
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushGameCreated(gameContext)
{

	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GC',
		data: game
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameClosed(gameContext)
{
	var req = {
		cmd: 'GR',
		data: gameContext.gameName
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameUpdated(gameContext)
{
	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GU',
		data: game
	};
}

function sendPushRequestToAllBut(req, clientContext)
{
	for (var key in NamedClients)
	{
		if (NamedClients.hasOwnProperty(key))
		{
			if (NamedClients[key] == clientContext)
				continue;
			NamedClients[key].cl_socket.emit('lobby', req);
		}
	}
}<commit_msg>MErging with master<commit_after>var fs = require('fs');
var cl_template = require('./client.js');
var game_template = require('./../Game/game.js');
var Clients = [];
var Games = [];
var NamedClients = [];
var SciNames;
var io;

fs.readFile(__dirname + '/scientist-names.json','utf8', function(err, data)
{
	if (err)
	{
		console.Error("Cannot load JSON file for scientist-names");
		return;
	}
	SciNames = JSON.parse(data);
});

exports.init = function(ioContext)
{
	io = ioContext;
};

function request(socket, data)
{
	if ( 'undefined' == typeof socket )
	{
		return;
	}

	var res = null;
	if ( 'undefined' == typeof data || 'undefined' == typeof data.cmd )
	{
		res = {
			approved: false,
			data: "Error invaild request",
			id: data.id
		};
	}

	else
	{
		var clientContext = Clients[socket.id];
		if (clientContext.isPlaying)
			return;

		switch ( data.cmd )
		{
			//Create Game
			case 'C':
				res = createGame(clientContext, data.id);
				break;

			//Leave Game
			case 'L':
				res = leaveGame(clientContext, data.id);
				break;

			//Join Game
			case 'J':
				res = joinGame(clientContext, data.data, data.id);
				break;

			//Set Ready
			case 'R':
				res = setReady(clientContext, data.id);
				break;

			//Set Wait
			case 'W':
				res = setWait(clientContext, data.id);
				break;

			//Set Name
			case 'N':
				res = setName(clientContext, data.data, data.id);
				break;

			case 'I':
				res = lobbyInit(clientContext, data.id);
			break;

			default:
				res = {
					approved: false,
					data: "Error cannot determine command",
					id: data.id
				};
				break;
		}
	}
	socket.emit( 'lobby', res );
}

// Helper for adding clients to the lobby.
// Should be done on connect
exports.AddClient = function(socket)
{
	Clients[socket.id] = new cl_template.CreateClient(socket);

	socket.on('lobby', function(data)
	{
		request(socket, data);
	});

	socket.on('disconnect', function()
	{
		onDisconnect(socket);
	});
};

exports.GetClients = function()
{
	return Clients;
};

function createGame(clientContext, reqId)
{
	//Check if the player is already in a game
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot create a game if you are in a game"

		};
	}

	//Check if the play has a name
	if('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot create a game. client name is invaild",
			id: reqId
		};
	}

	var game = game_template.CreateGame(clientContext);

	Games[game.gameName] = game;

	pushGameCreated(game);
	pushPlayerUpdate(clientContext);

	var ret = {};
	ret.approved = true;
	ret.id = reqId;
	ret.data = {};
	ret.data.players = [];
	var player = {
		name: clientContext.name,
		state: clientContext.isReady
	};
	ret.data.players.push(player);
	return ret;
}

function leaveGame(clientContext, reqId)
{
	if(clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot leave a game if you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot leave game. client name is invaild",
			id: reqId
		};
	}

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	var isGameDeleted = gameContext.leaveGame(clientContext);
	if (isGameDeleted === true)
	{
		pushGameClosed(gameContext);
		delete Games[gameContext.gameName];
	}
	else
	{
		pushGameUpdated(gameContext);
	}

	pushPlayerUpdate(clientContext);
	return{
		approved: true,
		id: reqId
	};
}

function joinGame(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot join a game if you are in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return{
			approved: false,
			data: "Cannot join a game if you do not have a name",
			id: reqId
		};
	}

	var gameContext = Games[data];

	if ('undefined' == typeof gameContext)
	{
		return{
			approved: false,
			data: "You dun fucked up"
		};
	}

	if (gameContext.joinGame(clientContext) === true)
	{
		clientContext.isInGame = true;
		clientContext.gameId = gameContext.gameId;

		pushGameUpdated(gameContext);

		return {
			approved: true,
			id: reqId
		};
	}
	else
		return{
			approved: false,
			data: "Game is either full or dosent exist anymore",
			id: reqId
		};
}

function setReady(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot ready whne you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot ready if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === true)
	{
		return {
			approved: false,
			data: "Cannot ready if you are already ready",
			id: reqId
		};
	}

	clientContext.isReady = true;

	var gameContext = {};

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setWait(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return {
			approved: false,
			data: "Must be in a game to be waiting",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot wait if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === false)
	{
		return {
			approved: false,
			data: "Cannot wait if you are already waiting",
			id: reqId
		};
	}

	clientContext.isReady = false;

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setName(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot change your name if you are in a game",
			id: reqId
		};
	}

	var isPlayerCreated = false;

	if (clientContext.name !== "")
	{
		if ('undefined' != typeof NamedClients[clientContext.name])
			delete NamedClients[clientContext.name];

	}
	else
	{
		isPlayerCreated = true;
	}

	//Change the name
	if (data === '')
	{

		var name;
		do
		{
			var potentialName = SciNames[Math.floor(Math.random()*SciNames.length)];

			if ('undefined' == typeof NamedClients[potentialName])
			{
				name = potentialName;
				break;
			}

		} while (true);

		clientContext.name = name;
		NamedClients[name] = clientContext;

		if(isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return{
			approved: true,
			data: name,
			id: reqId
		};
	}

	else
	{

		if ('undefined' != typeof NamedClients[data])
		{
			return {
				approved:false,
				data: "Name is already taken",
				id: reqId
			};
		}

		clientContext.name = data;
		NamedClients[data] = clientContext;

		if (isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return {
			approved: true,
			data: data,
			id: reqId
		};
	}
}

function lobbyInit(clientContext, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "something very bad happened to the client state. contact help fast",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "get the lobby if you do not have a name",
			id: reqId
		};
	}
	var ret = {};
	ret.approved = true;
	ret.data = {};
	ret.data.players = [];

	for (var key in NamedClients)
	{
		if(NamedClients.hasOwnProperty(key))
		{
			var player = {};
			player.name = NamedClients[key].name;
			player.state = (NamedClients[key].isInGame ? 'Playing' : 'Available');
			ret.data.players.push(player);
		}
	}

	ret.data.games = [];

	for (key in Games)
	{
		if(Games.hasOwnProperty(key))
		{
			var game = {};
			game.players = [];
			for (var j = 0; j < Games[key].players.length; j++)
			{
				var gamePlayer = {};
				gamePlayer.name = Games[key].players[j].name;
				gamePlayer.ready = Games[key].players[j].isReady;
				game.players.push(gamePlayer);
			}
			ret.data.games.push(game);
		}
	}

	ret.id = reqId;
	clientContext.isInitalized = true;
	pushPlayerCreated(clientContext);
	return ret;
}

function onDisconnect(socket)
{
	var client = Clients[socket.id];
	pushPlayerDisconnect(client);
	var name = client.name;

	if (client.isInGame === true)
	{
		var gameContext;

		for (var key in Games)
		{
			if (Games.hasOwnProperty(key))
			{
				if (Games[key].id === client.gameId)
				{
					gameContext0 = Games[key];
				}
			}
		}
		if('undefined' != typeof gameContext)
		{
			var isGameDeleted = gameContext.leaveGame(client);
			if (isGameDeleted === true)
			{
				pushGameClosed(game);
				delete Games[game.gameName];
			}
			else
			{
				pushGameUpdated(game);
			}
		}

	}

	delete Clients[socket.id];
	delete NamedClients[name];
}

function pushPlayerCreated(clientContext)
{

	var req = {
		cmd: "PC",
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerDisconnect(clientContext)
{
	var req = {
		cmd: 'PR',
		data: clientContext.name
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerUpdate(clientContext)
{
	var req = {
		cmd: 'PU',
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushGameCreated(gameContext)
{

	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GC',
		data: game
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameClosed(gameContext)
{
	var req = {
		cmd: 'GR',
		data: gameContext.gameName
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameUpdated(gameContext)
{
	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GU',
		data: game
	};
}

function sendPushRequestToAllBut(req, clientContext)
{
	for (var key in NamedClients)
	{
		if (NamedClients.hasOwnProperty(key))
		{
			if (NamedClients[key] == clientContext)
				continue;
			NamedClients[key].cl_socket.emit('lobby', req);
		}
	}
}<|endoftext|>


<commit_before>(function (root, undefined) {
    "use strict";

    var FrameworkFactory = root.FrameworkFactory;

    function _initTypeHandlers(Class) {
        var types = FrameworkFactory.typeHandlers.getTypes(),
            type, typeHandler,
            i, iLen;

        for (i=0, iLen=types.length; i < iLen; i += 1) {
            type = types[i];
            typeHandler = FrameworkFactory.typeHandlers.get(type);
            if (typeHandler.init) {
                typeHandler.init(Class);
            }
        }
    }

    function _plainObject (val) {
        if (val === undefined || val === null) { return false; }
        return ((typeof val === 'object') && (val.constructor === Object));
    }

    function _copyKeys(o, newO, overrideExisting) {
        var key, val;

        overrideExisting = (overrideExisting === undefined) ? true : overrideExisting;

        for(key in o) {
            if (o.hasOwnProperty(key)) {
                val = o[key];
                if (overrideExisting) {
                    newO[key] = val;
                }
                else {
                    if(key in newO === false) {
                        newO[key] = val;
                    }
                }
            }
        }
    }

    function _updateMeta(Class) {
        var meta = Class.__meta__,
            parentMeta = {};

        if(Class.constructor.__baseMeta__) {
            _copyKeys(Class.constructor.__baseMeta__, parentMeta);
        }

        _copyKeys(parentMeta, meta, false);
    }

    function plugin($f) {

        var initializing = true,
            fnTest = /xyz/.test(function (){xyz;}) ? /\bbase\b/ : /.*/,
            defaultBaseClass = $f.config('defaultBaseClass'),
            requireNew = $f.config('requireNew', false),
            Class;

        Class = function (prop, parent) {
            var hasProp = Object.prototype.hasOwnProperty,
                proto, key, Constructor, __base__, funcString,
                create = Object.create;

            if ($f[defaultBaseClass] !== undefined) {
                parent  = parent || $f[defaultBaseClass];
            }
            else {
                parent = parent || Object;
            }
            prop    = prop || {};
            proto = create(parent.prototype);

            if (requireNew) {
                Constructor = function () {
                    if (this instanceof Constructor === false) {
                        throw new Error('Constructor used as function.');
                    }
                    //this.constructor = Constructor;
                    if (initializing === false && this.init !== undefined) {
                        this.init.apply(this, arguments);
                    }
                };
            }
            else {
                Constructor = function () {
                    var inst = null;

                    // Constructor is called as function,
                    // instanciate it and return instance object.
                    if(this instanceof Constructor === false) {
                        inst = create(Constructor.prototype);
                        if (inst.init !== undefined) {
                            inst.init.apply(inst, arguments);
                        }
                        return inst;
                    }
                    //this.constructor = Constructor;
                    if (this.init !== undefined) {
                        this.init.apply(this, arguments);
                    }
                };
            }

            //for each static members in parents, copy'em to child
            for (key in parent) {
                //if parent owns the key, set child item = parent item
                if (hasProp.call(parent, key)) {
                    Constructor[key] = parent[key];
                }
            }

            __base__ = parent.prototype;

            Constructor.prototype = proto;
            Constructor.prototype.constructor = Constructor;
            Constructor.__base__ = __base__;

            Constructor.attach = function attach(prop) {

                var item, type, val, processed,
                    key,
                    typeHandler;

                for(key in prop) {
                    if (hasProp.call(prop, key)) {
                        item = prop[key];
                        type = typeof item;
                        val = item;
                        processed = false;

                        if ($f.is.plainObject(item)) {
                            typeHandler = FrameworkFactory.typeHandlers.get(item.type).handler;
                            if (typeHandler !== undefined) {
                                typeHandler(Constructor, key, item);
                                processed = true;
                            }
                        }
                        else if (type === 'function' &&
                                typeof __base__[key] === 'function' &&
                                fnTest.test(item)) {
                            proto[key] = (function (key, fn) {
                                var baseFunc = function () {
                                        __base__[key].apply(this, arguments);
                                    },
                                    wrapper = function () {
                                        this.base =  baseFunc;
                                        var ret = fn.apply(this, arguments);
                                        this.base = null;
                                        return ret;
                                    };
                                return wrapper;
                            })(key, item);
                            processed = true;
                        }

                        if (!processed) {
                            proto[key] = val;
                        }
                        Constructor.__meta__[key] = item;
                    }
                }
                _updateMeta(Constructor);
            };

            Constructor.__meta__ = {};
            Constructor.__baseMeta__ = __base__.constructor.__meta__;
            _initTypeHandlers(Constructor);
            Constructor.attach(prop);

            //return
            return Constructor;

        };

        $f.Class = Class;

    }

    plugin.info = {
        name: "classes"
    };

    FrameworkFactory.plugins.register(plugin);

})(this);<commit_msg>Doc update<commit_after>(function (root, undefined) {
    "use strict";

    var FrameworkFactory = root.FrameworkFactory;

    function _initTypeHandlers(Class) {
        var types = FrameworkFactory.typeHandlers.getTypes(),
            type, typeHandler,
            i, iLen;

        for (i=0, iLen=types.length; i < iLen; i += 1) {
            type = types[i];
            typeHandler = FrameworkFactory.typeHandlers.get(type);
            if (typeHandler.init) {
                typeHandler.init(Class);
            }
        }
    }

    function _plainObject (val) {
        if (val === undefined || val === null) { return false; }
        return ((typeof val === 'object') && (val.constructor === Object));
    }

    function _copyKeys(o, newO, overrideExisting) {
        var key, val;

        overrideExisting = (overrideExisting === undefined) ? true : overrideExisting;

        for(key in o) {
            if (o.hasOwnProperty(key)) {
                val = o[key];
                if (overrideExisting) {
                    newO[key] = val;
                }
                else {
                    if(key in newO === false) {
                        newO[key] = val;
                    }
                }
            }
        }
    }

    function _updateMeta(Class) {
        var meta = Class.__meta__,
            parentMeta = {};

        if(Class.constructor.__baseMeta__) {
            _copyKeys(Class.constructor.__baseMeta__, parentMeta);
        }

        _copyKeys(parentMeta, meta, false);
    }

    function plugin($f) {

        var initializing = true,
            fnTest = /xyz/.test(function (){xyz;}) ? /\bbase\b/ : /.*/,
            defaultBaseClass = $f.config('defaultBaseClass'),
            requireNew = $f.config('requireNew', false),
            Class;

        Class = function (prop, parent) {
            var hasProp = Object.prototype.hasOwnProperty,
                proto, key, Constructor, __base__, funcString,
                create = Object.create;

            if ($f[defaultBaseClass] !== undefined) {
                parent  = parent || $f[defaultBaseClass];
            }
            else {
                parent = parent || Object;
            }
            prop    = prop || {};
            proto = create(parent.prototype);

            if (requireNew) {
                Constructor = function () {
                    if (this instanceof Constructor === false) {
                        throw new Error('Constructor used as function.');
                    }
                    //this.constructor = Constructor;
                    if (initializing === false && this.init !== undefined) {
                        this.init.apply(this, arguments);
                    }
                };
            }
            else {
                Constructor = function () {
                    var inst = null;

                    // Constructor is called as function,
                    // instanciate it and return instance object.
                    if(this instanceof Constructor === false) {
                        inst = create(Constructor.prototype);
                        if (inst.init !== undefined) {
                            inst.init.apply(inst, arguments);
                        }
                        return inst;
                    }
                    //this.constructor = Constructor;
                    if (this.init !== undefined) {
                        this.init.apply(this, arguments);
                    }
                };
            }

            //for each static members in parents, copy'em to child
            for (key in parent) {
                //if parent owns the key, set child item = parent item
                if (hasProp.call(parent, key)) {
                    Constructor[key] = parent[key];
                }
            }

            __base__ = parent.prototype;

            Constructor.prototype = proto;
            Constructor.prototype.constructor = Constructor;
            Constructor.__base__ = __base__;

            Constructor.attach = function attach(prop) {

                var item, type, val, processed,
                    key,
                    typeHandler;

                for(key in prop) {
                    if (hasProp.call(prop, key)) {
                        item = prop[key];
                        type = typeof item;
                        val = item;
                        processed = false;

                        if ($f.is.plainObject(item)) {
                            typeHandler = FrameworkFactory.typeHandlers.get(item.type).handler;
                            if (typeHandler !== undefined) {
                                typeHandler(Constructor, key, item);
                                processed = true;
                            }
                        }
                        else if (type === 'function' &&
                                typeof __base__[key] === 'function' &&
                                fnTest.test(item)) {
                            proto[key] = (function (key, fn) {
                                var baseFunc = function () {
                                        __base__[key].apply(this, arguments);
                                    },
                                    wrapper = function () {
                                        this.base =  baseFunc;
                                        var ret = fn.apply(this, arguments);
                                        this.base = null;
                                        return ret;
                                    };
                                return wrapper;
                            })(key, item);
                            processed = true;
                        }

                        if (!processed) {
                            proto[key] = val;
                        }
                        Constructor.__meta__[key] = item;
                    }
                }
                _updateMeta(Constructor);
            };

            Constructor.__meta__ = {};
            Constructor.__baseMeta__ = __base__.constructor.__meta__;
            _initTypeHandlers(Constructor);
            Constructor.attach(prop);

            //return
            return Constructor;

        };

        /**
         * Creates a new class for $f.
         * @function Class(o)
         * @param {object} o The class definition object.
         * @example
         * $f.Test = $f.Class()
         *
         * @public
         * @version 1.0
         **/
        $f.Class = Class;

    }

    plugin.info = {
        name: "classes"
    };

    FrameworkFactory.plugins.register(plugin);

})(this);<|endoftext|>


<commit_before>eav.factory("aiService", function ($http, localStorageService, userService) {
    var aiService = {
        //actionItemDllBaseUrl:"https://www.euclidtechnology.com/cvweb/cgi-bin/actionitemsdll.dll/list?",
        actionItemDllBaseUrl: "http://localhost/eav/cgi-bin/utilities.dll/customlist?",
        bookmarks: localStorageService.get('userBookmarks') || [],
        getUserAis: function (username) {
            //console.log("getUserAis Called.");
            //var userId = localStorageService.get("username");
            return $http({
                url: aiService.actionItemDllBaseUrl,
                method: 'GET',
                params: {
                    "user": username,
                    "sqlname": "GETEAVUSERAIS",
                    //"RANGE": "1/15",
                    "SORT": "LISTITEMNUM DESC",
                    "WBP": "ai_list_JSON.json",
                    "WHP": "ai_list_header_JSON.json",
                    "wmt": "none"
                }
            });

        },
        getAiNotes: function (aiNumber) {
            return $http({
                url: "http://localhost/eav/cgi-bin/actionitemsdll.dll/info?",
                method: 'GET',
                params: {
                    "LISTITEMNUM": aiNumber,
                    "RESPONSEPAGE": "actionNote.htm",
                    "WMT": "none"
                }
            });
        },

        getAiDetails: function (aiNumber) {
            return $http({
                //url: "https://www.euclidtechnology.com/cvweb/cgi-bin/actionitemsdll.dll/info?",
                url: "http://localhost/eav/cgi-bin/utilities.dll/customlist?",
                method: 'GET',
                params: {
                    "sqlname": "GETEAVUSERAIS",
                    "aiNum": aiNumber,
                    "WMT": "none",
                    "WBP": "ai_list_JSON.json",
                }
            });
        },

        getBookmarks: function () {
            //console.log("getBookmarks Called.");
            return aiService.bookmarks;
        },
        storeBookmark: function (actionItem) {
            //console.log("storeBookmark Called.");
            //console.log("this is the action item to store", actionItem);
            //console.log("this is what aiService.bookmarks looks like now", aiService.bookmarks);
            aiService.bookmarks.push(actionItem);
            //console.log("this is what it looks like after the push", aiService.bookmarks);
            //console.log("here is what the localstorage looks like b4 push", localStorage["euclidAV.userBookmarks"]);
            localStorageService.add('userBookmarks', aiService.bookmarks);
            //console.log("here is what the localstorage looks like after push", localStorage["euclidAV.userBookmarks"]);
        },

        removeBookmark: function (actionItem) {
            //console.log("removeBookmark Called.");
            //console.log("Removing", actionItem);
            //console.log("matching to", aiService.bookmarks);

            //aiService.bookmarks = _.without(aiService.bookmarks,actionItem);
            _.remove(aiService.bookmarks, function (aiObj) {
                return aiObj.LISTITEMNUM == actionItem.LISTITEMNUM;
            });
            //console.log("New array is", aiService.bookmarks);
            localStorageService.add('userBookmarks', aiService.bookmarks);
        },

        toggleBookmark: function (actionItem) {
            ////console.log(_.indexOf(bookmarks, actionItem.LISTITEMNUM)!==-1);
            //console.log("toggleBookmark Called.");
            // var containsBookmark = _.indexOf(aiService.bookmarks, actionItem.LISTITEMNUM)!==-1;
            var containsBookmark = _.any(aiService.bookmarks, function (aiObj) {
                return aiObj.LISTITEMNUM == actionItem.LISTITEMNUM;
            });

            if (containsBookmark == true) {
                //console.log("The bookmark is already there");
                actionItem.bookmarked = false;
                aiService.removeBookmark(actionItem);
            } else if (containsBookmark == false) {
                //console.log("The bookmark is NOT already there");
                actionItem.bookmarked = true;
                aiService.storeBookmark(actionItem);
            }
            //console.log(actionItem);
            //console.log("aiServBookmarks", aiService.bookmarks);
        },

        isBookmarked: function (actionItem) {
            //console.log("isBookmarked Called.");
            //return _.indexOf(aiService.bookmarks, aiNumber)!==-1 ? true : false;
            return _.any(aiService.bookmarks, function (aiObj) {
                return aiObj.LISTITEMNUM == actionItem.LISTITEMNUM;
            });
        },
        openUserAi: function (aiNumber) {
//            chrome.tabs.create({
//                "url": "https://www.euclidtechnology.com/support/ActionItem.aspx?cv_ActionItem=" + aiNumber
//            });
            window.open('https://www.euclidtechnology.com/support/ActionItem.aspx?cv_ActionItem=' + aiNumber ,'_blank');
        },
        modifyAis: function (actionItems) {
            //console.log("modifyAis Called.");
            $.each(actionItems, function (index, actionItem) {
                actionItem = aiService.modifyAi(actionItem);
            });
            return actionItems;
        },
        modifyAi: function (actionItem) {
            //console.log("modifyAi Called.");
            actionItem.actionTypeClass = actionItem.ACTIONTYPE.replace(/\s+/g, '').replace("/", "");
            actionItem.bookmarked = aiService.isBookmarked(actionItem);
            console.log(actionItem.bookmarked);
            return actionItem;
        },
        setBadge: function (text) {
//            chrome.browserAction.setBadgeText({
//                "text": text
//            });
        }

    }; //end aiService Object
    return aiService;

});
<commit_msg>Added client filter support to aiService<commit_after>eav.factory("aiService", function ($http, localStorageService, userService) {
    var aiService = {
        //actionItemDllBaseUrl:"https://www.euclidtechnology.com/cvweb/cgi-bin/actionitemsdll.dll/list?",
        actionItemDllBaseUrl: "http://localhost/eav/cgi-bin/utilities.dll/customlist?",
        bookmarks: localStorageService.get('userBookmarks') || [],
//        aiListFilter : "CLE",
        getUserAis: function (username) {
            //console.log("getUserAis Called.");
            //var userId = localStorageService.get("username");
            return $http({
                url: aiService.actionItemDllBaseUrl,
                method: 'GET',
                params: {
                    "user": username,
                    "sqlname": "GETEAVUSERAIS",
                    //"RANGE": "1/15",
                    "SORT": "LISTITEMNUM DESC",
                    "WBP": "ai_list_JSON.json",
                    "WHP": "ai_list_header_JSON.json",
                    "wmt": "none"
                }
            });

        },
        getAiNotes: function (aiNumber) {
            return $http({
                url: "http://localhost/eav/cgi-bin/actionitemsdll.dll/info?",
                method: 'GET',
                params: {
                    "LISTITEMNUM": aiNumber,
                    "RESPONSEPAGE": "actionNote.htm",
                    "WMT": "none"
                }
            });
        },

        getAiDetails: function (aiNumber) {
            return $http({
                //url: "https://www.euclidtechnology.com/cvweb/cgi-bin/actionitemsdll.dll/info?",
                url: "http://localhost/eav/cgi-bin/utilities.dll/customlist?",
                method: 'GET',
                params: {
                    "sqlname": "GETEAVUSERAIS",
                    "aiNum": aiNumber,
                    "WMT": "none",
                    "WBP": "ai_list_JSON.json",
                }
            });
        },

        getBookmarks: function () {
            //console.log("getBookmarks Called.");
            return aiService.bookmarks;
        },
        storeBookmark: function (actionItem) {
            //console.log("storeBookmark Called.");
            //console.log("this is the action item to store", actionItem);
            //console.log("this is what aiService.bookmarks looks like now", aiService.bookmarks);
            aiService.bookmarks.push(actionItem);
            //console.log("this is what it looks like after the push", aiService.bookmarks);
            //console.log("here is what the localstorage looks like b4 push", localStorage["euclidAV.userBookmarks"]);
            localStorageService.add('userBookmarks', aiService.bookmarks);
            //console.log("here is what the localstorage looks like after push", localStorage["euclidAV.userBookmarks"]);
        },

        removeBookmark: function (actionItem) {
            //console.log("removeBookmark Called.");
            //console.log("Removing", actionItem);
            //console.log("matching to", aiService.bookmarks);

            //aiService.bookmarks = _.without(aiService.bookmarks,actionItem);
            _.remove(aiService.bookmarks, function (aiObj) {
                return aiObj.LISTITEMNUM == actionItem.LISTITEMNUM;
            });
            //console.log("New array is", aiService.bookmarks);
            localStorageService.add('userBookmarks', aiService.bookmarks);
        },

        toggleBookmark: function (actionItem) {
            ////console.log(_.indexOf(bookmarks, actionItem.LISTITEMNUM)!==-1);
            //console.log("toggleBookmark Called.");
            // var containsBookmark = _.indexOf(aiService.bookmarks, actionItem.LISTITEMNUM)!==-1;
            var containsBookmark = _.any(aiService.bookmarks, function (aiObj) {
                return aiObj.LISTITEMNUM == actionItem.LISTITEMNUM;
            });

            if (containsBookmark == true) {
                //console.log("The bookmark is already there");
                actionItem.bookmarked = false;
                aiService.removeBookmark(actionItem);
            } else if (containsBookmark == false) {
                //console.log("The bookmark is NOT already there");
                actionItem.bookmarked = true;
                aiService.storeBookmark(actionItem);
            }
            //console.log(actionItem);
            //console.log("aiServBookmarks", aiService.bookmarks);
        },

        isBookmarked: function (actionItem) {
            //console.log("isBookmarked Called.");
            //return _.indexOf(aiService.bookmarks, aiNumber)!==-1 ? true : false;
            return _.any(aiService.bookmarks, function (aiObj) {
                return aiObj.LISTITEMNUM == actionItem.LISTITEMNUM;
            });
        },
        openUserAi: function (aiNumber) {
//            chrome.tabs.create({
//                "url": "https://www.euclidtechnology.com/support/ActionItem.aspx?cv_ActionItem=" + aiNumber
//            });
            window.open('https://www.euclidtechnology.com/support/ActionItem.aspx?cv_ActionItem=' + aiNumber ,'_blank');
        },
        modifyAis: function (actionItems) {
            //console.log("modifyAis Called.");
            $.each(actionItems, function (index, actionItem) {
                actionItem = aiService.modifyAi(actionItem);
            });
            return actionItems;
        },
        modifyAi: function (actionItem) {
            //console.log("modifyAi Called.");
            actionItem.actionTypeClass = actionItem.ACTIONTYPE.replace(/\s+/g, '').replace("/", "");
            actionItem.bookmarked = aiService.isBookmarked(actionItem);
            //console.log(actionItem.bookmarked);
            return actionItem;
        },
        setBadge: function (text) {
//            chrome.browserAction.setBadgeText({
//                "text": text
//            });
        },
        setAiListFilter: function (filter){
        aiService.aiListFilter = filter;
    },
           getAiListFilter: function (){
        return aiService.aiListFilter;
    }

    }; //end aiService Object
    return aiService;

});
<|endoftext|>


<commit_before>angular.module('objective-fire')
.factory('ObjectArray', ["$firebaseArray", function($firebaseArray) {
  var getFactory = function(fireObject) {
    return $firebaseArray.$extend({
      $$added: function(snapshot) {
        return fireObject.instance(snapshot.val());
      },
      $$updated: function(snapshot) {
        var changed = false;
        var curO = this.$getRecord(snapshot.val());
        var newO = fireObject.instance(snapshot.val());
        if (!angular.equals(curO, newO)) {
          change = true;
        }
        return changed;
      }
    });
  };
  /**
  An array of objects in the Firebase. The objects are of some class.
  @class ObjectArray
  @constructor
  @param ref {Firebase} Firebase reference to the location where this ObjectArray resides
  @param fireObject {FireObject} FireObject that is the class that each element of this array will be
  */
  return function(ref, fireObject) {
    var obj = new getFactory(fireObject);
    return obj;
  };
}]);
<commit_msg>removed unused objectArray.js<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

import runAll from "./index";
import Promise from "./promise"; // eslint-disable-line no-redeclare

const SUCCESS = Promise.resolve(null);

function printHelp(stdout) {
    stdout.write(`
Usage: npm-run-all [OPTIONS] [...tasks]

  Run specified tasks.

  Options:
    -h, --help                  Print this text.
    -p, --parallel [...tasks]   Run a group of tasks in parallel.
    -s, --sequential [...tasks] Run a group of tasks sequentially.
    -v, --version               Print version number.

  See Also:
    https://github.com/mysticatea/npm-run-all

`);
}

function printVersion(stdout) {
    stdout.write(`v${require("../package.json").version}\n`);
}

function createQueue(args) {
    return args.reduce((queue, arg) => {
        switch (arg) {
            case "-s":
            case "--sequential":
                queue.push({parallel: false, tasks: []});
                break;

            case "-p":
            case "--parallel":
                queue.push({parallel: true, tasks: []});
                break;

            default:
                if (arg[0] === "-") {
                    throw new Error(`Invalid Option: ${arg}`);
                }
                queue[queue.length - 1].tasks.push(arg);
                break;
        }
        return queue;
    }, [{parallel: false, tasks: []}]);
}

export default function main(
    args,
    stdout = process.stdout,
    stderr = process.stderr
) {
    if (args.length === 0) {
        args.push("--help");
    }
    switch (args[0]) {
        case "-h":
        case "--help":
            printHelp(stdout);
            return SUCCESS;

        case "-v":
        case "--version":
            printVersion(stdout);
            return SUCCESS;

        default:
            break;
    }

    let queue; // eslint-disable-line init-declarations
    try {
        queue = createQueue(args);
    }
    catch (err) {
        return Promise.reject(err);
    }

    let currentPromise = null;
    let aborted = false;
    const resultPromise = queue.reduce((prevPromise, group) => {
        return prevPromise.then(() => {
            if (group == null || group.tasks.length === 0 || aborted) {
                return undefined;
            }

            currentPromise = runAll(
                group.tasks,
                {
                    stdout,
                    stderr,
                    stdin: process.stdin,
                    parallel: group.parallel
                });

            return currentPromise;
        });
    }, SUCCESS);

    // Define abort method.
    resultPromise.abort = function abort() {
        aborted = true;
        if (currentPromise != null) {
            currentPromise.abort();
        }
    };

    return resultPromise;
}

/* eslint no-process-exit:0 */
/* istanbul ignore if */
if (require.main === module) {
    // Execute.
    const promise = main(process.argv.slice(2));

    // SIGINT/SIGTERM Handling.
    process.on("SIGINT", () => {
        promise.abort();
    });
    process.on("SIGTERM", () => {
        promise.abort();
    });

    // Error Handling.
    promise.catch(err => {
        console.error("ERROR:", err.message); // eslint-disable-line no-console
        process.exit(1);
    });
}
<commit_msg>Remove aborting with SIGINT since stdin is inherited.<commit_after>#!/usr/bin/env node

import runAll from "./index";
import Promise from "./promise"; // eslint-disable-line no-redeclare

const SUCCESS = Promise.resolve(null);

function printHelp(stdout) {
    stdout.write(`
Usage: npm-run-all [OPTIONS] [...tasks]

  Run specified tasks.

  Options:
    -h, --help                  Print this text.
    -p, --parallel [...tasks]   Run a group of tasks in parallel.
    -s, --sequential [...tasks] Run a group of tasks sequentially.
    -v, --version               Print version number.

  See Also:
    https://github.com/mysticatea/npm-run-all

`);
}

function printVersion(stdout) {
    stdout.write(`v${require("../package.json").version}\n`);
}

function createQueue(args) {
    return args.reduce((queue, arg) => {
        switch (arg) {
            case "-s":
            case "--sequential":
                queue.push({parallel: false, tasks: []});
                break;

            case "-p":
            case "--parallel":
                queue.push({parallel: true, tasks: []});
                break;

            default:
                if (arg[0] === "-") {
                    throw new Error(`Invalid Option: ${arg}`);
                }
                queue[queue.length - 1].tasks.push(arg);
                break;
        }
        return queue;
    }, [{parallel: false, tasks: []}]);
}

export default function main(
    args,
    stdout = process.stdout,
    stderr = process.stderr
) {
    if (args.length === 0) {
        args.push("--help");
    }
    switch (args[0]) {
        case "-h":
        case "--help":
            printHelp(stdout);
            return SUCCESS;

        case "-v":
        case "--version":
            printVersion(stdout);
            return SUCCESS;

        default:
            break;
    }

    let queue; // eslint-disable-line init-declarations
    try {
        queue = createQueue(args);
    }
    catch (err) {
        return Promise.reject(err);
    }

    let currentPromise = null;
    let aborted = false;
    const resultPromise = queue.reduce((prevPromise, group) => {
        return prevPromise.then(() => {
            if (group == null || group.tasks.length === 0 || aborted) {
                return undefined;
            }

            currentPromise = runAll(
                group.tasks,
                {
                    stdout,
                    stderr,
                    stdin: process.stdin,
                    parallel: group.parallel
                });

            return currentPromise;
        });
    }, SUCCESS);

    // Define abort method.
    resultPromise.abort = function abort() {
        aborted = true;
        if (currentPromise != null) {
            currentPromise.abort();
        }
    };

    return resultPromise;
}

/* eslint no-process-exit:0 */
/* istanbul ignore if */
if (require.main === module) {
    // Execute.
    const promise = main(process.argv.slice(2));

    // Error Handling.
    promise.catch(err => {
        console.error("ERROR:", err.message); // eslint-disable-line no-console
        process.exit(1);
    });
}
<|endoftext|>