<commit_before>'use strict';

var twitter = require('twitter-text');
var Publico = require('meatspace-publico');

var convert2webm = require('./convert2webm');

var publico = new Publico('none', {
  db: './db/db-messages',
  limit: 20
});

var IMAGE_TYPE = 'jpeg';

var validateImageTypeAndSize = function (data, next) {
  if (!data.length || data.length !== 10) {
    next(new Error('Invalid number of frames'));
    return;
  }

  var isJPG = true;

  for (var i = 0; i < data.length; i ++) {
    if (!data[i].match(/^data:image\/jpeg;base64,/)) {
      isJPG = false;
      break;
    }
  }

  if (!isJPG) {
    next(new Error('No JPEG detected'));
    return;
  }

  next(null, true);
};

exports.recent = function (next) {
  publico.getChats(true, function (err, c) {
    if (err) {
      next(err);
      return;
    }

    if (c.chats && c.chats.length > 0) {
      c.chats.reverse();
    }

    next(null, c.chats);
  });
};

exports.addMessage = function (payload, next) {
  validateImageTypeAndSize(payload.media, function (err) {
    if (err) {
      next(err);
      return;
    }

    convert2webm.transform(payload.media, function (err, media) {
      if (err) {
        next(err);
        return;
      }

      var message = twitter.autoLink(twitter.htmlEscape(payload.message), {
        targetBlank: true
      });

      publico.addChat(message.slice(0, 250), {
        ttl: 600000,
        media: media,
        fingerprint: payload.fingerprint
      }, function (err, chat) {
        if (err) {
          next(err);
          return;
        }

        next(null, chat);
      });
    });
  });
};
<commit_msg>change function name<commit_after>'use strict';

var twitter = require('twitter-text');
var Publico = require('meatspace-publico');

var convert2webm = require('./convert2webm');

var publico = new Publico('none', {
  db: './db/db-messages',
  limit: 20
});

var IMAGE_TYPE = 'jpeg';

var validateImageType = function (data, next) {
  if (!data.length || data.length !== 10) {
    next(new Error('Invalid number of frames'));
    return;
  }

  var isJPG = true;

  for (var i = 0; i < data.length; i ++) {
    if (!data[i].match(/^data:image\/jpeg;base64,/)) {
      isJPG = false;
      break;
    }
  }

  if (!isJPG) {
    next(new Error('No JPEG detected'));
    return;
  }

  next(null, true);
};

exports.recent = function (next) {
  publico.getChats(true, function (err, c) {
    if (err) {
      next(err);
      return;
    }

    if (c.chats && c.chats.length > 0) {
      c.chats.reverse();
    }

    next(null, c.chats);
  });
};

exports.addMessage = function (payload, next) {
  validateImageType(payload.media, function (err) {
    if (err) {
      next(err);
      return;
    }

    convert2webm.transform(payload.media, function (err, media) {
      if (err) {
        next(err);
        return;
      }

      var message = twitter.autoLink(twitter.htmlEscape(payload.message), {
        targetBlank: true
      });

      publico.addChat(message.slice(0, 250), {
        ttl: 600000,
        media: media,
        fingerprint: payload.fingerprint
      }, function (err, chat) {
        if (err) {
          next(err);
          return;
        }

        next(null, chat);
      });
    });
  });
};
<|endoftext|>


<commit_before>var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
<commit_msg>fix prod webpack config<commit_after>var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env,
        ALLOW_DEBUG: JSON.stringify(false)
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
<|endoftext|>


<commit_before>'use strict';

angular.module('hackatonAApp')
  .controller('AddprojCtrl', function ($scope, $resource) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
        var Project = $resource("/api/project", null,
        {
                create: {method: "POST", data: {}, isArray: false}
        });

        $scope.send=function(){
            var proj=$scope.project;
            proj.event_id=1;
            proj.owner_id=2;

            Project.create(proj);
        }
  });
<commit_msg>fixed<commit_after>'use strict';

angular.module('hackatonAApp')
  .controller('AddprojCtrl', function ($scope, $resource) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
        var Project = $resource("/api/project", null,
        {
                create: {method: "POST", data: {}, isArray: false}
        });

        $scope.send=function(){
            var proj=$scope.project;
            proj.event_id=1;
            proj.owner_id=2;

            Project.create(proj,function(){
                $location.path("/#/addProj");
            });
        }
  });
<|endoftext|>


<commit_before>// ==UserScript==
// @name        QQ音乐 online scrobbler
// @namespace   http://gmscrobber.whosemind.net
// @description 记录qq在线音乐到 last.fm
// @match       http://y.qq.com/
// @match       http://y.qq.com/?*
// @match       http://y.qq.com/#*
// @exclude     http://y.qq.com/y/*
// @require     https://raw.github.com/justan/gmscrobber/master/simple_scrobbler_user.js
// @version     0.0.1
// ==/UserScript==

var init = function(){
  log('init');
  scrobber.setSongInfoFN(getSongInfo, {checktime: 4000});
  document.getElementsByClassName('player_bar')[0].addEventListener('click', function(e){
    var oldTime = getSongInfo().playTime;
    setTimeout(function(){
      var newTime = getSongInfo().playTime;
      offset = oldTime - newTime;
      scrobber.seek(offset);
    }, 0);
  }, true);

  scrobber.on('nowplaying', function(){
    var loveEle = document.getElementsByClassName('music_op')[0].firstChild;
    loveEle.addEventListener('click', function(e){
      if(loveEle.title == '喜欢'){
        scrobber.love();
      }else if(loveEle.title == '取消喜欢'){
        scrobber.unlove();
      }
    }, false);
    scrobber.getInfo(scrobber.song, function(info){
      document.getElementById('divplayer').title = '在 last.fm 中记录: ' + info.len + ' 次';
    });
  });
};

var scrobber = new Scrobbler({
  name: 'QQ 音乐',
  ready: init
});

var getSongInfo = function(){
  var song = {};
  var songinfo = document.getElementById('divsonginfo');
  song.title = songinfo.getElementsByClassName('music_name')[0].title;
  song.artist = songinfo.getElementsByClassName('singer_name')[0].title;
  song.duration = timeParse(document.getElementById('ptime').innerHTML);
  song.playTime = song.duration * document.getElementById('spanplaybar').style.width.replace(/%/, '') / 100;
  song.album = songinfo.getElementsByClassName('album_pic')[0].title;
  return song;
};

var timeParse = function(timeStr){
  var ts = timeStr.split(':');
  return ts[0] * 60 + ts[1] * 1;
};<commit_msg>以 last.fm 红星歌曲为标准, 同步红星/取消红星到 music.qq.com<commit_after>// ==UserScript==
// @name        QQ音乐 online scrobbler
// @namespace   http://gmscrobber.whosemind.net
// @description 记录qq在线音乐到 last.fm
// @match       http://y.qq.com/
// @match       http://y.qq.com/?*
// @match       http://y.qq.com/#*
// @exclude     http://y.qq.com/y/*
// @require     https://raw.github.com/justan/gmscrobber/master/simple_scrobbler_user.js
// @version     0.0.1
// ==/UserScript==

var init = function(){
  log('init');
  scrobber.setSongInfoFN(getSongInfo, {checktime: 4000});
  document.getElementsByClassName('player_bar')[0].addEventListener('click', function(e){
    var oldTime = getSongInfo().playTime;
    setTimeout(function(){
      var newTime = getSongInfo().playTime;
      offset = oldTime - newTime;
      scrobber.seek(offset);
    }, 0);
  }, true);

  scrobber.on('nowplaying', function(){
    var loveEle = document.getElementsByClassName('music_op')[0].firstChild;
    loveEle.addEventListener('click', function(e){
      if(loveEle.title == '喜欢'){
        scrobber.love();
      }else if(loveEle.title == '取消喜欢'){
        scrobber.unlove();
      }
    }, false);
    scrobber.getInfo(scrobber.song, function(info){
      document.getElementById('divplayer').title = '在 last.fm 中记录: ' + info.len + ' 次';
      //同步 last.fm 红星歌曲到 qq music
      if(info.islove == '1' && loveEle.title == '喜欢' || info.islove == '0' && loveEle.title == '取消喜欢'){
        unsafeWindow.g_topPlayer.like(null, loveEle, unsafeWindow.g_topPlayer.getCurSongInfo());
      }
    });
  });
};

var scrobber = new Scrobbler({
  name: 'QQ 音乐',
  ready: init
});

var getSongInfo = function(){
  var song = {};
  var songinfo = document.getElementById('divsonginfo');
  song.title = songinfo.getElementsByClassName('music_name')[0].title;
  song.artist = songinfo.getElementsByClassName('singer_name')[0].title;
  song.duration = timeParse(document.getElementById('ptime').innerHTML);
  song.playTime = song.duration * document.getElementById('spanplaybar').style.width.replace(/%/, '') / 100;
  song.album = songinfo.getElementsByClassName('album_pic')[0].title;
  return song;
};

var timeParse = function(timeStr){
  var ts = timeStr.split(':');
  return ts[0] * 60 + ts[1] * 1;
};<|endoftext|>


<commit_before>const express = require('express')
const logger = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')

const app = express()
/*
  * ROUTES
*/
const routeUsers = require('./routes/routes.api.users')
const routeAuth = require('./routes/routes.api.auth')
const routeIdeas = require('./routes/routes.api.ideas')
const routeComments = require('./routes/routes.api.comments')
const routeVotes = require('./routes/routes.api.votes')
const routeReports = require('./routes/routes.api.reports')
const routeNotifs = require('./routes/routes.api.notifs')

/*
  * Models
*/
const models = require ('./models')
const Users = models.Users

// JSON Web Tokens
const jwt = require('jsonwebtoken')

// Authentication
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy

const PORT = process.env.PORT || 8080

app.use(cors())
app.use(logger())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))
app.use('/api/users', routeUsers)
app.use('/api/auth', routeAuth)
app.use('/api/ideas', routeIdeas)
app.use('/api/ideas', routeComments)
app.use('/api/ideas', routeVotes)
app.use('/api/ideas', routeReports)
app.use('/api/notif', routeNotifs)

// passport.use(new LocalStrategy(Users.authenticate()))
passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  }, function (username, password, cb) {
      Users.findByUsername(username, function (err, user) {
          if (err) { return cb(err); }

          if (user) {
              return user.authenticate(password, cb);
          } else {
              return cb(null, false, { message: 'Incorrect password' });
          }
      });
  }))

app.use(passport.initialize());
passport.serializeUser(Users.serializeUser());
passport.deserializeUser(Users.deserializeUser());

app.listen(PORT, (err) => {
  if(err){
    console.error(err);
  }else{
    console.log(`server is running in port ${PORT}`);
  }
})
/*
db name : db_partneran_dev

MODULE USERS
create table users :
sequelize model:create --name Users --attributes "userId:integer,email:string,myhash:string(1024),mysalt:string,photo_URL:string,verify:boolean"

create db_partneran_dev in postgres server, choose owner : postgres

migrate :
sequelize db:migrate

edit users model, config passport-local-sequelize

testing :
db_partneran_dev

sequelize migration:create --name add_short_bio_to_users_table

MODULE IDEAS
sequelize model:create --name Ideas --attributes "ideaId:integer,title:string,description:string,status:string,image:str
ing,video:string"

sequelize db:migrate

add FK userId
sequelize migration:create --name add_FK_userId_to_Ideas_table

MODULE CATEGORIES
sequelize model:create --name Categories --attributes "categoryId:integer,name:string"

add FK categoryId to Ideas table
sequelize migration:create --name add_FK_categoryId_to_Ideas_table

sequelize migration:create --name add_slug_to_Ideas_table

create table comments :
sequelize model:create --name Comments --attributes "commentId:integer,content:text"

create table roles :
sequelize model:create --name Roles --attributes "roleId:integer,roles:string"

create table votes :
sequelize model:create --name Votes --attributes "voteId:integer,votes:string"

sequelize migration:create --name add_isSuper_column_to_users_table

create table reports :
sequelize model:create --name Reports --attributes "reportId:integer,reason:string,status:boolean"

create table notifications :
sequelize model:create --name Notifications --attributes "notificationId:integer,message:string,status:boolean"

create table user_notifs :
sequelize model:create --name User_notifs --attributes "user_notif_id:integer"

seeder Categories :
sequelize seed:create --name seed_categories

migrate seeder Categories
sequelize db:seed --seed seeders/20161212144451-seed_categories.js

*/
<commit_msg>updated server.js routeCategories<commit_after>const express = require('express')
const logger = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')

const app = express()
/*
  * ROUTES
*/
const routeUsers = require('./routes/routes.api.users')
const routeAuth = require('./routes/routes.api.auth')
const routeIdeas = require('./routes/routes.api.ideas')
const routeComments = require('./routes/routes.api.comments')
const routeVotes = require('./routes/routes.api.votes')
const routeReports = require('./routes/routes.api.reports')
const routeNotifs = require('./routes/routes.api.notifs')
const routeCategories = require('./routes/routes.api.categories')

/*
  * Models
*/
const models = require ('./models')
const Users = models.Users

// JSON Web Tokens
const jwt = require('jsonwebtoken')

// Authentication
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy

const PORT = process.env.PORT || 8080

app.use(cors())
app.use(logger())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))
app.use('/api/users', routeUsers)
app.use('/api/auth', routeAuth)
app.use('/api/ideas', routeIdeas)
app.use('/api/ideas', routeComments)
app.use('/api/ideas', routeVotes)
app.use('/api/ideas', routeReports)
app.use('/api/notif', routeNotifs)
app.use('/api/categories', routeCategories)

// passport.use(new LocalStrategy(Users.authenticate()))
passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  }, function (username, password, cb) {
      Users.findByUsername(username, function (err, user) {
          if (err) { return cb(err); }

          if (user) {
              return user.authenticate(password, cb);
          } else {
              return cb(null, false, { message: 'Incorrect password' });
          }
      });
  }))

app.use(passport.initialize());
passport.serializeUser(Users.serializeUser());
passport.deserializeUser(Users.deserializeUser());

app.listen(PORT, (err) => {
  if(err){
    console.error(err);
  }else{
    console.log(`server is running in port ${PORT}`);
  }
})
/*
db name : db_partneran_dev

MODULE USERS
create table users :
sequelize model:create --name Users --attributes "userId:integer,email:string,myhash:string(1024),mysalt:string,photo_URL:string,verify:boolean"

create db_partneran_dev in postgres server, choose owner : postgres

migrate :
sequelize db:migrate

edit users model, config passport-local-sequelize

testing :
db_partneran_dev

sequelize migration:create --name add_short_bio_to_users_table

MODULE IDEAS
sequelize model:create --name Ideas --attributes "ideaId:integer,title:string,description:string,status:string,image:str
ing,video:string"

sequelize db:migrate

add FK userId
sequelize migration:create --name add_FK_userId_to_Ideas_table

MODULE CATEGORIES
sequelize model:create --name Categories --attributes "categoryId:integer,name:string"

add FK categoryId to Ideas table
sequelize migration:create --name add_FK_categoryId_to_Ideas_table

sequelize migration:create --name add_slug_to_Ideas_table

create table comments :
sequelize model:create --name Comments --attributes "commentId:integer,content:text"

create table roles :
sequelize model:create --name Roles --attributes "roleId:integer,roles:string"

create table votes :
sequelize model:create --name Votes --attributes "voteId:integer,votes:string"

sequelize migration:create --name add_isSuper_column_to_users_table

create table reports :
sequelize model:create --name Reports --attributes "reportId:integer,reason:string,status:boolean"

create table notifications :
sequelize model:create --name Notifications --attributes "notificationId:integer,message:string,status:boolean"

create table user_notifs :
sequelize model:create --name User_notifs --attributes "user_notif_id:integer"

seeder Categories :
sequelize seed:create --name seed_categories

migrate seeder Categories
sequelize db:seed --seed seeders/20161212144451-seed_categories.js

*/
<|endoftext|>


<commit_before>/*
 * jquery.starter
 * A jQuery plugin to start another jQuery plugin.
 *
 * Copyright (c) 2013 Aleksej Romanovskij
 * Licensed under the MIT license.
 */

(function ($, undefined) {
    'use strict';

    // Plugin constructor
    var Starter = function (elem, options) {
            this.elem     = elem;
            this.$elem    = $(elem);
            this.options  = options;

            this.metadata = this.$elem.data();

            this._init();
        },
        namespace = 'starter';

    // The plugin prototype
    Starter.prototype = {
        version     : 0.1,

        // Plugin defaults options
        defaults    : {
            autoStart: true
        },

        /**
         * Initialization procedures
         * @private
         */
        _init: function () {
            var starter = this,
                _arguments,
                plugin;

            if (typeof starter.options == 'string') {
                starter.config = $.extend(true, {}, starter.defaults, starter.metadata);
                plugin = starter.options;
            } else {
                starter.config = $.extend(true, {}, starter.defaults, starter.options, starter.metadata);
                plugin = starter.config[namespace];
            }

            if (typeof plugin == 'undefined') {
                starter._error('Nothing to start :(');
            }

            if ('arguments' in starter.config) {
                _arguments = starter.config['arguments'];
            } else {
                _arguments = starter.config;
            }

            if (plugin && plugin in $.fn) {
                starter.$elem[plugin](_arguments);
            } else {
                starter._error('Please add jQuery plugin "' + plugin + '" js-file to document.');
            }
        },

        /**
         * Show error message in console
         * @private
         */
        _error: function (error_message) {
            if ('console' in window) {
                window.console.error(error_message);
            }

            throw new Error(error_message);
        }
    };

    $.fn[namespace] = function (options) {
        return this.each(function () {
            var $this       = $(this),
                plugin_here = namespace + ' here',
                data        = $this.data(plugin_here);

            if (!data) {
                $this.data(plugin_here, new Starter(this, options));
            }
        });
    };

    $.fn[namespace].Constructor   = Starter;
    $.fn[namespace].defaults      = Starter.prototype.defaults;

    // Plugin initialization on DOM ready event
    $(function () {
        if ($.fn[namespace].defaults.autoStart) {
            $('[data-' + namespace + ']')[namespace]();
        }
    });
})(window.jQuery);
<commit_msg>Clear start options for started plugin<commit_after>/*
 * jquery.starter
 * A jQuery plugin to start another jQuery plugin.
 *
 * Copyright (c) 2013 Aleksej Romanovskij
 * Licensed under the MIT license.
 */

(function ($, undefined) {
    'use strict';

    // Plugin constructor
    var Starter = function (elem, options) {
            this.elem     = elem;
            this.$elem    = $(elem);
            this.options  = options;

            this.metadata = this.$elem.data();

            this._init();
        },
        namespace = 'starter';

    // The plugin prototype
    Starter.prototype = {
        version     : 0.1,

        // Plugin defaults options
        defaults    : {
            autoStart   : true,
            plugin      : ''
        },

        /**
         * Initialization procedures
         * @private
         */
        _init: function () {
            var starter         = this,
                arguments_key   = 'arguments',
                _arguments      = $.extend(true, {}, starter.metadata),
                plugin;

            if (typeof starter.options == 'string') {
                starter.config = $.extend(true, {}, starter.defaults, starter.metadata);
                plugin = starter.options;
            } else {
                starter.config = $.extend(true, {}, starter.defaults, starter.options, starter.metadata);
                plugin = starter.config[namespace];
            }

            if (typeof plugin == 'undefined') {
                starter._error('Nothing to start :(');
            }

            if (arguments_key in starter.config) {
                _arguments = starter.config[arguments_key];
            } else {
                // Clear arguments...
                delete _arguments[namespace + '_here'];
                delete _arguments[namespace];
                delete _arguments[arguments_key];

                $.each(starter.defaults, function (key) {
                    delete(_arguments[key]);
                });
            }

            if (plugin && plugin in $.fn) {
                starter.$elem[plugin](_arguments);
            } else {
                starter._error('Please add jQuery plugin "' + plugin + '" js-file to document.');
            }
        },

        /**
         * Show error message in console
         * @private
         */
        _error: function (error_message) {
            if ('console' in window) {
                window.console.error(error_message);
            }

            throw new Error(error_message);
        }
    };

    $.fn[namespace] = function (options) {
        return this.each(function () {
            var $this       = $(this),
                plugin_here = namespace + '_here',
                data        = $this.data(plugin_here);

            if (!data) {
                $this.data(plugin_here, new Starter(this, options));
            }
        });
    };

    $.fn[namespace].Constructor   = Starter;
    $.fn[namespace].defaults      = Starter.prototype.defaults;

    // Plugin initialization on DOM ready event
    $(function () {
        if ($.fn[namespace].defaults.autoStart) {
            $('[data-' + namespace + ']')[namespace]();
        }
    });
})(window.jQuery);
<|endoftext|>


<commit_before>// Load modules.
var decisions = require('decisions')
  , pkginfo = require('pkginfo')
  , os = require('os')
  , path = require('path-os')
  , fs = require('fs')
  , existsSync = fs.existsSync || path.existsSync; // <=0.6

/**
 * Settings.
 *
 * To utilize this object within an application, register `bixby-common` as a
 * source of objects with the IoC container.
 *
 *     IoC.use(require('bixby-common'));
 *
 * @returns {Settings}
 * @access public
 */
exports = module.exports = function() {
  var approot = path.dirname(pkginfo.find(require.main));
  var ostype = os.type().toLowerCase();
  var settings = decisions.createSettings();

  var dirname = path.resolve(approot, 'etc')
    , exts = [ '.toml', '.yaml', '.json' ]
    , ext, i, len, file;

  // Load default settings.
  //
  // The default settings are defined in a file relative to the application's
  // main script, at etc/settings.toml.  Note that this file is considered
  // internal application configuration, and as such does not vary between
  // deployment environments.  As such, it is suitable for maintaining under
  // source control.
  //
  // Separate files, located outside of source control, will be loaded in order
  // to override defaults, allowing settings to be modified according to
  // deployment specific requirements.
  for (i = 0, len = exts.length; i < len; ++i) {
    ext = exts[i];
    file = path.join(dirname, 'settings' + ext);
    if (existsSync(file)) {
      settings.load(file);
      break;
    }
  }

  var pkg = pkginfo.read(require.main).package;
  var vend = pkg.author && pkg.author.organization
           ? path.join(pkg.author.organization, pkg.name)
           : pkg.name;

  // Load host-specific settings.
  //
  // Host-specific settings are loaded from system-wide configuration files.
  //
  // It is recommended to use host-specific settings in deployment environments,
  // overriding any defaults that are not suitable to the requirements.
  if (ostype.indexOf('darwin') === 0) {
    dirname = '/Library/Preferences'
  } else { // UNIX
    dirname = '/etc';
  }

  for (i = 0, len = exts.length; i < len; ++i) {
    ext = exts[i];
    file = path.join(dirname, vend + ext);
    if (existsSync(file)) {
      settings.load(file);
      break;
    }
  }

  // Load user-specific settings.
  //
  // User-specific settings are loaded from directories owned by the user.  This
  // allows users to override system-wide settings according to user specific
  // requirements.
  //
  // It is recommended to use user-specific settings in development, allowing
  // each developer to tune their environment without risk of conflicts with
  // settings used by other developers.
  //
  // The location of user-specific settings vary depending on the OS, and can be
  // found at the following locations:
  //
  //   Linux: /home/<username>/.config/<package>.toml
  //   Mac OS X: /Users/<username>/Library/Preferences/<package>.toml
  for (i = 0, len = exts.length; i < len; ++i) {
    ext = exts[i];
    file = path.configdir(vend + ext);
    if (existsSync(file)) {
      settings.load(file);
      break;
    }
  }

  // load environment variables
  file = path.resolve(approot, 'app/env.json');
  if (existsSync(file)) {
    var data = fs.readFileSync(file, 'utf8')
      , map, sk, val;
    try {
      map = JSON.parse(data);
      Object.keys(map).forEach(function(ek) {
        sk = map[ek];
        val = process.env[ek];
        if (val) {
          settings.set(sk, val);
        }
      });
    } catch (_) {
    }
  }

  return settings;
}

exports['@singleton'] = true;
<commit_msg>Document host-specific configuration locations.<commit_after>// Load modules.
var decisions = require('decisions')
  , pkginfo = require('pkginfo')
  , os = require('os')
  , path = require('path-os')
  , fs = require('fs')
  , existsSync = fs.existsSync || path.existsSync; // <=0.6

/**
 * Settings.
 *
 * To utilize this object within an application, register `bixby-common` as a
 * source of objects with the IoC container.
 *
 *     IoC.use(require('bixby-common'));
 *
 * @returns {Settings}
 * @access public
 */
exports = module.exports = function() {
  var approot = path.dirname(pkginfo.find(require.main));
  var ostype = os.type().toLowerCase();
  var settings = decisions.createSettings();

  var dirname = path.resolve(approot, 'etc')
    , exts = [ '.toml', '.yaml', '.json' ]
    , ext, i, len, file;

  // Load default settings.
  //
  // The default settings are defined in a file relative to the application's
  // main script, at etc/settings.toml.  Note that this file is considered
  // internal application configuration, and as such does not vary between
  // deployment environments.  As such, it is suitable for maintaining under
  // source control.
  //
  // Separate files, located outside of source control, will be loaded in order
  // to override defaults, allowing settings to be modified according to
  // deployment specific requirements.
  for (i = 0, len = exts.length; i < len; ++i) {
    ext = exts[i];
    file = path.join(dirname, 'settings' + ext);
    if (existsSync(file)) {
      settings.load(file);
      break;
    }
  }

  var pkg = pkginfo.read(require.main).package;
  var vend = pkg.author && pkg.author.organization
           ? path.join(pkg.author.organization, pkg.name)
           : pkg.name;

  // Load host-specific settings.
  //
  // Host-specific settings are loaded from system-wide configuration files.
  //
  // It is recommended to use host-specific settings in deployment environments,
  // overriding any defaults that are not suitable to the requirements.
  //
  // The location of host-specific settings vary depending on the OS, and can be
  // found at the following locations:
  //
  //   Linux: /etc/<package>.toml
  //   Mac OS X: /Library/Preferences/<package>.toml
  if (ostype.indexOf('darwin') === 0) {
    dirname = '/Library/Preferences'
  } else { // UNIX
    dirname = '/etc';
  }

  for (i = 0, len = exts.length; i < len; ++i) {
    ext = exts[i];
    file = path.join(dirname, vend + ext);
    if (existsSync(file)) {
      settings.load(file);
      break;
    }
  }

  // Load user-specific settings.
  //
  // User-specific settings are loaded from directories owned by the user.  This
  // allows users to override system-wide settings according to user specific
  // requirements.
  //
  // It is recommended to use user-specific settings in development, allowing
  // each developer to tune their environment without risk of conflicts with
  // settings used by other developers.
  //
  // The location of user-specific settings vary depending on the OS, and can be
  // found at the following locations:
  //
  //   Linux: /home/<username>/.config/<package>.toml
  //   Mac OS X: /Users/<username>/Library/Preferences/<package>.toml
  for (i = 0, len = exts.length; i < len; ++i) {
    ext = exts[i];
    file = path.configdir(vend + ext);
    if (existsSync(file)) {
      settings.load(file);
      break;
    }
  }

  // load environment variables
  file = path.resolve(approot, 'app/env.json');
  if (existsSync(file)) {
    var data = fs.readFileSync(file, 'utf8')
      , map, sk, val;
    try {
      map = JSON.parse(data);
      Object.keys(map).forEach(function(ek) {
        sk = map[ek];
        val = process.env[ek];
        if (val) {
          settings.set(sk, val);
        }
      });
    } catch (_) {
    }
  }

  return settings;
}

exports['@singleton'] = true;
<|endoftext|>


<commit_before>import assign from 'object.assign';
import serialize, { hash_serializer } from 'form-serialize';

export const inputPropsLookup = (inputProps, inputName) => {
  var props = inputProps[inputName];
  if (props) return assign({ label: inputName }, props); // props found, easy.

  var inputNameTree = hash_serializer({}, inputName, null);
  var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

  props = inputProps[attrName];

  if (!isNaN(parseInt(attrName, 10))) {
    // skip number
    props = inputProps;
  } else if (props && props.type === 'nested') {
    // continue with nested props
    props = props.fields;
  } else if (props) {
    return props;
  } else {
    return undefined;
  }

  var newInputName = inputName.replace(attrName, '');
  var nextAttrName = Object.keys(inputNameTree[attrName])[0];

  // remove bracket
  newInputName = newInputName.replace('[' + nextAttrName + ']', '');
  newInputName = nextAttrName + newInputName;

  return inputPropsLookup(props, newInputName);
};

export const inputValueLookup = (serializedValues, inputName) => {
  if (!serializedValues || Object.keys(serializedValues).length === 0)
    return undefined;

  var value = serializedValues[inputName];
  if (typeof value !== 'undefined' && value !== null) return value; // value found, easy.

  // try to serialize and traverse
  var inputNameTree = hash_serializer({}, inputName, null);
  var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

  var next = inputNameTree[attrName];
  if (next == null) return undefined; // if it's already leaf, then no chance to be found.

  var nextAttrName = Object.keys(next)[0];
  var newInputName = inputName.replace(attrName, '');

  // remove bracket
  newInputName = newInputName.replace('[' + nextAttrName + ']', '');

  if (newInputName === '') {
    return serializedValues[attrName]
      ? serializedValues[attrName][nextAttrName]
      : undefined;
  }
  newInputName = nextAttrName + newInputName;

  var nestedValues = serializedValues[attrName];
  return inputValueLookup(nestedValues, newInputName);
};

export const formSerialize = (form, options) => {
  options = options || { hash: true };
  return serialize(form, options);
};
<commit_msg>use scoped package <commit_after>import assign from 'object.assign';
import serialize, { hash_serializer } from '@alvinsj/form-serialize';

export const inputPropsLookup = (inputProps, inputName) => {
  var props = inputProps[inputName];
  if (props) return assign({ label: inputName }, props); // props found, easy.

  var inputNameTree = hash_serializer({}, inputName, null);
  var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

  props = inputProps[attrName];

  if (!isNaN(parseInt(attrName, 10))) {
    // skip number
    props = inputProps;
  } else if (props && props.type === 'nested') {
    // continue with nested props
    props = props.fields;
  } else if (props) {
    return props;
  } else {
    return undefined;
  }

  var newInputName = inputName.replace(attrName, '');
  var nextAttrName = Object.keys(inputNameTree[attrName])[0];

  // remove bracket
  newInputName = newInputName.replace('[' + nextAttrName + ']', '');
  newInputName = nextAttrName + newInputName;

  return inputPropsLookup(props, newInputName);
};

export const inputValueLookup = (serializedValues, inputName) => {
  if (!serializedValues || Object.keys(serializedValues).length === 0)
    return undefined;

  var value = serializedValues[inputName];
  if (typeof value !== 'undefined' && value !== null) return value; // value found, easy.

  // try to serialize and traverse
  var inputNameTree = hash_serializer({}, inputName, null);
  var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

  var next = inputNameTree[attrName];
  if (next == null) return undefined; // if it's already leaf, then no chance to be found.

  var nextAttrName = Object.keys(next)[0];
  var newInputName = inputName.replace(attrName, '');

  // remove bracket
  newInputName = newInputName.replace('[' + nextAttrName + ']', '');

  if (newInputName === '') {
    return serializedValues[attrName]
      ? serializedValues[attrName][nextAttrName]
      : undefined;
  }
  newInputName = nextAttrName + newInputName;

  var nestedValues = serializedValues[attrName];
  return inputValueLookup(nestedValues, newInputName);
};

export const formSerialize = (form, options) => {
  options = options || { hash: true };
  return serialize(form, options);
};
<|endoftext|>


<commit_before>/**
 * Created by pavlheo on 5/30/2016.
 */
var express  = require('express');
var playService = require('./playService.js');
var bodyParser = require('body-parser');
var morgan      = require('morgan');
var mongoose    = require('mongoose');
var jwt = require('jsonwebtoken');
var socketioJwt = require('socketio-jwt');
var config = require('./config'); // get our config file
var User   = require('./user'); // get our mongoose model
var ChatMessage = require('./chatMessage');
var GameDots = require('./gameDots');
var http = require('http');
var app = express();                               // create our app w/ express
var server = http.createServer(app);
var io = require('socket.io').listen(server);

app.use('/bower_components',express.static('app/bower_components'));
app.use(express.static('app'));
app.use(bodyParser.json());
app.use(morgan('dev'));

mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret);

// API ROUTES -------------------

// get an instance of the router for api routes
var apiRoutes = express.Router();

apiRoutes.post('/users', function (req, res) {
    var user = new User(req.body);
    user.save(function (err) {
        if (err) throw err;

        console.log('User saved successfully');
        res.json({success: true});
    });
});

apiRoutes.post('/authenticate', function (req, res) {
    // find the user

    User.findOne({
        username: req.body.username
    }, function (err, user) {
        if (err) throw err;

        if (!user) {
            res.json({success: false, message: 'Authentication failed. User not found.'});
        } else if (user) {

            // check if password matches
            if (user.password != req.body.password) {
                res.json({success: false, message: 'Authentication failed. Wrong password.'});
            } else {

                // if user is found and password is right
                // create a token
                var token = jwt.sign(user, app.get('superSecret'), {
                    expiresIn: '24h' // expires in 24 hours
                });

                // return the information including token as JSON
                res.json({
                    success: true,
                    message: 'Enjoy your token!',
                    token: token
                });
            }
        }
    });
});

// route middleware to verify a token
apiRoutes.use(function(req, res, next) {
    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {

        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function (err, decoded) {
            if (err) {
                console.log('Invalid token');
                return res.json({success: false, message: 'Failed to authenticate token.'});
            } else {
                console.log('Auth OK');
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;
                next();
            }
        });

    } else {
        console.log('No token');
        // if there is no token
        // return an error
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
});

// route to show a random message (GET http://localhost:8080/api/)
apiRoutes.get('/', function(req, res) {
    res.json({message: 'Welcome to the coolest API on earth!'});
});

// route to return all users (GET http://localhost:8080/api/users)
apiRoutes.get('/users', function(req, res) {
    User.find({}, '_id firstName lastName username', function (err, users) {
        res.json(users);
    });
});

apiRoutes.get('/dots', function (req, res) {
    var player1Id = req.decoded._doc._id;
    GameDots
        .findOne({'state': 'accepted', $or: [{'player1': player1Id}, {'player2': player1Id}]})
        .sort({createdAt: -1})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            console.log(gameData);
            res.json(gameData);
        });
});

apiRoutes.post('/dots/invite', function(req, res) {  //POST (authorized via JWT)/dots/invite {userId: userId}
    var player1Id = req.decoded._doc._id;
    var player2Id = req.body.userId;
    var newGame = new GameDots({
        player1: player1Id,
        player2: player2Id,
        state: 'invited',
        playerInTurn: 1,
        gameData: playService.getGameData()
    });
    newGame.save(function (err) {
        if (err) {
            throw err;
        }
        GameDots
            .findById(newGame._id)
            .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
            .populate('player2', '_id firstName lastName username')
            .exec(function (err, gameData) {
                if (err) {
                    throw err;
                }
                console.log(gameData);
                io.to(player2Id).emit('dots.invited', gameData);
                res.json(gameData);
            });
    });
});

apiRoutes.post('/dots/accept', function(req, res) {  //POST (authorized via JWT)/dots/accept {gameId: gameId}
    var playerId = req.decoded._doc._id;
    var gameId = req.body.gameId;
    GameDots
        .findOne({'_id': gameId, 'state': 'invited', 'player2': playerId})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            if (gameData) {
                gameData.state = 'accepted';
                gameData.save(function (errSave) {
                    if (errSave) {
                        throw errSave;
                    }
                    io.to(gameData.player1._id).emit('dots.accepted', gameData);
                    res.json(gameData);
                });
            }
            else {
                res.json();
            }
        });
});

apiRoutes.post('/dots/decline', function(req, res) {  //POST (authorized via JWT)/dots/decline {gameId: gameId}
    var playerId = req.decoded._doc._id;
    var gameId = req.body.gameId;
    GameDots
        .findOne({'_id': gameId, 'state': 'invited', 'player2': playerId})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            if (gameData) {
                gameData.state = 'declined';
                gameData.save(function (errSave) {
                    if (errSave) {
                        throw errSave;
                    }
                    io.to(gameData.player1._id).emit('dots.declined', gameData);
                    res.json(gameData);
                });
            }
            else {
                res.json();
            }
        });
});

apiRoutes.post('/dots/play', function(req, res) {  //POST (authorized via JWT)/dots/play {gameId: gameId, indexX: indexX, indexY: indexY}
    var playerId = req.decoded._doc._id;
    GameDots
        .findOne({'_id': req.body.gameId, 'state': 'accepted'})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            if (gameData && playerId == gameData['player' + gameData.playerInTurn]._id) {//All is ok, right player makes turn
                if (playService.makeTurn(gameData.gameData, gameData.playerInTurn, req.body.indexX, req.body.indexY)) {
                    gameData.playerInTurn = 3 - gameData.playerInTurn;//Pass the move to other player
                    gameData.markModified('gameData');
                    if (gameData.gameData.remainingMoves == 0) {
                        gameData.state = 'finished';//No more moves allowed - does not make sense to continue
                    }
                    gameData.save(function (err) {
                        if (err) {
                            throw err;
                        }
                        io.to(gameData['player' + gameData.playerInTurn]._id).emit('dots.played', gameData);
                        res.json(gameData);
                    });
                }
            }
            else {
                res.json(gameData); // do nothing otherwise
            }
        });
});

apiRoutes.post('/dots/abandon', function(req, res) {  //POST (authorized via JWT)/dots/giveup {gameId: gameId}
    var playerId = req.decoded._doc._id;
    GameDots
        .findOne({'_id': req.body.gameId, 'state': 'accepted'})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (gameData && playerId == gameData['player' + gameData.playerInTurn]._id) {//All is ok, right player makes turn
                if (err) {
                    console.log('when finding: error '+err);
                    throw err;
                }
                if (gameData.gameData.scores[gameData.playerInTurn].score < gameData.gameData.scores[3 - gameData.playerInTurn].score) { //This is losing player
                    gameData.state = 'finished';
                    gameData.save(function (err) {
                        if (err) {
                            console.log('when saving: error '+err);
                            throw err;
                        }
                        io.to(gameData['player' + (3 - gameData.playerInTurn)]._id).emit('dots.abandoned', gameData);
                        res.json(gameData);
                    });
                }
            }
            else {
                res.json(gameData); // do nothing otherwise
            }
        });
});

apiRoutes.get('/chat', function (req, res){
    ChatMessage
        .find({})
        .sort({createdAt: 'desc'})
        .populate('user','username')
        .exec(function (err, chatMessages) {
            if (err) throw (err);
            res.json(chatMessages);
        });
});

apiRoutes.post('/chat', function (req, res) {
    var chatMessage = new ChatMessage();
    chatMessage.user = req.decoded._doc._id;
    chatMessage.message = req.body.message;
    chatMessage.save(function (err) {
        if (err) throw err;

        io.sockets.emit('chat.message', {
            payload: req.body.message,
            source: req.decoded._doc.username
        });

        console.log('ChatMessage saved successfully');
        res.json({success: true});
    });
});

// apply the routes to our application with the prefix /api
app.use('/api', apiRoutes);
app.listen(8080);
console.log("App listening on port 8080");

io
    .on('connection', socketioJwt.authorize({
        secret: app.get('superSecret'),
        timeout: 15000 // 15 seconds to send the authentication message
    }))
    .on('authenticated', function(socket) {
        console.log('connected & authenticated: ' + JSON.stringify(socket.decoded_token));
        socket
            .join(socket.decoded_token._doc._id)
            .on('disconnect', function () {
                console.log('user disconnected');
            });
    });

server.listen(8188, function() {
    console.log('listening on *:8188');
});<commit_msg>__dirName is used instead of app (hardcoded)<commit_after>/**
 * Created by pavlheo on 5/30/2016.
 */
var express  = require('express');
var playService = require('./playService.js');
var bodyParser = require('body-parser');
var morgan      = require('morgan');
var mongoose    = require('mongoose');
var jwt = require('jsonwebtoken');
var socketioJwt = require('socketio-jwt');
var config = require('./config'); // get our config file
var User   = require('./user'); // get our mongoose model
var ChatMessage = require('./chatMessage');
var GameDots = require('./gameDots');
var http = require('http');
var app = express();                               // create our app w/ express
var server = http.createServer(app);
var io = require('socket.io').listen(server);

app.use('/bower_components',express.static(__dirname+'/bower_components'));
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(morgan('dev'));

mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret);

// API ROUTES -------------------

// get an instance of the router for api routes
var apiRoutes = express.Router();

apiRoutes.post('/users', function (req, res) {
    var user = new User(req.body);
    user.save(function (err) {
        if (err) throw err;

        console.log('User saved successfully');
        res.json({success: true});
    });
});

apiRoutes.post('/authenticate', function (req, res) {
    // find the user

    User.findOne({
        username: req.body.username
    }, function (err, user) {
        if (err) throw err;

        if (!user) {
            res.json({success: false, message: 'Authentication failed. User not found.'});
        } else if (user) {

            // check if password matches
            if (user.password != req.body.password) {
                res.json({success: false, message: 'Authentication failed. Wrong password.'});
            } else {

                // if user is found and password is right
                // create a token
                var token = jwt.sign(user, app.get('superSecret'), {
                    expiresIn: '24h' // expires in 24 hours
                });

                // return the information including token as JSON
                res.json({
                    success: true,
                    message: 'Enjoy your token!',
                    token: token
                });
            }
        }
    });
});

// route middleware to verify a token
apiRoutes.use(function(req, res, next) {
    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {

        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function (err, decoded) {
            if (err) {
                console.log('Invalid token');
                return res.json({success: false, message: 'Failed to authenticate token.'});
            } else {
                console.log('Auth OK');
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;
                next();
            }
        });

    } else {
        console.log('No token');
        // if there is no token
        // return an error
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
});

// route to show a random message (GET http://localhost:8080/api/)
apiRoutes.get('/', function(req, res) {
    res.json({message: 'Welcome to the coolest API on earth!'});
});

// route to return all users (GET http://localhost:8080/api/users)
apiRoutes.get('/users', function(req, res) {
    User.find({}, '_id firstName lastName username', function (err, users) {
        res.json(users);
    });
});

apiRoutes.get('/dots', function (req, res) {
    var player1Id = req.decoded._doc._id;
    GameDots
        .findOne({'state': 'accepted', $or: [{'player1': player1Id}, {'player2': player1Id}]})
        .sort({createdAt: -1})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            console.log(gameData);
            res.json(gameData);
        });
});

apiRoutes.post('/dots/invite', function(req, res) {  //POST (authorized via JWT)/dots/invite {userId: userId}
    var player1Id = req.decoded._doc._id;
    var player2Id = req.body.userId;
    var newGame = new GameDots({
        player1: player1Id,
        player2: player2Id,
        state: 'invited',
        playerInTurn: 1,
        gameData: playService.getGameData()
    });
    newGame.save(function (err) {
        if (err) {
            throw err;
        }
        GameDots
            .findById(newGame._id)
            .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
            .populate('player2', '_id firstName lastName username')
            .exec(function (err, gameData) {
                if (err) {
                    throw err;
                }
                console.log(gameData);
                io.to(player2Id).emit('dots.invited', gameData);
                res.json(gameData);
            });
    });
});

apiRoutes.post('/dots/accept', function(req, res) {  //POST (authorized via JWT)/dots/accept {gameId: gameId}
    var playerId = req.decoded._doc._id;
    var gameId = req.body.gameId;
    GameDots
        .findOne({'_id': gameId, 'state': 'invited', 'player2': playerId})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            if (gameData) {
                gameData.state = 'accepted';
                gameData.save(function (errSave) {
                    if (errSave) {
                        throw errSave;
                    }
                    io.to(gameData.player1._id).emit('dots.accepted', gameData);
                    res.json(gameData);
                });
            }
            else {
                res.json();
            }
        });
});

apiRoutes.post('/dots/decline', function(req, res) {  //POST (authorized via JWT)/dots/decline {gameId: gameId}
    var playerId = req.decoded._doc._id;
    var gameId = req.body.gameId;
    GameDots
        .findOne({'_id': gameId, 'state': 'invited', 'player2': playerId})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            if (gameData) {
                gameData.state = 'declined';
                gameData.save(function (errSave) {
                    if (errSave) {
                        throw errSave;
                    }
                    io.to(gameData.player1._id).emit('dots.declined', gameData);
                    res.json(gameData);
                });
            }
            else {
                res.json();
            }
        });
});

apiRoutes.post('/dots/play', function(req, res) {  //POST (authorized via JWT)/dots/play {gameId: gameId, indexX: indexX, indexY: indexY}
    var playerId = req.decoded._doc._id;
    GameDots
        .findOne({'_id': req.body.gameId, 'state': 'accepted'})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (err) {
                throw err;
            }
            if (gameData && playerId == gameData['player' + gameData.playerInTurn]._id) {//All is ok, right player makes turn
                if (playService.makeTurn(gameData.gameData, gameData.playerInTurn, req.body.indexX, req.body.indexY)) {
                    gameData.playerInTurn = 3 - gameData.playerInTurn;//Pass the move to other player
                    gameData.markModified('gameData');
                    if (gameData.gameData.remainingMoves == 0) {
                        gameData.state = 'finished';//No more moves allowed - does not make sense to continue
                    }
                    gameData.save(function (err) {
                        if (err) {
                            throw err;
                        }
                        io.to(gameData['player' + gameData.playerInTurn]._id).emit('dots.played', gameData);
                        res.json(gameData);
                    });
                }
            }
            else {
                res.json(gameData); // do nothing otherwise
            }
        });
});

apiRoutes.post('/dots/abandon', function(req, res) {  //POST (authorized via JWT)/dots/giveup {gameId: gameId}
    var playerId = req.decoded._doc._id;
    GameDots
        .findOne({'_id': req.body.gameId, 'state': 'accepted'})
        .populate('player1', '_id firstName lastName username') // <-- only return the Persons name
        .populate('player2', '_id firstName lastName username')
        .exec(function (err, gameData) {
            if (gameData && playerId == gameData['player' + gameData.playerInTurn]._id) {//All is ok, right player makes turn
                if (err) {
                    console.log('when finding: error '+err);
                    throw err;
                }
                if (gameData.gameData.scores[gameData.playerInTurn].score < gameData.gameData.scores[3 - gameData.playerInTurn].score) { //This is losing player
                    gameData.state = 'finished';
                    gameData.save(function (err) {
                        if (err) {
                            console.log('when saving: error '+err);
                            throw err;
                        }
                        io.to(gameData['player' + (3 - gameData.playerInTurn)]._id).emit('dots.abandoned', gameData);
                        res.json(gameData);
                    });
                }
            }
            else {
                res.json(gameData); // do nothing otherwise
            }
        });
});

apiRoutes.get('/chat', function (req, res){
    ChatMessage
        .find({})
        .sort({createdAt: 'desc'})
        .populate('user','username')
        .exec(function (err, chatMessages) {
            if (err) throw (err);
            res.json(chatMessages);
        });
});

apiRoutes.post('/chat', function (req, res) {
    var chatMessage = new ChatMessage();
    chatMessage.user = req.decoded._doc._id;
    chatMessage.message = req.body.message;
    chatMessage.save(function (err) {
        if (err) throw err;

        io.sockets.emit('chat.message', {
            payload: req.body.message,
            source: req.decoded._doc.username
        });

        console.log('ChatMessage saved successfully');
        res.json({success: true});
    });
});

// apply the routes to our application with the prefix /api
app.use('/api', apiRoutes);
app.listen(8080);
console.log("App listening on port 8080");

io
    .on('connection', socketioJwt.authorize({
        secret: app.get('superSecret'),
        timeout: 15000 // 15 seconds to send the authentication message
    }))
    .on('authenticated', function(socket) {
        console.log('connected & authenticated: ' + JSON.stringify(socket.decoded_token));
        socket
            .join(socket.decoded_token._doc._id)
            .on('disconnect', function () {
                console.log('user disconnected');
            });
    });

server.listen(8188, function() {
    console.log('listening on *:8188');
});<|endoftext|>


<commit_before>/**
 * Contains the logic for the sidebar.
 * @param graph the graph that belongs to these controls
 * @returns {{}}
 */
webvowlApp.sidebar = function (graph) {

	var sidebar = {};

	/**
	 * Setup the menu bar.
	 */
	sidebar.setup = function () {
		setupCollapsing();
	};

	function setupCollapsing() {
		// adapted version of this example: http://www.normansblog.de/simple-jquery-accordion/
		function collapseContainers(containers) {
			containers.style("display", "none");
		}

		function expandContainers(containers) {
			containers.style("display", null);
		}

		var triggers = d3.selectAll(".accordion-trigger");

		// Collapse all inactive triggers on startup
		collapseContainers(d3.selectAll(".accordion-trigger:not(.accordion-trigger-active) + div"));

		triggers.on("click", function () {
			var selectedTrigger = d3.select(this),
				activeTriggers = d3.selectAll(".accordion-trigger-active");

			if (selectedTrigger.classed("accordion-trigger-active")) {
				// Collapse the active (which is also the selected) trigger
				collapseContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", false);
			} else {
				// Collapse the other trigger ...
				collapseContainers(d3.selectAll(".accordion-trigger-active + div"));
				activeTriggers.classed("accordion-trigger-active", false);
				// ... and expand the selected one
				expandContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", true);
			}
		});
	}

	/**
	 * Updates the information of the passed ontology.
	 * @param data the graph data
	 * @param statistics the statistics module
	 */
	sidebar.updateOntologyInformation = function (data, statistics) {
		displayGraphInformation(data);
		displayGraphStatistics(data.metrics, statistics);
		// Reset the sidebar selection
		sidebar.updateSelectionInformation(undefined);

		setLanguages(data.languages);
	};

	function setLanguages(languages) {
		languages = languages || [];

		var languageSelection = d3.select("#language")
			.on("change", function () {
				graph.setLanguage(d3.event.target.value);
			});

		var languageOptions = languageSelection.selectAll("option").data(languages);
		languageOptions.exit().remove();
		languageOptions.enter().append("option")
			.attr("value", function (d) {
				return d;
			})
			.text(function (d) {
				return d;
			});

		if (!trySelectDefaultLanguage(languageSelection, languages, "en")) {
			trySelectDefaultLanguage(languageSelection, languages, "default");
		}
	}

	function trySelectDefaultLanguage(selection, languages, language) {
		var langIndex = languages.indexOf(language);
		if (langIndex >= 0) {
			selection.property("selectedIndex", langIndex);
			graph.setLanguage(language);
			return true;
		}

		return false;
	}

	function displayGraphInformation(data) {
		var header = data.header;

		d3.select("#title").text(header.title);
		d3.select("#about").attr("href", header.uri).attr("target", "_blank").text(header.uri);
		d3.select("#version").text(header.version);
		d3.select("#authors").text(header.author);
		d3.select("#description").text(header.description || "No description available.");
	}

	function displayGraphStatistics(deliveredMetrics, statistics) {
		// Metrics are optional and may be undefined
		deliveredMetrics = deliveredMetrics || {};

		d3.select("#classCount")
			.text(deliveredMetrics.classCount || statistics.classCount());
		d3.select("#objectPropertyCount")
			.text(deliveredMetrics.objectPropertyCount || statistics.objectPropertyCount());
		d3.select("#datatypePropertyCount")
			.text(deliveredMetrics.datatypePropertyCount || statistics.datatypePropertyCount());
		d3.select("#nodeCount")
			.text(statistics.nodeCount());
		d3.select("#edgeCount")
			.text(statistics.edgeCount());
	}

	/**
	 * Update the information of the selected node.
	 * @param selectedElement the selection or null if nothing is selected
	 */
	sidebar.updateSelectionInformation = function (selectedElement) {
		// Click event was prevented when dragging
		if (d3.event && d3.event.defaultPrevented) {
			return;
		}

		var isTriggerActive = d3.select("#selection-details-trigger").classed("accordion-trigger-active");
		if (selectedElement && !isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
		} else if (!selectedElement && isTriggerActive) {
			showSelectionAdvice();
			return;
		}

		if (selectedElement instanceof webvowl.labels.BaseLabel) {
			displayLabelInformation(selectedElement);
		} else if (selectedElement instanceof webvowl.nodes.BaseNode) {
			displayNodeInformation(selectedElement);
		}
	};

	function showSelectionAdvice() {
		setSelectionInformationVisibility(false, false, true);
	}

	function setSelectionInformationVisibility(showClasses, showProperties, showAdvice) {
		d3.select("#classSelectionInformation").classed("hidden", !showClasses);
		d3.select("#propertySelectionInformation").classed("hidden", !showProperties);
		d3.select("#noSelectionInformation").classed("hidden", !showAdvice);
	}

	function displayLabelInformation(property) {
		showPropertyInformations();

		setUriLabel(d3.select("#propname"), property.labelForCurrentLanguage(), property.uri());
		d3.select("#typeProp").text(property.type());

		if (property.inverse() !== undefined) {
			d3.select("#inverse").style("display", "block");
			setUriLabel(d3.select("#inverse span"), property.inverse().labelForCurrentLanguage(), property.inverse().uri());
		} else {
			d3.select("#inverse").style("display", "none");
		}

		var equivalentUriSpan = d3.select("#propEquivUri");
		listNodeArray(property.equivalents(), equivalentUriSpan);

		listNodeArray(property.subproperties(), d3.select("#subproperties"));
		listNodeArray(property.superproperties(), d3.select("#superproperties"));

		if (property.minCardinality() !== undefined) {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "block");
			d3.select("#minCardinality span").text(property.minCardinality());
			d3.select("#maxCardinality").style("display", "block");

			if (property.maxCardinality() !== undefined) {
				d3.select("#maxCardinality span").text(property.maxCardinality());
			} else {
				d3.select("#maxCardinality span").text("*");
			}

		} else if (property.cardinality() !== undefined) {
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
			d3.select("#infoCardinality").style("display", "block");
			d3.select("#infoCardinality span").text(property.cardinality());
		} else {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
		}

		setUriLabel(d3.select("#domain"), property.domain().labelForCurrentLanguage(), property.domain().uri());
		setUriLabel(d3.select("#range"), property.range().labelForCurrentLanguage(), property.range().uri());

		displayAttributes(property.attributes(), d3.select("#propAttributes"));
	}

	function showPropertyInformations() {
		setSelectionInformationVisibility(false, true, false);
	}

	function setUriLabel(element, name, uri) {
		element.selectAll("*").remove();
		appendUriLabel(element, name, uri);
	}

	function appendUriLabel(element, name, uri) {
		var tag;

		if (uri) {
			tag = element.append("a").attr("href", uri).attr("target", "_blank");
		} else {
			tag = element.append("span");
		}
		tag.text(name);
	}

	function displayAttributes(attributes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (attributes && attributes.length > 0) {
			// Remove redundant redundant attributes for sidebar
			removeElementFromArray("object", attributes);
			removeElementFromArray("datatype", attributes);
			removeElementFromArray("rdf", attributes);
		}

		if (attributes && attributes.length > 0) {
			textSpan.text(attributes.join(", "));

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	function removeElementFromArray(element, array) {
		var index = array.indexOf(element);
		if (index > -1) {
			array.splice(index, 1);
		}
	}

	function displayNodeInformation(node) {
		showClassInformations();

		setUriLabel(d3.select("#name"), node.labelForCurrentLanguage(), node.uri());

		/* Equivalent stuff. */
		var equivalentUriSpan = d3.select("#classEquivUri");
		listNodeArray(node.equivalents(), equivalentUriSpan);

		d3.select("#typeNode").text(node.type());
		d3.select("#instances").text(node.instances());

		/* Disjoint stuff. */
		var disjointNodes = d3.select("#disjointNodes");
		var disjointNodesParent = d3.select(disjointNodes.node().parentNode);

		if (node.disjointWith() !== undefined) {
			disjointNodes.selectAll("*").remove();

			node.disjointWith().forEach(function (element, index) {
				if (index > 0) {
					disjointNodes.append("span").text(", ");
				}
				appendUriLabel(disjointNodes, element.labelForCurrentLanguage(), element.uri());
			});

			disjointNodesParent.classed("hidden", false);
		} else {
			disjointNodesParent.classed("hidden", true);
		}

		displayAttributes(node.attributes(), d3.select("#classAttributes"));
	}

	function showClassInformations() {
		setSelectionInformationVisibility(true, false, false);
	}

	function listNodeArray(nodes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (nodes && nodes.length) {
			textSpan.selectAll("*").remove();
			nodes.forEach(function (element, index) {
				if (index > 0) {
					textSpan.append("span").text(", ");
				}
				appendUriLabel(textSpan, element.labelForCurrentLanguage(), element.uri());
			});

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	return sidebar;
};
<commit_msg>Place default option on top of the languages<commit_after>/**
 * Contains the logic for the sidebar.
 * @param graph the graph that belongs to these controls
 * @returns {{}}
 */
webvowlApp.sidebar = function (graph) {

	var sidebar = {};

	/**
	 * Setup the menu bar.
	 */
	sidebar.setup = function () {
		setupCollapsing();
	};

	function setupCollapsing() {
		// adapted version of this example: http://www.normansblog.de/simple-jquery-accordion/
		function collapseContainers(containers) {
			containers.style("display", "none");
		}

		function expandContainers(containers) {
			containers.style("display", null);
		}

		var triggers = d3.selectAll(".accordion-trigger");

		// Collapse all inactive triggers on startup
		collapseContainers(d3.selectAll(".accordion-trigger:not(.accordion-trigger-active) + div"));

		triggers.on("click", function () {
			var selectedTrigger = d3.select(this),
				activeTriggers = d3.selectAll(".accordion-trigger-active");

			if (selectedTrigger.classed("accordion-trigger-active")) {
				// Collapse the active (which is also the selected) trigger
				collapseContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", false);
			} else {
				// Collapse the other trigger ...
				collapseContainers(d3.selectAll(".accordion-trigger-active + div"));
				activeTriggers.classed("accordion-trigger-active", false);
				// ... and expand the selected one
				expandContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", true);
			}
		});
	}

	/**
	 * Updates the information of the passed ontology.
	 * @param data the graph data
	 * @param statistics the statistics module
	 */
	sidebar.updateOntologyInformation = function (data, statistics) {
		displayGraphInformation(data);
		displayGraphStatistics(data.metrics, statistics);
		// Reset the sidebar selection
		sidebar.updateSelectionInformation(undefined);

		setLanguages(data.languages);
	};

	function setLanguages(languages) {
		languages = languages || [];

		// Put the default label on top of the selection label
		languages.sort(function (a, b) {
			if (a === "default") {
				return -1;
			} else if (b === "default") {
				return 1;
			}
			return a.localeCompare(b);
		});

		var languageSelection = d3.select("#language")
			.on("change", function () {
				graph.setLanguage(d3.event.target.value);
			});

		var languageOptions = languageSelection.selectAll("option").data(languages);
		languageOptions.exit().remove();
		languageOptions.enter().append("option")
			.attr("value", function (d) {
				return d;
			})
			.text(function (d) {
				return d;
			});

		if (!trySelectDefaultLanguage(languageSelection, languages, "en")) {
			trySelectDefaultLanguage(languageSelection, languages, "default");
		}
	}

	function trySelectDefaultLanguage(selection, languages, language) {
		var langIndex = languages.indexOf(language);
		if (langIndex >= 0) {
			selection.property("selectedIndex", langIndex);
			graph.setLanguage(language);
			return true;
		}

		return false;
	}

	function displayGraphInformation(data) {
		var header = data.header;

		d3.select("#title").text(header.title);
		d3.select("#about").attr("href", header.uri).attr("target", "_blank").text(header.uri);
		d3.select("#version").text(header.version);
		d3.select("#authors").text(header.author);
		d3.select("#description").text(header.description || "No description available.");
	}

	function displayGraphStatistics(deliveredMetrics, statistics) {
		// Metrics are optional and may be undefined
		deliveredMetrics = deliveredMetrics || {};

		d3.select("#classCount")
			.text(deliveredMetrics.classCount || statistics.classCount());
		d3.select("#objectPropertyCount")
			.text(deliveredMetrics.objectPropertyCount || statistics.objectPropertyCount());
		d3.select("#datatypePropertyCount")
			.text(deliveredMetrics.datatypePropertyCount || statistics.datatypePropertyCount());
		d3.select("#nodeCount")
			.text(statistics.nodeCount());
		d3.select("#edgeCount")
			.text(statistics.edgeCount());
	}

	/**
	 * Update the information of the selected node.
	 * @param selectedElement the selection or null if nothing is selected
	 */
	sidebar.updateSelectionInformation = function (selectedElement) {
		// Click event was prevented when dragging
		if (d3.event && d3.event.defaultPrevented) {
			return;
		}

		var isTriggerActive = d3.select("#selection-details-trigger").classed("accordion-trigger-active");
		if (selectedElement && !isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
		} else if (!selectedElement && isTriggerActive) {
			showSelectionAdvice();
			return;
		}

		if (selectedElement instanceof webvowl.labels.BaseLabel) {
			displayLabelInformation(selectedElement);
		} else if (selectedElement instanceof webvowl.nodes.BaseNode) {
			displayNodeInformation(selectedElement);
		}
	};

	function showSelectionAdvice() {
		setSelectionInformationVisibility(false, false, true);
	}

	function setSelectionInformationVisibility(showClasses, showProperties, showAdvice) {
		d3.select("#classSelectionInformation").classed("hidden", !showClasses);
		d3.select("#propertySelectionInformation").classed("hidden", !showProperties);
		d3.select("#noSelectionInformation").classed("hidden", !showAdvice);
	}

	function displayLabelInformation(property) {
		showPropertyInformations();

		setUriLabel(d3.select("#propname"), property.labelForCurrentLanguage(), property.uri());
		d3.select("#typeProp").text(property.type());

		if (property.inverse() !== undefined) {
			d3.select("#inverse").style("display", "block");
			setUriLabel(d3.select("#inverse span"), property.inverse().labelForCurrentLanguage(), property.inverse().uri());
		} else {
			d3.select("#inverse").style("display", "none");
		}

		var equivalentUriSpan = d3.select("#propEquivUri");
		listNodeArray(property.equivalents(), equivalentUriSpan);

		listNodeArray(property.subproperties(), d3.select("#subproperties"));
		listNodeArray(property.superproperties(), d3.select("#superproperties"));

		if (property.minCardinality() !== undefined) {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "block");
			d3.select("#minCardinality span").text(property.minCardinality());
			d3.select("#maxCardinality").style("display", "block");

			if (property.maxCardinality() !== undefined) {
				d3.select("#maxCardinality span").text(property.maxCardinality());
			} else {
				d3.select("#maxCardinality span").text("*");
			}

		} else if (property.cardinality() !== undefined) {
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
			d3.select("#infoCardinality").style("display", "block");
			d3.select("#infoCardinality span").text(property.cardinality());
		} else {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
		}

		setUriLabel(d3.select("#domain"), property.domain().labelForCurrentLanguage(), property.domain().uri());
		setUriLabel(d3.select("#range"), property.range().labelForCurrentLanguage(), property.range().uri());

		displayAttributes(property.attributes(), d3.select("#propAttributes"));
	}

	function showPropertyInformations() {
		setSelectionInformationVisibility(false, true, false);
	}

	function setUriLabel(element, name, uri) {
		element.selectAll("*").remove();
		appendUriLabel(element, name, uri);
	}

	function appendUriLabel(element, name, uri) {
		var tag;

		if (uri) {
			tag = element.append("a").attr("href", uri).attr("target", "_blank");
		} else {
			tag = element.append("span");
		}
		tag.text(name);
	}

	function displayAttributes(attributes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (attributes && attributes.length > 0) {
			// Remove redundant redundant attributes for sidebar
			removeElementFromArray("object", attributes);
			removeElementFromArray("datatype", attributes);
			removeElementFromArray("rdf", attributes);
		}

		if (attributes && attributes.length > 0) {
			textSpan.text(attributes.join(", "));

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	function removeElementFromArray(element, array) {
		var index = array.indexOf(element);
		if (index > -1) {
			array.splice(index, 1);
		}
	}

	function displayNodeInformation(node) {
		showClassInformations();

		setUriLabel(d3.select("#name"), node.labelForCurrentLanguage(), node.uri());

		/* Equivalent stuff. */
		var equivalentUriSpan = d3.select("#classEquivUri");
		listNodeArray(node.equivalents(), equivalentUriSpan);

		d3.select("#typeNode").text(node.type());
		d3.select("#instances").text(node.instances());

		/* Disjoint stuff. */
		var disjointNodes = d3.select("#disjointNodes");
		var disjointNodesParent = d3.select(disjointNodes.node().parentNode);

		if (node.disjointWith() !== undefined) {
			disjointNodes.selectAll("*").remove();

			node.disjointWith().forEach(function (element, index) {
				if (index > 0) {
					disjointNodes.append("span").text(", ");
				}
				appendUriLabel(disjointNodes, element.labelForCurrentLanguage(), element.uri());
			});

			disjointNodesParent.classed("hidden", false);
		} else {
			disjointNodesParent.classed("hidden", true);
		}

		displayAttributes(node.attributes(), d3.select("#classAttributes"));
	}

	function showClassInformations() {
		setSelectionInformationVisibility(true, false, false);
	}

	function listNodeArray(nodes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (nodes && nodes.length) {
			textSpan.selectAll("*").remove();
			nodes.forEach(function (element, index) {
				if (index > 0) {
					textSpan.append("span").text(", ");
				}
				appendUriLabel(textSpan, element.labelForCurrentLanguage(), element.uri());
			});

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	return sidebar;
};
<|endoftext|>


<commit_before>/*
 by "The One" @ http://whatisextjs.com/extjs/extjs-4-2-plugin-example
 usage: `plugins: ['ux.fadeinplugin']`
 */
Ext.define('Ext.uxo.component.FadeInPlugin', {
    extend: 'Ext.AbstractPlugin',
    alias: 'plugin.ux.fadeinplugin',
    requires: ['Ext.fx.Anim'],

    init: function (component) {
    //component.show()
        Ext.apply(component, {
            style: {
                //opacity: 0
            }
        });
        component.fadeIn = this.fadeIn.bind(component);

    },

    fadeIn: function () {
        var me = this;
        Ext.create('Ext.fx.Anim', {
            target: me,
            duration: 400,
            from: {
                opacity: 0
            },
            to: {
                opacity: 1
            }
        });
    } // eo fadeIn()
});
<commit_msg>FadeInPlugin fix: whitespace<commit_after>/*
 by "The One" @ http://whatisextjs.com/extjs/extjs-4-2-plugin-example
 usage: `plugins: ['ux.fadeinplugin']`
 */
Ext.define('Ext.uxo.component.FadeInPlugin', {
    extend: 'Ext.AbstractPlugin',
    alias: 'plugin.ux.fadeinplugin',
    requires: ['Ext.fx.Anim'],

    init: function (component) {
    //component.show()
        Ext.apply(component, {
            style: {
                //opacity: 0
            }
        });
        component.fadeIn = this.fadeIn.bind(component);
    },

    fadeIn: function () {
        var me = this;
        Ext.create('Ext.fx.Anim', {
            target: me,
            duration: 400,
            from: {
                opacity: 0
            },
            to: {
                opacity: 1
            }
        });
    } // eo fadeIn()
});
<|endoftext|>


<commit_before>var os = require('os'),
    path = require('path'),
    fs = require('fs');

var _ = require('underscore');

var defaults = require('./defaults'),
    signals = require('./signals'),
    util = require('./util');

const ENV = 'CAPTAINJS_SETTINGS';
const FILE = 'settings.js';
const TMPL = _.template('exports.<%= key %> = <%= value %>;');

try {
  var lookup = process.env[ENV] || path.join(process.cwd(), FILE);
  var settings = require(lookup);
  var keys = Object.keys(settings);
} catch(e) {
  if(e.code === 'MODULE_NOT_FOUND') {
    settings = {};
  } else {
    throw e;
  }
}

exports.get = function get(key, other) {
  return settings[key] || other || defaults[key];
};

exports.set = function set(key, value) {
  if(_.isObject(key)) {
    _.each(key, function(value, key) {
      exports.set(key, value);
    });
  } else {
    settings[key] = value;
  }
  signals.emit('settings:change');
};

exports.toJSON = function toJSON() {
  var obj = {};
  _.each(defaults, function(value, key) {
    obj[key] = exports.get(key);
  });
  return obj;
};

exports.save = function save(fn) {
  var output = [],
      toJSON = exports.toJSON();
  _.each(toJSON, function(value, key) {
    if(~keys.indexOf(key) || settings[key] !== defaults[key]){
      value = typeof value === 'string' ? "'" + value + "'" : value;
      output.push(TMPL({value: value, key: key}));
    }
  });
  fs.writeFile(lookup, output.join(os.EOL), fn);
};

exports.length = function length() {
  return _.size(settings);
};<commit_msg>Added a function to get the default settings file<commit_after>var os = require('os'),
    path = require('path'),
    fs = require('fs');

var _ = require('underscore');

var defaults = require('./defaults'),
    signals = require('./signals'),
    util = require('./util');

const ENV = 'CAPTAINJS_SETTINGS';
const FILE = exports.FILE = 'settings.js';
const TMPL = _.template('exports.<%= key %> = <%= value %>;');

try {
  var lookup = process.env[ENV] || path.join(process.cwd(), FILE);
  var settings = require(lookup);
  var keys = Object.keys(settings);
} catch(e) {
  if(e.code === 'MODULE_NOT_FOUND') {
    settings = {};
  } else {
    throw e;
  }
}

exports.get = function get(key, other) {
  return settings[key] || other || defaults[key];
};

exports.set = function set(key, value) {
  if(_.isObject(key)) {
    _.each(key, function(value, key) {
      exports.set(key, value);
    });
  } else {
    settings[key] = value;
  }
  signals.emit('settings:change');
};

exports.toJSON = function toJSON() {
  var obj = {};
  _.each(defaults, function(value, key) {
    obj[key] = exports.get(key);
  });
  return obj;
};

exports.save = function save(fn) {
  var output = [],
      toJSON = exports.toJSON();
  _.each(toJSON, function(value, key) {
    if(~keys.indexOf(key) || settings[key] !== defaults[key]){
      value = typeof value === 'string' ? "'" + value + "'" : value;
      output.push(TMPL({value: value, key: key}));
    }
  });
  fs.writeFile(lookup, output.join(os.EOL), fn);
};

exports.length = function length() {
  return _.size(settings);
};

exports.getFile = function getFile() {
  return path.join(util.APP_ROOT, FILE);
};<|endoftext|>


<commit_before>
var Promise = require('any-promise')
var fs
try {
  fs = require('graceful-fs')
} catch(err) {
  fs = require('fs')
}

var api = [
  'appendFile',
  'chmod',
  'chown',
  'close',
  'fchmod',
  'fchown',
  'fdatasync',
  'fstat',
  'fsync',
  'ftruncate',
  'futimes',
  'lchown',
  'link',
  'lstat',
  'mkdir',
  'open',
  'read',
  'readFile',
  'readdir',
  'readlink',
  'realpath',
  'rename',
  'rmdir',
  'stat',
  'symlink',
  'truncate',
  'unlink',
  'utimes',
  'write',
  'writeFile'
]

typeof fs.access === 'function' && api.push('access')
typeof fs.mkdtemp === 'function' && api.push('mkdtemp')

require('thenify-all').withCallback(fs, exports, api)

exports.exists = function (filename, callback) {
  // callback
  if (typeof callback === 'function') {
    return fs.stat(filename, function (err) {
      callback(null, !err);
    })
  }
  // or promise
  return new Promise(function (resolve) {
    fs.stat(filename, function (err) {
      resolve(!err)
    })
  })
}
<commit_msg>Modernize copyFile in enviroments that support it<commit_after>
var Promise = require('any-promise')
var fs
try {
  fs = require('graceful-fs')
} catch(err) {
  fs = require('fs')
}

var api = [
  'appendFile',
  'chmod',
  'chown',
  'close',
  'fchmod',
  'fchown',
  'fdatasync',
  'fstat',
  'fsync',
  'ftruncate',
  'futimes',
  'lchown',
  'link',
  'lstat',
  'mkdir',
  'open',
  'read',
  'readFile',
  'readdir',
  'readlink',
  'realpath',
  'rename',
  'rmdir',
  'stat',
  'symlink',
  'truncate',
  'unlink',
  'utimes',
  'write',
  'writeFile'
]

typeof fs.access === 'function' && api.push('access')
typeof fs.copyFile === 'function' && api.push('copyFile')
typeof fs.mkdtemp === 'function' && api.push('mkdtemp')

require('thenify-all').withCallback(fs, exports, api)

exports.exists = function (filename, callback) {
  // callback
  if (typeof callback === 'function') {
    return fs.stat(filename, function (err) {
      callback(null, !err);
    })
  }
  // or promise
  return new Promise(function (resolve) {
    fs.stat(filename, function (err) {
      resolve(!err)
    })
  })
}
<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    fadecandyClient = require('nd-fadecandy-client')
;

// sendFile options
var options = {
  root: __dirname + '/public/',
  dotfiles: 'deny',
  headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
  }
};

// Enable static files
app.use(express.static('public/asset'));

// Send the index.html to new clients
app.get('/', function(req, res){
  res.sendFile('index.html', options);
});

http.listen(1337, function(){
  console.log('listening on *:1337');
});

var pixels = null;
var color = { red : 0, green : 0, blue : 0 };

// Connect to the Fadecandy Server
var client = new fadecandyClient({
  host: 'localhost',
  port: 7890,
  debug : false
});

/**
 * Connections from the browser (NERDDISCO Studio)
 */
// Create custom namespace
var socket_studio = io.of('/NERDDISCO-Studio');

// Listen to connections on this custom namespace
socket_studio.on('connection', function(socket) {
  console.log('NERD DISCO - Studio connected');

  // Received and LED array from the client
  socket.on('NERDDISCO.input', function(data) {
    pixels = data;
    draw();
  });

});

/**
 * Extract the pixel data from the given position
 *
 * @param  Interger position
 *
 * @return Object pixel
 */
function getPixel(position) {
  var pixel = {};

  var _position = position * 3;

  // Pixel exists
  if (pixels !== null && pixels[_position - 1] !== undefined) {
    // Blue
    pixel.b = pixels[_position - 1];

    // Green
    pixel.g = pixels[_position - 2];

    // Red
    pixel.r = pixels[_position - 3];
  } else {
    // Black
    pixel.a = pixel.r = pixel.g = pixel.b = 0;

  }

  return pixel;
}

function draw() {

    var amount = 64 * 5;

    for (var pixel = 0; pixel < amount; pixel++) {
      color = getPixel(pixel + 1);
      client.setPixel(pixel, color.r, color.g, color.b);
    }

    client.writePixels();
}
<commit_msg>Added "dotenv" to load env variables.<commit_after>var express = require('express'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    fadecandyClient = require('nd-fadecandy-client')
;
require('dotenv').load();

// sendFile options
var options = {
  root: __dirname + '/public/',
  dotfiles: 'deny',
  headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
  }
};

// Enable static files
app.use(express.static('public/asset'));

// Send the index.html to new clients
app.get('/', function(req, res){
  res.sendFile('index.html', options);
});

http.listen(1337, function(){
  console.log('listening on *:1337');
});

var pixels = null;
var color = { red : 0, green : 0, blue : 0 };

// Connect to the Fadecandy Server
var client = new fadecandyClient({
  host: 'localhost',
  port: 7890,
  debug : false
});

/**
 * Connections from the browser (NERDDISCO Studio)
 */
// Create custom namespace
var socket_studio = io.of('/NERDDISCO-Studio');

// Listen to connections on this custom namespace
socket_studio.on('connection', function(socket) {
  console.log('NERD DISCO - Studio connected');

  // Received and LED array from the client
  socket.on('NERDDISCO.input', function(data) {
    pixels = data;
    draw();
  });

});

/**
 * Extract the pixel data from the given position
 *
 * @param  Interger position
 *
 * @return Object pixel
 */
function getPixel(position) {
  var pixel = {};

  var _position = position * 3;

  // Pixel exists
  if (pixels !== null && pixels[_position - 1] !== undefined) {
    // Blue
    pixel.b = pixels[_position - 1];

    // Green
    pixel.g = pixels[_position - 2];

    // Red
    pixel.r = pixels[_position - 3];
  } else {
    // Black
    pixel.a = pixel.r = pixel.g = pixel.b = 0;

  }

  return pixel;
}

function draw() {

    var amount = 64 * 5;

    for (var pixel = 0; pixel < amount; pixel++) {
      color = getPixel(pixel + 1);
      client.setPixel(pixel, color.r, color.g, color.b);
    }

    client.writePixels();
}
<|endoftext|>