<commit_before>var _ = require('lodash');
var uploader = require('./middlewares/uploader');

var router = {
  routeMap: {}
};

/**
 * Bind one we.js route
 *
 * This function bind context loader, acl, upload and controller middlewares
 *
 * @param  {Object} we     we.js object
 * @param  {String} route  route like "get /route"
 * @param  {Object} config route configs
 */
router.bindRoute = function bindRoute(we, route, config) {
  var method, path;
  // parse method and url
  var r = route.split(' ');
  if (r.length > 1) {
    method = r[0];
    path = r[1];
  } else {
    method = 'get';
    path = r[0];
  }

  if (config.method) {
    method = config.method;
  }

  var actionFunction = '';
  // search for the controller action to bind
  if (
    we.controllers[config.controller] &&
    we.controllers[config.controller][config.action]
  ) {
    actionFunction = we.controllers[config.controller][config.action];
  } else {
    return we.log.warn('we.router.bindRoute: Unknow controller or action:', path, config);
  }

  var middlewares = [
    // bind context loader
    router.contextLoader.bind({
      config: config
    }),
    // bind acl middleware
    we.acl.canMiddleware.bind({
      config: config
    })
  ];

  we.events.emit('router:add:acl:middleware', {
    we: we, middlewares: middlewares, config: config
  });

  // bind upload  if have config and after ACL check
  if (config.upload) {
    middlewares.push(uploader(config.upload));
  }

  we.events.emit('router:before:set:controller:middleware', {we: we, middlewares: middlewares, config: config});
  // bind contoller
  middlewares.push(actionFunction);

  we.express[method](path, middlewares);

  var mapName = config.name;
  if (!mapName) {
    mapName = config.controller + '.' + config.action;
  }

  if (!we.router.routeMap[method]) we.router.routeMap[method] = {};

  // map get routes for use with link-to
  we.router.routeMap[method][mapName] = {
    map: router.parseRouteToMap(path),
    config: config
  };

  we.log.silly('Route bind:', method ,path);
}

router.parseRouteToMap = function parseRouteToMap(route) {
  return route.split('/').map(function(r, i){
    if(r[0] === ':'){
      return { name: r, i: i };
    } else {
      return r;
    }
  });
}

router.urlTo = function urlTo(name, params ,we) {
  var url = '';
  var route = {};

  if (we.router.routeMap.get[name]) {
    route = we.router.routeMap.get[name];
    var mapI = 0;
    for (var i = 0; i < route.map.length; i++) {
      // skip empty path parts linke  // and fist /
      if (!route.map[i]) continue;
      if (typeof route.map[i] == 'string') {
        url += '/' + route.map[i];
      } else if (params && params[mapI]){
        url += '/' + params[mapI];
        mapI++;
      } else {
        we.log.warn('Invalid or undefined argument: ' + params +' ', route.map[i]);
      }
    }
  } else {
    we.log.warn('Route map not found: ' + name);
  }

  if (route.map && route.map.length && !url) url = '/';

  return url;
}

/**
 * Context loader middleware
 */
router.contextLoader = function contextLoader(req, res, next) {
  // only load context one time per request
  if (req.weContextLoaded) return next();

  var we = req.getWe();
  // save current user reference
  res.locals.currentUser = req.user;
  // get route configs
  var config = this.config;
  // merge context var with route configs
  _.merge(res.locals, config);

  res.locals.metadata = {};
  // set user role names array
  req.userRoleNames = [];

  if (res.header) {
    // set header to never cache API responses for skip IE 11 cache bug
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
  }

  router.parseQuery(req, res, function(err, query) {
    res.locals.query = query;
    if (!res.locals.model ) return contextLoaded();
    // set model class
    res.locals.Model = we.db.models[res.locals.model];
    // set id if exists and not is set
    if (!res.locals.id) {
      if (req.params[res.locals.model + 'Id']) {
        res.locals.id = req.params[res.locals.model + 'Id'];
      } else if (req.params.id) {
        res.locals.id = req.params.id;
      }
    }
    // set load current record flag for single records requests
    res.locals.loadCurrentRecord = router.needLoadCurrentModel(req, res);
    // default template
    if (!res.locals.template)
      res.locals.template = res.locals.model + '/' + res.locals.action;

    // run model context loader if exists
    if (
      we.db.models[res.locals.model] &&
      typeof we.db.models[res.locals.model].contextLoader == 'function'
    ) {
      we.db.models[res.locals.model].contextLoader(req, res, function afterRunModelContextLoader(err) {
        return contextLoaded(err);
      });
    } else {
      return contextLoaded();
    }

    function contextLoaded(err) {
      req.weContextLoaded = true;

      if (err) return next(err);

      if (!req.user) {
        return next();
      }

      return req.user.getRoles().then(function (result) {
        next(null, result);
      });
    }
  });
}

/**
 * Add one route after 404 middleware
 */
router.liveBindRoute = function bindRoute(we, route, config) {
  var allRoutes = we.express._router.stack;
  we.router.bindRoute(we, route, config);
  // push this new route to after 404 and error middlewares
  allRoutes.splice(allRoutes.length-3, 0, allRoutes.splice(allRoutes.length-1, 1)[0]);
}

// router.bindShadownRoutes = function bindShadownRoutes(we, cb) {
//   if (!we.db.models || !we.controllers) return cb();

//   var modelNames = Object.keys(we.db.models);

//   var shadownRoutesToBind = [];
//   for (var i = modelNames.length - 1; i >= 0; i--) {
//     if (router.haveShadownRoute(we,  modelNames[i])) {
//       shadownRoutesToBind.push(modelNames[i]);
//     }
//   }

//   shadownRoutesToBind.forEach(function(model) {
//     // get / find
//     router.bindShadownFindRoute(we, model);
//     // post / create
//     router.bindShadownCreateRoute(we, model);
//     // get :id / findOne
//     router.bindShadownFindOneRoute(we, model);
//     // put / update
//     router.bindShadownUpdateRoute(we, model);
//     // delete / destroy
//     router.bindShadownDeleteRoute(we, model);
//   });

//   cb();
// }

/**
 * Check if one model have shadownRoutes
 *
 * @param  {Object} we        We.js object
 * @param  {String} modelName
 * @return {Boolean}
 */
router.haveShadownRoute = function haveShadownRoute(we, modelName) {
  if ( !we.controllers[modelName] || !we.db.models[modelName] ) return false;
  if ( we.controllers[modelName] &&
    we.controllers[modelName]._config &&
    (we.controllers[modelName]._config.shadownRoutes === false)
  ) {
    return false;
  }
  return true;
}

// -- wejs shadown routes bind functions, override if need something diferent

/**
 * Bind find shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownFindRoute = function bindShadownFindRoute(we, model) {
  var configs  = {
    action: 'find',
    model: model,
    controller: model
  };

  var route = '/' + model;

  we.router.bindRoute(we, route, configs);
}

/**
 * Bind create shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownCreateRoute = function bindShadownCreateRoute(we, model) {
  var configs  = {
    method: 'post',
    action: 'create',
    model: model,
    controller: model
  };

  var route = 'post /' + model;

  we.router.bindRoute(we, route, configs);
}

router.bindShadownGenericRoute = function bindShadownGenericRoute(we, model, action, method) {
  var configs  = {
    method: method,
    action: action,
    model: model,
    controller: model
  };

  var route = method + ' /' + model + '/:id';

  we.router.bindRoute(we, route, configs);
}

/**
 * Bind findOne shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownFindOneRoute = function bindShadownFindOneRoute(we, model) {
  router.bindShadownGenericRoute(we, model, 'findOne', 'get');
}

/**
 * Bind update shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownUpdateRoute = function bindShadownUpdateRoute(we, model) {
  router.bindShadownGenericRoute(we, model, 'update', 'put');
}

/**
 * Bind delete shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownDeleteRoute = function bindShadownDeleteRoute(we, model) {
  router.bindShadownGenericRoute(we, model, 'destroy', 'delete');
}

/**
 * Bind updateAtribute shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownUpdateAtributeRoute = function bindShadownUpdateAtributeRoute(we, model) {
  var configs  = {
    method: 'put',
    action: 'updateAtribute',
    model: model,
    controller: model
  };

  var route = 'put /' + model + '/:id/:atribute';
  we.router.bindRoute(we, route, configs);
}

router.singleRecordActions = [
  'findOne', 'update', 'destroy', 'updateAttribute', 'deleteAttribute', 'addRecord', 'removeRecord', 'getRecord'
];

router.needLoadCurrentModel = function needLoadCurrentModel(req, res) {
  if (res.locals.loadRecord === false) return false;
  if (res.locals.loadRecord === true) return true;

  if (!res.locals.action) return false;

  if ( router.singleRecordActions.indexOf( res.locals.action ) >-1 ) {
    return true;
  }
}

/**
 * Parse query for current request
 */
router.parseQuery = function parseQuery(req, res, next) {
  var we = req.getWe();
  var query = {
    // set subQuery to false by default
    subQuery: false,
    where: {}
  };

  if (res.locals.skipParseQuery) return query;

  if (req.query.offset) {
    query.offset = req.query.offset;
  } else if (req.query.skip) {
    query.offset = req.query.skip;
  }

  if (req.query.limit) {
    query.limit = req.query.limit;
  }

  if (req.query.order) {
    query.order = res.locals.model + '.' +req.query.order;
  } else if (req.query.sort) {
    query.order = res.locals.model + '.' +req.query.sort;
  }

  query.include = [{ all: true,  attributes: ['id'] }];

  // parse where
  try {
    if (req.query.where) query.where = JSON.parse( req.query.where );
  } catch(e) {
    we.log.warn('req.query.where have a invalid format', req.query.where);
    return res.badRequest();
  }

  // parse associations
  if (res.locals.model && we.db.models[res.locals.model]) {
    // we.log.info('Models>',we.db.models[res.locals.model]);

    if (we.db.models[res.locals.model].associations) {
      var assocFields = Object.keys(we.db.models[res.locals.model].associations);
      var identifier;
      for (var i = assocFields.length - 1; i >= 0; i--) {
        identifier = we.db.models[res.locals.model].associations[assocFields[i]].identifier;
        // parse in body params
        if (req.body && req.body[assocFields[i]]) {
          req.body[identifier] = req.body[assocFields[i]];
        }
        // parse in where
        if (query.where && query.where[assocFields[i]]) {
          query.where[identifier] = query.where[assocFields[i]];
        }
      }
    }
  }

  return next(null, query);
}

module.exports = router;
<commit_msg>remove uneed cache header<commit_after>var _ = require('lodash');
var uploader = require('./middlewares/uploader');

var router = {
  routeMap: {}
};

/**
 * Bind one we.js route
 *
 * This function bind context loader, acl, upload and controller middlewares
 *
 * @param  {Object} we     we.js object
 * @param  {String} route  route like "get /route"
 * @param  {Object} config route configs
 */
router.bindRoute = function bindRoute(we, route, config) {
  var method, path;
  // parse method and url
  var r = route.split(' ');
  if (r.length > 1) {
    method = r[0];
    path = r[1];
  } else {
    method = 'get';
    path = r[0];
  }

  if (config.method) {
    method = config.method;
  }

  var actionFunction = '';
  // search for the controller action to bind
  if (
    we.controllers[config.controller] &&
    we.controllers[config.controller][config.action]
  ) {
    actionFunction = we.controllers[config.controller][config.action];
  } else {
    return we.log.warn('we.router.bindRoute: Unknow controller or action:', path, config);
  }

  var middlewares = [
    // bind context loader
    router.contextLoader.bind({
      config: config
    }),
    // bind acl middleware
    we.acl.canMiddleware.bind({
      config: config
    })
  ];

  we.events.emit('router:add:acl:middleware', {
    we: we, middlewares: middlewares, config: config
  });

  // bind upload  if have config and after ACL check
  if (config.upload) {
    middlewares.push(uploader(config.upload));
  }

  we.events.emit('router:before:set:controller:middleware', {we: we, middlewares: middlewares, config: config});
  // bind contoller
  middlewares.push(actionFunction);

  we.express[method](path, middlewares);

  var mapName = config.name;
  if (!mapName) {
    mapName = config.controller + '.' + config.action;
  }

  if (!we.router.routeMap[method]) we.router.routeMap[method] = {};

  // map get routes for use with link-to
  we.router.routeMap[method][mapName] = {
    map: router.parseRouteToMap(path),
    config: config
  };

  we.log.silly('Route bind:', method ,path);
}

router.parseRouteToMap = function parseRouteToMap(route) {
  return route.split('/').map(function(r, i){
    if(r[0] === ':'){
      return { name: r, i: i };
    } else {
      return r;
    }
  });
}

router.urlTo = function urlTo(name, params ,we) {
  var url = '';
  var route = {};

  if (we.router.routeMap.get[name]) {
    route = we.router.routeMap.get[name];
    var mapI = 0;
    for (var i = 0; i < route.map.length; i++) {
      // skip empty path parts linke  // and fist /
      if (!route.map[i]) continue;
      if (typeof route.map[i] == 'string') {
        url += '/' + route.map[i];
      } else if (params && params[mapI]){
        url += '/' + params[mapI];
        mapI++;
      } else {
        we.log.warn('Invalid or undefined argument: ' + params +' ', route.map[i]);
      }
    }
  } else {
    we.log.warn('Route map not found: ' + name);
  }

  if (route.map && route.map.length && !url) url = '/';

  return url;
}

/**
 * Context loader middleware
 */
router.contextLoader = function contextLoader(req, res, next) {
  // only load context one time per request
  if (req.weContextLoaded) return next();

  var we = req.getWe();
  // save current user reference
  res.locals.currentUser = req.user;
  // get route configs
  var config = this.config;
  // merge context var with route configs
  _.merge(res.locals, config);

  res.locals.metadata = {};
  // set user role names array
  req.userRoleNames = [];

  router.parseQuery(req, res, function(err, query) {
    res.locals.query = query;
    if (!res.locals.model ) return contextLoaded();
    // set model class
    res.locals.Model = we.db.models[res.locals.model];
    // set id if exists and not is set
    if (!res.locals.id) {
      if (req.params[res.locals.model + 'Id']) {
        res.locals.id = req.params[res.locals.model + 'Id'];
      } else if (req.params.id) {
        res.locals.id = req.params.id;
      }
    }
    // set load current record flag for single records requests
    res.locals.loadCurrentRecord = router.needLoadCurrentModel(req, res);
    // default template
    if (!res.locals.template)
      res.locals.template = res.locals.model + '/' + res.locals.action;

    // run model context loader if exists
    if (
      we.db.models[res.locals.model] &&
      typeof we.db.models[res.locals.model].contextLoader == 'function'
    ) {
      we.db.models[res.locals.model].contextLoader(req, res, function afterRunModelContextLoader(err) {
        return contextLoaded(err);
      });
    } else {
      return contextLoaded();
    }

    function contextLoaded(err) {
      req.weContextLoaded = true;

      if (err) return next(err);

      if (!req.user) {
        return next();
      }

      return req.user.getRoles().then(function (result) {
        next(null, result);
      });
    }
  });
}

/**
 * Add one route after 404 middleware
 */
router.liveBindRoute = function bindRoute(we, route, config) {
  var allRoutes = we.express._router.stack;
  we.router.bindRoute(we, route, config);
  // push this new route to after 404 and error middlewares
  allRoutes.splice(allRoutes.length-3, 0, allRoutes.splice(allRoutes.length-1, 1)[0]);
}

// router.bindShadownRoutes = function bindShadownRoutes(we, cb) {
//   if (!we.db.models || !we.controllers) return cb();

//   var modelNames = Object.keys(we.db.models);

//   var shadownRoutesToBind = [];
//   for (var i = modelNames.length - 1; i >= 0; i--) {
//     if (router.haveShadownRoute(we,  modelNames[i])) {
//       shadownRoutesToBind.push(modelNames[i]);
//     }
//   }

//   shadownRoutesToBind.forEach(function(model) {
//     // get / find
//     router.bindShadownFindRoute(we, model);
//     // post / create
//     router.bindShadownCreateRoute(we, model);
//     // get :id / findOne
//     router.bindShadownFindOneRoute(we, model);
//     // put / update
//     router.bindShadownUpdateRoute(we, model);
//     // delete / destroy
//     router.bindShadownDeleteRoute(we, model);
//   });

//   cb();
// }

/**
 * Check if one model have shadownRoutes
 *
 * @param  {Object} we        We.js object
 * @param  {String} modelName
 * @return {Boolean}
 */
router.haveShadownRoute = function haveShadownRoute(we, modelName) {
  if ( !we.controllers[modelName] || !we.db.models[modelName] ) return false;
  if ( we.controllers[modelName] &&
    we.controllers[modelName]._config &&
    (we.controllers[modelName]._config.shadownRoutes === false)
  ) {
    return false;
  }
  return true;
}

// -- wejs shadown routes bind functions, override if need something diferent

/**
 * Bind find shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownFindRoute = function bindShadownFindRoute(we, model) {
  var configs  = {
    action: 'find',
    model: model,
    controller: model
  };

  var route = '/' + model;

  we.router.bindRoute(we, route, configs);
}

/**
 * Bind create shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownCreateRoute = function bindShadownCreateRoute(we, model) {
  var configs  = {
    method: 'post',
    action: 'create',
    model: model,
    controller: model
  };

  var route = 'post /' + model;

  we.router.bindRoute(we, route, configs);
}

router.bindShadownGenericRoute = function bindShadownGenericRoute(we, model, action, method) {
  var configs  = {
    method: method,
    action: action,
    model: model,
    controller: model
  };

  var route = method + ' /' + model + '/:id';

  we.router.bindRoute(we, route, configs);
}

/**
 * Bind findOne shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownFindOneRoute = function bindShadownFindOneRoute(we, model) {
  router.bindShadownGenericRoute(we, model, 'findOne', 'get');
}

/**
 * Bind update shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownUpdateRoute = function bindShadownUpdateRoute(we, model) {
  router.bindShadownGenericRoute(we, model, 'update', 'put');
}

/**
 * Bind delete shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownDeleteRoute = function bindShadownDeleteRoute(we, model) {
  router.bindShadownGenericRoute(we, model, 'destroy', 'delete');
}

/**
 * Bind updateAtribute shadown route
 *
 * @param  {object} we      we.js object
 * @param  {string} model   model Name, same as controller name
 */
router.bindShadownUpdateAtributeRoute = function bindShadownUpdateAtributeRoute(we, model) {
  var configs  = {
    method: 'put',
    action: 'updateAtribute',
    model: model,
    controller: model
  };

  var route = 'put /' + model + '/:id/:atribute';
  we.router.bindRoute(we, route, configs);
}

router.singleRecordActions = [
  'findOne', 'update', 'destroy', 'updateAttribute', 'deleteAttribute', 'addRecord', 'removeRecord', 'getRecord'
];

router.needLoadCurrentModel = function needLoadCurrentModel(req, res) {
  if (res.locals.loadRecord === false) return false;
  if (res.locals.loadRecord === true) return true;

  if (!res.locals.action) return false;

  if ( router.singleRecordActions.indexOf( res.locals.action ) >-1 ) {
    return true;
  }
}

/**
 * Parse query for current request
 */
router.parseQuery = function parseQuery(req, res, next) {
  var we = req.getWe();
  var query = {
    // set subQuery to false by default
    subQuery: false,
    where: {}
  };

  if (res.locals.skipParseQuery) return query;

  if (req.query.offset) {
    query.offset = req.query.offset;
  } else if (req.query.skip) {
    query.offset = req.query.skip;
  }

  if (req.query.limit) {
    query.limit = req.query.limit;
  }

  if (req.query.order) {
    query.order = res.locals.model + '.' +req.query.order;
  } else if (req.query.sort) {
    query.order = res.locals.model + '.' +req.query.sort;
  }

  query.include = [{ all: true,  attributes: ['id'] }];

  // parse where
  try {
    if (req.query.where) query.where = JSON.parse( req.query.where );
  } catch(e) {
    we.log.warn('req.query.where have a invalid format', req.query.where);
    return res.badRequest();
  }

  // parse associations
  if (res.locals.model && we.db.models[res.locals.model]) {
    // we.log.info('Models>',we.db.models[res.locals.model]);

    if (we.db.models[res.locals.model].associations) {
      var assocFields = Object.keys(we.db.models[res.locals.model].associations);
      var identifier;
      for (var i = assocFields.length - 1; i >= 0; i--) {
        identifier = we.db.models[res.locals.model].associations[assocFields[i]].identifier;
        // parse in body params
        if (req.body && req.body[assocFields[i]]) {
          req.body[identifier] = req.body[assocFields[i]];
        }
        // parse in where
        if (query.where && query.where[assocFields[i]]) {
          query.where[identifier] = query.where[assocFields[i]];
        }
      }
    }
  }

  return next(null, query);
}

module.exports = router;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// http://www.discoversdk.com/blog/grid-control-with-different-javascript-frameworks

foam.CLASS({
  package: 'com.google.foam.demos.grid',
  name: 'Resource',

  tableProperties: [ 'description', 'url' ],

  properties: [
    { name: 'id', hidden: true },
    { class: 'String', name: 'description', width: 25, label: 'Description: ' },
    { class: 'String', name: 'url',         width: 50, label: 'URL: ' }
  ]
});

foam.CLASS({
  package: 'com.google.foam.demos.grid',
  name: 'Controller',
  extends: 'foam.u2.Controller',

  requires: [
    'foam.u2.DetailView',
    'foam.u2.TableView',
    'com.google.foam.demos.grid.Resource'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function() {/*
        body {
          font-family:Arial;
          color:#3a3a3a;
        }
        ^list {
          border:none;
          text-align:left;
          margin-bottom:20px;
        }
        ^list tr th {
          background-color: #3b97d3;
          color: #fff;
          padding: 5px;
          border-right: solid 1px #3b97d3;
          border-left: solid 1px #fff;
        }
        ^list tr th:first-child {
          border-left: solid 1px #3b97d3;
        }
        ^list tr td {
          padding:5px;
          padding: 5px;
          border-right: solid 1px #d4d4d4;
        }
        ^list tr td:first-child {
          border-left: solid 1px #d4d4d4;
        }
        ^list tr:last-child td {
          border-bottom: solid 1px #d4d4d4;
        }
        input[type="text"] {
          height:20px;
          font-size:14px;
        }
        ^ .foam.u2-ActionView {
          vertical-align: bottom;
        }
        button, ^ .foam-u2-ActionView {
          border:none;
          color:#fff;
          background:#3b97d3;
          padding:0px 10px;
          height:26px;
          display:inline-block;
          line-height:26px;
          text-decoration:none;
          border-radius:3px;
          -moz-border-radius:3px;
          -webkit-border-radius:3px;
          cursor:pointer;
        }
        ^ button:hover {
          background-color:#73c7ff;
        }
        ^ .foam-u2-DetailView tr {
          display: inline;
          font-size: 16px;
        }
      */}
    })
  ],

  properties: [
    {
      name: 'dao',
       view: { class: 'foam.u2.TableView', of: com.google.foam.demos.grid.Resource }
//       view: { class: 'foam.u2.DAOList', of: com.google.foam.demos.grid.Resource, rowView: 'com.google.foam.demos.grid.ResourceView' }
    },
    {
      name: 'person',
      view: 'foam.u2.DetailView',
      factory: function() { return this.Resource.create(); }
    }
  ],

  methods: [
    function initE() {
      var dao = this.dao;

      this.
        cssClass(this.myCls()).
        start('h3').add('Add Resources').end().

        // Use this block to create the form manually
        /*
        add('Description: ').
        start(this.person.DESCRIPTION, {data$: this.person.description$}).end().
        add(' URL: ').
        start(this.person.URL,         {data$: this.person.url$}).end().
        */

        // Or this to use a DetailView
        start('span').style({display: "flex"}).
          add(this.PERSON).
          add(this.ADD_RESOURCE).
        end().

        start('h3').add('List of Resources').end().

        // Use a Standard TableView
        // add(this.DAO).

        // Or make one manually
        start('table').
          cssClass(this.myCls('list')).
          start('tr').
            start('th').add('Description').end().
            start('th').add('URL').end().
            start('th').end().
          end().
          select(this.dao, function(r) {
            return this.E('tr').
              start('td').
                start('div').add(r.DESCRIPTION).end().
              end().
              start('td').
                start('div').add(r.URL).end().
              end().
              start('td').
                start('button').on('click', function() { dao.remove(r); }).add('Remove').end().
              end();
          }, true).
        end().

        add(this.SHOW);
    }
  ],

  actions: [
    {
      name: 'addResource',
      label: 'Add',
      code: function() {
        var p = this.person;
        // TODO: remove clone()
        this.dao.put(p.clone());
        p.id = p.description = p.url = undefined;
      }
    },
    {
      name: 'show',
      code: function() {
        console.log('show');
        this.dao.select().then(function(s) {
          window.alert(foam.json.Outputer.create({
            pretty: false,
            outputClassNames: false
          }).stringify(s.a));
        });
      }
    },
    {
      name: 'deleteItem',
      label: 'Delete',
      code: function() {
      }
    }
  ]
});

// Didn't specify view for dao
// Didn't specify 'of' for TableView
// Invalid names in tableProperties:
// added invalid action name, no error
// clone on DAO.put
// width support is missing
// DAO.put(null) didn't give meaningful error
// Typo causing null to pass to Element.add()
// Problems getting rid of CSS
// Set Slot to non Slot
<commit_msg>Made Grid demo use new DetailView.config property.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// http://www.discoversdk.com/blog/grid-control-with-different-javascript-frameworks

foam.CLASS({
  package: 'com.google.foam.demos.grid',
  name: 'Resource',

  tableProperties: [ 'description', 'url' ],

  properties: [
    { name: 'id', hidden: true },
    { class: 'String', name: 'description', width: 25 },
    { class: 'String', name: 'url',         width: 50 }
  ]
});

foam.CLASS({
  package: 'com.google.foam.demos.grid',
  name: 'Controller',
  extends: 'foam.u2.Controller',

  requires: [
    'foam.u2.DetailView',
    'foam.u2.TableView',
    'com.google.foam.demos.grid.Resource'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function() {/*
        body {
          font-family:Arial;
          color:#3a3a3a;
        }
        ^list {
          border:none;
          text-align:left;
          margin-bottom:20px;
        }
        ^list tr th {
          background-color: #3b97d3;
          color: #fff;
          padding: 5px;
          border-right: solid 1px #3b97d3;
          border-left: solid 1px #fff;
        }
        ^list tr th:first-child {
          border-left: solid 1px #3b97d3;
        }
        ^list tr td {
          padding:5px;
          padding: 5px;
          border-right: solid 1px #d4d4d4;
        }
        ^list tr td:first-child {
          border-left: solid 1px #d4d4d4;
        }
        ^list tr:last-child td {
          border-bottom: solid 1px #d4d4d4;
        }
        input[type="text"] {
          height:20px;
          font-size:14px;
        }
        ^ .foam.u2-ActionView {
          vertical-align: bottom;
        }
        button, ^ .foam-u2-ActionView {
          border:none;
          color:#fff;
          background:#3b97d3;
          padding:0px 10px;
          height:26px;
          display:inline-block;
          line-height:26px;
          text-decoration:none;
          border-radius:3px;
          -moz-border-radius:3px;
          -webkit-border-radius:3px;
          cursor:pointer;
        }
        ^ button:hover {
          background-color:#73c7ff;
        }
        ^ .foam-u2-DetailView tr {
          display: inline;
          font-size: 16px;
        }
      */}
    })
  ],

  properties: [
    {
      name: 'dao',
       view: { class: 'foam.u2.TableView', of: com.google.foam.demos.grid.Resource }
//       view: { class: 'foam.u2.DAOList', of: com.google.foam.demos.grid.Resource, rowView: 'com.google.foam.demos.grid.ResourceView' }
    },
    {
      name: 'person',
      view: {
        class: 'foam.u2.DetailView',
        config: {
          url:         { label: 'URL:' },
          description: { label: 'Description:' }
        }
      },
      factory: function() { return this.Resource.create(); }
    }
  ],

  methods: [
    function initE() {
      var dao = this.dao;

      this.
        cssClass(this.myCls()).
        start('h3').add('Add Resources').end().

        // Use this block to create the form manually
        /*
        add('Description: ').
        start(this.person.DESCRIPTION, {data$: this.person.description$}).end().
        add(' URL: ').
        start(this.person.URL,         {data$: this.person.url$}).end().
        */

        // Or this to use a DetailView
        start('span').style({display: "flex"}).
          add(this.PERSON).
          add(this.ADD_RESOURCE).
        end().

        start('h3').add('List of Resources').end().

        // Use a Standard TableView
        // add(this.DAO).

        // Or make one manually
        start('table').
          cssClass(this.myCls('list')).
          start('tr').
            start('th').add('Description').end().
            start('th').add('URL').end().
            start('th').end().
          end().
          select(this.dao, function(r) {
            return this.E('tr').
              start('td').
                start('div').add(r.DESCRIPTION).end().
              end().
              start('td').
                start('div').add(r.URL).end().
              end().
              start('td').
                start('button').on('click', function() { dao.remove(r); }).add('Remove').end().
              end();
          }, true).
        end().

        add(this.SHOW);
    }
  ],

  actions: [
    {
      name: 'addResource',
      label: 'Add',
      code: function() {
        var p = this.person;
        // TODO: remove clone()
        this.dao.put(p.clone());
        p.id = p.description = p.url = undefined;
      }
    },
    {
      name: 'show',
      code: function() {
        console.log('show');
        this.dao.select().then(function(s) {
          window.alert(foam.json.Outputer.create({
            pretty: false,
            outputClassNames: false
          }).stringify(s.a));
        });
      }
    },
    {
      name: 'deleteItem',
      label: 'Delete',
      code: function() {
      }
    }
  ]
});

// Didn't specify view for dao
// Didn't specify 'of' for TableView
// Invalid names in tableProperties:
// added invalid action name, no error
// clone on DAO.put
// width support is missing
// DAO.put(null) didn't give meaningful error
// Typo causing null to pass to Element.add()
// Problems getting rid of CSS
// Set Slot to non Slot
<|endoftext|>


<commit_before>'use strict';

const rethinkDB = require('rethinkdb');

const log = require('./../server/log');

export class Location {
  constructor(conn, locationSize, locationId, dungeonBP) {
    this.conn = conn;
    this.locationSize = locationSize;
    this.locationId = locationId;
    this.dungeonBP = dungeonBP;

    this.locationMap = [];
    for (let i = 0; i < locationSize; i++) this.locationMap.push([]);
  }

  createTable() {
    rethinkDB
      .tableCreate(this.locationId)
      .run(this.conn, (err) => {
        if (err) throw err;

        log.info(`Table for ${this.locationId} created`);
        this.writeNewLocationMap();
      });
  }

  writeNewLocationMap() {
    let buffer = [];

    for (let y = 0; y < this.locationMap.length; y++) {
      let mapRow = this.locationMap[y];

      for (let x = 0; x < mapRow.length; x++) {
        let elem = {};
        elem['x'] = x;
        elem['y'] = y;
        elem['type'] = mapRow[x];
        buffer.push(elem);
      }
    }

    rethinkDB
      .table(this.locationId)
      .insert(buffer)
      .run(this.conn, (err, res) => {
        if (err) throw err;

        log.info(`Location map done. We inserted ${res['inserted']} elements to ${this.locationId}`);
        log.info(`Let's create the index for ${this.locationId}!`);

        rethinkDB
          .table(this.locationId)
          .indexCreate('coord', [rethinkDB.row('x'), rethinkDB.row('y')])
          .run(this.conn, (err) => {
            if (err) throw err;

            rethinkDB
              .table(this.locationId)
              .indexWait('coord')
              .run(this.conn, (err) => {
                if (err) throw err;

                log.info(`Index for ${this.locationId} created!`);
              });
          });
      });
  }
}
<commit_msg>Add log.error for process of table creation<commit_after>'use strict';

const rethinkDB = require('rethinkdb');

const log = require('./../server/log');

export class Location {
  constructor(conn, locationSize, locationId, dungeonBP) {
    this.conn = conn;
    this.locationSize = locationSize;
    this.locationId = locationId;
    this.dungeonBP = dungeonBP;

    this.locationMap = [];
    for (let i = 0; i < locationSize; i++) this.locationMap.push([]);
  }

  createTable() {
    rethinkDB
      .tableCreate(this.locationId)
      .run(this.conn, (err) => {
        if (err) {
          log.error(`Table for ${this.locationId} not created`);
          throw err;
        }

        log.info(`Table for ${this.locationId} created`);
        this.writeNewLocationMap();
      });
  }

  writeNewLocationMap() {
    let buffer = [];

    for (let y = 0; y < this.locationMap.length; y++) {
      let mapRow = this.locationMap[y];

      for (let x = 0; x < mapRow.length; x++) {
        let elem = {};
        elem['x'] = x;
        elem['y'] = y;
        elem['type'] = mapRow[x];
        buffer.push(elem);
      }
    }

    rethinkDB
      .table(this.locationId)
      .insert(buffer)
      .run(this.conn, (err, res) => {
        if (err) {
          log.error(`Data for ${this.locationId} not inserted`);
          throw err;
        }

        log.info(`Location map done. We inserted ${res['inserted']} elements to ${this.locationId}`);
        log.info(`Let's create the index for ${this.locationId}!`);

        rethinkDB
          .table(this.locationId)
          .indexCreate('coord', [rethinkDB.row('x'), rethinkDB.row('y')])
          .run(this.conn, (err) => {
            if (err) {
              log.error(`Index for ${this.locationId} not created`);
              throw err;
            }

            rethinkDB
              .table(this.locationId)
              .indexWait('coord')
              .run(this.conn, (err) => {
                if (err) throw err;

                log.info(`Index for ${this.locationId} created!`);
              });
          });
      });
  }
}
<|endoftext|>


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

w.info('Found %s at %s', 'error', new Date());
w.info('Found %s at %s', 'error', new Error('chill winston'));
w.info('Found %s at %s', 'error', /WUT/);
w.info('Found %s at %s', 'error', true);
w.info('Found %s at %s', 'error', 100.00);
w.info('Found %s at %s', 'error', ['1, 2, 3']);
// prints "Found error at %s"

// console.log('Found %s at %s', 'error', new Date())
// prints "Found error at Tue Jan 20 2015 10:14:26 GMT-0800 (PST)"
<commit_msg>[fix doc] Update string interpolation example.<commit_after>const { createLogger, format, transports } = require('../');
const logger = createLogger({
  format: format.combine(
    format.splat(),
    format.simple()
  ),
  transports: [
    new transports.Console()
  ]
});

// info: test message my string {}
logger.log('info', 'test message %s', 'my string');

// info: test message my 123 {}
logger.log('info', 'test message %d', 123);

// info: test message first second {number: 123}
logger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 });

// prints "Found error at %s"
logger.info('Found %s at %s', 'error', new Date());
logger.info('Found %s at %s', 'error', new Error('chill winston'));
logger.info('Found %s at %s', 'error', /WUT/);
logger.info('Found %s at %s', 'error', true);
logger.info('Found %s at %s', 'error', 100.00);
logger.info('Found %s at %s', 'error', ['1, 2, 3']);

<|endoftext|>


<commit_before>const { stripIndents, oneLine } = require('common-tags')
const Command = require('../Command')
const Util = require('../../Util')
const VirtualGroups = require('../../VirtualGroups.js')
const config = require('../../data/client.json')

module.exports =
class BindGroupCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'bindrank',
      properName: 'BindRank',
      aliases: ['roverbindgrouprank', 'bindgroup', 'bindgrouprank', 'roverbind', 'bind'],
      description: '`<"Discord Role"> <group_id>:<rank_id>` Binds Roblox group membership or group rank to a Discord role. Example: `!BindRank "High Rank" 372372:150,200-255` or `!BindRank "Group Member" 372372` or `!BindRank "Faction Leader" 372372:255 3723293:255 584584:250-255` or `!BindRank "DevForum Member" DevForum`. For help see https://github.com/evaera/RoVer#setting-up-roles-for-roblox-group-members-and-group-ranks',

      args: [
        {
          key: 'role',
          prompt: 'Discord Role to bind:',
          type: 'role'
        },
        {
          key: 'groups',
          prompt: 'Group ranks to bind:',
          type: 'string',
          infinite: true
        }
      ]
    })
  }

  async fn (msg, args) {
    if (this.server.ongoingSettingsUpdate) return msg.reply('Server settings are currently being saved - please try again in a few moments.')
    if (config.maxServerBindings && this.server.getSetting('groupRankBindings').length > config.maxServerBindings) {
      return msg.reply('This server has exceeded the maximum amount of allowed role bindings.\n\nTo bind an unlimited number of roles, please consider a $6 monthly donation for RoVer Plus:\n <https://www.patreon.com/erynlynn>.\n\n*Please be aware that this is a temporary restriction as part of an effort to reduce resource consumption. In the future, more role bindings will be available for free.*')
    }

    const binding = {}

    if (this.server.isRoleInUse(args.role.id)) {
      msg.reply(
        oneLine`:no_entry_sign: That role is already in use. (verified role, not verified role, or from a group binding).
        Run \`${msg.guild.commandPrefix}bindings\` to see all role bindings.`
      )
      return
    }

    if (args.role.name === '@everyone' || role.name === '@here') return msg.reply('You are unable to bind this role.')

    binding.role = args.role.id
    binding.groups = []

    for (const groupString of args.groups) {
      const [groupId, ranksString] = groupString.split(':')
      const group = { id: groupId }

      if (groupId.match(/[^\d]/) && !VirtualGroups[groupId]) {
        return msg.reply(
          stripIndents`:no_entry_sign: You have attempted to bind an invalid group (\`${groupId}\`). Possible causes:

          - You may have forgotten to put the Discord role name in quotation marks when it has spaces

          - You may have used invalid syntax: must match pattern "group_id:rank", "group_id:rank,rank,rank", or "group_id:rank-rank". (Pattern uses colons \`:\`, not semicolons \`;\`.)

          - You may have attempted to bind an invalid group id. Group IDs must be a whole number or be a valid VirtualGroup name.`
        )
      }

      if (ranksString != null) {
        const ranks = []
        const unparsedRanks = ranksString.split(',')
        for (const rank of unparsedRanks) {
          const rangeMatch = rank.match(/(\d+)-(\d+)/)
          const rankNumber = parseInt(rank, 10)

          if (rangeMatch) {
            const start = parseInt(rangeMatch[1], 10)
            const stop = parseInt(rangeMatch[2], 10)

            if (start && stop) {
              for (let i = start; i <= stop; i++) {
                ranks.push(i)
              }
            }
          } else if (rankNumber != null) {
            ranks.push(rankNumber)
          }
        }
        group.ranks = ranks
      } else if (!groupId.match(/[a-z]/i)) {
        group.ranks = []
        for (let i = 1; i <= 255; i++) {
          group.ranks.push(i)
        }
      } else {
        group.ranks = []
      }

      binding.groups.push(group)
    }

    // Delete any previous binding with that role.
    this.server.deleteGroupRankBinding(binding.role)

    // Add the new binding.
    const serverBindings = this.server.getSetting('groupRankBindings')
    serverBindings.push(binding)
    this.server.setSetting('groupRankBindings', serverBindings)

    let bindingSuccessMessage = `:white_check_mark: Successfully bound role "${args.role.name}".\`\`\`markdown\n`

    bindingSuccessMessage += Util.getBindingText(binding)

    bindingSuccessMessage += '```\n'

    msg.reply(bindingSuccessMessage)
  }
}
<commit_msg>Fix typo<commit_after>const { stripIndents, oneLine } = require('common-tags')
const Command = require('../Command')
const Util = require('../../Util')
const VirtualGroups = require('../../VirtualGroups.js')
const config = require('../../data/client.json')

module.exports =
class BindGroupCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'bindrank',
      properName: 'BindRank',
      aliases: ['roverbindgrouprank', 'bindgroup', 'bindgrouprank', 'roverbind', 'bind'],
      description: '`<"Discord Role"> <group_id>:<rank_id>` Binds Roblox group membership or group rank to a Discord role. Example: `!BindRank "High Rank" 372372:150,200-255` or `!BindRank "Group Member" 372372` or `!BindRank "Faction Leader" 372372:255 3723293:255 584584:250-255` or `!BindRank "DevForum Member" DevForum`. For help see https://github.com/evaera/RoVer#setting-up-roles-for-roblox-group-members-and-group-ranks',

      args: [
        {
          key: 'role',
          prompt: 'Discord Role to bind:',
          type: 'role'
        },
        {
          key: 'groups',
          prompt: 'Group ranks to bind:',
          type: 'string',
          infinite: true
        }
      ]
    })
  }

  async fn (msg, args) {
    if (this.server.ongoingSettingsUpdate) return msg.reply('Server settings are currently being saved - please try again in a few moments.')
    if (config.maxServerBindings && this.server.getSetting('groupRankBindings').length > config.maxServerBindings) {
      return msg.reply('This server has exceeded the maximum amount of allowed role bindings.\n\nTo bind an unlimited number of roles, please consider a $6 monthly donation for RoVer Plus:\n <https://www.patreon.com/erynlynn>.\n\n*Please be aware that this is a temporary restriction as part of an effort to reduce resource consumption. In the future, more role bindings will be available for free.*')
    }

    const binding = {}

    if (this.server.isRoleInUse(args.role.id)) {
      msg.reply(
        oneLine`:no_entry_sign: That role is already in use. (verified role, not verified role, or from a group binding).
        Run \`${msg.guild.commandPrefix}bindings\` to see all role bindings.`
      )
      return
    }

    if (args.role.name === '@everyone' || args.role.name === '@here') return msg.reply('You are unable to bind this role.')

    binding.role = args.role.id
    binding.groups = []

    for (const groupString of args.groups) {
      const [groupId, ranksString] = groupString.split(':')
      const group = { id: groupId }

      if (groupId.match(/[^\d]/) && !VirtualGroups[groupId]) {
        return msg.reply(
          stripIndents`:no_entry_sign: You have attempted to bind an invalid group (\`${groupId}\`). Possible causes:

          - You may have forgotten to put the Discord role name in quotation marks when it has spaces

          - You may have used invalid syntax: must match pattern "group_id:rank", "group_id:rank,rank,rank", or "group_id:rank-rank". (Pattern uses colons \`:\`, not semicolons \`;\`.)

          - You may have attempted to bind an invalid group id. Group IDs must be a whole number or be a valid VirtualGroup name.`
        )
      }

      if (ranksString != null) {
        const ranks = []
        const unparsedRanks = ranksString.split(',')
        for (const rank of unparsedRanks) {
          const rangeMatch = rank.match(/(\d+)-(\d+)/)
          const rankNumber = parseInt(rank, 10)

          if (rangeMatch) {
            const start = parseInt(rangeMatch[1], 10)
            const stop = parseInt(rangeMatch[2], 10)

            if (start && stop) {
              for (let i = start; i <= stop; i++) {
                ranks.push(i)
              }
            }
          } else if (rankNumber != null) {
            ranks.push(rankNumber)
          }
        }
        group.ranks = ranks
      } else if (!groupId.match(/[a-z]/i)) {
        group.ranks = []
        for (let i = 1; i <= 255; i++) {
          group.ranks.push(i)
        }
      } else {
        group.ranks = []
      }

      binding.groups.push(group)
    }

    // Delete any previous binding with that role.
    this.server.deleteGroupRankBinding(binding.role)

    // Add the new binding.
    const serverBindings = this.server.getSetting('groupRankBindings')
    serverBindings.push(binding)
    this.server.setSetting('groupRankBindings', serverBindings)

    let bindingSuccessMessage = `:white_check_mark: Successfully bound role "${args.role.name}".\`\`\`markdown\n`

    bindingSuccessMessage += Util.getBindingText(binding)

    bindingSuccessMessage += '```\n'

    msg.reply(bindingSuccessMessage)
  }
}
<|endoftext|>


<commit_before>/**

  Default routes

**/

var compiler = require("./compiler"),
    statics = require("./statics");

module.exports = function() {

  var router = global.shipp.router();

  for (var route in global.shipp.config.routes) {

    global.shipp.log("Adding routes for", route);

    // Copy options and add in route
    options = Object.assign({}, global.shipp.config.routes[route]);
    options.url = route;

    switch (options.type) {
      case "scripts":
      case "styles":
      case "views":
        router.use(compiler(options));
        break;
      case "statics":
        router.use(statics(options));
        break;
      default:
        throw new Error("Unrecognized route type", options.type);
    }
  }

  return router;

};

<commit_msg>Improves logging information for routes<commit_after>/**

  Default routes

**/

var compiler = require("./compiler"),
    statics = require("./statics");

module.exports = function() {

  var router = global.shipp.router();

  for (var route in global.shipp.config.routes) {

    // Copy options and add in route
    options = Object.assign({}, global.shipp.config.routes[route]);
    options.url = route;

    global.shipp.log("Serving", options.type, "from", route);

    switch (options.type) {
      case "scripts":
      case "styles":
      case "views":
        router.use(compiler(options));
        break;
      case "statics":
        router.use(statics(options));
        break;
      default:
        throw new Error("Unrecognized route type", options.type);
    }
  }

  return router;

};
<|endoftext|>


<commit_before>/**
 * Created by gnf on 11/01/17.
 */
import React from 'react';
import _isEmpty from 'lodash/isEmpty';
import _assign from 'lodash/assign';

class FilterOptions extends React.Component {

  constructor(props) {
    super(props);
    this.state = { isOpen: false };
    this.namesOfFields = [];
    this.fields = [];
    this.filterValues = {};
    this.applyFilter = this.applyFilter.bind(this);
  }

  componentDidMount() {
    for(let i = 0; i<this.namesOfFields.length; i++) {
      // Nomes iguais, nao podem ser colocados no formFields
      if(this.namesOfFields[i] !== this.namesOfFields[i+1]) {
        //[].slice.call converte o NodeList para um array Javascript normal
        let formFields = [].slice.call(document.getElementsByName(this.namesOfFields[i]));
        formFields.map((formField) => this.fields.push(formField));
      }
    }
  }

  clearAll() {
    if(this.props.onClearAll) {
      this.props.onClearAll();
    } else {
      for(let i = 0; i<this.fields.length; i++) {
        if(this.fields[i].type === 'radio' || this.fields[i].type === 'checkbox') {
          this.fields[i].checked = false;
        } else {
          this.fields[i].value = '';
        }
      }
    }
  }

  applyFilter() {
    this.fields.map((field) => {
      if(field.type === 'select-one' && field.value !== '') {
        this.filterValues[field.name] = field.value;
      } else {
        if(field.type === 'radio' && field.checked) {
          this.filterValues[field.name] = field.value;
        } else {
          if (field.type === 'checkbox' && field.checked) {
            if(this.filterValues[field.name]) {
              this.filterValues[field.name].push(field.value);
            } else {
              this.filterValues[field.name] = [field.value];
            }
          }
        }
      }
    });
    this.props.addSearchValueToFilterValues(this.filterValues);
    this.filterValues = {};
  }

  toggleVisibility() {
    this.setState({isOpen: !this.state.isOpen});
  }

  close() {
    this.setState({isOpen: false});
  }

  renderChildrenAndGetFieldNames(children) {
    return (
      React.Children.map(children, (child) => {
        if(Array.isArray(children)) {
          if(child.type === 'select') {
            this.namesOfFields.push(child.props.name);
          }
          if(typeof child !== 'string') {
            if(child.props.type === 'checkbox') {
              this.namesOfFields.push(child.props.name);
            }
            if(child.props.type === 'radio') {
              this.namesOfFields.push(child.props.name);
            }
            this.renderChildrenAndGetFieldNames(child.props.children);
          }
          return child;
        } else {
          if(!_isEmpty(children.props)) {
            if(children.props.type === 'radio') {
              this.namesOfFields(children.props.name);
            }
            this.renderChildrenAndGetFieldNames(child.props.children);
            return child;
          }
        }
      })
    );
  }

  render() {

    let {
      applyFilterButtonLabel,
      cancelButtonLabel,
      clearFilterOptionsButtonLabel,
      filterButtonLabel,
    } = this.props;

    let filterOptionsStyles = _assign(
      {width: '100%'},
      {display: this.state.isOpen ? 'block': 'none'}
    );

    let filterSpanStyles = _assign(
      {display: this.props.hasFilterOptions ? 'block': 'none'},
      {color: this.state.isOpen ? '#2196f3': '#455a64'}
    );

    return (

         this.toggleVisibility()}
          style={filterSpanStyles}>
          {filterButtonLabel}

            {this.renderChildrenAndGetFieldNames(this.props.children)}

              <button
                className='sv-button link link-danger sv-pull-left'
                onClick={(e) => { e.preventDefault(); this.clearAll(); }}>
                {clearFilterOptionsButtonLabel} {filterButtonLabel}
              </button>
              <button
                className='sv-button link link-info sv-pull-right'
                onClick={(e) => { e.preventDefault(); this.applyFilter(); }}>
                {applyFilterButtonLabel}
              </button>
              <button
                className='sv-button link link-cancel sv-pull-right'
                onClick={(e) => { e.preventDefault(); this.close(); }}>
                {cancelButtonLabel}
              </button>

    );
  }
}

FilterOptions.propTypes = {
  addSearchValueToFilterValues: React.PropTypes.func,
  applyFilterButtonLabel: React.PropTypes.string,
  cancelButtonLabel: React.PropTypes.string,
  clearFilterOptionsButtonLabel: React.PropTypes.string,
  filterButtonLabel: React.PropTypes.string,
  hasFilterOptions: React.PropTypes.bool,
  onClearAll: React.PropTypes.func,
  onFilter: React.PropTypes.func,
};

FilterOptions.displayName = 'FilterOptions';

export default FilterOptions;
<commit_msg>Detalhe no filtro para ser possível a filtragem por campos de texto e refactor<commit_after>/**
 * Created by gnf on 11/01/17.
 */
import React from 'react';
import _isEmpty from 'lodash/isEmpty';
import _assign from 'lodash/assign';

class FilterOptions extends React.Component {

  constructor(props) {
    super(props);
    this.state = { isOpen: false };
    this.namesOfFields = [];
    this.fields = [];
    this.filterValues = {};
    this.applyFilter = this.applyFilter.bind(this);
  }

  componentDidMount() {
    debugger;
    for(let i = 0; i<this.namesOfFields.length; i++) {
      // Nomes iguais, nao podem ser colocados no formFields
      if(this.namesOfFields[i] !== this.namesOfFields[i+1]) {
        //[].slice.call converte o NodeList para um array Javascript normal
        let formFields = [].slice.call(document.getElementsByName(this.namesOfFields[i]));
        formFields.map((formField) => this.fields.push(formField));
      }
    }
  }

  clearAll() {
    if(this.props.onClearAll) {
      this.props.onClearAll();
    } else {
      for(let i = 0; i<this.fields.length; i++) {
        if(this.fields[i].type === 'radio' || this.fields[i].type === 'checkbox') {
          this.fields[i].checked = false;
        } else {
          this.fields[i].value = '';
        }
      }
    }
  }

  applyFilter() {
    this.fields.map((field) => {
      if(field.type === 'text' || field.type === 'select-one') {
        if(field.value !== '') {
          this.filterValues[field.name] = field.value;
        }
      } else if(field.type === 'radio' && field.checked) {
        this.filterValues[field.name] = field.value;
      } else if(field.type === 'checkbox' && field.checked) {
        if(this.filterValues[field.name]) {
          this.filterValues[field.name].push(field.value);
        } else {
          this.filterValues[field.name] = [field.value];
        }
      }
    });
    this.props.addSearchValueToFilterValues(this.filterValues);
    this.filterValues = {};
  }

  toggleVisibility() {
    this.setState({isOpen: !this.state.isOpen});
  }

  close() {
    this.setState({isOpen: false});
  }

  verifyTypesAndGetNames(child) {
    if(child.type === 'input') {
      if(child.props.type === 'text' ||
         child.props.type === 'radio' ||
         child.props.type === 'checkbox') {
        this.namesOfFields.push(child.props.name);
      }
    } else if(child.type === 'select') {
      this.namesOfFields.push(child.props.name);
    }
  }

  renderChildren(children) {
    return (
      React.Children.map(children, (child) => {
        if(Array.isArray(children)) {
          this.verifyTypesAndGetNames(child);
          if(typeof child !== 'string') {
            this.renderChildren(child.props.children);
          }
          return child;
        } else {
          if(!_isEmpty(children.props)) {
            this.verifyTypesAndGetNames(child);
            this.renderChildren(child.props.children);
            return child;
          }
        }
      })
    );
  }

  render() {

    let {
      applyFilterButtonLabel,
      cancelButtonLabel,
      clearFilterOptionsButtonLabel,
      filterButtonLabel,
    } = this.props;

    let filterOptionsStyles = _assign(
      {width: '100%'},
      {display: this.state.isOpen ? 'block': 'none'}
    );

    let filterSpanStyles = _assign(
      {display: this.props.hasFilterOptions ? 'block': 'none'},
      {color: this.state.isOpen ? '#2196f3': '#455a64'}
    );

    return (

         this.toggleVisibility()}
          style={filterSpanStyles}>
          {filterButtonLabel}

            {this.renderChildren(this.props.children)}

              <button
                className='sv-button link link-danger sv-pull-left'
                onClick={(e) => { e.preventDefault(); this.clearAll(); }}>
                {clearFilterOptionsButtonLabel} {filterButtonLabel}
              </button>
              <button
                className='sv-button link link-info sv-pull-right'
                onClick={(e) => { e.preventDefault(); this.applyFilter(); }}>
                {applyFilterButtonLabel}
              </button>
              <button
                className='sv-button link link-cancel sv-pull-right'
                onClick={(e) => { e.preventDefault(); this.close(); }}>
                {cancelButtonLabel}
              </button>

    );
  }
}

FilterOptions.propTypes = {
  addSearchValueToFilterValues: React.PropTypes.func,
  applyFilterButtonLabel: React.PropTypes.string,
  cancelButtonLabel: React.PropTypes.string,
  clearFilterOptionsButtonLabel: React.PropTypes.string,
  filterButtonLabel: React.PropTypes.string,
  hasFilterOptions: React.PropTypes.bool,
  onClearAll: React.PropTypes.func,
  onFilter: React.PropTypes.func,
};

FilterOptions.displayName = 'FilterOptions';

export default FilterOptions;
<|endoftext|>


<commit_before>var fortunes = require('./api/fortunes');
var lottos = require('./api/lottos');
var lessons = require('./api/lessons');
var cookie = require('./api/cookie');

exports.setup = function (app) {
  app.get('/v1/fortunes', fortunes.findAll);
  app.get('/v1/fortunes/:id', fortunes.findById);
  app.get('/v1/lottos', lottos.findAll);
  app.get('/v1/lottos/:id', lottos.findById);
  app.get('/v1/lessons', lessons.findAll);
  app.get('/v1/lessons/:id', lessons.findById);
  app.get('/v1/cookie', cookie.build);

  app.set('views', __dirname + '/../views');
  app.set('view engine', 'jade');

  app.get('/', function (req, res) {
    res.render('documentation.jade');
  });

  app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
};<commit_msg>moving cors enable to before defining gets<commit_after>var fortunes = require('./api/fortunes');
var lottos = require('./api/lottos');
var lessons = require('./api/lessons');
var cookie = require('./api/cookie');

exports.setup = function (app) {
  // enable cors
  app.get('/v1/*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

  app.get('/v1/fortunes', fortunes.findAll);
  app.get('/v1/fortunes/:id', fortunes.findById);
  app.get('/v1/lottos', lottos.findAll);
  app.get('/v1/lottos/:id', lottos.findById);
  app.get('/v1/lessons', lessons.findAll);
  app.get('/v1/lessons/:id', lessons.findById);
  app.get('/v1/cookie', cookie.build);

  app.set('views', __dirname + '/../views');
  app.set('view engine', 'jade');

  app.get('/', function (req, res) {
    res.render('documentation.jade');
  });
};<|endoftext|>


<commit_before>Tabris.load(function() {

    var message;

    var page = Tabris.createPage({
        title: "Oceanic Flight 815 Booking",
        topLevel: true
    });

    var firstNameLabel = page.append("Label", {
        layoutData: {
            left: 10,
            right: [70, 0],
            top: 10,
            height: 30
        },
        alignment: "left",
        text: "First Name:"
    });

    var firstNameInput = page.append("Text", {
        layoutData: {
            left: [firstNameLabel, 10],
            right: 10,
            top: 10
        },
        message: "First Name"
    });

    var lastNameLabel = page.append("Label", {
        layoutData: {
            left: 10,
            right: [70, 0],
            top: [firstNameLabel, 10],
            height: 30
        },
        alignment: "left",
        text: "Last Name:"
    });

    var lastNameInput = page.append("Text", {
        layoutData: {
            left: [lastNameLabel, 10],
            right: 10,
            top: [firstNameInput, 10]
        },
        message: "Last Name"
    });

    var passphraseLabel = page.append("Label", {
        layoutData: {
            left: 10,
            right: [70, 0],
            top: [lastNameLabel, 10],
            height: 30
        },
        alignment: "left",
        text: "Passphrase:"
    });

    var passphraseInput = page.append("Text", {
        style: ["PASSWORD"],
        layoutData: {
            left: [passphraseLabel, 10],
            right: 10,
            top: [lastNameInput, 10]
        },
        message: "Passphrase"
    });

    var countryLabel = page.append("Label", {
        layoutData: {
            left: 10,
            right: [70, 0],
            top: [passphraseLabel, 10],
            height: 30
        },
        alignment: "left",
        text: "Country:"
    });

    var countryCombo = page.append("Combo", {
        layoutData: {
            left: [countryLabel, 10],
            right: 10,
            top: [passphraseInput, 10]
        },
        items: ["Germany", "Canada", "USA", "Bulgaria"],
        selectionIndex: 0
    });

    var classLabel = page.append("Label", {
        layoutData: {
            left: 10,
            right: [70, 0],
            top: [countryLabel, 10],
            height: 30
        },
        alignment: "left",
        text: "Class:"
    });

    var classCombo = page.append("Combo", {
        layoutData: {
            left: [classLabel, 10],
            right: 10,
            top: [countryCombo, 10]
        },
        items: ["Business", "Economy", "Economy Plus"],
        selectionIndex: 0
    });

    var dateTimeLabel = page.append("Label", {
        layoutData: {
            left: 10,
            right: [70, 0],
            top: [classLabel, 10],
            height: 30
        },
        alignment: "left",
        text: "Date:"
    });

    var dateTime = page.append("DateTime", {
        style: ["DATE"],
        layoutData: {
            left: [dateTimeLabel, 10],
            right: 10,
            top: [classCombo, 10]
        },
        year: 2014,
        day: 20,
        month: 5,
    });

    var checkbox = page.append("Button", {
        layoutData: {
            left: [dateTimeLabel, 10],
            right: 10,
            top: [dateTime, 10]
        },
        style: ["CHECK"],
        text: "Vegetarian"
    });

    var button = page.append("Button", {
        layoutData: {
            left: 10,
            right: 10,
            top: [checkbox, 20]
        },
        text: "Place Reservation",
        background: [139, 0, 0],
        foreground: [255, 255, 255]
    });

    button.on("Selection", function() {
        populateMessage();
    })

    function populateMessage() {
        if (!message) {
            message = page.append("Label", {
                layoutData: {
                    left: 10,
                    right: 10,
                    top: [button, 10],
                    height: 500
                },
                alignment: "left",
                text: "Flight booked for: " + firstNameInput.get("text") + " "
                                            + lastNameInput.get("text") + "\n"
                    + "Departure: " + dateTime.get("year") + "/"
                                    + (dateTime.get("month") + 1) + "/"
                                    + dateTime.get("day")
            });
        } else {
            message.dispose();
            message = null;
            populateMessage();
        }
    }

    page.open();

});
<commit_msg>Input demo refactoring.<commit_after>Tabris.load(function() {

  var message;

  var page = Tabris.createPage({
    title: "Oceanic Flight 815 Booking",
    topLevel: true
  });

  var firstNameLabel = page.append("Label", {
    layoutData: {
      left: 10,
      right: [70, 0],
      top: 10
    },
    alignment: "left",
    text: "First Name:"
  });

  var firstNameInput = page.append("Text", {
    layoutData: {
      left: [firstNameLabel, 10],
      right: 10,
      top: 10
    },
    message: "First Name"
  });

  var lastNameLabel = page.append("Label", {
    layoutData: {
      left: 10,
      right: [70, 0],
      top: [firstNameInput, 10]
    },
    alignment: "left",
    text: "Last Name:"
  });

  var lastNameInput = page.append("Text", {
    layoutData: {
      left: [lastNameLabel, 10],
      right: 10,
      top: [firstNameInput, 10]
    },
    message: "Last Name"
  });

  var passphraseLabel = page.append("Label", {
    layoutData: {
      left: 10,
      right: [70, 0],
      top: [lastNameInput, 10]
    },
    alignment: "left",
    text: "Passphrase:"
  });

  var passphraseInput = page.append("Text", {
    style: ["PASSWORD"],
    layoutData: {
      left: [passphraseLabel, 10],
      right: 10,
      top: [lastNameInput, 10]
    },
    message: "Passphrase"
  });

  var countryLabel = page.append("Label", {
    layoutData: {
      left: 10,
      right: [70, 0],
      top: [passphraseInput, 10]
    },
    alignment: "left",
    text: "Country:"
  });

  var countryCombo = page.append("Combo", {
    layoutData: {
      left: [countryLabel, 10],
      right: 10,
      top: [passphraseInput, 10]
    },
    items: ["Germany", "Canada", "USA", "Bulgaria"],
    selectionIndex: 0
  });

  var classLabel = page.append("Label", {
    layoutData: {
      left: 10,
      right: [70, 0],
      top: [countryCombo, 10]
    },
    alignment: "left",
    text: "Class:"
  });

  var classCombo = page.append("Combo", {
    layoutData: {
      left: [classLabel, 10],
      right: 10,
      top: [countryCombo, 10]
    },
    items: ["Business", "Economy", "Economy Plus"],
    selectionIndex: 0
  });

  var dateTimeLabel = page.append("Label", {
    layoutData: {
      left: 10,
      right: [70, 0],
      top: [classCombo, 10]
    },
    alignment: "left",
    text: "Date:"
  });

  var dateTime = page.append("DateTime", {
    style: ["DATE"],
    layoutData: {
      left: [dateTimeLabel, 10],
      right: 10,
      top: [classCombo, 10]
    },
    year: 2014,
    day: 20,
    month: 5,
  });

  var checkbox = page.append("Button", {
    layoutData: {
      left: [dateTimeLabel, 10],
      right: 10,
      top: [dateTime, 10]
    },
    style: ["CHECK"],
    text: "Vegetarian"
  });

  var button = page.append("Button", {
    layoutData: {
      left: 10,
      right: 10,
      top: [checkbox, 20]
    },
    text: "Place Reservation",
    background: [139, 0, 0],
    foreground: [255, 255, 255]
  });

  button.on("Selection", function() {
    populateMessage();
  });

  function populateMessage() {
    if (!message) {
      message = page.append("Label", {
        layoutData: {
          left: 10,
          right: 10,
          top: [button, 10]
        },
        alignment: "left",
        text: "Flight booked for: " + createName() + "\n" + "Departure: " + createDepartureDate()
      });
    } else {
      message.dispose();
      message = null;
      populateMessage();
    }
  }

  function createName() {
    return [firstNameInput.get("text"), lastNameInput.get("text")].join(" ");
  }

  function createDepartureDate() {
    return [dateTime.get("year"), (dateTime.get("month") + 1), dateTime.get("day")].join("/");
  }

  page.open();

});
<|endoftext|>


<commit_before>'use strict'

const so     = require('so')
const time   = require('parse-messy-time')

const _      = require('./index')
const render = require('./render')

const unknownLocation = `\
I don't know about this location, please double-check for typos.
If you're sure it's my fault, please let my creator @derhuerst know.`
const textOrLocation = `\
Please enter a location like "U mehringdamm", "Kaiserdamm 26" or send your location.`

const currentLocation = (msg) => ({
	type: 'address', name: 'your location',
	latitude: msg.location.latitude,
	longitude: msg.location.longitude
})

const routes = so(function* (ctx, msg) {
	const state = yield ctx.get('state')

	if (state === 'time') {
		if (!msg.text) return ctx.message(`Please enter text.`)
		const from = yield ctx.get('from')
		const to = yield ctx.get('to')
		const when = time(msg.text)
		ctx.typing()
		const routes = yield _.routes(from, to, when)
		yield ctx.keyboard(render.routes(routes), ctx.keys)
		yield ctx.done()
	}

	else if (state === 'to') {
		ctx.typing()
		let location
		if (msg.text) {
			location = yield _.location(msg.text)
			if (!location) return ctx.message(unknownLocation)
		} else if (msg.location) location = currentLocation(msg)
		else return ctx.message(textOrLocation)
		yield ctx.set('to', location)
		yield ctx.set('state', 'time')
		yield ctx.message(`\
*When?*
e.g. "now", "in 10 minutes" or "tomorrow 17:20"`)
	}

	else if (state === 'from') {
		ctx.typing()
		let location
		if (msg.text) {
			location = yield _.location(msg.text)
			if (!location) return ctx.message(unknownLocation)
		} else if (msg.location) location = currentLocation(msg)
		else return ctx.message(textOrLocation)
		yield ctx.set('from', location)
		yield ctx.set('state', 'to')
		yield ctx.requestLocation(`\
*Where do you want to go?*`, 'send location')
	}

	else {
		yield ctx.set('state', 'from')
		yield ctx.requestLocation(`\
*Where do you start?*
Enter a location like "U mehringdamm", "Kaiserdamm 26" or send your location.`, 'send location')
	}

})

module.exports = routes
<commit_msg>refactor /route<commit_after>'use strict'

const so     = require('so')
const time   = require('parse-messy-time')

const _      = require('./index')
const render = require('./render')

const when = so(function* (ctx, msg) {
	if (!msg.text) return ctx.message(`Please enter text.`)
	const from = yield ctx.get('origin')
	const to = yield ctx.get('destination')
	const when = time(msg.text)
	ctx.typing()
	const routes = yield _.routes(from, to, when)
	yield ctx.keyboard(render.routes(routes), ctx.keys)
})

const unknownLocation = `\
I don't know about this location, please double-check for typos.
If you're sure it's my fault, please let my creator @derhuerst know.`
const textOrLocation = `\
Please enter a location like "U mehringdamm", "Kaiserdamm 26" or send your location.`
const currentLocation = (msg) => ({
	type: 'address', name: 'your location',
	latitude: msg.location.latitude,
	longitude: msg.location.longitude
})

const where = so(function* (key, ctx, msg) {
	ctx.typing()
	let location
	if (msg.text) {
		location = yield _.location(msg.text)
		if (!location) return ctx.message(unknownLocation)
	} else if (msg.location) location = currentLocation(msg)
	else return ctx.message(textOrLocation)
	yield ctx.set(key, location)
})

const promptWhen = `\
*When?*
e.g. "now", "in 10 minutes" or "tomorrow 17:20"`
const promptDestination = `\
*Where do you want to go?*`
const promptOrigin = `\
*Where do you start?*
Enter a location like "U mehringdamm", "Kaiserdamm 26" or send your location.`

const routes = so(function* (ctx, msg) {
	const state = yield ctx.get('state')

	if (state === 'when') {
		yield when(ctx, msg)
		yield ctx.done()
	}
	else if (state === 'destination') {
		yield where('destination', ctx, msg)
		yield ctx.set('state', 'when')
		yield ctx.message(promptWhen)
	}
	else if (state === 'origin') {
		yield where('origin', ctx, msg)
		yield ctx.set('state', 'destination')
		yield ctx.message(promptDestination, 'send location')
	}
	else {
		yield ctx.set('state', 'origin')
		yield ctx.requestLocation(promptOrigin, 'send location')
	}
})

module.exports = routes
<|endoftext|>


<commit_before>// usage without warranty!
var usb = require("../../usb.js"),
	assert = require('assert'),
	http = require('http'),
	qs = require('querystring');

// taken from freenect_internal.h
var VID_MICROSOFT = 0x45e, PID_NUI_CAMERA = 0x02ae, PID_NUI_MOTOR = 0x02b0;

// taken from libfreenect.h
var LED_OPTIONS = new Object();
LED_OPTIONS['OFF'] 		= 0;
LED_OPTIONS['GREEN'] 		= 1;
LED_OPTIONS['RED']		= 2;
LED_OPTIONS['YELLOW']		= 3;
LED_OPTIONS['BLINK_YELLOW']	= 4;
LED_OPTIONS['BLINK_GREEN']	= 5;
LED_OPTIONS['BLINK_RED_YELLOW'] = 6;

var MAX_TILT_ANGLE = 31, MIN_TILT_ANGLE = -31;

// Search for motor device

var motorDevices = usb.find_by_vid_and_pid(VID_MICROSOFT, PID_NUI_MOTOR);
assert.ok((motorDevices.length >= 1));
console.log("Total motor devices found: " + motorDevices.length);

var motor = motorDevices[0];

// get interfaces of motor
assert.ok((motor.interfaces.length >= 1));
console.log("Motor contains interfaces: " + motor.interfaces.length);

// claim first interface
var motorInterface = motor.interfaces[0];
console.log("Claiming motor interface for further actions");
motorInterface.claim();

// create simple web GUI. don't blame me - I know it's dirty
http.createServer(function(req, res) {
	res.writeHead(200, {'Content-Type': 'text/html'});
	var incomingBody = "";
	req.on('data', function(data) { incomingBody += data; });
	req.on('end', function() {
		var postData = qs.parse(incomingBody);
		var bulkOutput = "no data";

		switch (req.url) {
			case '/updateLed':
				var light = postData['light'];

				if (!light || (typeof(LED_OPTIONS[light]) == undefined)) {
					console.log(" - No light available");
				}
				else {
					var lightId = LED_OPTIONS[light];

					// send control information
					motor.controlTransfer(0x40, 0x06, lightId, 0x0, new Buffer(0), function(data) {
						console.log(" + LED toggled");
					});
				}
				break;
			case '/updateAngle':
				var angle = parseInt(postData['angle']);

				if (isNaN(angle)) {
					angle = 0;
				}

				angle = (angle < MIN_TILT_ANGLE) ? MIN_TILT_ANGLE : ((angle > MAX_TILT_ANGLE) ? MAX_TILT_ANGLE : angle);
				angle = angle * 2;
				console.log("Angle set to " + angle);
				motor.controlTransfer(new Buffer(0), 0x40, 0x31, angle, 0x0, function(data) {
					console.log(" + Angle set");
				});

				break;
			case '/getCoordinates':
				motor.controlTransfer(0xC0 /* bmRequestType */, 0x32 /* bRequest */, 0, 0, 10 /* read 10 bytes */, function(data) {
					for (var i = 0; i < 10; i++) {
						console.log("buffer[" + i + "]: " + data[i])
					}
					console.log("Accelerometer axis:")
					var x = ((data[2] << 8) | data[3]), y = ((data[4] << 8) | data[5]), z = ((data[6] << 8) | data[7])
					x = (x + Math.pow(2,15)) % Math.pow(2,16) - Math.pow(2,15)
					y = (y + Math.pow(2,15)) % Math.pow(2,16) - Math.pow(2,15)
					z = (z + Math.pow(2,15)) % Math.pow(2,16) - Math.pow(2,15)

					console.log("  X:" + x)
					console.log("  Y:" + y)
					console.log("  Z:" + z)
				})
				break;
		}
	});

	var html = "<title>node-usb :: Microsoft Kinect example</title>
Control your Microsoft Kinect via node.js / node-usb
<form method='post' action='updateLed'>";
	html += "Select LED light: <select name='light'>";

	for (var prop in LED_OPTIONS) {
		html += "<option value='" + prop + "'>" + prop + "</option>";
	}

	html += "</select><input type='submit' value='change color' /></form>";
	html += "<form method='post' action='updateAngle'>";
	html += "Set angle (-31 - +31) <input type='text' name='angle' size='2' /><input type='submit' value='change angle'/></form>";
	html += "Retrieve coordinates from Kinect via control transfer";
	html += "";

	res.write(html);
	res.end();
}).listen(8080);
<commit_msg>Fix controlTransfer usage in kinect.js<commit_after>// usage without warranty!
var usb = require("../../usb.js"),
	assert = require('assert'),
	http = require('http'),
	qs = require('querystring');

// taken from freenect_internal.h
var VID_MICROSOFT = 0x45e, PID_NUI_CAMERA = 0x02ae, PID_NUI_MOTOR = 0x02b0;

// taken from libfreenect.h
var LED_OPTIONS = new Object();
LED_OPTIONS['OFF'] 		= 0;
LED_OPTIONS['GREEN'] 		= 1;
LED_OPTIONS['RED']		= 2;
LED_OPTIONS['YELLOW']		= 3;
LED_OPTIONS['BLINK_YELLOW']	= 4;
LED_OPTIONS['BLINK_GREEN']	= 5;
LED_OPTIONS['BLINK_RED_YELLOW'] = 6;

var MAX_TILT_ANGLE = 31, MIN_TILT_ANGLE = -31;

// Search for motor device

var motorDevices = usb.find_by_vid_and_pid(VID_MICROSOFT, PID_NUI_MOTOR);
assert.ok((motorDevices.length >= 1));
console.log("Total motor devices found: " + motorDevices.length);

var motor = motorDevices[0];

// get interfaces of motor
assert.ok((motor.interfaces.length >= 1));
console.log("Motor contains interfaces: " + motor.interfaces.length);

// claim first interface
var motorInterface = motor.interfaces[0];
console.log("Claiming motor interface for further actions");
motorInterface.claim();

// create simple web GUI. don't blame me - I know it's dirty
http.createServer(function(req, res) {
	res.writeHead(200, {'Content-Type': 'text/html'});
	var incomingBody = "";
	req.on('data', function(data) { incomingBody += data; });
	req.on('end', function() {
		var postData = qs.parse(incomingBody);
		var bulkOutput = "no data";

		switch (req.url) {
			case '/updateLed':
				var light = postData['light'];

				if (!light || (typeof(LED_OPTIONS[light]) == undefined)) {
					console.log(" - No light available");
				}
				else {
					var lightId = LED_OPTIONS[light];

					// send control information
					motor.controlTransfer(0x40, 0x06, lightId, 0x0, new Buffer(0), function(data) {
						console.log(" + LED toggled");
					});
				}
				break;
			case '/updateAngle':
				var angle = parseInt(postData['angle']);

				if (isNaN(angle)) {
					angle = 0;
				}

				angle = (angle < MIN_TILT_ANGLE) ? MIN_TILT_ANGLE : ((angle > MAX_TILT_ANGLE) ? MAX_TILT_ANGLE : angle);
				angle = angle * 2;
				console.log("Angle set to " + angle);
				motor.controlTransfer(0x40, 0x31, angle, 0x0, new Buffer(0), function(data) {
					console.log(" + Angle set");
				});

				break;
			case '/getCoordinates':
				motor.controlTransfer(0xC0 /* bmRequestType */, 0x32 /* bRequest */, 0, 0, 10 /* read 10 bytes */, function(data) {
					for (var i = 0; i < 10; i++) {
						console.log("buffer[" + i + "]: " + data[i])
					}
					console.log("Accelerometer axis:")
					var x = ((data[2] << 8) | data[3]), y = ((data[4] << 8) | data[5]), z = ((data[6] << 8) | data[7])
					x = (x + Math.pow(2,15)) % Math.pow(2,16) - Math.pow(2,15)
					y = (y + Math.pow(2,15)) % Math.pow(2,16) - Math.pow(2,15)
					z = (z + Math.pow(2,15)) % Math.pow(2,16) - Math.pow(2,15)

					console.log("  X:" + x)
					console.log("  Y:" + y)
					console.log("  Z:" + z)
				})
				break;
		}
	});

	var html = "<title>node-usb :: Microsoft Kinect example</title>
Control your Microsoft Kinect via node.js / node-usb
<form method='post' action='updateLed'>";
	html += "Select LED light: <select name='light'>";

	for (var prop in LED_OPTIONS) {
		html += "<option value='" + prop + "'>" + prop + "</option>";
	}

	html += "</select><input type='submit' value='change color' /></form>";
	html += "<form method='post' action='updateAngle'>";
	html += "Set angle (-31 - +31) <input type='text' name='angle' size='2' /><input type='submit' value='change angle'/></form>";
	html += "Retrieve coordinates from Kinect via control transfer";
	html += "";

	res.write(html);
	res.end();
}).listen(8080);
<|endoftext|>


<commit_before>var _u = require('underscore'), invoker = require('./invoke'),
    util = require('./util'),
    _q = require('./query'),
    populate = _q.populate,
    sort = _q.sort,
    paginate = _q.paginate,
    clean = _q.clean,
    filter = _q.filter,
    idObj = _q.idObj
    ;
module.exports = function MongooseRestRouter(base, router, options) {
    var ResponseStream = options.responseStream;

    var mongoose = options.mongoose;
    var errorFunc = options.error.bind(options);
    var m = function (model) {

        return _q.m(mongoose, model.param && model.param('type') || model)
    };

    var finder = function (Model, find, req, res, next) {
        res.contentType('json');
        var single = req.query.single;
        return function (err, count) {
            if (err) return next(err);
            populate(find, req.query);
            paginate(find, req.query);
            sort(find, req.query);
            var stream = transform(createstream(find, req, res, next), req.query, Model);
            if (req.query.filter && Model) {
                filter(find, req.query, Model);
                find.count(function (err, fcount) {
                    if (err) return next(err);
                    stream.pipe(new ResponseStream({total:count, filterTotal:fcount}, single)).pipe(res);
                });
            } else {
                stream.pipe(new ResponseStream({total:count}, single)).pipe(res);
            }
        }
    }

    router.get(base + '/:type', function (req, res, next) {
        res.contentType('json');
        var type = req.param('type');
        var Model = m(type);
        Model.count({}, finder(Model, Model.find({}), req, res, next));
    });

    var reFinder = new RegExp('^\\' + base + '\\/(?:([^\\/]+?))\\/finder/(?:([^\\/]+?))(?:\\/([\\w\\/]+?))?\\/?$', 'i');
    //   var reFinder = new RegExp('^\\' + base + '\\/(?:([^\\/]+?))\\/finder/(?:([^\\/]+?))(?:\\/([\\w\\/]+?))?\\/?$');
    router.get(reFinder, function (req, res, next) {
        res.contentType('json')

        var _f = req.params[1];

        req.params.type = req.params[0];
        var Model = m(req)
        var args = [req.query];
        if (req.params.length > 2)
            args = args.concat(util.split(req.params[2]));
        var find = Model[_f].apply(Model, args);

        find.count(finder(Model, find, req, res, next));
    });

    /*
     /^\/rest\/(?:([^\/]+?))\/(?:([^\/]+?))\/?$/
     /^\/rest\/(?:([^\/]+?))\/(?:([^\/]+?))(?:\/([\w\/]+?))?\/?$/
     */

    var reGet = new RegExp('^\\' + base + '\\/(?:([^\\/]+?))\\/(?:([^\\/]+?))(?:\\/([\\w\\/]+?))?\\/?$');
    router.get(reGet, function (req, res, next) {
        res.contentType('json');
        var single = req.query.single;
        var Model = m(req.params[0]);
        var find = Model.findOne(idObj(req.params[1]));
        populate(find, req.query);

        var stuff = req.params.length > 1 ? req.params[2] : null;
        if (stuff) {
            populate(find, {populate:[stuff]});

            var cbs = new options.streams.CallbackStream();
            transform(createstream(cbs, req, res, next), req.query, Model).pipe(new ResponseStream(null, single)).pipe(res);
            find.exec(function (err, obj) {
                if (err) return cbs.emit('error', err);
                invoker.invoke(obj, stuff, cbs.asCallback());
            });
        } else {
            transform(createstream(find, req, res, next), req.query, Model).pipe(new ResponseStream(null, single)).pipe(res);
        }
    });
    router.get(base + '/:type?', function (req, res, next) {
        console.log('error no handler for ', req.url);
        res.send({
            status:1,
            message:'No such url'
        });

    });
    router.post(base + '/:type', function (req, res, next) {
        var Model = m(req);
        new Model(clean(req.body)).save(run(res));
    });

    router.put(base + '/:type/:id', function (req, res, next) {
        var id = req.param('id');
        m(req).findOne(idObj(req), function (err, obj) {
            if (err)return next(err);
            _u.extend(obj, clean(req.body));
            obj.save(function (err, ret) {
                if (err) return next(err);
                res.contentType('json');
                var obj = ret.toJSON();
                res.send({
                    status:0,
                    payload:obj
                })
            });
        });

    });
    router.del(base + '/:type/:id?', function (req, res, next) {
        var M = m(req);
        var send = function(err, d){
            if (err)
                return next(err);
            res.send({
                status:0,
                payload:null
            })
        }

        if (M.findOneAndRemove)
             M.findOneAndRemove(idObj(req), send);
        else
            M.findOne(idObj(req), function(err, doc){
                if (err) return next(err);
                doc.remove(send);
            });

    });
    function createstream(query, req, res, next) {
        var stream = query.stream();
        stream.on('error', function (err) {
            console.warn('stream error [' + (err && err.message || 'unknown') + ']');
            this.destroy();
            errorFunc(err, req, res, next);
        });
        return stream;
    }

    function run(meta, tostream) {
        if (!tostream) {
            tostream = meta;
            meta = {};
        }

        return new ResponseStream(meta).asCallback(tostream);
    }

    function transform(stream, query, Model) {
        return options.transformer.pump(stream, Model, query.transform);
    }

    function isTrue(val) {
        return /^true$/i.test(val)
    }
}<commit_msg>removed findOneAndRemove<commit_after>var _u = require('underscore'), invoker = require('./invoke'),
    util = require('./util'),
    _q = require('./query'),
    populate = _q.populate,
    sort = _q.sort,
    paginate = _q.paginate,
    clean = _q.clean,
    filter = _q.filter,
    idObj = _q.idObj
    ;
module.exports = function MongooseRestRouter(base, router, options) {
    var ResponseStream = options.responseStream;

    var mongoose = options.mongoose;
    var errorFunc = options.error.bind(options);
    var m = function (model) {

        return _q.m(mongoose, model.param && model.param('type') || model)
    };

    var finder = function (Model, find, req, res, next) {
        res.contentType('json');
        var single = req.query.single;
        return function (err, count) {
            if (err) return next(err);
            populate(find, req.query);
            paginate(find, req.query);
            sort(find, req.query);
            var stream = transform(createstream(find, req, res, next), req.query, Model);
            if (req.query.filter && Model) {
                filter(find, req.query, Model);
                find.count(function (err, fcount) {
                    if (err) return next(err);
                    stream.pipe(new ResponseStream({total:count, filterTotal:fcount}, single)).pipe(res);
                });
            } else {
                stream.pipe(new ResponseStream({total:count}, single)).pipe(res);
            }
        }
    }

    router.get(base + '/:type', function (req, res, next) {
        res.contentType('json');
        var type = req.param('type');
        var Model = m(type);
        Model.count({}, finder(Model, Model.find({}), req, res, next));
    });

    var reFinder = new RegExp('^\\' + base + '\\/(?:([^\\/]+?))\\/finder/(?:([^\\/]+?))(?:\\/([\\w\\/]+?))?\\/?$', 'i');
    //   var reFinder = new RegExp('^\\' + base + '\\/(?:([^\\/]+?))\\/finder/(?:([^\\/]+?))(?:\\/([\\w\\/]+?))?\\/?$');
    router.get(reFinder, function (req, res, next) {
        res.contentType('json')

        var _f = req.params[1];

        req.params.type = req.params[0];
        var Model = m(req)
        var args = [req.query];
        if (req.params.length > 2)
            args = args.concat(util.split(req.params[2]));
        var find = Model[_f].apply(Model, args);

        find.count(finder(Model, find, req, res, next));
    });

    /*
     /^\/rest\/(?:([^\/]+?))\/(?:([^\/]+?))\/?$/
     /^\/rest\/(?:([^\/]+?))\/(?:([^\/]+?))(?:\/([\w\/]+?))?\/?$/
     */

    var reGet = new RegExp('^\\' + base + '\\/(?:([^\\/]+?))\\/(?:([^\\/]+?))(?:\\/([\\w\\/]+?))?\\/?$');
    router.get(reGet, function (req, res, next) {
        res.contentType('json');
        var single = req.query.single;
        var Model = m(req.params[0]);
        var find = Model.findOne(idObj(req.params[1]));
        populate(find, req.query);

        var stuff = req.params.length > 1 ? req.params[2] : null;
        if (stuff) {
            populate(find, {populate:[stuff]});

            var cbs = new options.streams.CallbackStream();
            transform(createstream(cbs, req, res, next), req.query, Model).pipe(new ResponseStream(null, single)).pipe(res);
            find.exec(function (err, obj) {
                if (err) return cbs.emit('error', err);
                invoker.invoke(obj, stuff, cbs.asCallback());
            });
        } else {
            transform(createstream(find, req, res, next), req.query, Model).pipe(new ResponseStream(null, single)).pipe(res);
        }
    });
    router.get(base + '/:type?', function (req, res, next) {
        console.log('error no handler for ', req.url);
        res.send({
            status:1,
            message:'No such url'
        });

    });
    router.post(base + '/:type', function (req, res, next) {
        var Model = m(req);
        new Model(clean(req.body)).save(run(res));
    });

    router.put(base + '/:type/:id', function (req, res, next) {
        var id = req.param('id');
        m(req).findOne(idObj(req), function (err, obj) {
            if (err)return next(err);
            _u.extend(obj, clean(req.body));
            obj.save(function (err, ret) {
                if (err) return next(err);
                res.contentType('json');
                var obj = ret.toJSON();
                res.send({
                    status:0,
                    payload:obj
                })
            });
        });

    });
    router.del(base + '/:type/:id?', function (req, res, next) {
        var M = m(req);
        var send = function(err, d){
            if (err)
                return next(err);
            res.send({
                status:0,
                payload:null
            })
        }

        M.findOne(idObj(req), function(err, doc){
            if (err) return next(err);
            doc.remove(send);
        });

    });
    function createstream(query, req, res, next) {
        var stream = query.stream();
        stream.on('error', function (err) {
            console.warn('stream error [' + (err && err.message || 'unknown') + ']');
            this.destroy();
            errorFunc(err, req, res, next);
        });
        return stream;
    }

    function run(meta, tostream) {
        if (!tostream) {
            tostream = meta;
            meta = {};
        }

        return new ResponseStream(meta).asCallback(tostream);
    }

    function transform(stream, query, Model) {
        return options.transformer.pump(stream, Model, query.transform);
    }

    function isTrue(val) {
        return /^true$/i.test(val)
    }
}<|endoftext|>