<commit_before>import { scheduleOnce } from '@ember/runloop';
import { isEmpty } from '@ember/utils';
import Controller from '@ember/controller';
import Ember from 'ember';
import eventually from 'travis/utils/eventually';
import Visibility from 'npm:visibilityjs';
import { service } from 'ember-decorators/service';
import { controller } from 'ember-decorators/controller';
import { computed } from 'ember-decorators/object';
import { alias } from 'ember-decorators/object/computed';

export default Controller.extend({
  @service repositories: null,
  @service tabStates: null,
  @service('updateTimes') updateTimesService: null,

  @controller('job') jobController: null,
  @controller('build') buildController: null,
  @controller('builds') buildsController: null,

  @alias('repositories.accessible') repos: null,
  @alias('auth.currentUser') currentUser: null,
  @alias('buildController.build') build: null,
  @alias('buildsController.content') builds: null,
  @alias('jobController.job') job: null,

  classNames: ['repo'],

  reset() {
    this.set('repo', null);
  },

  @computed('repos.isLoaded', 'repos.[]')
  isEmpty(loaded, repos) {
    return loaded && isEmpty(repos);
  },

  init() {
    this._super(...arguments);
    if (!Ember.testing) {
      Visibility.every(this.config.intervals.updateTimes, this.updateTimes.bind(this));
    }
  },

  updateTimes() {
    let updateTimesService = this.get('updateTimesService');

    updateTimesService.push(this.get('build'));
    updateTimesService.push(this.get('builds'));
    updateTimesService.push(this.get('build.jobs'));
  },

  deactivate() {
    return this.stopObservingLastBuild();
  },

  activate(action) {
    this.stopObservingLastBuild();

    const observesLastBuild = ['index', 'current'];

    if (observesLastBuild.includes(action)) {
      this.observeLastBuild();
      this.set('tabStates.mainTab', 'current');
    } else {
      this.set('tabStates.mainTab', action);
    }
  },

  currentBuildDidChange() {
    return scheduleOnce('actions', this, this._currentBuildDidChange);
  },

  _currentBuildDidChange() {
    let currentBuild = this.get('repo.currentBuild');
    if (currentBuild && currentBuild.get('id')) {
      eventually(currentBuild, (build) => {
        this.set('build', build);

        if (build.get('jobs.length') === 1) {
          this.set('job', build.get('jobs.firstObject'));
        }
      });
    }
  },

  stopObservingLastBuild() {
    return this.removeObserver('repo.currentBuild', this, 'currentBuildDidChange');
  },

  observeLastBuild() {
    this.currentBuildDidChange();
    return this.addObserver('repo.currentBuild', this, 'currentBuildDidChange');
  }
});
<commit_msg>Remove deprecated alias (#1370)<commit_after>import { scheduleOnce } from '@ember/runloop';
import { isEmpty } from '@ember/utils';
import Controller from '@ember/controller';
import Ember from 'ember';
import eventually from 'travis/utils/eventually';
import Visibility from 'npm:visibilityjs';
import { service } from 'ember-decorators/service';
import { controller } from 'ember-decorators/controller';
import { computed } from 'ember-decorators/object';
import { alias } from 'ember-decorators/object/computed';

export default Controller.extend({
  @service repositories: null,
  @service tabStates: null,
  @service('updateTimes') updateTimesService: null,

  @controller('job') jobController: null,
  @controller('build') buildController: null,
  @controller('builds') buildsController: null,

  @alias('repositories.accessible') repos: null,
  @alias('auth.currentUser') currentUser: null,
  @alias('buildController.build') build: null,
  @alias('buildsController.model') builds: null,
  @alias('jobController.job') job: null,

  classNames: ['repo'],

  reset() {
    this.set('repo', null);
  },

  @computed('repos.isLoaded', 'repos.[]')
  isEmpty(loaded, repos) {
    return loaded && isEmpty(repos);
  },

  init() {
    this._super(...arguments);
    if (!Ember.testing) {
      Visibility.every(this.config.intervals.updateTimes, this.updateTimes.bind(this));
    }
  },

  updateTimes() {
    let updateTimesService = this.get('updateTimesService');

    updateTimesService.push(this.get('build'));
    updateTimesService.push(this.get('builds'));
    updateTimesService.push(this.get('build.jobs'));
  },

  deactivate() {
    return this.stopObservingLastBuild();
  },

  activate(action) {
    this.stopObservingLastBuild();

    const observesLastBuild = ['index', 'current'];

    if (observesLastBuild.includes(action)) {
      this.observeLastBuild();
      this.set('tabStates.mainTab', 'current');
    } else {
      this.set('tabStates.mainTab', action);
    }
  },

  currentBuildDidChange() {
    return scheduleOnce('actions', this, this._currentBuildDidChange);
  },

  _currentBuildDidChange() {
    let currentBuild = this.get('repo.currentBuild');
    if (currentBuild && currentBuild.get('id')) {
      eventually(currentBuild, (build) => {
        this.set('build', build);

        if (build.get('jobs.length') === 1) {
          this.set('job', build.get('jobs.firstObject'));
        }
      });
    }
  },

  stopObservingLastBuild() {
    return this.removeObserver('repo.currentBuild', this, 'currentBuildDidChange');
  },

  observeLastBuild() {
    this.currentBuildDidChange();
    return this.addObserver('repo.currentBuild', this, 'currentBuildDidChange');
  }
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var http = require('http');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');

var LocalStrategy = require('passport-local').Strategy;

require('./model/events/schemas/event.schema');
require('./model/mongo_connection');
require('./model/account/schemas/user');
require('./model/instances/schemas/workshop-instance.schema');
require('./model/catalogue/schemas/workshop');
var pass = require('./configurations/pass');
var auth = require('./routes/auth');
var users = require('./routes/users');
var catalogue = require('./routes/catalogue');
var feedback = require('./routes/feedback');
var cloudinaryUploader = require('./routes/cloudinaryUploader');
var dbCleaner = require('./routes/db.dev');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public/')));

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:8100");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods","PUT, GET, POST, DELETE, OPTIONS");
    next();
});
// required for passport
app.use(require('express-session')({
    secret: 'MEAN',
    resave: false,
    saveUninitialized: false
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

app.use('/auth', auth);
app.use('/users', users);
app.use('/api/v1/catalogue', catalogue);
app.use('/api/v1/feedback', feedback);
app.use('/api/v1/photos-uploader', cloudinaryUploader);
app.use('/api/v1/db-cleaner', dbCleaner);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function(err, req, res) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;<commit_msg>Ajout de mon adresse ip pour lancer l'application tablette depuis un autre ordinateur afin de record la vidéo<commit_after>var express = require('express');
var path = require('path');
var http = require('http');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');

var LocalStrategy = require('passport-local').Strategy;

require('./model/events/schemas/event.schema');
require('./model/mongo_connection');
require('./model/account/schemas/user');
require('./model/instances/schemas/workshop-instance.schema');
require('./model/catalogue/schemas/workshop');
var pass = require('./configurations/pass');
var auth = require('./routes/auth');
var users = require('./routes/users');
var catalogue = require('./routes/catalogue');
var feedback = require('./routes/feedback');
var cloudinaryUploader = require('./routes/cloudinaryUploader');
var dbCleaner = require('./routes/db.dev');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public/')));

app.use(function(req, res, next) {
    // TODO : I suggest to change "localhost:8100" to a real domain set with a proxy in the ionic app
    var allowedOrigins = ["http://localhost:8100", "http://10.212.100.185:8100"];
    var origin = req.headers.origin;
    if(allowedOrigins.indexOf(origin) > -1){
        res.setHeader('Access-Control-Allow-Origin', origin);
    }
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods","PUT, GET, POST, DELETE, OPTIONS");
    next();
});
// required for passport
app.use(require('express-session')({
    secret: 'MEAN',
    resave: false,
    saveUninitialized: false
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

app.use('/auth', auth);
app.use('/users', users);
app.use('/api/v1/catalogue', catalogue);
app.use('/api/v1/feedback', feedback);
app.use('/api/v1/photos-uploader', cloudinaryUploader);
app.use('/api/v1/db-cleaner', dbCleaner);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function(err, req, res) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var mongoose = require('mongoose')
  , Article = mongoose.model('Article')

/**
 * List items tagged with a tag
 */

exports.index = function (req, res) {
  var criteria = { tags: req.param('tag') }
  var perPage = 5
  var page = req.param('page') > 0 ? req.param('page') : 0
  var options = {
    perPage: perPage,
    page: page,
    criteria: criteria
  }

  Article.list(options, function(err, articles) {
    if (err) return res.render('500')
    Article.count(criteria).exec(function (err, count) {
      res.render('articles/index', {
        title: 'Articles tagged ' + req.param('tag'),
        articles: articles,
        page: page,
        pages: Math.ceil(count / perPage)
      })
    })
  })
}
<commit_msg>Fix paging<commit_after>/**
 * Module dependencies.
 */

var mongoose = require('mongoose')
  , Article = mongoose.model('Article')

/**
 * List items tagged with a tag
 */

exports.index = function (req, res) {
  var criteria = { tags: req.param('tag') }
  var perPage = 5
  var page = (req.param('page') > 0 ? req.param('page') : 1) - 1
  var options = {
    perPage: perPage,
    page: page,
    criteria: criteria
  }

  Article.list(options, function(err, articles) {
    if (err) return res.render('500')
    Article.count(criteria).exec(function (err, count) {
      res.render('articles/index', {
        title: 'Articles tagged ' + req.param('tag'),
        articles: articles,
        page: page + 1,
        pages: Math.ceil(count / perPage)
      })
    })
  })
}
<|endoftext|>


<commit_before>import {join, buildQueryString} from 'aurelia-path';
import {Headers} from './headers';

export class RequestMessage {
  constructor(method: string, url: string, content: any, headers?: Headers) {
    this.method = method;
    this.url = url;
    this.content = content;
    this.headers = headers || new Headers();
    this.baseUrl = '';
  }

  buildFullUrl(): string {
    let url = join(this.baseUrl, this.url);

    if (this.params) {
      let qs = buildQueryString(this.params);
      url = qs ? `${url}?${qs}` : url;
    }

    return url;
  }
}
<commit_msg>Ignore baseUrl with absolute URIs<commit_after>import {join, buildQueryString} from 'aurelia-path';
import {Headers} from './headers';

export class RequestMessage {
  constructor(method: string, url: string, content: any, headers?: Headers) {
    this.method = method;
    this.url = url;
    this.content = content;
    this.headers = headers || new Headers();
    this.baseUrl = '';
  }

  buildFullUrl(): string {
    let url = this.url.match(/^(http(s?))\:\/\//i) ? this.url : join(this.baseUrl, this.url);

    if (this.params) {
      let qs = buildQueryString(this.params);
      url = qs ? `${url}?${qs}` : url;
    }

    return url;
  }
}
<|endoftext|>


<commit_before>//initiate the client
var oh = Ohmage("/app", "documents-app")

//attach global callbacks
oh.callback("done", function(x, status, req){
})

//global error handler. In ohmage 200 means unauthenticated
oh.callback("error", function(msg, code, req){
	(code == 200) ? window.location.replace("../web/#login") : alert("Error!\n" + msg);
});

//main app
$(function() {
oh.user.whoami().done(function(username){

	//make sure we don't timeout
	oh.keepalive();

  oh.user.info().done(function(x){
    sorted_classes = _.sortBy(x[username]['classes'])
    $.each(sorted_classes, function(k,v) {
      $('#modal-class')
        .append($("<option></option>")
        .attr("value",k)
        .text(v));
    });
    $('#modal-class').multiselect({maxHeight:200});
    $.each(x[username]['campaigns'], function(k,v) {
      $('#modal-campaign')
        .append($("<option></option>")
        .attr("value",k)
        .text(v));
    });
    $('#modal-campaign').multiselect({maxHeight:200});
  });
        //grab list of documents and provide them to datatables
  oh.document.search("").done(function(x){
	 document_data = $.map(x, function(val,key){val.uuid=key; return val;});
    $.each(document_data, function(k,v){
     v['size'] = bytesToSize(v['size'])
     v['campaign_class'] = [];
     v['edit-button'] = '<button type="button" class="btn btn-success" data-toggle="modal" data-target="#detail-modal" data-uuid="'+v['uuid']+'">Edit</button>'
	   v['button'] = '<form action="/app/document/read/contents" method="post" target="outputframe"><input type="hidden" name="document_id" value="'+v['uuid']+'"><input type="hidden" name="client" value="doc_app"><input type="submit" class="btn btn-primary" value="Download">'
	   $.isEmptyObject(v['campaign_role']) || v['campaign_class'].push(_.keys(v['campaign_role']));
	   $.isEmptyObject(v['class_role']) || v['campaign_class'].push(_.keys(v['class_role']));
    });
   var table = $('#documents').DataTable( {
    "data": document_data,
	  "lengthMenu": [25, 50, 100, "All"],
	  "oSearch": {"sSearch": "",
  	 "bRegex": true
		},
    "columns": [
     { "data": "name" },
     { "data": "creator" },
     { "data": "campaign_class[, ]" },
     { "data": "creation_date" },
     { "data": "privacy_state" },
     { "data": "size" },
     { "data": "edit-button" },
     { "data": "button" }
    ],
    "columnDefs": [
       { type: 'file-size', targets: -3 }
     ]
   });
	});

  //modify modal contents if we click the edit button?
  $('#detail-modal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    if(button.data('uuid')){
      $('#modal-download').show();
      var doc_uuid = button.data('uuid');
      var editing_doc = _.filter(document_data, {uuid: doc_uuid});
      $('#detail-modal-title').text(editing_doc[0]['name']);
      $('#modal-save').text('Update');
      $('#modal-group-file').hide();
      $('#form-group-size').show();
      $('#modal-size').val(editing_doc[0]['size'])
      $('#modal-name').val(editing_doc[0]['name']);
      $('#modal-description').text(editing_doc[0]['description']);
      $('#modal-creator').val(editing_doc[0]['creator']);
      $('#modal-privacy').val(editing_doc[0]['privacy_state']);
      $('#modal-download').show();
      $('#modal-delete').show();
      $('#modal-delete').data('uuid', editing_doc[0]['uuid']);
      $("input[name='document_id']", "#detail-modal").val(editing_doc[0]['uuid']);
      class_values = $.map(editing_doc[0]['class_role'], function(val,key){ return key;});
      $('#modal-class').multiselect('select', class_values);
      campaign_values = $.map(editing_doc[0]['campaign_role'], function(val,key){ return key;});
      $('#modal-campaign').multiselect('select', campaign_values);
      if(editing_doc[0]['user_max_role'] == "reader") {
        $('.writer').prop('disabled', true);
        $('#modal-campaign').multiselect('disable');
        $('#modal-class').multiselect('disable');
        $('#modal-delete').hide();
      } else {
        $('.writer').prop('disabled', false);
        $('#modal-campaign').multiselect('enable');
        $('#modal-class').multiselect('enable');
        $('#modal-delete').show();
      }
    }else{
      $('.writer').prop('disabled', false);
      $('#modal-campaign').multiselect('enable');
      $('#modal-class').multiselect('enable');
      $('#detail-modal-title').text("Add New Document");
      $('#modal-save').text('Save');
      $('#modal-group-file').show();
      $('#form-group-size').hide();
      $('#modal-name').val($('#modal-file').val().split('\\').pop());
      $('#modal-description').text('');
      $('#modal-creator').val(username);
      $('#modal-privacy').val('private');
      $('#modal-download').hide();
      $('#modal-delete').hide();
      $('#modal-class').multiselect('deselectAll', false);
      $('#modal-campaign').multiselect('deselectAll', false);
    }
  });
  $('#modal-delete').on('click', function () {
    $('#modal-delete').prop('disabled', true);
    var $el = $(this)
    if (confirm("Are you sure you want to delete this document? This action is irreversible!")) {
      oh.document.delete({
        document_id: $el.data('uuid')
      }).done(function(){
        alert("Successfully deleted this document");
        location.reload();
      })
    }
  });
  $('#modal-file').change(function(e){
    $('#modal-name').val($('#modal-file').val().split('\\').pop());
  });
  var createdocFormOptions = {
    success: showSuccess,
    dataType: "json"
  }

  $('#createdoc').submit(function(e){
    e.preventDefault();
    $("#modal-class").val() == null || $("#submit_class").val($("#modal-class").val().join(';reader,') + ";reader");
    $("#modal-campaign").val() == null || $("#submit_campaign").val($("#modal-campaign").val().join(';reader,') + ";reader");
    switch($('#modal-save').text()) {
      case "Save":
        $("#submit_auth_token").val($.cookie("auth_token"));
        if ($('#modal-file').val() == "" ) {
         alert('Please select a document to upload')
        } else if ( $("#modal-class").val() == null && $("#modal-campaign").val() == null ) {
         alert('Please link your document to either a class or a campaign');
        } else {
        $('#modal-save').prop('disabled', true);
        $(this).ajaxSubmit(createdocFormOptions);
        }
        break;
      case "Update":
        if ($("#modal-class").val() == null && $("#modal-campaign").val() == null) {
          alert('Please link your document to either a class or a campaign');
        } else {
          $('#modal-save').prop('disabled', true);
          var class_to_delete = _.difference(class_values, $("#modal-class").val());
          var campaign_to_delete = _.difference(campaign_values, $("#modal-campaign").val());
          var submit_class_remove = class_to_delete.join(',');
          var submit_campaign_remove = campaign_to_delete.join(',');
          oh.document.update({
            document_id: $("#modal-delete").data('uuid'),
            description: $("#modal-description").text(),
            privacy_state: $("#modal-privacy").val(),
            class_role_list_add: $('#submit_class').val(),
            class_list_remove: submit_class_remove,
            campaign_role_list_add: $('#submit_campaign').val(),
            campaign_list_remove: submit_campaign_remove
          }).done(function(x){
            alert("Document updated successfully!");
            location.reload();
          }).error(function(msg){
            $('#modal-save').prop('disabled', false);
          });
        }
        break;
    }

    return false;
  });
  function showSuccess(responseText, statusText, xhr, $form){
    if(responseText['result'] == "success"){
      alert("Document created successfully!");
      location.reload();
    } else {
      alert(JSON.stringify(responseText['errors']))
    }
  };
  //thanks to http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
  function bytesToSize(bytes) {
   if(bytes == 0) return '0 Byte';
   var k = 1000;
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   var i = Math.floor(Math.log(bytes) / Math.log(k));
   return (bytes / Math.pow(k, i)).toPrecision(3) + sizes[i];
}
});
});<commit_msg>sorting works now!<commit_after>//initiate the client
var oh = Ohmage("/app", "documents-app")

//attach global callbacks
oh.callback("done", function(x, status, req){
})

//global error handler. In ohmage 200 means unauthenticated
oh.callback("error", function(msg, code, req){
	(code == 200) ? window.location.replace("../web/#login") : alert("Error!\n" + msg);
});

//main app
$(function() {
oh.user.whoami().done(function(username){

	//make sure we don't timeout
	oh.keepalive();

  oh.user.info().done(function(x){
    sorted_classes = _.sortBy(x[username]['classes'])
    $.each(sorted_classes, function(k,v) {
      $('#modal-class')
        .append($("<option></option>")
        .attr("value",k)
        .text(v));
    });
    $('#modal-class').multiselect({maxHeight:200});
    sorted_campaigns = _.sortBy(x[username]['campaigns'])
    $.each(sorted_campaigns, function(k,v) {
      $('#modal-campaign')
        .append($("<option></option>")
        .attr("value",k)
        .text(v));
    });
    $('#modal-campaign').multiselect({maxHeight:200});
  });
        //grab list of documents and provide them to datatables
  oh.document.search("").done(function(x){
	 document_data = $.map(x, function(val,key){val.uuid=key; return val;});
    $.each(document_data, function(k,v){
     v['size'] = bytesToSize(v['size'])
     v['campaign_class'] = [];
     v['edit-button'] = '<button type="button" class="btn btn-success" data-toggle="modal" data-target="#detail-modal" data-uuid="'+v['uuid']+'">Edit</button>'
	   v['button'] = '<form action="/app/document/read/contents" method="post" target="outputframe"><input type="hidden" name="document_id" value="'+v['uuid']+'"><input type="hidden" name="client" value="doc_app"><input type="submit" class="btn btn-primary" value="Download">'
	   $.isEmptyObject(v['campaign_role']) || v['campaign_class'].push(_.keys(v['campaign_role']));
	   $.isEmptyObject(v['class_role']) || v['campaign_class'].push(_.keys(v['class_role']));
    });
   var table = $('#documents').DataTable( {
    "data": document_data,
	  "lengthMenu": [25, 50, 100, "All"],
	  "oSearch": {"sSearch": "",
  	 "bRegex": true
		},
    "columns": [
     { "data": "name" },
     { "data": "creator" },
     { "data": "campaign_class[, ]" },
     { "data": "creation_date" },
     { "data": "privacy_state" },
     { "data": "size" },
     { "data": "edit-button" },
     { "data": "button" }
    ],
    "columnDefs": [
       { type: 'file-size', targets: -3 }
     ]
   });
	});

  //modify modal contents if we click the edit button?
  $('#detail-modal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    if(button.data('uuid')){
      $('#modal-download').show();
      var doc_uuid = button.data('uuid');
      var editing_doc = _.filter(document_data, {uuid: doc_uuid});
      $('#detail-modal-title').text(editing_doc[0]['name']);
      $('#modal-save').text('Update');
      $('#modal-group-file').hide();
      $('#form-group-size').show();
      $('#modal-size').val(editing_doc[0]['size'])
      $('#modal-name').val(editing_doc[0]['name']);
      $('#modal-description').text(editing_doc[0]['description']);
      $('#modal-creator').val(editing_doc[0]['creator']);
      $('#modal-privacy').val(editing_doc[0]['privacy_state']);
      $('#modal-download').show();
      $('#modal-delete').show();
      $('#modal-delete').data('uuid', editing_doc[0]['uuid']);
      $("input[name='document_id']", "#detail-modal").val(editing_doc[0]['uuid']);
      class_values = $.map(editing_doc[0]['class_role'], function(val,key){ return key;});
      $('#modal-class').multiselect('select', class_values);
      campaign_values = $.map(editing_doc[0]['campaign_role'], function(val,key){ return key;});
      $('#modal-campaign').multiselect('select', campaign_values);
      if(editing_doc[0]['user_max_role'] == "reader") {
        $('.writer').prop('disabled', true);
        $('#modal-campaign').multiselect('disable');
        $('#modal-class').multiselect('disable');
        $('#modal-delete').hide();
      } else {
        $('.writer').prop('disabled', false);
        $('#modal-campaign').multiselect('enable');
        $('#modal-class').multiselect('enable');
        $('#modal-delete').show();
      }
    }else{
      $('.writer').prop('disabled', false);
      $('#modal-campaign').multiselect('enable');
      $('#modal-class').multiselect('enable');
      $('#detail-modal-title').text("Add New Document");
      $('#modal-save').text('Save');
      $('#modal-group-file').show();
      $('#form-group-size').hide();
      $('#modal-name').val($('#modal-file').val().split('\\').pop());
      $('#modal-description').text('');
      $('#modal-creator').val(username);
      $('#modal-privacy').val('private');
      $('#modal-download').hide();
      $('#modal-delete').hide();
      $('#modal-class').multiselect('deselectAll', false);
      $('#modal-campaign').multiselect('deselectAll', false);
    }
  });
  $('#modal-delete').on('click', function () {
    $('#modal-delete').prop('disabled', true);
    var $el = $(this)
    if (confirm("Are you sure you want to delete this document? This action is irreversible!")) {
      oh.document.delete({
        document_id: $el.data('uuid')
      }).done(function(){
        alert("Successfully deleted this document");
        location.reload();
      })
    }
  });
  $('#modal-file').change(function(e){
    $('#modal-name').val($('#modal-file').val().split('\\').pop());
  });
  var createdocFormOptions = {
    success: showSuccess,
    dataType: "json"
  }

  $('#createdoc').submit(function(e){
    e.preventDefault();
    $("#modal-class").val() == null || $("#submit_class").val($("#modal-class").val().join(';reader,') + ";reader");
    $("#modal-campaign").val() == null || $("#submit_campaign").val($("#modal-campaign").val().join(';reader,') + ";reader");
    switch($('#modal-save').text()) {
      case "Save":
        $("#submit_auth_token").val($.cookie("auth_token"));
        if ($('#modal-file').val() == "" ) {
         alert('Please select a document to upload')
        } else if ( $("#modal-class").val() == null && $("#modal-campaign").val() == null ) {
         alert('Please link your document to either a class or a campaign');
        } else {
        $('#modal-save').prop('disabled', true);
        $(this).ajaxSubmit(createdocFormOptions);
        }
        break;
      case "Update":
        if ($("#modal-class").val() == null && $("#modal-campaign").val() == null) {
          alert('Please link your document to either a class or a campaign');
        } else {
          $('#modal-save').prop('disabled', true);
          var class_to_delete = _.difference(class_values, $("#modal-class").val());
          var campaign_to_delete = _.difference(campaign_values, $("#modal-campaign").val());
          var submit_class_remove = class_to_delete.join(',');
          var submit_campaign_remove = campaign_to_delete.join(',');
          oh.document.update({
            document_id: $("#modal-delete").data('uuid'),
            description: $("#modal-description").text(),
            privacy_state: $("#modal-privacy").val(),
            class_role_list_add: $('#submit_class').val(),
            class_list_remove: submit_class_remove,
            campaign_role_list_add: $('#submit_campaign').val(),
            campaign_list_remove: submit_campaign_remove
          }).done(function(x){
            alert("Document updated successfully!");
            location.reload();
          }).error(function(msg){
            $('#modal-save').prop('disabled', false);
          });
        }
        break;
    }

    return false;
  });
  function showSuccess(responseText, statusText, xhr, $form){
    if(responseText['result'] == "success"){
      alert("Document created successfully!");
      location.reload();
    } else {
      alert(JSON.stringify(responseText['errors']))
    }
  };
  //thanks to http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
  function bytesToSize(bytes) {
   if(bytes == 0) return '0 Byte';
   var k = 1000;
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   var i = Math.floor(Math.log(bytes) / Math.log(k));
   return (bytes / Math.pow(k, i)).toPrecision(3) + sizes[i];
}
});
});<|endoftext|>


<commit_before>/**
 * NOTE: this file is simply for testing your Connector and
 * not used or packaged with the actual connector when published
 */
var APIBuilder = require('appcelerator').apibuilder,
	server = new APIBuilder();

// lifecycle examples
server.on('starting', function() {
	server.logger.info('server is starting!');
});

server.on('started', function() {
	server.logger.info('server started!');
});

//--------------------- implement authorization ---------------------//

// fetch our configured apikey
var apikey = server.get('apikey');
server.logger.info('APIKey is:', apikey);

function APIKeyAuthorization(req, resp, next) {
	if (!apikey) {
		return next();
	}
	if (req.headers['apikey']) {
		var key = req.headers['apikey'];
		if (key == apikey) {
			return next();
		}
	}
	resp.status(401);
	return resp.json({
		id: "com.appcelerator.api.unauthorized",
		message: "Unauthorized",
		url: ""
	});
}

//--------------------- simple user model ---------------------//

var User = APIBuilder.Model.extend('user', {
	fields: {
		first_name: { type: String },
		last_name: { type: String },
		email: { type: String },
		role: { type: String },
		username: { type: String, readonly: true },
		password: { type: String, hidden: true },
		password_confirmation: { type: String, hidden: true }
	},
	connector: 'appc.acs'	// a model level connector
});

// add an authorization policy for all requests at the server log
server.authorization = APIKeyAuthorization;

// create a user api from a user model
server.addModel(User);

// start the server
server.start();
<commit_msg>https://jira.appcelerator.org/browse/API-230<commit_after>/**
 * NOTE: This file is simply for testing this connector and will not
 * be used or packaged with the actual connector when published.
 */
var APIBuilder = require('appcelerator').apibuilder,
	server = new APIBuilder();

var User = APIBuilder.Model.extend('user', {
	fields: {
		first_name: { type: String },
		last_name: { type: String },
		email: { type: String },
		role: { type: String },
		username: { type: String, readonly: true },
		password: { type: String, hidden: true },
		password_confirmation: { type: String, hidden: true }
	},
	connector: 'appc.acs'
});
server.addModel(User);

server.start();<|endoftext|>


<commit_before>import { includes } from 'lodash/collection';

const pieces = {
  1: {
    name: 'pawn',
    imgPath: 'pawn',
  },
  2: {
    name: 'knight',
    imgPath: 'pawn',
  },
  3: {
    name: 'bishop',
    imgPath: 'pawn',
  },
  4: {
    name: 'rook',
    imgPath: 'pawn',
  },
  5: {
    name: 'queen',
    imgPath: 'pawn',
  },
  6: {
    name: 'king',
    imgPath: 'pawn',
  },
};

const getPieceInfoById = (id) => {
  let prefix = Object.hasOwnProperty.call(pieces, id) ? 'white_' : null;
  prefix = Object.hasOwnProperty.call(pieces, Math.abs(id)) ? 'black_' : prefix;
  if (!prefix) throw new Error('Invalid piece id');

  return {
    name: prefix + pieces[id].name,
    imgPath: prefix + pieces[id].imgPath,
  };
};

const isPiece = (id) => (
  includes([1, 2, 3, 4, 5, 6], Math.abs(id))
);

export {
  isPiece,
  getPieceInfoById,
};

export default getPieceInfoById;
<commit_msg>Fix piece name bug<commit_after>import { includes } from 'lodash/collection';

const pieces = {
  1: {
    name: 'pawn',
    imgPath: 'pawn',
  },
  2: {
    name: 'knight',
    imgPath: 'pawn',
  },
  3: {
    name: 'bishop',
    imgPath: 'pawn',
  },
  4: {
    name: 'rook',
    imgPath: 'pawn',
  },
  5: {
    name: 'queen',
    imgPath: 'pawn',
  },
  6: {
    name: 'king',
    imgPath: 'pawn',
  },
};

const getPieceInfoById = (id) => {
  let prefix = Object.hasOwnProperty.call(pieces, id) ? 'w_' : null;
  prefix = !prefix && Object.hasOwnProperty.call(pieces, Math.abs(id)) ? 'b_' : prefix;
  if (!prefix) throw new Error('Invalid piece id');

  return {
    name: prefix + pieces[Math.abs(id)].name,
    imgPath: prefix + pieces[Math.abs(id)].imgPath,
  };
};

const isPiece = (id) => (
  includes([1, 2, 3, 4, 5, 6], Math.abs(id))
);

export {
  isPiece,
  getPieceInfoById,
};

export default getPieceInfoById;
<|endoftext|>


<commit_before>"use strict";

$(document).ready(function() {

  var CommandArray = function() {
    var commands = [];
    var addCommand = function(s, d) {
      commands.push({speed : s, direction : d});
    };
    return {
      add_cmd : addCommand,
      get_cmd : function (idx) { return commands[idx]; }
    };
  };

  var PointFrameArray = function(x, y) {
    var points = [];
    var status = 2;

    var clearHistory = function() {
      points.splice(1, points.length - 1);
    };

    var getFramePoint = function(i) {
      if (i < points.length) {
        return points[i];
      }
      return null;
    };

    var addFramePoint = function(x, y) {
      points.push({x : x, y : y});
    };

    var getLastPoint = function(p) {
      if (points.length == 0) {
        return null;
      }
      return points[points.length - 1];
    };

    addFramePoint(x, y);

    return {
      points : points,
      set_status : function (s) { status = s; },
      get_status : function () { return status; },
      clear_history : clearHistory,
      get_last_point : getLastPoint,
      get_frame_point : getFramePoint,
      add_frame_point : addFramePoint,
      get_num_points : function () { return points.length; }
    };
  };

  var IntensityAnalyzer = function () {
    var max;

    var analyze = function(points) {
      var i;
      var frame_intensities = [];
      for(i = 0; i < points.length; ++i) {
        if(points[i].get_status() === 0) {
          continue;
        }
        var frames_is = [];
        var frame_num = 0;
        var prev = points[i].get_last_point();
        var curr = points[i].get_frame_point(frame_num);
        while(curr !== null) {
          frames_is[frame_num] = Math.sqrt(Math.pow(curr.y - prev.y, 2) + Math.pow(curr.x - prev.x, 2));
          frame_num++;
          prev = curr;
          curr = points[i].get_frame_point(frame_num);
        }
        frame_intensities.push(frames_is);
      }
      var cmd = new CommandArray();
      var max = 0;
      var avg = 0;
      var avgs = [];
      var c, j;
      for(i = 0; i < frame_intensities[0].length; ++i) {
        c = 0;
        for(j = 0; j < frame_intensities.length; ++j) {
          c += frame_intensities[j][i];
        }
        avg = c / frame_intensities.length;
        if (avg > max) max = avg;
        avgs.push(avg);
      }
      var final_avg = [];
      for(i = 0; i < avgs.length; ++i) {
        final_avg.push(avgs[i]/max);
      }
      return final_avg;
    };
    return {
      analyze: analyze
    };
  };

  var JigglyOutput = function () {
    Jiggly.setOutputMethod(Jiggly.outputMethods.HTML5AUDIO);
    //Jiggly.setOutputMethod(Jiggly.outputMethods.WEBVIBRATION);
    var output = function(n) {
      Jiggly.runSpeed(255 * n, 1000);
    };
    return {
      output: output
    };
  };

  var OpticalFlowAnalyzer = function () {
    var opts = function() {
      this.win_size = 20;
      this.max_iterations = 30;
      this.epsilon = 0.01;
      this.min_eigen = 0.001;
    };

    var options = new opts();

    var analyze = function(sprite, points) {
      if (!points.length) {
        return;
      }

      var curr_img_pyr;
      var prev_img_pyr;
      var point_count;
      var point_status;
      var prev_xy;
      var curr_xy;
      var canvas = sprite.get_canvas();
      var ctx = canvas.getContext("2d");
      var cur_frame;
      var imageData;
      var i;

      curr_img_pyr = new jsfeat.pyramid_t(3);
      prev_img_pyr = new jsfeat.pyramid_t(3);
      curr_img_pyr.allocate(canvas.width, canvas.height, jsfeat.U8_t|jsfeat.C1_t);
      prev_img_pyr.allocate(canvas.width, canvas.height, jsfeat.U8_t|jsfeat.C1_t);

      point_status = new Uint8Array(points.length);
      point_count = points.length;
      prev_xy = new Float32Array(points.length*2);
      curr_xy = new Float32Array(points.length*2);
      for (i = 0; i < points.length; ++i) {
        points[i].clear_history();
        curr_xy[i*2] = points[i].get_frame_point(0).x;
        curr_xy[(i*2)+1] = points[i].get_frame_point(0).y;
      }

      // build first frame
      sprite.move_to(0);
      imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      jsfeat.imgproc.grayscale(imageData.data, curr_img_pyr.data[0].data);
      curr_img_pyr.build(curr_img_pyr.data[0], true);
      sprite.move_to(1);
      do {
        imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        // swap flow data
        var _pt_xy = prev_xy;
        prev_xy = curr_xy;
        curr_xy = _pt_xy;
        var _pyr = prev_img_pyr;
        prev_img_pyr = curr_img_pyr;
        curr_img_pyr = _pyr;

        jsfeat.imgproc.grayscale(imageData.data, curr_img_pyr.data[0].data);
        curr_img_pyr.build(curr_img_pyr.data[0], true);
        jsfeat.optical_flow_lk.track(prev_img_pyr, curr_img_pyr, prev_xy, curr_xy, point_count, options.win_size|0, options.max_iterations|0, point_status, options.epsilon, options.min_eigen);

        var current_point = 0;
        var new_point_count = 0;
        for (i = 0; i < point_count && current_point < points.length; ++i) {
          while(!points[current_point].get_status()) {
            current_point++;
            if (current_point == points.length) {
              return;
            }
          }

          points[current_point].add_frame_point(curr_xy[i*2], curr_xy[(i*2)+1]);
          points[current_point].set_status(point_status[i]);

          if (point_status[i]) {
            if (new_point_count != i) {
              // No splice for array buffers. :(
              curr_xy[new_point_count*2] = curr_xy[i*2];
              curr_xy[(new_point_count*2)+1] = curr_xy[(i*2)+1];
            }
            new_point_count = new_point_count + 1;
          }
          current_point++;
        }
        // Out of points to process. Exit.
        if(!new_point_count) {
          return;
        }
        point_count = new_point_count;
        cur_frame = sprite.get_current_frame();
        sprite.move_relative(1);
      } while(cur_frame < sprite.get_current_frame());
    };

    return {
      analyze : analyze,
      set_win_size : function(size) {
        options.win_size = size;
      },
      get_win_size : function() {
        return options.win_size;
      },
      set_max_iterations : function(size) {
        options.max_iterations = size;
      },
      get_max_iterations : function() {
        return options.max_iterations;
      },
      set_epsilon : function(size) {
        options.epsilon = size;
      },
      get_epsilon : function() {
        return options.epsilon;
      },
      set_min_eigen : function(size) {
        options.min_eigen = size;
      },
      get_min_eigen : function() {
        return options.min_eigen;
      }
    };
  };

  var FeelGIF = (function () {

    var sprite;
    var points = [];
    var canvas;
    var ctx;
    var overidx = -1;
    var output = null;
    var jig = new JigglyOutput();

    function on_point_list_click(e) {
      var targ;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      var id = targ.getAttribute("rel:index");
      points.splice(id, 1);
      rebuild_point_list();
      sprite.move_to(sprite.get_current_frame());
    }

    function rebuild_point_list() {
      var list = document.getElementById("pointlist");
      while (list.firstChild) {
        list.removeChild(list.firstChild);
      }
      points.forEach(function(element, index, array) {
        var li = document.createElement("li");
        var a = document.createElement("a");
        switch(element.get_status()) {
        case 0:
          a.setAttribute("id", "deadpoint");
          break;
        case 1:
          a.setAttribute("id", "livepoint");
          break;
        case 2:
          a.setAttribute("id", "newpoint");
          break;
        }
        a.setAttribute("rel:index", index);
        var text = document.createTextNode(element.get_frame_point(0).x.toString() + ", " + element.get_frame_point(0).y.toString());
        a.appendChild(text);
        li.appendChild(a);
        a.addEventListener("click", on_point_list_click);
        a.onmouseover = on_point_mouse_over;
        a.onmouseout = on_point_mouse_out;
        document.getElementById("pointlist").appendChild(li);
      });
    }

    function on_point_mouse_over(e) {
      var targ;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      overidx = targ.getAttribute("rel:index");
      drawPoints();
    }

    function on_point_mouse_out(e) {
      overidx = -1;
      drawPoints();
    }

    function on_canvas_click(e) {
      var coords = canvas.relMouseCoords(e);
      if(coords.x > 0 & coords.y > 0 & coords.x < canvas.width & coords.y < canvas.height) {
        points.push(new PointFrameArray(coords.x, coords.y));
        draw_circle(coords.x, coords.y, 2);
        rebuild_point_list();
      }
    }

    function draw_circle(x, y, status) {
      switch(status) {
      case 0:
        ctx.fillStyle = "rgb(255,0,0)";
        break;
      case 1:
        ctx.fillStyle = "rgb(0,255,0)";
        break;
      case 2:
        ctx.fillStyle = "rgb(0,0,255)";
        break;
      case 3:
        ctx.fillStyle = "rgb(0,128,128)";
        break;
      }
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, Math.PI*2, true);
      ctx.closePath();
      ctx.fill();
    }

    function relMouseCoords(event) {
      var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0;
      var currentElement = this;

      do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
      } while(currentElement = currentElement.offsetParent)

      canvasX = event.pageX - totalOffsetX;
      canvasY = event.pageY - totalOffsetY;

      return {x:canvasX, y:canvasY};
    }

    HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

    var drawPoints = function() {
      var p;
      var cur_frame = sprite.get_current_frame();
      for(var i = 0; i < points.length; ++i) {
        p = points[i].get_frame_point(cur_frame);
        if (p) {
          if (i == overidx) {
            draw_circle(p.x, p.y, 3);
          } else {
            draw_circle(p.x, p.y, points[i].get_status());
          }
        }
      }
      if(output !== null && sprite.get_playing()) {
        jig.output(output[cur_frame]);
      }
    };
    document.addEventListener('gifmove', drawPoints, false);

    var setupGifControls = function() {
      document.getElementById("stop").style.color = "red";
      document.getElementById("play").style.color = "black";
      document.getElementById("pause").style.color = "black";
      document.getElementById("loopgif").style.color = "black";

      document.getElementById("play").addEventListener("click", function() {
        document.getElementById("play").style.color = "red";
        document.getElementById("stop").style.color = "black";
        document.getElementById("pause").style.color = "black";
        sprite.play();
      });
      document.getElementById("pause").addEventListener("click", function() {
        document.getElementById("play").style.color = "black";
        document.getElementById("stop").style.color = "black";
        document.getElementById("pause").style.color = "red";
        sprite.pause();
        jig.output(0);
      });
      document.getElementById("stop").addEventListener("click", function() {
        document.getElementById("play").style.color = "black";
        document.getElementById("stop").style.color = "red";
        document.getElementById("pause").style.color = "black";
        sprite.pause();
        sprite.move_to(0);
        jig.output(0);
      });
      document.getElementById("backward").addEventListener("click", function() {
        sprite.pause();
        sprite.move_relative(-1);
      });
      document.getElementById("forward").addEventListener("click", function() {
        sprite.pause();
        sprite.move_relative(1);
      });
      document.getElementById("loopgif").addEventListener("click", function() {
        if(sprite.get_looping()) {
          sprite.setloop(false);
          document.getElementById("loopgif").style.color = "black";
        } else {
          sprite.setloop(true);
          document.getElementById("loopgif").style.color = "red";
        }
      });
      document.getElementById("analyze").addEventListener("click", function() {
        var o = new OpticalFlowAnalyzer();
        document.removeEventListener('gifmove', drawPoints, false);
        o.analyze(sprite, points);
        var a = new IntensityAnalyzer();
        output = a.analyze(points);
        rebuild_point_list();
        document.addEventListener('gifmove', drawPoints, false);
        sprite.move_to(0);
        drawPoints();
      });
      function updateControls(event) {
        if(!sprite.get_looping()) {
          document.getElementById("play").style.color = "black";
          document.getElementById("stop").style.color = "red";
          document.getElementById("pause").style.color = "black";
          jig.output(0);
        }
      }
      document.addEventListener('gifloop', updateControls, false);
    };

    document.getElementById("gifsubmit").addEventListener('click', (function() {
      var drawdiv = document.getElementById("pregifcanvas");
      var src;
      sprite = new SpriteCanvas({ auto_play: false, rubbable: false });
      sprite.init();
      var loader = new GifLoader(sprite.get_loader());
      if(document.getElementById("giffile").value != "") {
        src = document.getElementById("giffile").value;
      } else {
        src = document.getElementById("gifurl").value;
      }
      loader.load(src);
      canvas = sprite.get_canvas();
      ctx = canvas.getContext("2d");
      sprite.setloop(false);
      drawdiv.appendChild(sprite.get_canvas());
      setupGifControls();
      canvas.addEventListener('click', on_canvas_click, false);
      document.getElementById("fileinput").style.display = "none";
      document.getElementById("preprocessing").style.display = "block";
    }));
  });

  FeelGIF();
});
<commit_msg>Fixed exception when no successful flow points are found<commit_after>"use strict";

$(document).ready(function() {

  var CommandArray = function() {
    var commands = [];
    var addCommand = function(s, d) {
      commands.push({speed : s, direction : d});
    };
    return {
      add_cmd : addCommand,
      get_cmd : function (idx) { return commands[idx]; }
    };
  };

  var PointFrameArray = function(x, y) {
    var points = [];
    var status = 2;

    var clearHistory = function() {
      points.splice(1, points.length - 1);
    };

    var getFramePoint = function(i) {
      if (i < points.length) {
        return points[i];
      }
      return null;
    };

    var addFramePoint = function(x, y) {
      points.push({x : x, y : y});
    };

    var getLastPoint = function(p) {
      if (points.length == 0) {
        return null;
      }
      return points[points.length - 1];
    };

    addFramePoint(x, y);

    return {
      points : points,
      set_status : function (s) { status = s; },
      get_status : function () { return status; },
      clear_history : clearHistory,
      get_last_point : getLastPoint,
      get_frame_point : getFramePoint,
      add_frame_point : addFramePoint,
      get_num_points : function () { return points.length; }
    };
  };

  var IntensityAnalyzer = function () {
    var max;

    var analyze = function(points) {
      var i;
      var frame_intensities = [];
      for(i = 0; i < points.length; ++i) {
        if(points[i].get_status() === 0) {
          continue;
        }
        var frames_is = [];
        var frame_num = 0;
        var prev = points[i].get_last_point();
        var curr = points[i].get_frame_point(frame_num);
        while(curr !== null) {
          frames_is[frame_num] = Math.sqrt(Math.pow(curr.y - prev.y, 2) + Math.pow(curr.x - prev.x, 2));
          frame_num++;
          prev = curr;
          curr = points[i].get_frame_point(frame_num);
        }
        frame_intensities.push(frames_is);
      }
      if (frame_intensities.length == 0) {
        return;
      }
      var cmd = new CommandArray();
      var max = 0;
      var avg = 0;
      var avgs = [];
      var c, j;
      for(i = 0; i < frame_intensities[0].length; ++i) {
        c = 0;
        for(j = 0; j < frame_intensities.length; ++j) {
          c += frame_intensities[j][i];
        }
        avg = c / frame_intensities.length;
        if (avg > max) max = avg;
        avgs.push(avg);
      }
      var final_avg = [];
      for(i = 0; i < avgs.length; ++i) {
        final_avg.push(avgs[i]/max);
      }
      return final_avg;
    };
    return {
      analyze: analyze
    };
  };

  var JigglyOutput = function () {
    Jiggly.setOutputMethod(Jiggly.outputMethods.HTML5AUDIO);
    //Jiggly.setOutputMethod(Jiggly.outputMethods.WEBVIBRATION);
    var output = function(n) {
      Jiggly.runSpeed(255 * n, 1000);
    };
    return {
      output: output
    };
  };

  var OpticalFlowAnalyzer = function () {
    var opts = function() {
      this.win_size = 20;
      this.max_iterations = 30;
      this.epsilon = 0.01;
      this.min_eigen = 0.001;
    };

    var options = new opts();

    var analyze = function(sprite, points) {
      if (!points.length) {
        return;
      }

      var curr_img_pyr;
      var prev_img_pyr;
      var point_count;
      var point_status;
      var prev_xy;
      var curr_xy;
      var canvas = sprite.get_canvas();
      var ctx = canvas.getContext("2d");
      var cur_frame;
      var imageData;
      var i;

      curr_img_pyr = new jsfeat.pyramid_t(3);
      prev_img_pyr = new jsfeat.pyramid_t(3);
      curr_img_pyr.allocate(canvas.width, canvas.height, jsfeat.U8_t|jsfeat.C1_t);
      prev_img_pyr.allocate(canvas.width, canvas.height, jsfeat.U8_t|jsfeat.C1_t);

      point_status = new Uint8Array(points.length);
      point_count = points.length;
      prev_xy = new Float32Array(points.length*2);
      curr_xy = new Float32Array(points.length*2);
      for (i = 0; i < points.length; ++i) {
        points[i].clear_history();
        curr_xy[i*2] = points[i].get_frame_point(0).x;
        curr_xy[(i*2)+1] = points[i].get_frame_point(0).y;
      }

      // build first frame
      sprite.move_to(0);
      imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      jsfeat.imgproc.grayscale(imageData.data, curr_img_pyr.data[0].data);
      curr_img_pyr.build(curr_img_pyr.data[0], true);
      sprite.move_to(1);
      do {
        imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        // swap flow data
        var _pt_xy = prev_xy;
        prev_xy = curr_xy;
        curr_xy = _pt_xy;
        var _pyr = prev_img_pyr;
        prev_img_pyr = curr_img_pyr;
        curr_img_pyr = _pyr;

        jsfeat.imgproc.grayscale(imageData.data, curr_img_pyr.data[0].data);
        curr_img_pyr.build(curr_img_pyr.data[0], true);
        jsfeat.optical_flow_lk.track(prev_img_pyr, curr_img_pyr, prev_xy, curr_xy, point_count, options.win_size|0, options.max_iterations|0, point_status, options.epsilon, options.min_eigen);

        var current_point = 0;
        var new_point_count = 0;
        for (i = 0; i < point_count && current_point < points.length; ++i) {
          while(!points[current_point].get_status()) {
            current_point++;
            if (current_point == points.length) {
              return;
            }
          }

          points[current_point].add_frame_point(curr_xy[i*2], curr_xy[(i*2)+1]);
          points[current_point].set_status(point_status[i]);

          if (point_status[i]) {
            if (new_point_count != i) {
              // No splice for array buffers. :(
              curr_xy[new_point_count*2] = curr_xy[i*2];
              curr_xy[(new_point_count*2)+1] = curr_xy[(i*2)+1];
            }
            new_point_count = new_point_count + 1;
          }
          current_point++;
        }
        // Out of points to process. Exit.
        if(!new_point_count) {
          return;
        }
        point_count = new_point_count;
        cur_frame = sprite.get_current_frame();
        sprite.move_relative(1);
      } while(cur_frame < sprite.get_current_frame());
    };

    return {
      analyze : analyze,
      set_win_size : function(size) {
        options.win_size = size;
      },
      get_win_size : function() {
        return options.win_size;
      },
      set_max_iterations : function(size) {
        options.max_iterations = size;
      },
      get_max_iterations : function() {
        return options.max_iterations;
      },
      set_epsilon : function(size) {
        options.epsilon = size;
      },
      get_epsilon : function() {
        return options.epsilon;
      },
      set_min_eigen : function(size) {
        options.min_eigen = size;
      },
      get_min_eigen : function() {
        return options.min_eigen;
      }
    };
  };

  var FeelGIF = (function () {

    var sprite;
    var points = [];
    var canvas;
    var ctx;
    var overidx = -1;
    var output = null;
    var jig = new JigglyOutput();

    function on_point_list_click(e) {
      var targ;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      var id = targ.getAttribute("rel:index");
      points.splice(id, 1);
      rebuild_point_list();
      sprite.move_to(sprite.get_current_frame());
    }

    function rebuild_point_list() {
      var list = document.getElementById("pointlist");
      while (list.firstChild) {
        list.removeChild(list.firstChild);
      }
      points.forEach(function(element, index, array) {
        var li = document.createElement("li");
        var a = document.createElement("a");
        switch(element.get_status()) {
        case 0:
          a.setAttribute("id", "deadpoint");
          break;
        case 1:
          a.setAttribute("id", "livepoint");
          break;
        case 2:
          a.setAttribute("id", "newpoint");
          break;
        }
        a.setAttribute("rel:index", index);
        var text = document.createTextNode(element.get_frame_point(0).x.toString() + ", " + element.get_frame_point(0).y.toString());
        a.appendChild(text);
        li.appendChild(a);
        a.addEventListener("click", on_point_list_click);
        a.onmouseover = on_point_mouse_over;
        a.onmouseout = on_point_mouse_out;
        document.getElementById("pointlist").appendChild(li);
      });
    }

    function on_point_mouse_over(e) {
      var targ;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      overidx = targ.getAttribute("rel:index");
      drawPoints();
    }

    function on_point_mouse_out(e) {
      overidx = -1;
      drawPoints();
    }

    function on_canvas_click(e) {
      var coords = canvas.relMouseCoords(e);
      if(coords.x > 0 & coords.y > 0 & coords.x < canvas.width & coords.y < canvas.height) {
        points.push(new PointFrameArray(coords.x, coords.y));
        draw_circle(coords.x, coords.y, 2);
        rebuild_point_list();
      }
    }

    function draw_circle(x, y, status) {
      switch(status) {
      case 0:
        ctx.fillStyle = "rgb(255,0,0)";
        break;
      case 1:
        ctx.fillStyle = "rgb(0,255,0)";
        break;
      case 2:
        ctx.fillStyle = "rgb(0,0,255)";
        break;
      case 3:
        ctx.fillStyle = "rgb(0,128,128)";
        break;
      }
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, Math.PI*2, true);
      ctx.closePath();
      ctx.fill();
    }

    function relMouseCoords(event) {
      var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0;
      var currentElement = this;

      do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
      } while(currentElement = currentElement.offsetParent)

      canvasX = event.pageX - totalOffsetX;
      canvasY = event.pageY - totalOffsetY;

      return {x:canvasX, y:canvasY};
    }

    HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

    var drawPoints = function() {
      var p;
      var cur_frame = sprite.get_current_frame();
      for(var i = 0; i < points.length; ++i) {
        p = points[i].get_frame_point(cur_frame);
        if (p) {
          if (i == overidx) {
            draw_circle(p.x, p.y, 3);
          } else {
            draw_circle(p.x, p.y, points[i].get_status());
          }
        }
      }
      if(output !== null && sprite.get_playing()) {
        jig.output(output[cur_frame]);
      }
    };
    document.addEventListener('gifmove', drawPoints, false);

    var setupGifControls = function() {
      document.getElementById("stop").style.color = "red";
      document.getElementById("play").style.color = "black";
      document.getElementById("pause").style.color = "black";
      document.getElementById("loopgif").style.color = "black";

      document.getElementById("play").addEventListener("click", function() {
        document.getElementById("play").style.color = "red";
        document.getElementById("stop").style.color = "black";
        document.getElementById("pause").style.color = "black";
        sprite.play();
      });
      document.getElementById("pause").addEventListener("click", function() {
        document.getElementById("play").style.color = "black";
        document.getElementById("stop").style.color = "black";
        document.getElementById("pause").style.color = "red";
        sprite.pause();
        jig.output(0);
      });
      document.getElementById("stop").addEventListener("click", function() {
        document.getElementById("play").style.color = "black";
        document.getElementById("stop").style.color = "red";
        document.getElementById("pause").style.color = "black";
        sprite.pause();
        sprite.move_to(0);
        jig.output(0);
      });
      document.getElementById("backward").addEventListener("click", function() {
        sprite.pause();
        sprite.move_relative(-1);
      });
      document.getElementById("forward").addEventListener("click", function() {
        sprite.pause();
        sprite.move_relative(1);
      });
      document.getElementById("loopgif").addEventListener("click", function() {
        if(sprite.get_looping()) {
          sprite.setloop(false);
          document.getElementById("loopgif").style.color = "black";
        } else {
          sprite.setloop(true);
          document.getElementById("loopgif").style.color = "red";
        }
      });
      document.getElementById("analyze").addEventListener("click", function() {
        var o = new OpticalFlowAnalyzer();
        document.removeEventListener('gifmove', drawPoints, false);
        o.analyze(sprite, points);
        var a = new IntensityAnalyzer();
        output = a.analyze(points);
        rebuild_point_list();
        document.addEventListener('gifmove', drawPoints, false);
        sprite.move_to(0);
        drawPoints();
      });
      function updateControls(event) {
        if(!sprite.get_looping()) {
          document.getElementById("play").style.color = "black";
          document.getElementById("stop").style.color = "red";
          document.getElementById("pause").style.color = "black";
          jig.output(0);
        }
      }
      document.addEventListener('gifloop', updateControls, false);
    };

    document.getElementById("gifsubmit").addEventListener('click', (function() {
      var drawdiv = document.getElementById("pregifcanvas");
      var src;
      sprite = new SpriteCanvas({ auto_play: false, rubbable: false });
      sprite.init();
      var loader = new GifLoader(sprite.get_loader());
      if(document.getElementById("giffile").value != "") {
        src = document.getElementById("giffile").value;
      } else {
        src = document.getElementById("gifurl").value;
      }
      loader.load(src);
      canvas = sprite.get_canvas();
      ctx = canvas.getContext("2d");
      sprite.setloop(false);
      drawdiv.appendChild(sprite.get_canvas());
      setupGifControls();
      canvas.addEventListener('click', on_canvas_click, false);
      document.getElementById("fileinput").style.display = "none";
      document.getElementById("preprocessing").style.display = "block";
    }));
  });

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


<commit_before>var express        = require("express");
var router         = express.Router();
var http           = require('http');
var app            = express();
var db             = require("./model/db");
var sensorData     = require("./model/sensorData");
var rideInfo       = require("./model/rideInfo");
var mongoose       = require("mongoose");
var bodyParser     = require("body-parser");
var methodOverride = require("method-override");

app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next();
});

//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));

app.use(methodOverride(function(req, res){
      if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        var method = req.body._method
        delete req.body._method
        return method
      }
}));

//require("./router/crud.js")(app);

function normalise(obj) {
	for(var i in obj) {
		if(obj.hasOwnProperty(i)) {
      switch(typeof obj[i]) {
        case 'undefined':
          obj[i] = null;
        break;
        case 'string':
          if((obj[i].toLowerCase() == "undefined") || (obj[i].toLowerCase() == "null")){
            obj[i] = null;
          }
        break;
        }

		}
	}
	return obj;
}

app.get("/sensorData/:rideId/:tagId?", function(req, res){
				mongoose.model('sensorData').find({ "rideId" : req.params.rideId, "tagId" : req.params.tagId }, function (err, result) {
			        if (err) {
								  //res.status(404).send;
                  res.send(404, { "success" : false, error : { "message" : err } });
                  console.log("ERRORED at GET /   , ");
			            return console.error(err);
			        } else {
									console.log("SUCCESS at GET /   , for collection : sensorData");
                  console.log("Get results for RIDE ID =  " + req.params.rideId );
                  res.send(200, { "success" : true, "data" : result });
                  //res.json({ "success" : true, "data" : result });
                  //res.render("index.html");
			        }
			  });

});

app.get("/rideInfo/:rideId", function(req, res){
				mongoose.model('rideInfo').find({ "rideId" : req.params.rideId }, function (err, result) {
			        if (err) {
								  //res.status(404).send;
                  res.send(404, { "success" : false, error : { "message" : err } });
									console.log("ERRORED at GET /   , ");
			            return console.error(err);
			        } else {
									console.log("SUCCESS at GET /   , for collection : rideInfo");
                  console.log("Get results for RIDE ID =  " + req.params.rideId );
                  res.send(200, { "success" : true, "data" : result });
                  //res.json({ "success" : true, "data" : result });
                  //res.render("index.html");
			        }
			  });

});

app.post("/sensorData", function(req, resp){
				// Get values from POST request. These can be done through forms or REST calls. These rely on the "name" attributes for forms
        var acc = normalise({
					"x" : req.query.accX,
					"y" : req.query.accY,
					"z" : req.query.accZ,
				});
				var geo = normalise({
					"latitude"        : req.query.geoLatitude,
					"longitude"       : req.query.geoLongitude,
					"accuracy"        : req.query.geoAccuracy,
					"altitude"        : req.query.geoAltitude,
					"altitudeAccuracy": req.query.geoAltitudeAccuracy,
					"heading"         : req.query.geoHeading,
					"speed"           : req.query.geoSpeed
				});
				var comp = normalise({
					"magneticHeading": req.query.compMagneticHeading,
					"trueHeading"    : req.query.compTrueHeading,
					"headingAccuracy": req.query.compHeadingAccuracy,
				});
        var timestamp = req.query.timestamp;
				var rideId    = req.query.rideId;
        var tagId     = req.query.tagId;
				var version   = req.query.ver;

				mongoose.model('sensorData').create({
				                  "acc" : {
				                    "x" : acc.x,
				                    "y" : acc.y,
				                    "z" : acc.z,
				                  },
				                  "geo" : {
				                    "latitude"        : geo.latitude,
				                    "longitude"       : geo.longitude,
				                    "accuracy"        : geo.accuracy,
				                    "altitude"        : geo.altitude,
				                    "altitudeAccuracy": geo.altitudeAccuracy,
				                    "heading"         : geo.heading,
				                    "speed"           : geo.speed,
				                  },
				                  "comp" : {
				                    "magneticHeading" : comp.magneticHeading,
				                    "trueHeading"     : comp.trueHeading,
				                    "headingAccuracy" : comp.headingAccuracy,
				                  },
                          "timestamp" : timestamp,
				                  "rideId"   : rideId,
                          "tagId"    : tagId,
				                  "version"  : version
				}, function (err, sensorData) {
							if (err) {
								  console.log("ERRORED at POST /   , " + err);
                  resp.send(422, { "success" : false, error : { "message" : err } });
							} else {
									console.log("SUCCESS at POST /  for collection sensorData ############################# ");
									console.log('POST creating new entry: ' + sensorData);
                  resp.send(201, { "success" : true, "data" : sensorData });
							}
				});
})

app.post("/rideInfo", function(req, resp){

    if(req.query.rideId && req.query.startedAt){
        var rideStatus;
        if(req.query.status){
          rideStatus = req.query.status;
        } else {
          rideStatus = "inprogress";
        }

        if(req.query.analysisStatus){
          analysisStatus = req.query.analysisStatus;
        } else {
          analysisStatus = "pending";
        }

				mongoose.model('rideInfo').create({
          "rideId"            : req.query.rideId,
          "status"            : rideStatus,
          "startedAt"         : req.query.startedAt,
          "endedAt"           : req.query.endedAt,
          "analysisInfo"      : normalise({
            "status"          : analysisStatus,
            "version"         : req.query.analysisVersion,
            "startedAt"       : req.query.analysisStartedAt,
            "endedAt"         : req.query.analysisEndedAt
          })
				}, function (err, rideInfo) {
							if (err) {
								  console.log("ERRORED at POST /   , " + err);
                  resp.send(422, { "success" : false, error : { "message" : err }});
							} else {
									console.log("SUCCESS at POST /  for collection rideInfo ############################# ");
									console.log('POST creating new entry: ' + rideInfo);
                  resp.send(201, { "success" : true, "data" : rideInfo});
							}
				});
        return ;
      }
      resp.send(422, { "success" : false, error : { "message" : "Both rideId and startedAt are REQUIRED" } });
})

app.put("/rideInfo/:rideId", function(req, resp){

    if(req.query.rideId){
      var updateFields = {};
      for(var i in req.query){
        updateFields[i] = req.query[i];
      }

				mongoose.model('rideInfo').findOneAndUpdate({ rideId : req.query.rideId}, updateFields, function (err, rideInfo) {
							if (err) {
								  console.log("ERRORED at PUT /   , " + err);
                  resp.send(422, { "success" : false, error : { "message" : err }});
							} else {
									console.log("SUCCESS at PUT /  for collection rideInfo ############################# ");
									console.log('PUT updating entry: ' + rideInfo);
                  resp.send(201, { "success" : true, "data" : rideInfo});
							}
				});
        return ;
      }
      resp.send(422, { "success" : false, error : { "message" : "rideId is REQUIRED for PUT operation" } });
})

var server = app.listen(3000, function(){
	console.log("Running on port 3000");
});
<commit_msg>Reading rideId from params<commit_after>var express        = require("express");
var router         = express.Router();
var http           = require('http');
var app            = express();
var db             = require("./model/db");
var sensorData     = require("./model/sensorData");
var rideInfo       = require("./model/rideInfo");
var mongoose       = require("mongoose");
var bodyParser     = require("body-parser");
var methodOverride = require("method-override");

app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next();
});

//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));

app.use(methodOverride(function(req, res){
      if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        var method = req.body._method
        delete req.body._method
        return method
      }
}));

//require("./router/crud.js")(app);

function normalise(obj) {
	for(var i in obj) {
		if(obj.hasOwnProperty(i)) {
      switch(typeof obj[i]) {
        case 'undefined':
          obj[i] = null;
        break;
        case 'string':
          if((obj[i].toLowerCase() == "undefined") || (obj[i].toLowerCase() == "null")){
            obj[i] = null;
          }
        break;
        }

		}
	}
	return obj;
}

app.get("/sensorData/:rideId/:tagId?", function(req, res){
				mongoose.model('sensorData').find({ "rideId" : req.params.rideId, "tagId" : req.params.tagId }, function (err, result) {
			        if (err) {
								  //res.status(404).send;
                  res.send(404, { "success" : false, error : { "message" : err } });
                  console.log("ERRORED at GET /   , ");
			            return console.error(err);
			        } else {
									console.log("SUCCESS at GET /   , for collection : sensorData");
                  console.log("Get results for RIDE ID =  " + req.params.rideId );
                  res.send(200, { "success" : true, "data" : result });
                  //res.json({ "success" : true, "data" : result });
                  //res.render("index.html");
			        }
			  });

});

app.get("/rideInfo/:rideId", function(req, res){
				mongoose.model('rideInfo').find({ "rideId" : req.params.rideId }, function (err, result) {
			        if (err) {
								  //res.status(404).send;
                  res.send(404, { "success" : false, error : { "message" : err } });
									console.log("ERRORED at GET /   , ");
			            return console.error(err);
			        } else {
									console.log("SUCCESS at GET /   , for collection : rideInfo");
                  console.log("Get results for RIDE ID =  " + req.params.rideId );
                  res.send(200, { "success" : true, "data" : result });
                  //res.json({ "success" : true, "data" : result });
                  //res.render("index.html");
			        }
			  });

});

app.post("/sensorData", function(req, resp){
				// Get values from POST request. These can be done through forms or REST calls. These rely on the "name" attributes for forms
        var acc = normalise({
					"x" : req.query.accX,
					"y" : req.query.accY,
					"z" : req.query.accZ,
				});
				var geo = normalise({
					"latitude"        : req.query.geoLatitude,
					"longitude"       : req.query.geoLongitude,
					"accuracy"        : req.query.geoAccuracy,
					"altitude"        : req.query.geoAltitude,
					"altitudeAccuracy": req.query.geoAltitudeAccuracy,
					"heading"         : req.query.geoHeading,
					"speed"           : req.query.geoSpeed
				});
				var comp = normalise({
					"magneticHeading": req.query.compMagneticHeading,
					"trueHeading"    : req.query.compTrueHeading,
					"headingAccuracy": req.query.compHeadingAccuracy,
				});
        var timestamp = req.query.timestamp;
				var rideId    = req.query.rideId;
        var tagId     = req.query.tagId;
				var version   = req.query.ver;

				mongoose.model('sensorData').create({
				                  "acc" : {
				                    "x" : acc.x,
				                    "y" : acc.y,
				                    "z" : acc.z,
				                  },
				                  "geo" : {
				                    "latitude"        : geo.latitude,
				                    "longitude"       : geo.longitude,
				                    "accuracy"        : geo.accuracy,
				                    "altitude"        : geo.altitude,
				                    "altitudeAccuracy": geo.altitudeAccuracy,
				                    "heading"         : geo.heading,
				                    "speed"           : geo.speed,
				                  },
				                  "comp" : {
				                    "magneticHeading" : comp.magneticHeading,
				                    "trueHeading"     : comp.trueHeading,
				                    "headingAccuracy" : comp.headingAccuracy,
				                  },
                          "timestamp" : timestamp,
				                  "rideId"   : rideId,
                          "tagId"    : tagId,
				                  "version"  : version
				}, function (err, sensorData) {
							if (err) {
								  console.log("ERRORED at POST /   , " + err);
                  resp.send(422, { "success" : false, error : { "message" : err } });
							} else {
									console.log("SUCCESS at POST /  for collection sensorData ############################# ");
									console.log('POST creating new entry: ' + sensorData);
                  resp.send(201, { "success" : true, "data" : sensorData });
							}
				});
})

app.post("/rideInfo", function(req, resp){

    if(req.query.rideId && req.query.startedAt){
        var rideStatus;
        if(req.query.status){
          rideStatus = req.query.status;
        } else {
          rideStatus = "inprogress";
        }

        if(req.query.analysisStatus){
          analysisStatus = req.query.analysisStatus;
        } else {
          analysisStatus = "pending";
        }

				mongoose.model('rideInfo').create({
          "rideId"            : req.query.rideId,
          "status"            : rideStatus,
          "startedAt"         : req.query.startedAt,
          "endedAt"           : req.query.endedAt,
          "analysisInfo"      : normalise({
            "status"          : analysisStatus,
            "version"         : req.query.analysisVersion,
            "startedAt"       : req.query.analysisStartedAt,
            "endedAt"         : req.query.analysisEndedAt
          })
				}, function (err, rideInfo) {
							if (err) {
								  console.log("ERRORED at POST /   , " + err);
                  resp.send(422, { "success" : false, error : { "message" : err }});
							} else {
									console.log("SUCCESS at POST /  for collection rideInfo ############################# ");
									console.log('POST creating new entry: ' + rideInfo);
                  resp.send(201, { "success" : true, "data" : rideInfo});
							}
				});
        return ;
      }
      resp.send(422, { "success" : false, error : { "message" : "Both rideId and startedAt are REQUIRED" } });
})

app.put("/rideInfo/:rideId", function(req, resp){

    if(req.params.rideId){
      var updateFields = {};
      for(var i in req.query){
        updateFields[i] = req.query[i];
      }

				mongoose.model('rideInfo').findOneAndUpdate({ rideId : req.params.rideId}, updateFields, function (err, rideInfo) {
							if (err) {
								  console.log("ERRORED at PUT /   , " + err);
                  resp.send(422, { "success" : false, error : { "message" : err }});
							} else {
									console.log("SUCCESS at PUT /  for collection rideInfo ############################# ");
									console.log('PUT updating entry: ' + rideInfo);
                  resp.send(201, { "success" : true, "data" : rideInfo});
							}
				});
        return ;
      }
      resp.send(422, { "success" : false, error : { "message" : "rideId is REQUIRED for PUT operation" } });
})

var server = app.listen(3000, function(){
	console.log("Running on port 3000");
});
<|endoftext|>


<commit_before>var Vue = require('lib/vue');
var validator = require('common/validator');

var TipAlert = require('widget/tipalert/main');
var FormInput = require('widget/forminput/main');
var FormActions = require('widget/formactions/main');
var HeCheckbox = require('widget/hecheckbox/main');

module.exports = Vue.extend({
    template: __inline('main.html'),
    components: {
        TipAlert,
        FormInput,
        FormActions,
        HeCheckbox
    },
    ready: function() {

        handleValidator(this);
    }
});

function handleValidator(vm) {
    validator.check($('.login-form'), {
        username: {
            required: {
                rule: true,
                message: '用户名不能为空！'
            },
            minlength: {
                rule: 2,
                message: '最小长度为2'
            },
            maxlength: {
                rule: 6,
                message: '最大长度为6'
            }
        },
        password: {
            required: {
                rule: true,
                message: '密码不能为空！'
            },
            minlength: {
                rule: 6,
                message: '最小长度为6'
            }
        }
    }, {
        invalidHandler: function(event, validator) {
            vm.$refs.alert.show('登录失败，请输入正确的用户名和密码！');
        }
    });
}

var handleLogin = function(vm) {
    $('.login-form').validate({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            },
            remember: {
                required: false
            }
        },

        messages: {
            username: {
                required: "用户名不能为空！"
            },
            password: {
                required: "密码不能为空！"
            }
        },

        invalidHandler: function(event, validator) { //display error alert on form submit
            vm.$refs.alert.show('登录失败，请输入正确的用户名和密码！');
        },

        highlight: function(element) { // hightlight error inputs
            $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
        },

        success: function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },

        errorPlacement: function(error, element) {
            error.insertAfter(element.closest('.input-icon'));
        },

        submitHandler: function(form) {
            form.submit();
        }
    });

    $('.login-form input').keypress(function(e) {
        if (e.which == 13) {
            if ($('.login-form').validate().form()) {
                $('.login-form').submit();
            }
            return false;
        }
    });
}

<commit_msg>修改loginpanel<commit_after>var Vue = require('lib/vue');
var validator = require('common/validator');

var TipAlert = require('widget/tipalert/main');
var FormInput = require('widget/forminput/main');
var FormActions = require('widget/formactions/main');
var HeCheckbox = require('widget/hecheckbox/main');

module.exports = Vue.extend({
    template: __inline('main.html'),
    components: {
        TipAlert,
        FormInput,
        FormActions,
        HeCheckbox
    },
    ready: function() {
        // 缓存该值，避免重复获取
        this.$set('formElem', $(this.$el));

        handleValidator(this);

        handleEnter(this);
    }
});

function handleValidator(vm) {
    validator.check(vm.formElem, {
        username: {
            required: {
                rule: true,
                message: '用户名不能为空！'
            },
            minlength: {
                rule: 2,
                message: '最小长度为2'
            },
            maxlength: {
                rule: 6,
                message: '最大长度为6'
            }
        },
        password: {
            required: {
                rule: true,
                message: '密码不能为空！'
            },
            minlength: {
                rule: 6,
                message: '最小长度为6'
            }
        }
    }, {
        invalidHandler: function(event, validator) {
            vm.$refs.alert.show('登录失败，请输入正确的用户名和密码！');
        }
    });
}

function handleEnter(vm) {
    $('input', vm.formElem).keypress(function(e) {
        if (e.which == 13) {
            if (vm.formElem.validate().form()) {
                vm.formElem.submit();
            }
            return false;
        }
    });
}
<|endoftext|>


<commit_before>var File = require('./file');
var Cache = require('./cache');
var Module = require('./module');
var utils = require('./client/utils');

var composition_cache = Cache('compositions');

/**
 * Get module instance composition.
 */
module.exports = function (name, related, role, callback) {

    // get composition from cache
    var path = engine.paths.app_composition + name + '.json';
    var composition = composition_cache.get(path);
    if (composition) {

        if (composition === 'INVALID') {
            return callback(new Error('Invalid composition "' + name + '".'));
        }

        // check access for cached item
        if (!utils.roleAccess(composition, role)) {
            return callback(new Error('Access denied for composition "' + name + '"'));
        }

        // add related instances to composition and update cache
        if (related) {
            composition = File.relate(related, composition);
            composition_cache.set(path, composition);
        }

        return process.nextTick(callback, null, composition);
    }

    // read the composition json
    File.json(path, function (err, config) {

        // handle error
        if ((err = err || checkComposition(name, path, role, config))) {
            return callback(err);
        }

        // ensure name
        config.name = config.name || name;

        // set cache alias for entrypoints
        if (config.name !== name) {
            config._cache_alias = engine.paths.app_composition + config.name + '.json';
        }

        // merge related items to update cache on item change
        if (related) {
            config = File.relate(related, config);
        }

        // create mandatory package infos to custom module
        if (typeof config.module === 'object') {
            config.module = {composition: config.module};
            config.module.name = name;
            config.module.version = 'custom';
            config.module._id = name + '@custom';
            config.module._base = engine.repo;

            // move main out of the composition config
            if (config.module.composition.main) {
                config.module.main = config.module.composition.main;
                delete config.module.composition.main;
            }
        }

        // add composition to related items
        related = related || {};
        related.compositions = related.compositions || {};
        related.compositions[path] = true;

        Module(config.module, related, function (err, modulePackage) {

            // handle module package error
            if (err) {
                return callback(err);
            }

            // set packages server main in composition, to require server side module
            if (modulePackage.main) {
                config._main = modulePackage.main;
            }

            // prepare instance components
            if (config.client && (config.client.styles || config.client.markup)) {

                // send module id and module base
                var components = {
                    base: modulePackage._base,
                    module: modulePackage._id,
                    styles: config.client.styles,
                    markup: config.client.markup,
                    related: related
                };

                File.prepare(components, function (err, files) {

                    // update file paths in module package
                    if (files.styles) {
                        config.client.styles = files.styles;
                    }

                    if (files.markup) {
                        config.client.markup = files.markup;
                    }

                    finish(name, path, modulePackage, config, callback);
                });
                return;
            }

            finish(name, path, modulePackage, config, callback);
        });
    }, 'compositions');
};

function finish (name, path, modulePackage, config, callback) {

    // merge package data into config
    if (modulePackage.composition) {
        config = mergePackage(modulePackage.version, modulePackage.composition, config);
    }

    // save composition in cache
    composition_cache.set(path, config);

    // return composition configc
    callback(null, config);
}

/**
 * Check composition config.
 */
function checkComposition (name, path, role, config) {

    // handle not found
    if (!config) {
        return new Error('composition "' + name +'" not found.');
    }

    // check if composition has a module
    if (!config.module) {

        // save as invalid in cache
        composition_cache.set(path, 'INVALID');
        return new Error('No module info in composition "' + name + '".');
    }

    // check access
    if (!utils.roleAccess(config, role)) {

        // save access information in cache, to check access without loading the hole file again
        composition_cache.set(path, {roles: config.roles, LOAD: true});
        return new Error('Access denied: Role "' + role + '", Composition "' + name + '".');
    }

    // set composition name as custom module name
    if (typeof config.module === 'object' && !config.module.name) {
        config.module.name = config.name;
    }
}

/**
 * Merge package config into composition config.
 */
function mergePackage (version, package_instance, config) {

    // merge client related options
    if (package_instance.client) {

        // ensure client config object
        config.client = config.client || {};
        config.client.name = config.name;
        config.client.version = version;

        // set client module scripts
        if (package_instance.client.module) {
            config.client.module = package_instance.client.module;
        }

        // config
        if (package_instance.client.config) {
            for (var key in package_instance.client.config) {
                if (typeof config.client.config[key] === 'undefined') {
                    config.client.config[key] = package_instance.client.config[key];
                }
            }
        }

        // flow
        if (package_instance.client.flow) {
            config.client.flow = (config.client.flow || []).concat(package_instance.client.flow);
        }

        // markup
        if (package_instance.client.markup) {
            config.client.markup = (config.client.markup || []).concat(package_instance.client.markup);
        }

        // styles
        if (package_instance.client.styles) {
            config.client.styles = (config.client.styles || []).concat(package_instance.client.styles);
        }
    }

    // server flow
    if (package_instance.flow) {
        config.flow = (config.flow || []).concat(package_instance.flow);
    }

    // merge server config
    if (package_instance.config) {
        for (var prop in package_instance.config) {
            if (typeof config.config[prop] === 'undefined') {
                config.config[prop] = package_instance.config[prop];
            }
        }
    }

    return config;
}
<commit_msg>relate also entrypoints configured instance name<commit_after>var File = require('./file');
var Cache = require('./cache');
var Module = require('./module');
var utils = require('./client/utils');

var composition_cache = Cache('compositions');

/**
 * Get module instance composition.
 */
module.exports = function (name, related, role, callback) {

    // get composition from cache
    var path = engine.paths.app_composition + name + '.json';
    var composition = composition_cache.get(path);
    if (composition) {

        if (composition === 'INVALID') {
            return callback(new Error('Invalid composition "' + name + '".'));
        }

        // check access for cached item
        if (!utils.roleAccess(composition, role)) {
            return callback(new Error('Access denied for composition "' + name + '"'));
        }

        // add related instances to composition and update cache
        if (related) {
            composition = File.relate(related, composition);
            composition_cache.set(path, composition);
        }

        return process.nextTick(callback, null, composition);
    }

    // read the composition json
    File.json(path, function (err, config) {

        // handle error
        if ((err = err || checkComposition(name, path, role, config))) {
            return callback(err);
        }

        // ensure name
        config.name = config.name || name;

        // merge related items to update cache on item change
        if (related) {
            config = File.relate(related, config);
        }

        // create mandatory package infos to custom module
        if (typeof config.module === 'object') {
            config.module = {composition: config.module};
            config.module.name = name;
            config.module.version = 'custom';
            config.module._id = name + '@custom';
            config.module._base = engine.repo;

            // move main out of the composition config
            if (config.module.composition.main) {
                config.module.main = config.module.composition.main;
                delete config.module.composition.main;
            }
        }

        // add composition to related items
        related = related || {};
        related.compositions = related.compositions || {};
        related.compositions[path] = true;

        // set cache alias for entrypoints
        if (config.name !== name) {
            config._cache_alias = engine.paths.app_composition + config.name + '.json';
            related.compositions[config._cache_alias] = true;
        }

        Module(config.module, related, function (err, modulePackage) {

            // handle module package error
            if (err) {
                return callback(err);
            }

            // set packages server main in composition, to require server side module
            if (modulePackage.main) {
                config._main = modulePackage.main;
            }

            // prepare instance components
            if (config.client && (config.client.styles || config.client.markup)) {

                // send module id and module base
                var components = {
                    base: modulePackage._base,
                    module: modulePackage._id,
                    styles: config.client.styles,
                    markup: config.client.markup,
                    related: related
                };

                File.prepare(components, function (err, files) {

                    // update file paths in module package
                    if (files.styles) {
                        config.client.styles = files.styles;
                    }

                    if (files.markup) {
                        config.client.markup = files.markup;
                    }

                    finish(name, path, modulePackage, config, callback);
                });
                return;
            }

            finish(name, path, modulePackage, config, callback);
        });
    }, 'compositions');
};

function finish (name, path, modulePackage, config, callback) {

    // merge package data into config
    if (modulePackage.composition) {
        config = mergePackage(modulePackage.version, modulePackage.composition, config);
    }

    // save composition in cache
    composition_cache.set(path, config);

    // return composition configc
    callback(null, config);
}

/**
 * Check composition config.
 */
function checkComposition (name, path, role, config) {

    // handle not found
    if (!config) {
        return new Error('composition "' + name +'" not found.');
    }

    // check if composition has a module
    if (!config.module) {

        // save as invalid in cache
        composition_cache.set(path, 'INVALID');
        return new Error('No module info in composition "' + name + '".');
    }

    // check access
    if (!utils.roleAccess(config, role)) {

        // save access information in cache, to check access without loading the hole file again
        composition_cache.set(path, {roles: config.roles, LOAD: true});
        return new Error('Access denied: Role "' + role + '", Composition "' + name + '".');
    }

    // set composition name as custom module name
    if (typeof config.module === 'object' && !config.module.name) {
        config.module.name = config.name;
    }
}

/**
 * Merge package config into composition config.
 */
function mergePackage (version, package_instance, config) {

    // merge client related options
    if (package_instance.client) {

        // ensure client config object
        config.client = config.client || {};
        config.client.name = config.name;
        config.client.version = version;

        // set client module scripts
        if (package_instance.client.module) {
            config.client.module = package_instance.client.module;
        }

        // config
        if (package_instance.client.config) {
            for (var key in package_instance.client.config) {
                if (typeof config.client.config[key] === 'undefined') {
                    config.client.config[key] = package_instance.client.config[key];
                }
            }
        }

        // flow
        if (package_instance.client.flow) {
            config.client.flow = (config.client.flow || []).concat(package_instance.client.flow);
        }

        // markup
        if (package_instance.client.markup) {
            config.client.markup = (config.client.markup || []).concat(package_instance.client.markup);
        }

        // styles
        if (package_instance.client.styles) {
            config.client.styles = (config.client.styles || []).concat(package_instance.client.styles);
        }
    }

    // server flow
    if (package_instance.flow) {
        config.flow = (config.flow || []).concat(package_instance.flow);
    }

    // merge server config
    if (package_instance.config) {
        for (var prop in package_instance.config) {
            if (typeof config.config[prop] === 'undefined') {
                config.config[prop] = package_instance.config[prop];
            }
        }
    }

    return config;
}
<|endoftext|>