<commit_before>'use strict';

function freak(obj, root, parent) {

  var listeners = {
    'change': {},
    'insert': {},
    'delete': {}
  };
  var dependents = {};
  var children = {};

  parent = parent || null;
  root = root || obj;

  function assert(cond, msg) {
    if (!cond) {
      throw msg || 'assertion failed';
    }
  }

  // Mix properties into target
  function mixin(target, properties) {
    for (var i = 0, props = Object.getOwnPropertyNames(properties), len = props.length;
        i < len; i++) {
      target[props[i]] = properties[props[i]];
    }
  }

  // Event functions
  function on() {
    var event = arguments[0];
    var prop = typeof arguments[1] === 'string' ? arguments[1] : null;
    var callback =
      typeof arguments[1] === 'function' ?
        arguments[1] :
        typeof arguments[2] === 'function' ?
          arguments[2] : null;

    // Args check
    assert(['change', 'insert', 'delete'].indexOf(event) > -1);
    assert(
      (event === 'change' && prop) ||
      ((event === 'insert' || event === 'delete') && !prop)
    );

    // Init listeners for prop
    if (!listeners[event][prop]) {
      listeners[event][prop] = [];
    }
    // Already registered?
    if (listeners[event][prop].indexOf(callback) === -1) {
      listeners[event][prop].push(callback);
    }
  }

  function off() {
    var event = arguments[0];
    var prop = typeof arguments[1] === 'string' ? arguments[1] : null;
    var callback =
      typeof arguments[1] === 'function' ?
        arguments[1] :
        typeof arguments[2] === 'function' ?
          arguments[2] : null;
    var i;

    if (!listeners[event][prop]) return;

    // Remove all property watchers?
    if (!callback) {
      listeners[event][prop] = [];
    }
    else {
      // Remove specific callback
      i = listeners[event][prop].indexOf(callback);
      if (i > -1) {
        listeners[event][prop].splice(i, 1);
      }
    }

  }

  // trigger('change', prop)
  // trigger('insert' or 'delete', index, count)
  function trigger(event, a, b) {
    (listeners[event][event === 'change' ? a : null] || [])
      .map(function(listener) {
        listener.call(instance, a, b);
      });
  }

  // Functional accessor
  function accessor(prop, arg, refresh) {

    var i, len, dep, result, val;

    var getter = function(prop) {
      var result = obj[prop];
      return typeof result === 'function' ?
        result.call(getter) :
        result
    };

    var dependencyTracker = function(propToReturn) {
      // Update dependency tree
      if (!dependents[propToReturn]) {
        dependents[propToReturn] = [];
      }
      if (dependents[propToReturn].indexOf(prop) === -1) {
        dependents[propToReturn].push(prop);
      }
      return getter(propToReturn);
    };

    // Getter?
    if ((arg === undefined || typeof arg === 'function') && !refresh) {

      val = obj[prop];

      result = (typeof val === 'function') ?
        // Computed property
        val.call(dependencyTracker.bind(this)) :
        // Static property (leaf in the dependency tree)
        val;

      return typeof result === 'object' ?

        typeof children[prop] === 'function' ?
          children[prop] :
          children[prop] = freak(val, root, obj) :

        result;
    }

    // Setterchildren[prop]
    else {

      if (!refresh) {
        if (typeof obj[prop] === 'function') {
          // Computed property setter
          // TODO dependency tracker
          obj[prop].call(dependencyTracker.bind(this), arg);
        }
        else {
          // Simple property. `arg` is the new value
          obj[prop] = arg;
        }
      }

      // Notify dependents
      for (i = 0, dep = dependents[prop] || [], len = dep.length;
          i < len; i++) {
        accessor(dep[i], arg, true);
      }

      // Emit update event
      trigger('change', prop);

    } // if getter

  } // end accessor

  var instanceProperties = {
    values: obj,
    parent: parent,
    root: root,
    // .on(event[, prop], callback)
    on: on,
    // .off(event[, prop][, callback])
    off: off
  };

  var arrayProperties = {
    // Function prototype already contains length
    len: obj.length,

    pop: function() {
      var result = [].pop.apply(obj);
      this.len = this.values.length;
      trigger('delete', this.len, 1);
      return result;
    },

    push: function() {
      var result = [].push.apply(obj, arguments);
      this.len = this.values.length;
      trigger('insert', this.len - 1, 1);
      return result;
    },

    reverse: function() {
      var result = [].reverse.apply(obj);
      this.len = obj.length;
      trigger('delete', 0, this.len);
      trigger('insert', 0, this.len);
      return result;
    },

    shift: function() {
      var result = [].shift.apply(obj);
      this.len = obj.length;
      trigger('delete', 0, 1);
      return result;
    },

    unshift: function() {
      var result = [].unshift.apply(obj, arguments);
      this.len = obj.length;
      trigger('insert', 0, 1);
      return result;
    },

    sort: function() {
      var result = [].sort.apply(obj, arguments);
      trigger('delete', 0, this.len);
      trigger('insert', 0, this.len);
      return result;
    },

    splice: function() {
      var result = [].splice.apply(obj, arguments);
      this.len = obj.length;
      if (arguments[1]) {
        trigger('delete', arguments[0], arguments[1]);
      }
      if (arguments.length > 2) {
        trigger('insert', arguments[0], arguments.length - 2);
      }
      return result;
    }

  };

  var instance = function() {
    return accessor.apply(null, arguments);
  };
  mixin(instance, instanceProperties);

  if (Array.isArray(obj)) {
    mixin(instance, arrayProperties);
  }

  return instance;
}

// CommonJS export
if (typeof module === 'object') module.exports = freak;<commit_msg>dependency tracker cleanup<commit_after>'use strict';

function freak(obj, root, parent) {

  var listeners = {
    'change': {},
    'insert': {},
    'delete': {}
  };
  var dependents = {};
  var children = {};

  parent = parent || null;
  root = root || obj;

  function assert(cond, msg) {
    if (!cond) {
      throw msg || 'assertion failed';
    }
  }

  // Mix properties into target
  function mixin(target, properties) {
    for (var i = 0, props = Object.getOwnPropertyNames(properties), len = props.length;
        i < len; i++) {
      target[props[i]] = properties[props[i]];
    }
  }

  // Compose 2 functions
  // function compose(f, g) {
  //   var ctx = this;
  //   return function() {
  //     return f(g.apply(ctx, arguments));
  //   };
  // }

  // Event functions
  function on() {
    var event = arguments[0];
    var prop = typeof arguments[1] === 'string' ? arguments[1] : null;
    var callback =
      typeof arguments[1] === 'function' ?
        arguments[1] :
        typeof arguments[2] === 'function' ?
          arguments[2] : null;

    // Args check
    assert(['change', 'insert', 'delete'].indexOf(event) > -1);
    assert(
      (event === 'change' && prop) ||
      ((event === 'insert' || event === 'delete') && !prop)
    );

    // Init listeners for prop
    if (!listeners[event][prop]) {
      listeners[event][prop] = [];
    }
    // Already registered?
    if (listeners[event][prop].indexOf(callback) === -1) {
      listeners[event][prop].push(callback);
    }
  }

  function off() {
    var event = arguments[0];
    var prop = typeof arguments[1] === 'string' ? arguments[1] : null;
    var callback =
      typeof arguments[1] === 'function' ?
        arguments[1] :
        typeof arguments[2] === 'function' ?
          arguments[2] : null;
    var i;

    if (!listeners[event][prop]) return;

    // Remove all property watchers?
    if (!callback) {
      listeners[event][prop] = [];
    }
    else {
      // Remove specific callback
      i = listeners[event][prop].indexOf(callback);
      if (i > -1) {
        listeners[event][prop].splice(i, 1);
      }
    }

  }

  // trigger('change', prop)
  // trigger('insert' or 'delete', index, count)
  function trigger(event, a, b) {
    (listeners[event][event === 'change' ? a : null] || [])
      .map(function(listener) {
        listener.call(instance, a, b);
      });
  }

  // Functional accessor
  function accessor(prop, arg, refresh) {

    var i, len, dep, result, val;

    // Lift accessor, track dependencies
    function dependencyTracker(_prop, _arg, _refresh) {
      if (!dependents[_prop]) {
        dependents[_prop] = [];
      }
      if (dependents[_prop].indexOf(prop) === -1) {
        dependents[_prop].push(prop);
      }
      return accessor(_prop, _arg, _refresh);
    }

    // Getter?
    if ((arg === undefined || typeof arg === 'function') && !refresh) {

      val = obj[prop];

      result = (typeof val === 'function') ?
        // Computed property
        val.call(dependencyTracker) :
        // Static property (leaf in the dependency tree)
        val;

      return typeof result === 'object' ?

        typeof children[prop] === 'function' ?
          children[prop] :
          children[prop] = freak(val, root, obj) :

        result;
    }

    // Setterchildren[prop]
    else {

      if (!refresh) {
        if (typeof obj[prop] === 'function') {
          // Computed property setter
          obj[prop].call(dependencyTracker, arg);
        }
        else {
          // Simple property. `arg` is the new value
          obj[prop] = arg;
        }
      }

      // Notify dependents
      for (i = 0, dep = dependents[prop] || [], len = dep.length;
          i < len; i++) {
        accessor(dep[i], arg, true);
      }

      // Emit update event
      trigger('change', prop);

    } // if getter

  } // end accessor

  var instanceProperties = {
    values: obj,
    parent: parent,
    root: root,
    // .on(event[, prop], callback)
    on: on,
    // .off(event[, prop][, callback])
    off: off
  };

  var arrayProperties = {
    // Function prototype already contains length
    len: obj.length,

    pop: function() {
      var result = [].pop.apply(obj);
      this.len = this.values.length;
      trigger('delete', this.len, 1);
      return result;
    },

    push: function() {
      var result = [].push.apply(obj, arguments);
      this.len = this.values.length;
      trigger('insert', this.len - 1, 1);
      return result;
    },

    reverse: function() {
      var result = [].reverse.apply(obj);
      this.len = obj.length;
      trigger('delete', 0, this.len);
      trigger('insert', 0, this.len);
      return result;
    },

    shift: function() {
      var result = [].shift.apply(obj);
      this.len = obj.length;
      trigger('delete', 0, 1);
      return result;
    },

    unshift: function() {
      var result = [].unshift.apply(obj, arguments);
      this.len = obj.length;
      trigger('insert', 0, 1);
      return result;
    },

    sort: function() {
      var result = [].sort.apply(obj, arguments);
      trigger('delete', 0, this.len);
      trigger('insert', 0, this.len);
      return result;
    },

    splice: function() {
      var result = [].splice.apply(obj, arguments);
      this.len = obj.length;
      if (arguments[1]) {
        trigger('delete', arguments[0], arguments[1]);
      }
      if (arguments.length > 2) {
        trigger('insert', arguments[0], arguments.length - 2);
      }
      return result;
    }

  };

  var instance = function() {
    return accessor.apply(null, arguments);
  };
  mixin(instance, instanceProperties);

  if (Array.isArray(obj)) {
    mixin(instance, arrayProperties);
  }

  return instance;
}

// CommonJS export
if (typeof module === 'object') module.exports = freak;<|endoftext|>


<commit_before>/*
  Logging
*/

// Winston logging library
var winston = require('winston');
require('winston-mongo').Mongo;

// Settings
var logfile = './request.log';
var exceptionsfile = './exceptions.log';

// Set up logger and save locations
var logger = new (winston.Logger)({
  transports: [
    new winston.transports.Console()
    new winston.transports.File({filename: logfile})
    //new winston.transports.MongoDB({ db: 'db', level: 'info'})
  ]
  exceptionHandlers: [
    new winston.transports.File({ filename: exceptionsfile })
  ]
});

function getlogs(level) {
  var levels = ['error', 'warn', 'info'];

  var logs = [];

  return logs;
}
<commit_msg>File transport options<commit_after>/*
  Logging
*/

// Winston logging library
var winston = require('winston');
//require('winston-mongo').Mongo;

// Settings
var requestlog = ""./request.log";
var errorlog = "./error.log";
var exceptionsfile = "./exceptions.log";

// Set up logger and save locations
var logger = new (winston.Logger)({
  transports: [
    new winston.transports.Console({
      colorize: true
    }),

    new winston.transports.File({
      name: "request-log-file",
      filename: requestlog,
      timestamp: true,
      json: true,
      maxsize: 1000000,
      maxFiles: 1
    },

    new winston.transports.File({
      name: "error-log-file",
      filename: errorlog,
      level: 'error',
      timestamp: true,
      json: true,
      maxsize: 1000000,
      maxFiles: 1,
      handleExceptions: true
    })
    //new winston.transports.MongoDB({ db: 'db', level: 'info'})
  ]
});

function getlogs(level) {
  var levels = ['error', 'warn', 'info'];

  var logs = [];

  return logs;
}

// Tests
logger.info('Hello distributed logs. This is FYI only');
logger.warn('This is a warning');
logger.error('This is an error with some data', , {some: 'data''});

// Find items logged between today and yesterday.
var options = {
    from: new Date - 24 * 60 * 60 * 1000,
    until: new Date,
    limit: 10,
    start: 0,
    order: 'desc',
    fields: ['message']
  };

  winston.query(options, function (err, results) {
    if (err) {
      throw err;
    }
    console.log(results);
  });
<|endoftext|>


<commit_before>import Ember from 'ember';
import Queue from '../queue';
import sumBy from '../computed/sum-by';

const { get, set, computed, observer } = Ember;

/**
  The file queue service is a global file
  queue that manages all files being uploaded.

  This service can be used to query the current
  upload state when a user leaves the app,
  asking them whether they want to cancel
  the remaining uploads.

  @extends Ember.Service
  @for ember-file-upload
 */
export default Ember.Service.extend({

  /**
    @private
    Setup a map of uploaders so they may be
    accessed by name via the `find` method.
   */
  init() {
    set(this, 'queues', Ember.Map.create());
    set(this, 'files', Ember.A());
  },

  /**
    The list of all files in queues. This automatically gets
    flushed when all the files in the queue have settled.

    Note that files that have failed need to be manually
    removed from the queue. This is so they can be retried
    without resetting the state of the queue, orphaning the
    file from its queue. Upload failures can happen due to a
    timeout or a server response. If you choose to use the
    `abort` method, the file will fail to upload, but will
    be removed from the requeuing proccess, and will be
    considered to be in a settled state.

    @property files
    @type {File[]}
    @default []
   */
  files: [],

  /**
    @private

    Flushes the `files` property when they have settled. This
    will only flush files when all files have arrived at a terminus
    of their state chart.

    ```
        .------.     .---------.     .--------.
    o--| queued |-->| uploading |-->| uploaded |
        `------`     `---------`     `--------`
           ^              |    .-------.
           |              |`->| aborted |
           |              |    `-------`
           |  .------.    |    .---------.
           `-| failed |<-` `->| timed_out |-.
           |  `------`         `---------`  |
           `-------------------------------`
    ```

    Files *may* be requeued by the uesr in the `failed` or `timed_out`
    states.

    @method flushFilesWhenSettled
   */
  flushFilesWhenSettled: observer('files.@each.state', function () {
    let files = get(this, 'files');
    let allFilesHaveSettled = files.every(function (file) {
      return ['uploaded', 'aborted'].indexOf(file.state) !== -1;
    });

    if (allFilesHaveSettled) {
      get(this, 'files').forEach((file) => set(file, 'queue', null));
      set(this, 'files', Ember.A());
    }
  }),

  /**
    The total size of all files currently being uploaded in bytes.

    @property size
    @type Number
    @default 0
    @readonly
   */
  size: sumBy('files.@each.size'),

  /**
    The number of bytes that have been uploaded to the server.

    @property loaded
    @type Number
    @default 0
    @readonly
   */
  loaded: sumBy('files.@each.loaded'),

  /**
    The current progress of all uploads, as a percentage in the
    range of 0 to 100.

    @property progress
    @type Number
    @default 0
    @readonly
   */
  progress: computed('size', 'loaded', {
    get() {
      let percent = get(this, 'loaded') / get(this, 'size') || 0;
      return Math.floor(percent * 100);
    }
  }),

  /**
    Returns a queue with the given name

    @method find
    @param {String} name The name of the queue to find
    @return {Queue} The queue or null if it doesn't exist yet.
   */
  find(name) {
    return get(this, 'queues').get(name);
  },

  /**
    Create a new queue with the given name.

    @method create
    @param {String} name The name of the queue to create
    @return {Queue} The new queue.
   */
  create(name) {
    let queues = get(this, 'queues');
    Ember.assert(`Queue names are required to be unique. "${name}" has already been reserved.`, !queues.has(name));

    let queue = Queue.create({ name, fileQueue: this });
    queues.set(name, queue);

    return queue;
  }
});
<commit_msg>Return observer if files already is flushed or empty.<commit_after>import Ember from 'ember';
import Queue from '../queue';
import sumBy from '../computed/sum-by';

const { get, set, computed, observer } = Ember;

/**
  The file queue service is a global file
  queue that manages all files being uploaded.

  This service can be used to query the current
  upload state when a user leaves the app,
  asking them whether they want to cancel
  the remaining uploads.

  @extends Ember.Service
  @for ember-file-upload
 */
export default Ember.Service.extend({

  /**
    @private
    Setup a map of uploaders so they may be
    accessed by name via the `find` method.
   */
  init() {
    set(this, 'queues', Ember.Map.create());
    set(this, 'files', Ember.A());
  },

  /**
    The list of all files in queues. This automatically gets
    flushed when all the files in the queue have settled.

    Note that files that have failed need to be manually
    removed from the queue. This is so they can be retried
    without resetting the state of the queue, orphaning the
    file from its queue. Upload failures can happen due to a
    timeout or a server response. If you choose to use the
    `abort` method, the file will fail to upload, but will
    be removed from the requeuing proccess, and will be
    considered to be in a settled state.

    @property files
    @type {File[]}
    @default []
   */
  files: [],

  /**
    @private

    Flushes the `files` property when they have settled. This
    will only flush files when all files have arrived at a terminus
    of their state chart.

    ```
        .------.     .---------.     .--------.
    o--| queued |-->| uploading |-->| uploaded |
        `------`     `---------`     `--------`
           ^              |    .-------.
           |              |`->| aborted |
           |              |    `-------`
           |  .------.    |    .---------.
           `-| failed |<-` `->| timed_out |-.
           |  `------`         `---------`  |
           `-------------------------------`
    ```

    Files *may* be requeued by the uesr in the `failed` or `timed_out`
    states.

    @method flushFilesWhenSettled
   */
  flushFilesWhenSettled: observer('files.@each.state', function () {
    let files = get(this, 'files');
    let allFilesHaveSettled = files.every(function (file) {
      return ['uploaded', 'aborted'].indexOf(file.state) !== -1;
    });

    if (files.length <= 0) {
      return;
    }

    if (allFilesHaveSettled) {
      get(this, 'files').forEach((file) => set(file, 'queue', null));
      set(this, 'files', Ember.A());
    }
  }),

  /**
    The total size of all files currently being uploaded in bytes.

    @property size
    @type Number
    @default 0
    @readonly
   */
  size: sumBy('files.@each.size'),

  /**
    The number of bytes that have been uploaded to the server.

    @property loaded
    @type Number
    @default 0
    @readonly
   */
  loaded: sumBy('files.@each.loaded'),

  /**
    The current progress of all uploads, as a percentage in the
    range of 0 to 100.

    @property progress
    @type Number
    @default 0
    @readonly
   */
  progress: computed('size', 'loaded', {
    get() {
      let percent = get(this, 'loaded') / get(this, 'size') || 0;
      return Math.floor(percent * 100);
    }
  }),

  /**
    Returns a queue with the given name

    @method find
    @param {String} name The name of the queue to find
    @return {Queue} The queue or null if it doesn't exist yet.
   */
  find(name) {
    return get(this, 'queues').get(name);
  },

  /**
    Create a new queue with the given name.

    @method create
    @param {String} name The name of the queue to create
    @return {Queue} The new queue.
   */
  create(name) {
    let queues = get(this, 'queues');
    Ember.assert(`Queue names are required to be unique. "${name}" has already been reserved.`, !queues.has(name));

    let queue = Queue.create({ name, fileQueue: this });
    queues.set(name, queue);

    return queue;
  }
});
<|endoftext|>


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

var path = require('path');
var Runner = require('../lib/runner/runner')();
var utils = require('../lib/utils');
var argv = require('minimist')(process.argv.slice(2), {
  alias: {verbose: 'v'}
});

var cmd = utils.commands(argv);
var runner = new Runner(argv);

runner.base.option(argv);
runner.option(argv);

var task = cmd.list ? ['list', 'default'] : 'default';

runner.on('*', function(method, key, val) {
  console.log(method + ':', key, val);
});

if (argv.verbose) {
  runner.on('register', function(key) {
    utils.ok(utils.gray('registered'), 'updater', utils.cyan(key));
  });
}

runner.registerEach('update-*', {cwd: utils.gm});

runner.base.task('run', function(cb) {
  runner.run(cb);
});

runner.base.build(task, function(err) {
  if (err) return console.error(err);
  utils.timestamp('done ' + utils.green(utils.successSymbol));
});
<commit_msg>formatting, typo<commit_after>#!/usr/bin/env node

var path = require('path');
var Runner = require('../lib/runner/runner')();
var utils = require('../lib/utils');
var argv = require('minimist')(process.argv.slice(2), {
  alias: {verbose: 'v'}
});

var cmd = utils.commands(argv);
var runner = new Runner(argv);

runner.base.option(argv);
runner.option(argv);

var task = cmd.list ? ['list', 'default'] : ['default'];

runner.on('*', function(method, key, val) {
  console.log(method + ':', key, val);
});

if (argv.verbose) {
  runner.on('register', function(key) {
    utils.ok(utils.gray('registered'), 'updater', utils.cyan(key));
  });
}

runner.registerEach('update-*', {cwd: utils.gm});

runner.base.task('run', function(cb) {
  runner.run(cb);
});

runner.base.build(task, function(err) {
  if (err) return console.error(err);
  utils.timestamp('finished ' + utils.green(utils.successSymbol));
});
<|endoftext|>


<commit_before>'use strict';

var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del', '!gulp']
});
var _ = require('lodash');

module.exports = function(options) {
  var gulp = require(options.modulesData['gulp'].uses);

  gulp.task('partials', function () {

    return gulp.src([
      options.src + '/app/**/*.html',
      options.tmp + '/serve/app/**/*.html'
    ])
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true
      }))
      .pipe($.angularTemplatecache('templateCacheHtml.js', {
        module: options.mainAngularModule,
        root: 'app'
      }))
      .pipe(gulp.dest(options.tmp + '/partials/'));
  });

  gulp.task('copyEnviroments', ['scripts'], function(){
    var isDevTask = _.contains(options.devTasks, $.util.env._[0]);
    return gulp.src([options.srcEnv + '**/*.env.js'])
      .pipe( $.if(!isDevTask, gulp.dest(options.distEnv) ) );
  });

  gulp.task('copyEnviroments:tmp', ['scripts'], function(){
    return gulp.src([options.srcEnv + '**/*.env.js'])
      .pipe( gulp.dest(options.tmpEnv) )
  });

  gulp.task('html', ['inject', 'partials', 'copyEnviroments'], function () {
    var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', { read: false });
    var partialsInjectOptions = {
      starttag: '<!-- inject:partials -->',
      ignorePath: options.tmp + '/partials',
      addRootSlash: false
    };

    var htmlFilter = $.filter('*.html');
    var jsFilter = $.filter(['**/*.js', '!**/*.env.js']);
    var cssFilter = $.filter('**/*.css');
    var assets;

    return gulp.src(options.tmp + '/serve/*.html')
      .pipe($.inject(partialsInjectFile, partialsInjectOptions))
      .pipe(assets = $.useref.assets())
      .pipe($.rev())
      .pipe(jsFilter)
      .pipe($.ngAnnotate())
      .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', options.errorHandler('Uglify'))
      .pipe(jsFilter.restore())
      .pipe(cssFilter)
      .pipe($.replace('../../bower_components/bootstrap-sass-official/assets/fonts/bootstrap/', '../assets/fonts/'))
      .pipe($.csso())
      .pipe(cssFilter.restore())
      .pipe(assets.restore())
      .pipe($.useref())
      .pipe($.revReplace())
      .pipe(htmlFilter)
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true,
        conditionals: true
      }))
      .pipe(htmlFilter.restore())
      .pipe(gulp.dest(options.dist + '/'))
      .pipe($.size({ title: options.dist + '/', showFiles: true }));
  });

  gulp.task('templates:tmp', function () {
    return gulp.src([ options.src + '/app/**/*.html'])
      .pipe(gulp.dest(options.tmp + '/serve/app/'));
  });

  gulp.task('bower:tmp', function () {
    return gulp.src([ options.bowerComponents + '/**/*' ])
      .pipe(gulp.dest(options.tmp + '/serve/' + options.bowerComponents));
  });

  // Only applies for fonts from bower dependencies
  // Custom fonts are handled by the "other" task
  gulp.task('fonts', function () {
    return gulp.src($.mainBowerFiles())
      .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.dist + '/assets/fonts/'));
  });

  gulp.task('fonts:tmp', function () {
    return gulp.src($.mainBowerFiles())
      .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.tmp + '/serve/assets/fonts/'));
  });

  gulp.task('other', function () {
    return gulp.src([
      options.src + '/**/*',
      '!' + options.src + '/**/*.{html,css,js,scss,coffee}'
    ])
      .pipe(gulp.dest(options.dist + '/'));
  });

  gulp.task('other:tmp', function () {
    return gulp.src([
      options.src + '/**/*',
      '!' + options.src + '/**/*.{html,css,js,scss,coffee}'
    ])
      .pipe(gulp.dest(options.tmp + '/serve/'));
  });

  gulp.task('clean', function (done) {
    $.del([options.dist + '/', options.tmp + '/'], done);
  });

  gulp.task('build', ['html', 'fonts', 'other']);
};
<commit_msg>Changes the partials location<commit_after>'use strict';

var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del', '!gulp']
});
var _ = require('lodash');

module.exports = function(options) {
  var gulp = require(options.modulesData['gulp'].uses);

  gulp.task('partials', function () {

    return gulp.src([
      options.src + '/app/**/*.html',
      options.tmp + '/serve/app/**/*.html'
    ])
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true
      }))
      .pipe($.angularTemplatecache('templateCacheHtml.js', {
        module: options.mainAngularModule,
        root: 'app'
      }))
      .pipe(gulp.dest(options.tmp + '/serve/partials/'));
  });

  gulp.task('copyEnviroments', ['scripts'], function(){
    var isDevTask = _.contains(options.devTasks, $.util.env._[0]);
    return gulp.src([options.srcEnv + '**/*.env.js'])
      .pipe( $.if(!isDevTask, gulp.dest(options.distEnv) ) );
  });

  gulp.task('copyEnviroments:tmp', ['scripts'], function(){
    return gulp.src([options.srcEnv + '**/*.env.js'])
      .pipe( gulp.dest(options.tmpEnv) )
  });

  gulp.task('html', ['inject', 'partials', 'copyEnviroments'], function () {
    var partialsInjectFile = gulp.src(options.tmp + '/serve/partials/templateCacheHtml.js', { read: false });
    var partialsInjectOptions = {
      starttag: '<!-- inject:partials -->',
      ignorePath: options.tmp + '/serve/',
      addRootSlash: false
    };

    var htmlFilter = $.filter('*.html');
    var jsFilter = $.filter(['**/*.js', '!**/*.env.js']);
    var cssFilter = $.filter('**/*.css');
    var assets;

    return gulp.src(options.tmp + '/serve/*.html')
      .pipe($.inject(partialsInjectFile, partialsInjectOptions))
      .pipe(assets = $.useref.assets())
      .pipe($.rev())
      .pipe(jsFilter)
      .pipe($.ngAnnotate())
      .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', options.errorHandler('Uglify'))
      .pipe(jsFilter.restore())
      .pipe(cssFilter)
      .pipe($.replace('../../bower_components/bootstrap-sass-official/assets/fonts/bootstrap/', '../assets/fonts/'))
      .pipe($.csso())
      .pipe(cssFilter.restore())
      .pipe(assets.restore())
      .pipe($.useref())
      .pipe($.revReplace())
      .pipe(htmlFilter)
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true,
        conditionals: true
      }))
      .pipe(htmlFilter.restore())
      .pipe(gulp.dest(options.dist + '/'))
      .pipe($.size({ title: options.dist + '/', showFiles: true }));
  });

  gulp.task('templates:tmp', function () {
    return gulp.src([ options.src + '/app/**/*.html'])
      .pipe(gulp.dest(options.tmp + '/serve/app/'));
  });

  gulp.task('bower:tmp', function () {
    return gulp.src([ options.bowerComponents + '/**/*' ])
      .pipe(gulp.dest(options.tmp + '/serve/' + options.bowerComponents));
  });

  // Only applies for fonts from bower dependencies
  // Custom fonts are handled by the "other" task
  gulp.task('fonts', function () {
    return gulp.src($.mainBowerFiles())
      .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.dist + '/assets/fonts/'));
  });

  gulp.task('fonts:tmp', function () {
    return gulp.src($.mainBowerFiles())
      .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.tmp + '/serve/assets/fonts/'));
  });

  gulp.task('other', function () {
    return gulp.src([
      options.src + '/**/*',
      '!' + options.src + '/**/*.{html,css,js,scss,coffee}'
    ])
      .pipe(gulp.dest(options.dist + '/'));
  });

  gulp.task('other:tmp', function () {
    return gulp.src([
      options.src + '/**/*',
      '!' + options.src + '/**/*.{html,css,js,scss,coffee}'
    ])
      .pipe(gulp.dest(options.tmp + '/serve/'));
  });

  gulp.task('clean', function (done) {
    $.del([options.dist + '/', options.tmp + '/'], done);
  });

  gulp.task('build', ['html', 'fonts', 'other']);
};
<|endoftext|>


<commit_before>/* eslint-disable no-console */

import express from 'express';
import compression from 'compression';
import { resolve as pathResolve } from 'path';
import appRootDir from 'app-root-dir';
import reactApplication from './react-middleware';
import security from 'universally/src/server/middleware/security';
import clientBundle from 'universally/src/server/middleware/clientBundle';
import serviceWorker from 'universally/src/server/middleware/serviceWorker';
import offlinePage from 'universally/src/server/middleware/offlinePage';
import errorHandlers from 'universally/src/server/middleware/errorHandlers';
import config from 'universally/config';
import session from 'express-session';

// Create our express based server.
const app = express();

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

// Security middlewares.
app.use(...security);

// Gzip compress the responses.
app.use(compression());

// When in production mode, we will serve our service worker which was generated
// by the offline-plugin webpack plugin. See the webpack plugins section for
// more information.
// Note: the service worker needs to be served from the http root of your
// application for it to work correctly.
if (process.env.NODE_ENV === 'production' && config.serviceWorker.enabled) {
  app.get(`/${config.serviceWorker.fileName}`, serviceWorker);
  app.get(
    `${config.bundles.client.webPath}${config.serviceWorker.offlinePageFileName}`,
    offlinePage,
  );
}

// Configure serving of our client bundle.
app.use(config.bundles.client.webPath, clientBundle);

// Configure static serving of our "public" root http path static files.
// Note: these will be served off the root (i.e. '/') of our application.
app.use(express.static(pathResolve(appRootDir.get(), config.publicAssetsPath)));

app.useSession = (url, getArgs) => {
  app.set('trust proxy', 2);
  if (!getArgs) {
    getArgs = url;
    url = null;
  }
  const args = getArgs(session);
  if (url) app.use(url, session(args));
  else app.use(session(args));
};
app.useStatic = url => express.static(url);

try {
  const server = require('@root/server');
  if (server.default) {
    server.default(app);
  } else {
    server(app);
  }
} catch (err) { console.log('No server.js or server/index.js file found, using default settings'); }
// The React application middleware.
app.get('*', reactApplication);

// Error Handler middlewares.
app.use(...errorHandlers);

// Create an http listener for our express app.
const listener = app.listen(config.port, () =>
  console.log(`Server listening on port ${process.env.PORT || config.port}`),
);

// We export the listener as it will be handy for our development hot reloader,
// or for exposing a general extension layer for application customisations.
export default listener;
<commit_msg>fix graphiql<commit_after>/* eslint-disable no-console */

import express from 'express';
import compression from 'compression';
import { resolve as pathResolve } from 'path';
import appRootDir from 'app-root-dir';
import reactApplication from './react-middleware';
import security from 'universally/src/server/middleware/security';
import clientBundle from 'universally/src/server/middleware/clientBundle';
import serviceWorker from 'universally/src/server/middleware/serviceWorker';
import offlinePage from 'universally/src/server/middleware/offlinePage';
import errorHandlers from 'universally/src/server/middleware/errorHandlers';
import config from 'universally/config';
import session from 'express-session';

const launchAPI = () => {
  app.useSession = (url, getArgs) => {
    app.set('trust proxy', 2);
    if (!getArgs) {
      getArgs = url;
      url = null;
    }
    const args = getArgs(session);
    if (url) app.use(url, session(args));
    else app.use(session(args));
  };
  try {
    const server = require('@root/server');
    if (server.default) {
      server.default(app);
    } else {
      server(app);
    }
  } catch (err) { console.log('No server.js or server/index.js file found, using default settings'); }
}

// Create our express based server.
const app = express();

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

if (process.env.NODE_ENV !== 'production') launchAPI();
// Security middlewares.
app.use(...security);

// Gzip compress the responses.
app.use(compression());

// When in production mode, we will serve our service worker which was generated
// by the offline-plugin webpack plugin. See the webpack plugins section for
// more information.
// Note: the service worker needs to be served from the http root of your
// application for it to work correctly.
if (process.env.NODE_ENV === 'production' && config.serviceWorker.enabled) {
  app.get(`/${config.serviceWorker.fileName}`, serviceWorker);
  app.get(
    `${config.bundles.client.webPath}${config.serviceWorker.offlinePageFileName}`,
    offlinePage,
  );
}

// Configure serving of our client bundle.
app.use(config.bundles.client.webPath, clientBundle);

// Configure static serving of our "public" root http path static files.
// Note: these will be served off the root (i.e. '/') of our application.
app.use(express.static(pathResolve(appRootDir.get(), config.publicAssetsPath)));

app.useStatic = url => express.static(url);

if (process.env.NODE_ENV === 'production') launchAPI();
// The React application middleware.
app.get('*', reactApplication);

// Error Handler middlewares.
app.use(...errorHandlers);

// Create an http listener for our express app.
const listener = app.listen(config.port, () =>
  console.log(`Server listening on port ${process.env.PORT || config.port}`),
);

// We export the listener as it will be handy for our development hot reloader,
// or for exposing a general extension layer for application customisations.
export default listener;
<|endoftext|>


<commit_before>var utils = require('./_utils'),
  eslint = require('./eslint'),
  build = require('./build'),
  chokidar = require('chokidar')

module.exports = function(options) {

  options = utils.extend({
    // chokidar events we are going to watch
    // generally you should not touch them
    watchEvents: [
      'change',
      'add',
      'unlink',
      'unlinkDir',
      'addDir'
    ]
  }, options)

  // return a promise based on a certain task triggered
  var runOnlyOn = function(event) {
    if (~options.watchEvents.indexOf(event)) {
      // go to the next task
      return Promise.resolve()
    } else {
      return Promise.reject()
    }
  }

  // run eslint when a source file gets updated
  utils.print('Watching the files in the src/**/**/*.js path', 'cool')
  chokidar.watch('src/**/**/*.js', {
    ignoreInitial: true
  }).on('all', function(event) {
    // this tasks will run only if the current event matches the ones in the watchEvents array
    runOnlyOn(event)
      // .then(eslint)
      .then(build)
      .catch(e => utils.print(e, 'error'))
  })

}
<commit_msg>watch scss file changes too<commit_after>var utils = require('./_utils'),
  eslint = require('./eslint'),
  build = require('./build'),
  chokidar = require('chokidar')

module.exports = function(options) {

  options = utils.extend({
    // chokidar events we are going to watch
    // generally you should not touch them
    watchEvents: [
      'change',
      'add',
      'unlink',
      'unlinkDir',
      'addDir'
    ]
  }, options)

  // return a promise based on a certain task triggered
  var runOnlyOn = function(event) {
    if (~options.watchEvents.indexOf(event)) {
      // go to the next task
      return Promise.resolve()
    } else {
      return Promise.reject()
    }
  }

  // run eslint when a source file gets updated
  utils.print('Watching the files in the src/**/**/*.js path', 'cool')
  chokidar.watch(['src/**/**/*.js', '*.scss'], {
    ignoreInitial: true
  }).on('all', function(event) {
    // this tasks will run only if the current event matches the ones in the watchEvents array
    runOnlyOn(event)
      // .then(eslint)
      .then(build)
      .catch(e => utils.print(e, 'error'))
  })

}
<|endoftext|>


<commit_before>/* Copyright (c) 2015 Cristian Ianto, Richard Rodger MIT License */
'use strict'

var _ = require('lodash')
var Redis = require('redis')

var internals = {
  defaults: {
    'redis-queue': {
      timeout: 22222,
      type: 'redis-queue',
      host: 'localhost',
      port: 6379
    }
  }
}

module.exports = function (options) {
  var seneca = this
  var plugin = 'redis-queue-transport'

  var so = seneca.options()
  internals.defaults.timeout = so.timeout ? (so.timeout - 555) : internals.defaults.timeout

  options = seneca.util.deepextend(internals.defaults, so.transport, options)

  var tu = seneca.export('transport/utils')

  seneca.add({role: 'transport', hook: 'listen', type: 'redis-queue'}, hook_listen_redis)
  seneca.add({role: 'transport', hook: 'client', type: 'redis-queue'}, hook_client_redis)

  function hook_listen_redis (args, done) {
    var seneca = this
    var type = args.type
    var listen_options = seneca.util.clean(_.extend({}, options[type], args))

    var redis_in, redis_out
    if (listen_options.hasOwnProperty('url')) {
      redis_in = Redis.createClient(listen_options.url)
      redis_out = Redis.createClient(listen_options.url)
    }
    else {
      redis_in = Redis.createClient(listen_options.port, listen_options.host)
      redis_out = Redis.createClient(listen_options.port, listen_options.host)
    }

    handle_events(redis_in)
    handle_events(redis_out)

    function on_message (topic, msgstr) {
      var data = tu.parseJSON(seneca, 'listen-' + type, msgstr)

      tu.handle_request(seneca, data, listen_options, function (out) {
        if (out === null) {
          return
        }

        var outstr = tu.stringifyJSON(seneca, 'listen-' + type, out)
        redis_out.lpush(topic + '_res' + '/' + data.origin, outstr, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'redis-queue', err)
          }
        })
      })
    }

    tu.listen_topics(seneca, args, listen_options, function (topic) {
      seneca.log.debug('listen', 'brpop', topic + '_act', listen_options, seneca)

      var waiting = false
      function next () {
        waiting = true
        redis_in.brpop(topic + '_act', 0, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'server-redis-brpop', err)
            waiting = false
            return
          }
          if (!reply.length) {
            waiting = false
            return
          }
          on_message(topic, reply[1])
          setImmediate(next)
        })
      }
      setImmediate(function () {
        if (!waiting) {
          next()
        }
      })
    })

    seneca.add('role:seneca,cmd:close', function (close_args, done) {
      var closer = this

      redis_in.end(true)
      redis_out.end(true)
      closer.prior(close_args, done)
    })

    seneca.log.info('listen', 'open', listen_options, seneca)

    done()
  }

  function hook_client_redis (args, clientdone) {
    var seneca = this
    var type = args.type
    var client_options = seneca.util.clean(_.extend({}, options[type], args))

    tu.make_client(make_send, client_options, clientdone)

    function make_send (spec, topic, send_done) {
      var redis_in, redis_out
      if (listen_options.hasOwnProperty('url')) {
        redis_in = Redis.createClient(listen_options.url)
        redis_out = Redis.createClient(listen_options.url)
      }
      else {
        redis_in = Redis.createClient(listen_options.port, listen_options.host)
        redis_out = Redis.createClient(listen_options.port, listen_options.host)
      }

      handle_events(redis_in)
      handle_events(redis_out)

      function on_message (topic, msgstr) {
        var input = tu.parseJSON(seneca, 'client-' + type, msgstr)
        tu.handle_response(seneca, input, client_options)
      }

      seneca.log.debug('client', 'brpop', topic + '_res', client_options, seneca)

      var waiting = false
      function next () {
        waiting = true
        redis_in.brpop(topic + '_res' + '/' + seneca.id, 0, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'client-redis-brpop', err)
            waiting = false
            return
          }
          if (!reply.length) {
            waiting = false
            return
          }
          on_message(topic, reply[1])
          setImmediate(next)
        })
      }
      setImmediate(function () {
        if (!waiting) {
          next()
        }
      })

      send_done(null, function (args, done) {
        var outmsg = tu.prepare_request(this, args, done)
        var outstr = tu.stringifyJSON(seneca, 'client-' + type, outmsg)

        redis_out.lpush(topic + '_act', outstr, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'redis-queue', err)
          }
        })
      })

      seneca.add('role:seneca,cmd:close', function (close_args, done) {
        var closer = this

        redis_in.quit()
        redis_out.quit()
        closer.prior(close_args, done)
      })
    }
  }

  function handle_events (redisclient) {
    // Die if you can't connect initially
    redisclient.once('ready', function () {
      redisclient.on('error', function (err) {
        seneca.log.error('transport', 'redis', err)
      })
    })
  }

  return {
    name: plugin
  }
}
<commit_msg>Fix client options<commit_after>/* Copyright (c) 2015 Cristian Ianto, Richard Rodger MIT License */
'use strict'

var _ = require('lodash')
var Redis = require('redis')

var internals = {
  defaults: {
    'redis-queue': {
      timeout: 22222,
      type: 'redis-queue',
      host: 'localhost',
      port: 6379
    }
  }
}

module.exports = function (options) {
  var seneca = this
  var plugin = 'redis-queue-transport'

  var so = seneca.options()
  internals.defaults.timeout = so.timeout ? (so.timeout - 555) : internals.defaults.timeout

  options = seneca.util.deepextend(internals.defaults, so.transport, options)

  var tu = seneca.export('transport/utils')

  seneca.add({role: 'transport', hook: 'listen', type: 'redis-queue'}, hook_listen_redis)
  seneca.add({role: 'transport', hook: 'client', type: 'redis-queue'}, hook_client_redis)

  function hook_listen_redis (args, done) {
    var seneca = this
    var type = args.type
    var listen_options = seneca.util.clean(_.extend({}, options[type], args))

    var redis_in, redis_out
    if (listen_options.hasOwnProperty('url')) {
      redis_in = Redis.createClient(listen_options.url)
      redis_out = Redis.createClient(listen_options.url)
    }
    else {
      redis_in = Redis.createClient(listen_options.port, listen_options.host)
      redis_out = Redis.createClient(listen_options.port, listen_options.host)
    }

    handle_events(redis_in)
    handle_events(redis_out)

    function on_message (topic, msgstr) {
      var data = tu.parseJSON(seneca, 'listen-' + type, msgstr)

      tu.handle_request(seneca, data, listen_options, function (out) {
        if (out === null) {
          return
        }

        var outstr = tu.stringifyJSON(seneca, 'listen-' + type, out)
        redis_out.lpush(topic + '_res' + '/' + data.origin, outstr, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'redis-queue', err)
          }
        })
      })
    }

    tu.listen_topics(seneca, args, listen_options, function (topic) {
      seneca.log.debug('listen', 'brpop', topic + '_act', listen_options, seneca)

      var waiting = false
      function next () {
        waiting = true
        redis_in.brpop(topic + '_act', 0, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'server-redis-brpop', err)
            waiting = false
            return
          }
          if (!reply.length) {
            waiting = false
            return
          }
          on_message(topic, reply[1])
          setImmediate(next)
        })
      }
      setImmediate(function () {
        if (!waiting) {
          next()
        }
      })
    })

    seneca.add('role:seneca,cmd:close', function (close_args, done) {
      var closer = this

      redis_in.end(true)
      redis_out.end(true)
      closer.prior(close_args, done)
    })

    seneca.log.info('listen', 'open', listen_options, seneca)

    done()
  }

  function hook_client_redis (args, clientdone) {
    var seneca = this
    var type = args.type
    var client_options = seneca.util.clean(_.extend({}, options[type], args))

    tu.make_client(make_send, client_options, clientdone)

    function make_send (spec, topic, send_done) {
      var redis_in, redis_out
      if (client_options.hasOwnProperty('url')) {
        redis_in = Redis.createClient(client_options.url)
        redis_out = Redis.createClient(client_options.url)
      }
      else {
        redis_in = Redis.createClient(client_options.port, client_options.host)
        redis_out = Redis.createClient(client_options.port, client_options.host)
      }

      handle_events(redis_in)
      handle_events(redis_out)

      function on_message (topic, msgstr) {
        var input = tu.parseJSON(seneca, 'client-' + type, msgstr)
        tu.handle_response(seneca, input, client_options)
      }

      seneca.log.debug('client', 'brpop', topic + '_res', client_options, seneca)

      var waiting = false
      function next () {
        waiting = true
        redis_in.brpop(topic + '_res' + '/' + seneca.id, 0, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'client-redis-brpop', err)
            waiting = false
            return
          }
          if (!reply.length) {
            waiting = false
            return
          }
          on_message(topic, reply[1])
          setImmediate(next)
        })
      }
      setImmediate(function () {
        if (!waiting) {
          next()
        }
      })

      send_done(null, function (args, done) {
        var outmsg = tu.prepare_request(this, args, done)
        var outstr = tu.stringifyJSON(seneca, 'client-' + type, outmsg)

        redis_out.lpush(topic + '_act', outstr, function (err, reply) {
          if (err) {
            seneca.log.error('transport', 'redis-queue', err)
          }
        })
      })

      seneca.add('role:seneca,cmd:close', function (close_args, done) {
        var closer = this

        redis_in.quit()
        redis_out.quit()
        closer.prior(close_args, done)
      })
    }
  }

  function handle_events (redisclient) {
    // Die if you can't connect initially
    redisclient.once('ready', function () {
      redisclient.on('error', function (err) {
        seneca.log.error('transport', 'redis', err)
      })
    })
  }

  return {
    name: plugin
  }
}
<|endoftext|>


<commit_before>openerp.web_mobile.client_mobile = function(openerp) {
openerp.web_mobile.views.add('client_mobile', 'openerp.web_mobile.MobileWebClient');
openerp.web_mobile.MobileWebClient = openerp.web_mobile.Controller.extend({
    init: function(element_id) {
        var self = this;
        this._super(null, element_id);
        QWeb.add_template("xml/web_mobile.xml");
        var params = {};

        this.$element.html(QWeb.render("WebClient", {}));
        this.session = new openerp.base.Session("oe_errors");
        this.crashmanager =  new openerp.base.CrashManager(this.session);
        this.login = new openerp.web_mobile.Login(this.session, "oe_app");
        this.session.on_session_invalid.add(this.login.do_ask_login);
    },
    start: function() {
        this.session.start();
        this.login.start();
    }
});

openerp.web_mobile.mobilewebclient = function(element_id) {
    // TODO Helper to start mobile webclient rename it openerp.base.webclient
    var client = new openerp.web_mobile.MobileWebClient(element_id);
    client.start();
    return client;
};

openerp.web_mobile.Header =  openerp.base.Controller.extend({
    init: function(session, element_id) {
        this._super(session, element_id);
    },
    start: function() {
        this.$element.html(QWeb.render("Header", this));
        this.$element.find("a").click(this.on_clicked);
    },
    on_clicked: function(ev) {
        $opt = $(ev.currentTarget);
        current_id = $opt.attr('id');
        if (current_id == 'home') {
            this.homepage = new openerp.web_mobile.Login(this.session, "oe_app");
            this.homepage.on_login_valid();
        }
    }

});

openerp.web_mobile.Shortcuts =  openerp.base.Controller.extend({
    init: function(session, element_id) {
        this._super(session, element_id);
    },
    start: function() {
        var self = this;
        this.rpc('/base/session/sc_list',{} ,function(res){
            self.$element.html(QWeb.render("Shortcuts", {'sc' : res}))
            self.$element.find("a").click(self.on_clicked);
        })
    },
    on_clicked: function(ev) {
        $shortcut = $(ev.currentTarget);
        id = $shortcut.data('menu');
        res_id = $shortcut.data('res');
        jQuery("#oe_header").find("h1").html($shortcut.data('name'));
        this.listview = new openerp.web_mobile.ListView(this.session, "oe_app", res_id);
        this.listview.start();
    }
});
/*openerp.web_mobile.ListView = openerp.base.Controller.extend({
    init: function(session, element_id, list_id) {
        this._super(session, element_id);
        this.list_id = list_id;
    },
    start: function() {
        this.rpc('/base/menu/action', {'menu_id': this.list_id},
                    this.on_menu_action_loaded);
    },
    on_menu_action_loaded: function(data) {
        var self = this;
        if (data.action.length) {
            this.action = data.action[0][2];
            this.on_search_data('');
        }
    },
    on_search_data: function(request){
        if(request){
            if(request.term){
                var search_val = request.term;
            }else{
                if(request.which==27 || request.which==13 || request.which==9){
                    var search_val = '';
                }else if(request.which==38 || request.which==40 || request.which==39 || request.which==37){
                    return;
                }else if($("#searchid").val()==""){
                    var search_val = '';
                }else{
                    return;
                }
            }
        }
        else{
            var search_val = '';
        }
        var self = this;
        var dataset = new openerp.base.DataSetStatic(this.session, this.action.res_model, this.action.context);
        dataset.domain=[['name','ilike',search_val]];
        dataset.name_search(search_val, dataset.domain, 'ilike',false ,function(result){
            self.$element.html(QWeb.render("ListView", {'records' : result.result}));
            self.$element.find("#searchid").focus();
            if(request.term){
                self.$element.find("#searchid").val(request.term);
            }
            self.$element.find("#searchid").autocomplete({
                source: function(req) { self.on_search_data(req); },
                focus: function(e, ui) {
                    e.preventDefault();
                },
                html: true,
                minLength: 0,
                delay: 0
            });
            self.$element.find("#searchid").keyup(self.on_search_data);
            self.$element.find("a#list-id").click(self.on_list_click);
        });
    },
    on_list_click: function(ev) {
        $record = $(ev.currentTarget);
        var self = this;
        id = $record.data('id');
        model = this.action.res_model;
        view_id = this.action.views[1][0];
        this.dataset = new openerp.base.DataSetSearch(this.session, this.action.res_model, null, null);
        this.dataset.read_slice(false, false, false, function(result){
            for (var i = 0; i < result.length; i++) {
                if (result[i].id == id) {
                    var data = result[i];
                }
            }
            self.rpc("/base/formview/load", {"model": model, "view_id": view_id },
                function(result){
                    var view_fields = result.fields_view.arch.children;
                    get_fields = self.filter_fields(view_fields);
                    for (var j = 0; j < view_fields.length; j++) {
                        if (view_fields[j].tag == 'notebook') {
                            var notebooks = view_fields[j];
                        }
                    }
                    jQuery("#oe_header").find("h1").html(result.fields_view.arch.attrs.string);
                    self.$element.html(QWeb.render("FormView", {'get_fields': get_fields, 'notebooks': notebooks || false, 'fields' : result.fields_view.fields, 'values' : data}));
                });
        });
    },
    filter_fields: function(view_fields, fields) {
        this.fields = fields || [];
        for (var i=0; i < view_fields.length; i++){
            if (view_fields[i].tag == 'field') {
                this.fields.push(view_fields[i]);
            }
            if (view_fields[i].tag == 'group') {
                this.filter_fields(view_fields[i].children, this.fields);
            }
        }
        return this.fields;
    }
 });*/

openerp.web_mobile.Secondary =  openerp.base.Controller.extend({
    init: function(session, element_id, secondary_menu_id) {
        this._super(session, element_id);
        this.data = secondary_menu_id;
    },
    start: function(ev, id) {
        var v = { menu : this.data };
        this.$element.html(QWeb.render("Menu.secondary", v));
        this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
    },
    on_menu_click: function(ev, id) {
        $menu = $(ev.currentTarget);
        id = $menu.data('menu');
        for (var i = 0; i < this.data.children.length; i++) {
            if (this.data.children[i].id == id) {
                this.children = this.data.children[i];
            }
        }
        jQuery("#oe_header").find("h1").html($menu.data('name'));

        var child_len = this.children.children.length;
        if (child_len > 0) {
            this.$element
                .removeClass("secondary_menu")
                .addClass("content_menu");
                //.hide();
            this.secondary = new openerp.web_mobile.Secondary(this.session, "oe_app", this.children);
            this.secondary.start();
        }
        else {
            if (id) {
                this.listview = new openerp.web_mobile.ListView(this.session, "oe_app", id);
                this.listview.start();
            }
        }
    }
});

openerp.web_mobile.Menu =  openerp.base.Controller.extend({
    init: function(session, element_id, secondary_menu_id) {
        this._super(session, element_id);
        this.secondary_menu_id = secondary_menu_id;
        this.$secondary_menu = $("#" + secondary_menu_id);
        this.menu = false;
    },
    start: function() {
        this.rpc("/base/menu/load", {}, this.on_loaded);
    },
    on_loaded: function(data) {
        this.data = data;
        this.$element.html(QWeb.render("Menu", this.data));
        this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
    },
    on_menu_click: function(ev, id) {
        $menu = $(ev.currentTarget);
        id = $menu.data('menu');
        for (var i = 0; i < this.data.data.children.length; i++) {
            if (this.data.data.children[i].id == id) {
                this.children = this.data.data.children[i];
            }
        }
        jQuery("#oe_header").find("h1").html($menu.data('name'));
        this.$element
            .removeClass("login_valid")
            .addClass("secondary_menu");
            //.hide();
        this.secondary = new openerp.web_mobile.Secondary(this.session, "oe_app", this.children);
        this.secondary.start();
    }
});

openerp.web_mobile.Options =  openerp.base.Controller.extend({
    init: function(session, element_id) {
        this._super(session, element_id);
    },
    start: function() {
        var self = this;
        this.$element.html(QWeb.render("Options", this));
        self.$element.find("#logout").click(self.on_logout);
    },
    on_logout: function(ev) {
        this.session.logout();
        this.login = new openerp.web_mobile.Login(this.session, "oe_app");
        this.login.start();
    }
});
openerp.web_mobile.Login =  openerp.base.Controller.extend({
    init: function(session, element_id) {
        this._super(session, element_id);
    },
    start: function() {
        var self = this;

        jQuery("#oe_header").children().remove();
        this.rpc("/base/session/get_databases_list", {}, function(result) {
            self.db_list = result.db_list;
            self.$element.html(QWeb.render("Login", self));
            self.$element.find('#database').click(self.on_db_select);
            self.$element.find("#login").click(self.on_login);
            $.mobile.initializePage();
        })
    },
    on_db_select: function(ev) {
        var db = this.$element.find("#database option:selected").val();
        jQuery("#db_text").html(db);
    },
    on_login: function(ev) {
        ev.preventDefault();
        var self = this;
        var $e = this.$element;
        var db = $e.find("div select[name=database]").val();
        var login = $e.find("div input[name=login]").val();
        var password = $e.find("div input[name=password]").val();
        //$e.hide();
        // Should hide then call callback
        this.session.session_login(db, login, password, function() {
            if(self.session.session_is_valid()) {
                self.on_login_valid();
            } else {
                self.on_login_invalid();
            }
        });
    },
    on_login_invalid: function() {
        this.$element
            .removeClass("login_valid")
            .addClass("login_invalid")
            .show();
    },
    on_login_valid: function() {
        this.$element
            .removeClass("login_invalid")
            .addClass("login_valid");
            //.hide();
        this.$element.html(QWeb.render("HomePage", {}));
        this.header = new openerp.web_mobile.Header(this.session, "oe_header");
        this.shortcuts = new openerp.web_mobile.Shortcuts(this.session, "oe_shortcuts");
        this.menu = new openerp.web_mobile.Menu(this.session, "oe_menu", "oe_secondary_menu");
        this.options = new openerp.web_mobile.Options(this.session, "oe_options");
        this.header.start();
        this.shortcuts.start();
        this.menu.start();
        this.options.start();
        jQuery("#oe_header").find("h1").html('Home');

    },
    do_ask_login: function(continuation) {
        this.on_login_invalid();
        this.on_login_valid.add({
            position: "last",
            unique: true,
            callback: continuation
        });
    }
});
}
<commit_msg>[REM] Removed unnecessary file.<commit_after><|endoftext|>


<commit_before>// $Id$
(function ($) {

/**
 * Provides AJAX-like page updating via AHAH (Asynchronous HTML and HTTP).
 *
 * AHAH is a method of making a request via Javascript while viewing an HTML
 * page. The request returns a small chunk of HTML, which is then directly
 * injected into the page.
 *
 * Drupal uses this file to enhance form elements with #ahah[path] and
 * #ahah[wrapper] properties. If set, this file will automatically be included
 * to provide AHAH capabilities.
 */

/**
 * Attaches the ahah behavior to each ahah form element.
 */
Drupal.behaviors.ahah = {
  attach: function (context, settings) {
    for (var base in settings.ahah) {
      if (!$('#' + base + '.ahah-processed').size()) {
        var element_settings = settings.ahah[base];

        $(element_settings.selector).each(function () {
          element_settings.element = this;
          var ahah = new Drupal.ahah(base, element_settings);
        });

        $('#' + base).addClass('ahah-processed');
      }
    }
  }
};

/**
 * AHAH object.
 */
Drupal.ahah = function (base, element_settings) {
  // Set the properties for this object.
  this.element = element_settings.element;
  this.selector = element_settings.selector;
  this.event = element_settings.event;
  this.keypress = element_settings.keypress;
  this.url = element_settings.url;
  this.wrapper = '#' + element_settings.wrapper;
  this.effect = element_settings.effect;
  this.method = element_settings.method;
  this.progress = element_settings.progress;
  this.button = element_settings.button || { };

  if (this.effect == 'none') {
    this.showEffect = 'show';
    this.hideEffect = 'hide';
    this.showSpeed = '';
  }
  else if (this.effect == 'fade') {
    this.showEffect = 'fadeIn';
    this.hideEffect = 'fadeOut';
    this.showSpeed = 'slow';
  }
  else {
    this.showEffect = this.effect + 'Toggle';
    this.hideEffect = this.effect + 'Toggle';
    this.showSpeed = 'slow';
  }

  // Record the form action and target, needed for iFrame file uploads.
  var form = $(this.element).parents('form');
  this.form_action = form.attr('action');
  this.form_target = form.attr('target');
  this.form_encattr = form.attr('encattr');

  // Set the options for the ajaxSubmit function.
  // The 'this' variable will not persist inside of the options object.
  var ahah = this;
  var options = {
    url: ahah.url,
    data: ahah.button,
    beforeSubmit: function (form_values, element_settings, options) {
      return ahah.beforeSubmit(form_values, element_settings, options);
    },
    success: function (response, status) {
      // Sanity check for browser support (object expected).
      // When using iFrame uploads, responses must be returned as a string.
      if (typeof response == 'string') {
        response = Drupal.parseJson(response);
      }
      return ahah.success(response, status);
    },
    complete: function (response, status) {
      if (status == 'error' || status == 'parsererror') {
        return ahah.error(response, ahah.url);
      }
    },
    dataType: 'json',
    type: 'POST'
  };

  // Bind the ajaxSubmit function to the element event.
  $(element_settings.element).bind(element_settings.event, function () {
    $(element_settings.element).parents('form').ajaxSubmit(options);
    return false;
  });
  // If necessary, enable keyboard submission so that AHAH behaviors
  // can be triggered through keyboard input as well as e.g. a mousedown
  // action.
  if (element_settings.keypress) {
    $(element_settings.element).keypress(function (event) {
      // Detect enter key.
      if (event.keyCode == 13) {
        $(element_settings.element).trigger(element_settings.event);
        return false;
      }
    });
  }
};

/**
 * Handler for the form redirection submission.
 */
Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) {
  // Disable the element that received the change.
  $(this.element).addClass('progress-disabled').attr('disabled', true);

  // Insert progressbar or throbber.
  if (this.progress.type == 'bar') {
    var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
    if (this.progress.message) {
      progressBar.setProgress(-1, this.progress.message);
    }
    if (this.progress.url) {
      progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
    }
    this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar');
    this.progress.object = progressBar;
    $(this.element).after(this.progress.element);
  }
  else if (this.progress.type == 'throbber') {
    this.progress.element = $('

');
    if (this.progress.message) {
      $('.throbber', this.progress.element).after('
' + this.progress.message + '
');
    }
    $(this.element).after(this.progress.element);
  }
};

/**
 * Handler for the form redirection completion.
 */
Drupal.ahah.prototype.success = function (response, status) {
  var wrapper = $(this.wrapper);
  var form = $(this.element).parents('form');
  // Manually insert HTML into the jQuery object, using $() directly crashes
  // Safari with long string lengths. http://dev.jquery.com/ticket/1152
  var new_content = $('

').html(response.data);

  // Restore the previous action and target to the form.
  form.attr('action', this.form_action);
  this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
  this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');

  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').attr('disabled', false);

  // Add the new content to the page.
  Drupal.freezeHeight();
  if (this.method == 'replace') {
    wrapper.empty().append(new_content);
  }
  else {
    wrapper[this.method](new_content);
  }

  // Immediately hide the new content if we're using any effects.
  if (this.showEffect != 'show') {
    new_content.hide();
  }

  // Determine what effect use and what content will receive the effect, then
  // show the new content.
  if ($('.ahah-new-content', new_content).size() > 0) {
    $('.ahah-new-content', new_content).hide();
    new_content.show();
    $('.ahah-new-content', new_content)[this.showEffect](this.showSpeed);
  }
  else if (this.showEffect != 'show') {
    new_content[this.showEffect](this.showSpeed);
  }

  // Attach all javascript behaviors to the new content, if it was successfully
  // added to the page, this if statement allows #ahah[wrapper] to be optional.
  if (new_content.parents('html').length > 0) {
    // Apply any settings from the returned JSON if available.
    var settings = response.settings || Drupal.settings;
    Drupal.attachBehaviors(new_content, settings);
  }

  Drupal.unfreezeHeight();
};

/**
 * Handler for the form redirection error.
 */
Drupal.ahah.prototype.error = function (response, uri) {
  alert(Drupal.ahahError(response, uri));
  // Resore the previous action and target to the form.
  $(this.element).parent('form').attr({ action: this.form_action, target: this.form_target });
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progress-disabled').attr('disabled', false);
};

})(jQuery);
<commit_msg>- Patch #396466 by quicksketch: support custom success callbacks in ahah.js.<commit_after>// $Id$
(function ($) {

/**
 * Provides AJAX-like page updating via AHAH (Asynchronous HTML and HTTP).
 *
 * AHAH is a method of making a request via Javascript while viewing an HTML
 * page. The request returns a small chunk of HTML, which is then directly
 * injected into the page.
 *
 * Drupal uses this file to enhance form elements with #ahah[path] and
 * #ahah[wrapper] properties. If set, this file will automatically be included
 * to provide AHAH capabilities.
 */

Drupal.ahah = Drupal.ahah || {};

/**
 * Attaches the ahah behavior to each ahah form element.
 */
Drupal.behaviors.ahah = {
  attach: function (context, settings) {
    for (var base in settings.ahah) {
      if (!$('#' + base + '.ahah-processed').size()) {
        var element_settings = settings.ahah[base];

        $(element_settings.selector).each(function () {
          element_settings.element = this;
          Drupal.ahah[base] = new Drupal.ahah(base, element_settings);
        });

        $('#' + base).addClass('ahah-processed');
      }
    }
  }
};

/**
 * AHAH object.
 *
 * All AHAH objects on a page are accessible through the global Drupal.ahah object
 * and are keyed by the submit button's ID. You can access them from your module's
 * JavaScript file to override properties or functions.
 * For example, if your AHAH enabled button has the ID 'edit-submit', you can
 * redefine the function that is called to insert the new content like this
 * (inside a Drupal.behaviors attach block):
 * @code
 *    Drupal.behaviors.myCustomAhahStuff = {
 *      attach: function(context, settings) {
 *        Drupal.ahah['edit-submit'].insertNewContent = function(response, status) {
 *          new_content = $(response.data);
 *          $('#my-wrapper').append(new_content);
 *          alert('New content was appended to #my-wrapper');
 *        }
 *      }
 *    };
 * @endcode
 */
Drupal.ahah = function (base, element_settings) {
  // Set the properties for this object.
  this.element = element_settings.element;
  this.selector = element_settings.selector;
  this.event = element_settings.event;
  this.keypress = element_settings.keypress;
  this.url = element_settings.url;
  this.wrapper = '#' + element_settings.wrapper;
  this.effect = element_settings.effect;
  this.method = element_settings.method;
  this.progress = element_settings.progress;
  this.button = element_settings.button || { };

  if (this.effect == 'none') {
    this.showEffect = 'show';
    this.hideEffect = 'hide';
    this.showSpeed = '';
  }
  else if (this.effect == 'fade') {
    this.showEffect = 'fadeIn';
    this.hideEffect = 'fadeOut';
    this.showSpeed = 'slow';
  }
  else {
    this.showEffect = this.effect + 'Toggle';
    this.hideEffect = this.effect + 'Toggle';
    this.showSpeed = 'slow';
  }

  // Record the form action and target, needed for iFrame file uploads.
  var form = $(this.element).parents('form');
  this.form_action = form.attr('action');
  this.form_target = form.attr('target');
  this.form_encattr = form.attr('encattr');

  // Set the options for the ajaxSubmit function.
  // The 'this' variable will not persist inside of the options object.
  var ahah = this;
  var options = {
    url: ahah.url,
    data: ahah.button,
    beforeSubmit: function (form_values, element_settings, options) {
      return ahah.beforeSubmit(form_values, element_settings, options);
    },
    success: function (response, status) {
      // Sanity check for browser support (object expected).
      // When using iFrame uploads, responses must be returned as a string.
      if (typeof response == 'string') {
        response = Drupal.parseJson(response);
      }
      return ahah.success(response, status);
    },
    complete: function (response, status) {
      if (status == 'error' || status == 'parsererror') {
        return ahah.error(response, ahah.url);
      }
    },
    dataType: 'json',
    type: 'POST'
  };

  // Bind the ajaxSubmit function to the element event.
  $(element_settings.element).bind(element_settings.event, function () {
    $(element_settings.element).parents('form').ajaxSubmit(options);
    return false;
  });
  // If necessary, enable keyboard submission so that AHAH behaviors
  // can be triggered through keyboard input as well as e.g. a mousedown
  // action.
  if (element_settings.keypress) {
    $(element_settings.element).keypress(function (event) {
      // Detect enter key.
      if (event.keyCode == 13) {
        $(element_settings.element).trigger(element_settings.event);
        return false;
      }
    });
  }
};

/**
 * Handler for the form redirection submission.
 */
Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) {
  // Disable the element that received the change.
  $(this.element).addClass('progress-disabled').attr('disabled', true);

  // Insert progressbar or throbber.
  if (this.progress.type == 'bar') {
    var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
    if (this.progress.message) {
      progressBar.setProgress(-1, this.progress.message);
    }
    if (this.progress.url) {
      progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
    }
    this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar');
    this.progress.object = progressBar;
    $(this.element).after(this.progress.element);
  }
  else if (this.progress.type == 'throbber') {
    this.progress.element = $('

');
    if (this.progress.message) {
      $('.throbber', this.progress.element).after('
' + this.progress.message + '
');
    }
    $(this.element).after(this.progress.element);
  }
};

/**
 * Handler for the form redirection completion.
 */
Drupal.ahah.prototype.success = function (response, status) {
  var form = $(this.element).parents('form');

  // Restore the previous action and target to the form.
  form.attr('action', this.form_action);
  this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
  this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');

  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').attr('disabled', false);

  Drupal.freezeHeight();

  // Call the insertNewContent handler to insert the new content into the page.
  this.insertNewContent(response, status);

  Drupal.unfreezeHeight();
};

/**
 * Handler to insert the new content into the page.
 */
Drupal.ahah.prototype.insertNewContent = function (response, status) {
  var wrapper = $(this.wrapper);

  // Manually insert HTML into the jQuery object, using $() directly crashes
  // Safari with long string lengths. http://dev.jquery.com/ticket/1152
  var new_content = $('

').html(response.data);

  // Add the new content to the page.
  if (this.method == 'replace') {
    wrapper.empty().append(new_content);
  }
  else {
    wrapper[this.method](new_content);
  }

  // Immediately hide the new content if we're using any effects.
  if (this.showEffect != 'show') {
    new_content.hide();
  }

  // Determine what effect use and what content will receive the effect, then
  // show the new content.
  if ($('.ahah-new-content', new_content).size() > 0) {
    $('.ahah-new-content', new_content).hide();
    new_content.show();
    $('.ahah-new-content', new_content)[this.showEffect](this.showSpeed);
  }
  else if (this.showEffect != 'show') {
    new_content[this.showEffect](this.showSpeed);
  }

  // Attach all javascript behaviors to the new content, if it was successfully
  // added to the page, this if statement allows #ahah[wrapper] to be optional.
  if (new_content.parents('html').length > 0) {
    // Apply any settings from the returned JSON if available.
    var settings = response.settings || Drupal.settings;
    Drupal.attachBehaviors(new_content, settings);
  }
};

/**
 * Handler for the form redirection error.
 */
Drupal.ahah.prototype.error = function (response, uri) {
  alert(Drupal.ahahError(response, uri));
  // Resore the previous action and target to the form.
  $(this.element).parent('form').attr({ action: this.form_action, target: this.form_target });
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progress-disabled').attr('disabled', false);
};

})(jQuery);
<|endoftext|>


<commit_before>import moment from 'moment';
import React from 'react';

import { RelativeTime } from 'components/Time';

import { formatMb } from 'utils/Quota';
import { constraintToString, getResource, getResources, instanceRangeToString } from 'utils/Task';
import { COLLISION_POLICY } from 'utils/Thrift';

// ESLint doesn't like React's new adjacent elements, so we need to disable it here
/* eslint-disable */
function Resources({ config }) {
  return [

    Resources
    cpus
    {getResource(config.resources, 'numCpus').numCpus}

,

    ram
    {formatMb(getResource(config.resources, 'ramMb').ramMb)}

,

    disk
    {formatMb(getResource(config.resources, 'diskMb').diskMb)}

,

    ports
    {getResources(config.resources, 'namedPort').map((r) => r.namedPort).join(', ')}

];
}
/* eslint-enable */

function Constraints({ config }) {
  return (

    Constraints

      {config.constraints.map((t) => (
        {t.name}: {constraintToString(t.constraint)}
      ))}

);
}

function Metadata({ config }) {
  return (

    Metadata

      {config.metadata.map((m, i) => (<span className='task-metadata' key={`${m.key}-${i}`}>
        {m.key}: {m.value}
      ))}

);
}

export function CronConfigSummary({ cronJob }) {
  const config = cronJob.job.taskConfig;
  return (

          Cron Job Configuration

        Cron Schedule
        {cronJob.job.cronSchedule}

        Collision Policy
        {COLLISION_POLICY[cronJob.job.cronCollisionPolicy]}

        Next Cron Run

          {moment(cronJob.nextCronRunMs).utc().format('MMMM Do YYYY, h:mm:ss a')} UTC (
          <RelativeTime ts={cronJob.nextCronRunMs} />)

        # Instances
        {cronJob.job.instanceCount}

      <Resources config={config} />
      <Constraints config={config} />

        Tier
        {config.tier}

      <Metadata config={config} />

        Contact
        {config.contactEmail}

);
}

export default function TaskConfigSummary({ config, instances }) {
  return (

          Configuration for instance {instanceRangeToString(instances)}

      <Resources config={config} />
      <Constraints config={config} />

        Tier
        {config.tier}

        Service
        {config.isService ? 'true' : 'false'}

      <Metadata config={config} />

        Contact
        {config.contactEmail}

);
}
<commit_msg>Add PartitionPolicy to config summary when defined<commit_after>import moment from 'moment';
import React from 'react';

import { RelativeTime } from 'components/Time';

import { isNully } from 'utils/Common';
import { formatMb } from 'utils/Quota';
import { constraintToString, getResource, getResources, instanceRangeToString } from 'utils/Task';
import { COLLISION_POLICY } from 'utils/Thrift';

// ESLint doesn't like React's new adjacent elements, so we need to disable it here
/* eslint-disable */
function Resources({ config }) {
  return [

    Resources
    cpus
    {getResource(config.resources, 'numCpus').numCpus}

,

    ram
    {formatMb(getResource(config.resources, 'ramMb').ramMb)}

,

    disk
    {formatMb(getResource(config.resources, 'diskMb').diskMb)}

,

    ports
    {getResources(config.resources, 'namedPort').map((r) => r.namedPort).join(', ')}

];
}
/* eslint-enable */

function Constraints({ config }) {
  return (

    Constraints

      {config.constraints.map((t) => (
        {t.name}: {constraintToString(t.constraint)}
      ))}

);
}

function Metadata({ config }) {
  return (

    Metadata

      {config.metadata.map((m, i) => (<span className='task-metadata' key={`${m.key}-${i}`}>
        {m.key}: {m.value}
      ))}

);
}

// ESLint doesn't like React's new adjacent elements, so we need to disable it here
/* eslint-disable */
function PartitionPolicy({ config }) {
  if (isNully(config.partitionPolicy)) {
    return null;
  }

  return [

    Partition Policy
    reschedule
    {'' + config.partitionPolicy.reschedule}

,

    delay secs
    {config.partitionPolicy.delaySecs}

];
}
/* eslint-enable */

export function CronConfigSummary({ cronJob }) {
  const config = cronJob.job.taskConfig;
  return (

          Cron Job Configuration

        Cron Schedule
        {cronJob.job.cronSchedule}

        Collision Policy
        {COLLISION_POLICY[cronJob.job.cronCollisionPolicy]}

        Next Cron Run

          {moment(cronJob.nextCronRunMs).utc().format('MMMM Do YYYY, h:mm:ss a')} UTC (
          <RelativeTime ts={cronJob.nextCronRunMs} />)

        # Instances
        {cronJob.job.instanceCount}

      <Resources config={config} />
      <Constraints config={config} />

        Tier
        {config.tier}

      <Metadata config={config} />
      <PartitionPolicy config={config} />

        Contact
        {config.contactEmail}

);
}

export default function TaskConfigSummary({ config, instances }) {
  return (

          Configuration for instance {instanceRangeToString(instances)}

      <Resources config={config} />
      <Constraints config={config} />

        Tier
        {config.tier}

        Service
        {config.isService ? 'true' : 'false'}

      <Metadata config={config} />
      <PartitionPolicy config={config} />

        Contact
        {config.contactEmail}

);
}
<|endoftext|>


<commit_before>var fileSets = [
  [
    "canvas/init.js",
    "draw/init.js",
    "physics/init.js"
  ],
  [
    "canvas/utils/configure.js",
    "canvas/utils/deconfigure.js",
    "canvas/utils/resize.js",
    "canvas/utils/coordinates.js",
    "physics/minilibs/equation.js",
    "physics/minilibs/vector2.js",
    "physics/minilibs/collisiondetection.js",
  ],
  [
    "draw/colors/fill.js",
    "draw/colors/stroke.js",
    "draw/colors/nostroke.js",
    "draw/colors/nofill.js",
    "draw/colors/getfill.js",
    "draw/colors/getstroke.js",
    "draw/settings/strokeweight.js",
    "draw/settings/getstrokeweight.js",
    "draw/settings/rectmode.js",
    "draw/settings/ellipsemode.js",
    "draw/settings/imagemode.js",
    "draw/settings/getrectmode.js",
    "draw/settings/getellipsemode.js",
    "draw/settings/getimagemode.js",
    "draw/settings/strokejoin.js",
    "draw/settings/strokecap.js",
    "draw/settings/getstrokejoin.js",
    "draw/settings/getstrokecap.js",
    "draw/settings/textfont.js",
    "draw/settings/gettextfont.js",
    "draw/settings/textsize.js",
    "draw/settings/gettextsize.js",
    "draw/transform/popmatrix.js",
    "draw/transform/pushmatrix.js",
    "draw/transform/resetmatrix.js",
    "draw/transform/rotate.js",
    "draw/transform/scale.js",
    "draw/transform/skew.js",
    "draw/transform/translate.js",
    "draw/shapes/arc.js",
    "draw/shapes/background.js",
    "draw/shapes/beginshape.js",
    "draw/shapes/beziervertex.js",
    "draw/shapes/ellipse.js",
    "draw/shapes/endshape.js",
    "draw/shapes/line.js",
    "draw/shapes/point.js",
    "draw/shapes/poly.js",
    "draw/shapes/quadvertex.js",
    "draw/shapes/rect.js",
    "draw/shapes/text.js",
    "draw/shapes/vertex.js",
    "draw/image/images.js",
    "draw/image/loadimage.js",
    "draw/image/loadimageset.js",
    "draw/image/image.js",
    "draw/image/get.js",
  ],
  [
    "physics/entities/circle.js",
    "physics/entities/line.js",
    "physics/entities/constraints/constraint.js",
    "physics/entities/constraints/bungee.js",
    "physics/entities/constraints/compressor.js",
    "physics/entities/constraints/cord.js",
    "physics/entities/constraints/extender.js",
    "physics/entities/constraints/rod.js",
    "physics/entities/constraints/spring.js",
  ]
];

function load(onComplete, override) {
  if(KAPhy.version === KAPhy.current) {
    if(onComplete) onComplete();
    return;
  }

  function importJS(filename, onLoad) {
    var newScript = document.createElement("script");

    newScript.type = "text/javascript";
    newScript.src = "https://rawgit.com/TemporalFuzz/KAPhy/master/" + filename;

    newScript.onload = onLoad;

    document.head.appendChild(newScript);
  }

  function importSetJS(fileset, onFinish) {
    var filesLoaded = 0;

    for(var i = 0; i < fileset.length; i++) {
      importJS(fileset[i], function() {
        filesLoaded++;
        if(filesLoaded >= fileset.length - 1) {
          if(onFinish) onFinish();
        }
      });
    }
  }

  var i = 0;
  function loadNext() {
    i++;
    console.log(i + " packages loaded!");
    if (i >= fileSets.length) {
      KAPhy.finishUpdate();
      if (onComplete) onComplete();
      return;
    }
    importSetJS(filesSets[i], loadNext);
  };
  importSetJS(filesSets[i], loadNext);
}
<commit_msg>Update init.js<commit_after>var fileSets = [
  [
    "canvas/init.js",
    "draw/init.js",
    "physics/init.js"
  ],
  [
    "canvas/utils/configure.js",
    "canvas/utils/deconfigure.js",
    "canvas/utils/resize.js",
    "canvas/utils/coordinates.js",
    "physics/minilibs/equation.js",
    "physics/minilibs/vector2.js",
    "physics/minilibs/collisiondetection.js",
  ],
  [
    "draw/colors/fill.js",
    "draw/colors/stroke.js",
    "draw/colors/nostroke.js",
    "draw/colors/nofill.js",
    "draw/colors/getfill.js",
    "draw/colors/getstroke.js",
    "draw/settings/strokeweight.js",
    "draw/settings/getstrokeweight.js",
    "draw/settings/rectmode.js",
    "draw/settings/ellipsemode.js",
    "draw/settings/imagemode.js",
    "draw/settings/getrectmode.js",
    "draw/settings/getellipsemode.js",
    "draw/settings/getimagemode.js",
    "draw/settings/strokejoin.js",
    "draw/settings/strokecap.js",
    "draw/settings/getstrokejoin.js",
    "draw/settings/getstrokecap.js",
    "draw/settings/textfont.js",
    "draw/settings/gettextfont.js",
    "draw/settings/textsize.js",
    "draw/settings/gettextsize.js",
    "draw/transform/popmatrix.js",
    "draw/transform/pushmatrix.js",
    "draw/transform/resetmatrix.js",
    "draw/transform/rotate.js",
    "draw/transform/scale.js",
    "draw/transform/skew.js",
    "draw/transform/translate.js",
    "draw/shapes/arc.js",
    "draw/shapes/background.js",
    "draw/shapes/beginshape.js",
    "draw/shapes/beziervertex.js",
    "draw/shapes/ellipse.js",
    "draw/shapes/endshape.js",
    "draw/shapes/line.js",
    "draw/shapes/point.js",
    "draw/shapes/poly.js",
    "draw/shapes/quadvertex.js",
    "draw/shapes/rect.js",
    "draw/shapes/text.js",
    "draw/shapes/vertex.js",
    "draw/image/images.js",
    "draw/image/loadimage.js",
    "draw/image/loadimageset.js",
    "draw/image/image.js",
    "draw/image/get.js",
  ],
  [
    "physics/entities/circle.js",
    "physics/entities/line.js",
    "physics/entities/constraints/constraint.js",
    "physics/entities/constraints/bungee.js",
    "physics/entities/constraints/compressor.js",
    "physics/entities/constraints/cord.js",
    "physics/entities/constraints/extender.js",
    "physics/entities/constraints/rod.js",
    "physics/entities/constraints/spring.js",
  ]
];

function load(onComplete, override) {
  if(KAPhy.version === KAPhy.current) {
    if(onComplete) onComplete();
    return;
  }

  function importJS(filename, onLoad) {
    var newScript = document.createElement("script");

    newScript.type = "text/javascript";
    newScript.src = "https://rawgit.com/TemporalFuzz/KAPhy/master/" + filename;

    newScript.onload = onLoad;

    document.head.appendChild(newScript);
  }

  function importSetJS(fileset, onFinish) {
    var filesLoaded = 0;

    for(var i = 0; i < fileset.length; i++) {
      importJS(fileset[i], function() {
        filesLoaded++;
        if(filesLoaded >= fileset.length - 1) {
          if(onFinish) onFinish();
        }
      });
    }
  }

  var i = 0;
  function loadNext() {
    i++;
    console.log(i + " packages loaded!");
    if (i >= fileSets.length) {
      KAPhy.finishUpdate();
      if (onComplete) onComplete();
      return;
    }
    importSetJS(fileSets[i], loadNext);
  };
  importSetJS(fileSets[i], loadNext);
}
<|endoftext|>


<commit_before>
var compose = require('request-compose')
var oauth = require('request-oauth')
var qs = require('qs')
var pkg = require('../package')

var defaults = (args) => () => {
  var {options} = compose.Request.defaults(args)()
  options.headers['user-agent'] = `simov/grant/${pkg.version}`
  return {options}
}

var parse = () => ({options, res, res: {headers}, body, raw}) => {

  raw = body

  var header = Object.keys(headers)
    .find((name) => name.toLowerCase() === 'content-type')

  if (/json|javascript/.test(headers[header])) {
    try {
      body = JSON.parse(body)
    }
    catch (err) {}
  }

  else if (/application\/x-www-form-urlencoded/.test(headers[header])) {
    try {
      body = qs.parse(body) // use qs instead of querystring for nested objects
    }
    catch (err) {}
  }

  // some providers return incorrect content-type like text/html or text/plain
  else {
    try {
      body = JSON.parse(body)
    }
    catch (err) {
      body = qs.parse(body) // use qs instead of querystring for nested objects
    }
  }

  log({json: body})

  return {options, res, body, raw}
}

var log = (data) => {
  if (process.env.DEBUG) {
    try {
      require('request-logs')(data)
    }
    catch (err) {}
  }
}

module.exports = compose.extend({
  Request: {defaults, oauth},
  Response: {parse}
}).client
<commit_msg>Fix logs<commit_after>
var compose = require('request-compose')
var oauth = require('request-oauth')
var qs = require('qs')
var pkg = require('../package')

var defaults = (args) => () => {
  var {options} = compose.Request.defaults(args)()
  options.headers['user-agent'] = `simov/grant/${pkg.version}`
  return {options}
}

var parse = () => ({options, res, res: {headers}, body, raw}) => {

  raw = body

  var header = Object.keys(headers)
    .find((name) => name.toLowerCase() === 'content-type')

  if (/json|javascript/.test(headers[header])) {
    try {
      body = JSON.parse(body)
    }
    catch (err) {}
  }

  else if (/application\/x-www-form-urlencoded/.test(headers[header])) {
    try {
      body = qs.parse(body) // use qs instead of querystring for nested objects
    }
    catch (err) {}
  }

  // some providers return incorrect content-type like text/html or text/plain
  else {
    try {
      body = JSON.parse(body)
    }
    catch (err) {
      body = qs.parse(body) // use qs instead of querystring for nested objects
    }
  }

  log({parse: {res, body}})

  return {options, res, body, raw}
}

var log = (data) => {
  if (process.env.DEBUG) {
    try {
      require('request-logs')(data)
    }
    catch (err) {}
  }
}

module.exports = compose.extend({
  Request: {defaults, oauth},
  Response: {parse}
}).client
<|endoftext|>


<commit_before>var _ = require('./utils'),
    Reflux = require('../src');

/**
 * Creates an action functor object
 */
module.exports = function(definition) {

    definition = definition || {};

    var context = _.extend({
        eventLabel: "action",
        emitter: new _.EventEmitter()
    },definition,Reflux.publisherMethods,{
        preEmit: definition.preEmit || Reflux.publisherMethods.preEmit,
        shouldEmit: definition.shouldEmit || Reflux.publisherMethods.shouldEmit
    });

    var functor = function() {
        this.triggerAsync.apply(this,arguments);
    }.bind(context);

    _.extend(functor,context);

    return functor;

};
<commit_msg>modified bind call<commit_after>var _ = require('./utils'),
    Reflux = require('../src');

/**
 * Creates an action functor object
 */
module.exports = function(definition) {

    definition = definition || {};

    var context = _.extend({
        eventLabel: "action",
        emitter: new _.EventEmitter()
    },definition,Reflux.publisherMethods,{
        preEmit: definition.preEmit || Reflux.publisherMethods.preEmit,
        shouldEmit: definition.shouldEmit || Reflux.publisherMethods.shouldEmit
    });

    var functor = (function() {
        this.triggerAsync.apply(this,arguments);
    }).bind(context);

    _.extend(functor,context);

    return functor;

};
<|endoftext|>