<commit_before>/* globals __webpack_hash__ */

import LogColors from './LogColors';
import Logger from './Logger';
import { LogLevel } from './LogLevel';
import messageActionType from './messageActionType';

export class HmrClient {
  logger = new Logger(LogColors.cyan('[HMR]'));

  lastHash = '';

  sendRestartMessage = () => {
    // If forked process
    if (process.send) {
      const message = { action: messageActionType.RestartRequired };
      process.send(message);
    }
  };

  logApplyResult = (logLevel, outdatedModules, renewedModules) => {
    const unacceptedModules =
      !renewedModules || !renewedModules.length
        ? outdatedModules
        : outdatedModules.filter((moduleId) => renewedModules.indexOf(moduleId) < 0);

    if (unacceptedModules.length > 0 && logLevel >= LogLevel.ERRORS) {
      this.logger.warn(
        "The following modules couldn't be hot updated: (They would need to restart the application!)"
      );
      unacceptedModules.forEach((moduleId) => {
        this.logger.warn(` - ${moduleId}`);
      });
      this.sendRestartMessage();
    }

    if (!renewedModules || !renewedModules.length) {
      if (logLevel >= LogLevel.MINIMAL) {
        this.logger.info('Nothing hot updated.');
      }
      return;
    }

    if (logLevel >= LogLevel.NORMAL) {
      this.logger.info('Updated modules:');
      renewedModules.forEach((moduleId) => {
        this.logger.info(` - ${moduleId}`);
      });
      const numberIds = renewedModules.every((moduleId) => typeof moduleId === 'number');
      if (numberIds) {
        this.logger.info('Consider using the NamedModulesPlugin for module names.');
      }
    }

    if (this.isUpToDate()) {
      this.logUpToDate(logLevel);
    }
  };

  logUpToDate = (logLevel) => {
    if (logLevel >= LogLevel.MINIMAL) {
      this.logger.info('App is up to date.');
    }
  };

  defaultMessageListener = ({ action, stats, logLevel }) => {
    // webpackHotUpdate
    if (action !== messageActionType.CompilerDone) {
      return;
    }

    this.lastHash = stats.hash;

    if (!this.isUpToDate()) {
      const status = module.hot.status();

      if (status === 'idle') {
        if (logLevel >= LogLevel.MINIMAL) {
          this.logger.info('Checking for updates...');
        }
        this.checkAndApplyUpdates(logLevel);
      } else if (['abort', 'fail'].indexOf(status) >= 0) {
        if (logLevel >= LogLevel.ERRORS) {
          this.logger.warn(
            `Cannot apply update as a previous update ${status}ed. You need to restart the application!`
          );
        }
        this.sendRestartMessage();
      }
    } else {
      this.logUpToDate(logLevel);
    }
  };

  isUpToDate = () => this.lastHash.indexOf(__webpack_hash__) >= 0;

  checkAndApplyUpdates = (logLevel) => {
    module.hot
      .check()
      .then((outdatedModules) => {
        if (!outdatedModules) {
          if (logLevel >= LogLevel.ERRORS) {
            this.logger.warn('Cannot find update. You need to restart the application!');
          }
          return Promise.resolve();
        }

        return module.hot
          .apply({
            ignoreUnaccepted: true,
            ignoreDeclined: true,
            ignoreErrored: true, // true - allows to restore state after errors.
            onUnaccepted: (info) => {
              if (logLevel >= LogLevel.ERRORS) {
                this.logger.warn(
                  `Ignored an update to unaccepted module ${info.chain.join(' -> ')}`
                );
              }
            },
            onDeclined: (info) => {
              if (logLevel >= LogLevel.ERRORS) {
                this.logger.warn(`Ignored an update to declined module ${info.chain.join(' -> ')}`);
              }
            },
            onErrored: (info) => {
              if (logLevel >= LogLevel.ERRORS) {
                this.logger.warn(
                  `Ignored an error while updating module ${info.moduleId} (${info.type})`
                );
                // If ignoreErrored is true and throw info.error then module.hot.status() always
                // equals 'apply' and module.hot.check() will not work.
                this.logger.error(info.error);
              }
            },
          })
          .then((renewedModules) => {
            if (!this.isUpToDate()) {
              this.checkAndApplyUpdates(logLevel);
            }

            this.logApplyResult(logLevel, outdatedModules, renewedModules);
          });
      })
      .catch((err) => {
        if (['abort', 'fail'].indexOf(module.hot.status()) >= 0) {
          if (logLevel >= LogLevel.ERRORS) {
            this.logger.error('Cannot check for update. You need to restart the application!');
            this.logger.error(err.stack || err.message);
          }
          this.sendRestartMessage();
        } else if (logLevel >= LogLevel.ERRORS) {
          this.logger.error(`Check updates failed: ${err.stack}` || err.message);
        }
      });
  };

  run(messageListener = this.defaultMessageListener) {
    if (!module.hot) {
      throw new Error('Hot Module Replacement is disabled.');
    }

    this.logger.info('Waiting for update signal from webpack...');
    process.on('message', messageListener);
    return this;
  }
}

export default new HmrClient().run();
<commit_msg>Update log<commit_after>/* globals __webpack_hash__ */

import LogColors from './LogColors';
import Logger from './Logger';
import { LogLevel } from './LogLevel';
import messageActionType from './messageActionType';

export class HmrClient {
  logger = new Logger(LogColors.cyan('[HMR]'));

  lastHash = '';

  sendRestartMessage = () => {
    // If forked process
    if (process.send) {
      const message = { action: messageActionType.RestartRequired };
      process.send(message);
    }
  };

  logApplyResult = (logLevel, outdatedModules, renewedModules) => {
    const unacceptedModules =
      !renewedModules || !renewedModules.length
        ? outdatedModules
        : outdatedModules.filter((moduleId) => renewedModules.indexOf(moduleId) < 0);

    if (unacceptedModules.length > 0 && logLevel >= LogLevel.ERRORS) {
      this.logger.warn(
        "The following modules couldn't be hot updated: (They would need to restart the application!)"
      );
      unacceptedModules.forEach((moduleId) => {
        this.logger.warn(` - ${moduleId}`);
      });
      this.sendRestartMessage();
    }

    if (!renewedModules || !renewedModules.length) {
      if (logLevel >= LogLevel.MINIMAL) {
        this.logger.info('Nothing hot updated.');
      }
      return;
    }

    if (logLevel >= LogLevel.NORMAL) {
      this.logger.info('Updated modules:');
      renewedModules.forEach((moduleId) => {
        this.logger.info(` - ${moduleId}`);
      });
      const numberIds = renewedModules.every((moduleId) => typeof moduleId === 'number');
      if (numberIds) {
        this.logger.info('Consider using the NamedModulesPlugin for module names.');
      }
    }

    if (this.isUpToDate()) {
      this.logUpToDate(logLevel);
    }
  };

  logUpToDate = (logLevel) => {
    if (logLevel >= LogLevel.MINIMAL) {
      this.logger.info('App is up to date.');
    }
  };

  defaultMessageListener = ({ action, stats, logLevel }) => {
    // webpackHotUpdate
    if (action !== messageActionType.CompilerDone) {
      return;
    }

    this.lastHash = stats.hash;

    if (!this.isUpToDate()) {
      const status = module.hot.status();

      if (status === 'idle') {
        if (logLevel >= LogLevel.MINIMAL) {
          this.logger.info('Checking for updates...');
        }
        this.checkAndApplyUpdates(logLevel);
      } else if (['abort', 'fail'].indexOf(status) >= 0) {
        if (logLevel >= LogLevel.ERRORS) {
          this.logger.warn(
            `Cannot apply update as a previous update ${status}ed. You need to restart the application!`
          );
        }
        this.sendRestartMessage();
      }
    } else {
      this.logUpToDate(logLevel);
    }
  };

  isUpToDate = () => this.lastHash.indexOf(__webpack_hash__) >= 0;

  checkAndApplyUpdates = (logLevel) => {
    module.hot
      .check()
      .then((outdatedModules) => {
        if (!outdatedModules) {
          if (logLevel >= LogLevel.ERRORS) {
            this.logger.warn('Cannot find update. You need to restart the application!');
          }
          return Promise.resolve();
        }

        return module.hot
          .apply({
            ignoreUnaccepted: true,
            ignoreDeclined: true,
            ignoreErrored: true, // true - allows to restore state after errors.
            onUnaccepted: (info) => {
              if (logLevel >= LogLevel.ERRORS) {
                this.logger.warn(
                  `Ignored an update to unaccepted module ${info.chain.join(' -> ')}`
                );
              }
            },
            onDeclined: (info) => {
              if (logLevel >= LogLevel.ERRORS) {
                this.logger.warn(`Ignored an update to declined module ${info.chain.join(' -> ')}`);
              }
            },
            onErrored: (info) => {
              if (logLevel >= LogLevel.ERRORS) {
                this.logger.warn(
                  `Ignored an error while updating module ${info.moduleId} (${info.type})`
                );
                // If ignoreErrored is true and throw info.error then module.hot.status() always
                // equals 'apply' and module.hot.check() will not work.
                this.logger.error(info.error);
              }
            },
          })
          .then((renewedModules) => {
            if (!this.isUpToDate()) {
              this.checkAndApplyUpdates(logLevel);
            }

            this.logApplyResult(logLevel, outdatedModules, renewedModules);
          });
      })
      .catch((err) => {
        if (['abort', 'fail'].indexOf(module.hot.status()) >= 0) {
          if (logLevel >= LogLevel.ERRORS) {
            this.logger.error('Cannot check for updates. You need to restart the application!');
            this.logger.error(err.stack || err.message);
          }
          this.sendRestartMessage();
        } else if (logLevel >= LogLevel.ERRORS) {
          this.logger.error(`Check updates failed: ${err.stack}` || err.message);
        }
      });
  };

  run(messageListener = this.defaultMessageListener) {
    if (!module.hot) {
      throw new Error('Hot Module Replacement is disabled.');
    }

    this.logger.info('Waiting for update signal from webpack...');
    process.on('message', messageListener);
    return this;
  }
}

export default new HmrClient().run();
<|endoftext|>


<commit_before>define([
    'underscore', 'backbone', '../mixin', '../mixins/observable', '../mixins/deferrable', '../mixins/startable'
], function (_, Backbone, Mixin, Observable, Deferrable, Startable) {

    var ViewExtension = {
        // if `template` is a string, it will be processed through Handlebars.
        // otherwise it leaves it untouched.
        precompile: function (template) {
            if (typeof template === "string") {
                return _.template(template);
            }
            return template;
        },
        // allow an extra helper parameter to view render, as defaults for
        // template data.
        //
        // This is desined to be used with the engine `render()`
        // method.
        renderHtml: function (data, extra) {
            return this.template(_.defaults(data, extra));
        }
    };

    var Engine = Mixin.extend({
        // extends Backbone.View prototype
        _firstStart: function () {
            _.defaults(Backbone.View.prototype, ViewExtension);
            Startable._firstStart.apply(this, arguments);
        },

        // removes Backbone.View prototype engine functions.
        _doStop: function () {
            var engine = this.engine;
            _.each(ViewExtension, function unmix(method, name) {
                if (Backbone.View.prototype[name] === method) {
                    Backbone.View.prototype[name] = null;
                }
            });
        },

        // render a view and format all required extra data for template
        // engine in use.
        //
        // View has been extended to accept formatted Handlebars extra data.
        // learn more at http://handlebarsjs.com/execution.html#Options
        render: function (view, helpers, data) {
            var extra = _.extend(
                {},
                // extra helpers to use for this context
                helpers || {},
                // add global available data
                data || {}
            );

            return view.render(extra);
        }
    });

    Engine.mix([Observable, Deferrable, Startable]);

    return Engine;
});
<commit_msg>Update underscore engine to provide handlebars style data to templates.<commit_after>define([
    'underscore', 'backbone', '../mixin', '../mixins/observable', '../mixins/deferrable', '../mixins/startable'
], function (_, Backbone, Mixin, Observable, Deferrable, Startable) {

    var ViewExtension = {
        // if `template` is a string, it will be processed through Handlebars.
        // otherwise it leaves it untouched.
        precompile: function (template) {
            if (typeof template === "string") {
                return _.template(template);
            }
            return template;
        },
        // allow an extra helper parameter to view render, as defaults for
        // template data.
        //
        // This is desined to be used with the engine `render()`
        // method.
        renderHtml: function (data, extra) {
            return this.template(_.defaults(data, extra));
        }
    };

    var Engine = Mixin.extend({
        // extends Backbone.View prototype
        _firstStart: function () {
            _.defaults(Backbone.View.prototype, ViewExtension);
            Startable._firstStart.apply(this, arguments);
        },

        // removes Backbone.View prototype engine functions.
        _doStop: function () {
            var engine = this.engine;
            _.each(ViewExtension, function unmix(method, name) {
                if (Backbone.View.prototype[name] === method) {
                    Backbone.View.prototype[name] = null;
                }
            });
        },

        // render a view and format all required extra data for template
        // engine in use.
        //
        // View has been extended to accept formatted Handlebars extra data.
        // learn more at http://handlebarsjs.com/execution.html#Options
        render: function (view, helpers, data) {
            var extraTpl, extra;

            // emulate handlebars style extra data for template helpers.
            extraTpl = {
                // extra helpers to use for this context
                helpers: helpers,
                // add global available data
                data: data
            };

            // wrap helpers sot it receives the extra data.
            _.each(helpers || {}, function (helper, key) {
                helpers[key] = function () {
                    return helper.apply(this, _.toArray(arguments).concat([extraTpl]));
                };
            });

            // data to be passed to
            extra = _.extend(
                {},
                // extra helpers to use for this context
                helpers || {},
                // add global available data
                data || {}
            );

            return view.render(extra);
        }
    });

    Engine.mix([Observable, Deferrable, Startable]);

    return Engine;
});
<|endoftext|>


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

var servers = function(api, next){

  api.servers = {};
  api.servers.servers = [];

  api.servers._start = function(api, next){
    var started = 0;
    if(api.utils.hashLength(api.config.servers) == 0){ next() }
    for(var server in api.servers.servers){
      started++;
      api.log('starting server: ' + server, 'notice');
      api.servers.servers[server]._start(function(){
        process.nextTick(function(){
          started--;
          if(started == 0){ next() }
        });
      });
    }
  }

  api.servers._stop = function(api, next){
    var started = 0;
    if(api.utils.hashLength(api.servers.servers) == 0){ next() }
    for(var server in api.servers.servers){
      started++;
      (function(server){
        api.log('stopping server: ' + server, 'notice');
        api.servers.servers[server]._stop(function(){
          process.nextTick(function(){
            api.log('server stopped: ' + server, 'debug');
            started--;
            if(started == 0){ next() }
          });
        });
      })(server)
    }
  }

  // Load the servers

  var serverFolders = [
    path.resolve(__dirname + '/../servers')
  ];

  api.config.general.paths.server.forEach(function(p){
    p = path.resolve(p);
    if(serverFolders.indexOf(p) < 0){
      serverFolders.push(p);
    }
  })

  var inits = {}

  serverFolders.forEach(function(p){
    api.utils.recusiveDirecotryGlob(p).forEach(function(f){
      var parts = f.split('/')
      var server = parts[(parts.length - 1)].split('.')[0];
      if(api.config.servers[server] != null && api.config.servers[server].enabled === true){
        inits[server] = require(f)[server];
      }
      api.watchFileAndAct(f, function(){
        api.log('\r\n\r\n*** rebooting due to server ('+server+') change ***\r\n\r\n', 'info');
        api.commands.restart.call(api._self);
      });
    });
  })

  var started = 0;
  for(var server in inits){
    started++;
    (function(server){
      var options = api.config.servers[server];
      inits[server](api, options, function(serverObject){
        api.servers.servers[server] = serverObject;
        api.log('initialized server: ' + server, 'debug');
        process.nextTick(function(){
          started--;
          if(started == 0){ next() }
        });
      });
    })(server)
  }
  if(started == 0){ next() }
}

exports.servers = servers;
<commit_msg>server.js initializer windows path fix<commit_after>var fs = require('fs');
var path = require('path');

var servers = function(api, next){

  api.servers = {};
  api.servers.servers = [];

  api.servers._start = function(api, next){
    var started = 0;
    if(api.utils.hashLength(api.config.servers) == 0){ next() }
    for(var server in api.servers.servers){
      started++;
      api.log('starting server: ' + server, 'notice');
      api.servers.servers[server]._start(function(){
        process.nextTick(function(){
          started--;
          if(started == 0){ next() }
        });
      });
    }
  }

  api.servers._stop = function(api, next){
    var started = 0;
    if(api.utils.hashLength(api.servers.servers) == 0){ next() }
    for(var server in api.servers.servers){
      started++;
      (function(server){
        api.log('stopping server: ' + server, 'notice');
        api.servers.servers[server]._stop(function(){
          process.nextTick(function(){
            api.log('server stopped: ' + server, 'debug');
            started--;
            if(started == 0){ next() }
          });
        });
      })(server)
    }
  }

  // Load the servers

  var serverFolders = [
    path.resolve(__dirname + '/../servers')
  ];

  api.config.general.paths.server.forEach(function(p){
    p = path.resolve(p);
    if(serverFolders.indexOf(p) < 0){
      serverFolders.push(p);
    }
  })

  var inits = {}

  serverFolders.forEach(function(p){
    api.utils.recusiveDirecotryGlob(p).forEach(function(f){
      var parts = f.split(/[\/\\]+/)
      var server = parts[(parts.length - 1)].split('.')[0];
      if(api.config.servers[server] != null && api.config.servers[server].enabled === true){
        inits[server] = require(f)[server];
      }
      api.watchFileAndAct(f, function(){
        api.log('\r\n\r\n*** rebooting due to server ('+server+') change ***\r\n\r\n', 'info');
        api.commands.restart.call(api._self);
      });
    });
  })

  var started = 0;
  for(var server in inits){
    started++;
    (function(server){
      var options = api.config.servers[server];
      inits[server](api, options, function(serverObject){
        api.servers.servers[server] = serverObject;
        api.log('initialized server: ' + server, 'debug');
        process.nextTick(function(){
          started--;
          if(started == 0){ next() }
        });
      });
    })(server)
  }
  if(started == 0){ next() }
}

exports.servers = servers;
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var moment = require('moment-timezone');
var NodeCache = require('node-cache');

function init(profileData) {

  var profile = { };

  profile.timeValueCache = new NodeCache({ stdTTL: 600, checkperiod: 600 });

  profile.loadData = function loadData(profileData) {
    if (profileData && profileData.length) {
      profile.data = _.cloneDeep(profileData);
      profile.preprocessProfileOnLoad(profile.data[0]);
    }
  };

  profile.timeStringToSeconds = function timeStringToSeconds(time) {
    var split = time.split(':');
    return parseInt(split[0])*3600 + parseInt(split[1])*60;
  };

  // preprocess the timestamps to seconds for a couple orders of magnitude faster operation
  profile.preprocessProfileOnLoad = function preprocessProfileOnLoad(container) {
    _.each(container, function eachValue (value) {
      if( Object.prototype.toString.call(value) === '[object Array]' ) {
        profile.preprocessProfileOnLoad(value);
      }

      if (value.time) {
        var sec = profile.timeStringToSeconds(value.time);
        if (!isNaN(sec)) { value.timeAsSeconds = sec; }
      }
    });
  };

  profile.getValueByTime = function getValueByTime (time, valueType) {
    if (!time) { time = Date.now(); }

    //round to the minute for better caching
    var minuteTime = Math.round(time / 60000) * 60000;

    var cacheKey = (minuteTime + valueType);
    var returnValue = profile.timeValueCache[cacheKey];

    if (returnValue) {
      return returnValue;
    }

    var valueContainer = profile.getCurrentProfile()[valueType];

    // Assumes the timestamps are in UTC
    // Use local time zone if profile doesn't contain a time zone
    // This WILL break on the server; added warnings elsewhere that this is missing
    // TODO: Better warnings to user for missing configuration

    var t = profile.getTimezone() ? moment(minuteTime).tz(profile.getTimezone()) : moment(minuteTime);

    // Convert to seconds from midnight
    var mmtMidnight = t.clone().startOf('day');
    var timeAsSecondsFromMidnight = t.clone().diff(mmtMidnight, 'seconds');

    // If the container is an Array, assume it's a valid timestamped value container

    returnValue = valueContainer;

    if( Object.prototype.toString.call(valueContainer) === '[object Array]' ) {
      _.each(valueContainer, function eachValue (value) {
        if (timeAsSecondsFromMidnight >= value.timeAsSeconds) {
          returnValue = value.value;
        }
      });
    }

	returnValue = parseFloat(returnValue);

    profile.timeValueCache[cacheKey] = returnValue;

    return returnValue;
  };

  profile.getCurrentProfile = function getCurrentProfile() {
    return profile.hasData() ? profile.data[0] : {};
  };

  profile.getUnits = function getUnits() {
    return profile.getCurrentProfile()['units'];
  };

  profile.getTimezone = function getTimezone() {
    return profile.getCurrentProfile()['timezone'];
  };

  profile.hasData = function hasData() {
    return profile.data ? true : false;
  };

  profile.getDIA = function getDIA(time) {
    return profile.getValueByTime(time, 'dia');
  };

  profile.getSensitivity = function getSensitivity(time) {
    return profile.getValueByTime(time, 'sens');
  };

  profile.getCarbRatio = function getCarbRatio(time) {
    return profile.getValueByTime(time, 'carbratio');
  };

  profile.getCarbAbsorptionRate = function getCarbAbsorptionRate(time) {
    return profile.getValueByTime(time, 'carbs_hr');
  };

  profile.getLowBGTarget = function getLowBGTarget(time) {
    return profile.getValueByTime(time, 'target_low');
  };

  profile.getHighBGTarget = function getHighBGTarget(time) {
    return profile.getValueByTime(time, 'target_high');
  };

  profile.getBasal = function getBasal(time) {
    return profile.getValueByTime(time,'basal');
  };

  if (profileData) { profile.loadData(profileData); }

  return profile;
}

module.exports = init;<commit_msg>Fixes tests<commit_after>'use strict';

var _ = require('lodash');
var moment = require('moment-timezone');
var NodeCache = require('node-cache');

function init(profileData) {

  var profile = { };

  profile.timeValueCache = new NodeCache({ stdTTL: 600, checkperiod: 600 });

  profile.loadData = function loadData(profileData) {
    if (profileData && profileData.length) {
      profile.data = _.cloneDeep(profileData);
      profile.preprocessProfileOnLoad(profile.data[0]);
    }
  };

  profile.timeStringToSeconds = function timeStringToSeconds(time) {
    var split = time.split(':');
    return parseInt(split[0])*3600 + parseInt(split[1])*60;
  };

  // preprocess the timestamps to seconds for a couple orders of magnitude faster operation
  profile.preprocessProfileOnLoad = function preprocessProfileOnLoad(container) {
    _.each(container, function eachValue (value) {
      if( Object.prototype.toString.call(value) === '[object Array]' ) {
        profile.preprocessProfileOnLoad(value);
      }

      if (value.time) {
        var sec = profile.timeStringToSeconds(value.time);
        if (!isNaN(sec)) { value.timeAsSeconds = sec; }
      }
    });
  };

  profile.getValueByTime = function getValueByTime (time, valueType) {
    if (!time) { time = Date.now(); }

    //round to the minute for better caching
    var minuteTime = Math.round(time / 60000) * 60000;

    var cacheKey = (minuteTime + valueType);
    var returnValue = profile.timeValueCache[cacheKey];

    if (returnValue) {
      return returnValue;
    }

    var valueContainer = profile.getCurrentProfile()[valueType];

    // Assumes the timestamps are in UTC
    // Use local time zone if profile doesn't contain a time zone
    // This WILL break on the server; added warnings elsewhere that this is missing
    // TODO: Better warnings to user for missing configuration

    var t = profile.getTimezone() ? moment(minuteTime).tz(profile.getTimezone()) : moment(minuteTime);

    // Convert to seconds from midnight
    var mmtMidnight = t.clone().startOf('day');
    var timeAsSecondsFromMidnight = t.clone().diff(mmtMidnight, 'seconds');

    // If the container is an Array, assume it's a valid timestamped value container

    returnValue = valueContainer;

    if( Object.prototype.toString.call(valueContainer) === '[object Array]' ) {
      _.each(valueContainer, function eachValue (value) {
        if (timeAsSecondsFromMidnight >= value.timeAsSeconds) {
          returnValue = value.value;
        }
      });
    }

	if (returnValue) { returnValue = parseFloat(returnValue); }

    profile.timeValueCache[cacheKey] = returnValue;

    return returnValue;
  };

  profile.getCurrentProfile = function getCurrentProfile() {
    return profile.hasData() ? profile.data[0] : {};
  };

  profile.getUnits = function getUnits() {
    return profile.getCurrentProfile()['units'];
  };

  profile.getTimezone = function getTimezone() {
    return profile.getCurrentProfile()['timezone'];
  };

  profile.hasData = function hasData() {
    return profile.data ? true : false;
  };

  profile.getDIA = function getDIA(time) {
    return profile.getValueByTime(time, 'dia');
  };

  profile.getSensitivity = function getSensitivity(time) {
    return profile.getValueByTime(time, 'sens');
  };

  profile.getCarbRatio = function getCarbRatio(time) {
    return profile.getValueByTime(time, 'carbratio');
  };

  profile.getCarbAbsorptionRate = function getCarbAbsorptionRate(time) {
    return profile.getValueByTime(time, 'carbs_hr');
  };

  profile.getLowBGTarget = function getLowBGTarget(time) {
    return profile.getValueByTime(time, 'target_low');
  };

  profile.getHighBGTarget = function getHighBGTarget(time) {
    return profile.getValueByTime(time, 'target_high');
  };

  profile.getBasal = function getBasal(time) {
    return profile.getValueByTime(time,'basal');
  };

  if (profileData) { profile.loadData(profileData); }

  return profile;
}

module.exports = init;<|endoftext|>


<commit_before>import pathIsAbsolute from 'path-is-absolute';
import fs from 'fs';
import { fork } from 'child_process';
import LogColors from './LogColors';

class HmrServer {

  static defaultReporter(reporterOptions) {
    const { state, stats, options } = reporterOptions;

    if (state) {
      let displayStats = (!options.quiet && options.stats !== false);
      if (displayStats && !(stats.hasErrors() || stats.hasWarnings()) && options.noInfo) {
        displayStats = false;
      }
      if (displayStats) {
        options.log(stats.toString(options.stats));
      }
      if (!options.noInfo && !options.quiet) {
        let msg = 'Compiled successfully.';
        if (stats.hasErrors()) {
          msg = 'Failed to compile.';
        } else if (stats.hasWarnings()) {
          msg = 'Compiled with warnings.';
        }
        options.log(`${LogColors.magenta('Webpack')}: ${msg}`);
      }
    } else {
      options.log(`${LogColors.magenta('Webpack')}: Compiling...`);
    }
  }

  constructor(context) {
    this.context = Object.assign({}, context);
    const options = context.options || {};
    if (typeof options.watchOptions === 'undefined') options.watchOptions = {};
    if (typeof options.reporter !== 'function') options.reporter = HmrServer.defaultReporter;
    if (typeof options.log !== 'function') options.log = console.log.bind(console);
    if (typeof options.warn !== 'function') options.warn = console.warn.bind(console);
    if (typeof options.error !== 'function') options.error = console.error.bind(console);
    if (typeof options.watchOptions.aggregateTimeout === 'undefined') options.watchOptions.aggregateTimeout = 200;
    if (typeof options.stats === 'undefined') options.stats = {};
    if (!options.stats.context) options.stats.context = process.cwd();
    const compiler = this.context.compiler;
    if (typeof compiler.outputPath === 'string' && !pathIsAbsolute.posix(compiler.outputPath) && !pathIsAbsolute.win32(compiler.outputPath)) {
      throw new Error('`output.path` needs to be an absolute path or `/`.');
    }
    this.context.options = options;
    // Don use memory-fs because we can't fork bundle fom in-memory file.
    this.context.fs = fs;
  }

  sendMessage(action) {
    this.context.serverProcess && this.context.serverProcess.send({
      action,
      stats: this.context.webpackStats.toJson(),
    });
  }

  compilerDone = (stats) => {
    // We are now on valid state
    this.context.state = true;
    this.context.webpackStats = stats;

    // Do the stuff in nextTick, because bundle may be invalidated
    // if a change happened while compiling
    process.nextTick(() => {
      // check if still in valid state
      if (!this.context.state) return;

      // print webpack output
      this.context.options.reporter({
        state: true,
        stats,
        options: this.context.options,
      });

      if (this.context.serverProcess) {
        this.sendMessage('built');
      } else {
        // execute built scripts
        const options = {
          cwd: process.cwd(),
          env: process.env,
        };
        if (process.getuid) {
          options.uid = process.getuid();
          options.gid = process.getgid();
        }
        const assetsNames = Object.getOwnPropertyNames(stats.compilation.assets);
        const main = stats.compilation.assets[assetsNames[assetsNames.length - 1]];
        this.context.serverProcess = fork(main.existsAt, process.argv, options);
      }
    });
  };

  compilerInvalid = () => {
    this.sendMessage('compile');

    if (this.context.state && (!this.context.options.noInfo && !this.context.options.quiet)) {
      this.context.options.reporter({
        state: false,
        options: this.context.options,
      });
    }

    // We are now in invalid state
    this.context.state = false;
    // resolve async
    if (arguments.length === 2 && typeof arguments[1] === 'function') {
      const callback = arguments[1];
      callback();
    }
  };

  compilerWatch = (err) => {
    if (err) {
      this.context.options.error(err.stack || err);
      if (err.details) this.context.options.error(err.details);
    }
  };

  startWatch() {
    const options = this.context.options;
    const compiler = this.context.compiler;
    // start watching
    this.context.watching = compiler.watch(options.watchOptions, this.compilerWatch);
    console.info(LogColors.cyan('[HMR]'), 'Waiting webpack...');
  }

  run() {
    this.context.compiler.plugin('done', this.compilerDone);
    this.context.compiler.plugin('compile', this.compilerInvalid);
    this.startWatch();
    return this;
  }
}

export default HmrServer;
<commit_msg>feature: add support for launching of any number of entries<commit_after>import pathIsAbsolute from 'path-is-absolute';
import fs from 'fs';
import path from 'path';
import { fork } from 'child_process';
import LogColors from './LogColors';

class HmrServer {

  static defaultReporter(reporterOptions) {
    const { state, stats, options } = reporterOptions;

    if (state) {
      let displayStats = (!options.quiet && options.stats !== false);
      if (displayStats && !(stats.hasErrors() || stats.hasWarnings()) && options.noInfo) {
        displayStats = false;
      }
      if (displayStats) {
        options.log(stats.toString(options.stats));
      }
      if (!options.noInfo && !options.quiet) {
        let msg = 'Compiled successfully.';
        if (stats.hasErrors()) {
          msg = 'Failed to compile.';
        } else if (stats.hasWarnings()) {
          msg = 'Compiled with warnings.';
        }
        options.log(`${LogColors.magenta('Webpack')}: ${msg}`);
      }
    } else {
      options.log(`${LogColors.magenta('Webpack')}: Compiling...`);
    }
  }

  constructor(context) {
    this.context = Object.assign({}, context);
    const options = context.options || {};
    if (typeof options.watchOptions === 'undefined') options.watchOptions = {};
    if (typeof options.reporter !== 'function') options.reporter = HmrServer.defaultReporter;
    if (typeof options.log !== 'function') options.log = console.log.bind(console);
    if (typeof options.warn !== 'function') options.warn = console.warn.bind(console);
    if (typeof options.error !== 'function') options.error = console.error.bind(console);
    if (typeof options.watchOptions.aggregateTimeout === 'undefined') options.watchOptions.aggregateTimeout = 200;
    if (typeof options.stats === 'undefined') options.stats = {};
    if (!options.stats.context) options.stats.context = process.cwd();
    const compiler = this.context.compiler;
    if (typeof compiler.outputPath === 'string' && !pathIsAbsolute.posix(compiler.outputPath) && !pathIsAbsolute.win32(compiler.outputPath)) {
      throw new Error('`output.path` needs to be an absolute path or `/`.');
    }
    this.context.options = options;
    // Don use memory-fs because we can't fork bundle fom in-memory file.
    this.context.fs = fs;
  }

  sendMessage = (action) => {
    this.context.serverProcess && this.context.serverProcess.send({
      action,
      stats: this.context.webpackStats.toJson(),
    });
  };

  forkProcess = (stats) => {
    const getLauncherFileName = () => {
      const assets = stats.compilation.assets;
      const names = Object.getOwnPropertyNames(assets)
          .filter(k => assets[k].emitted && path.extname(assets[k].existsAt) === '.js');

      if (names.length === 1) {
        // Only one valid assets, so just return it path
        return assets[names[0]].existsAt;
      } else {
        // Create temp launcher file which aggregates all assets.
        const launcherString = names
            .map(k => `require('${assets[k].existsAt.replace(/\\/g, '/')}');`)
            .join('\n');

        const launcherFileName = path.resolve(stats.compilation.compiler.outputPath, `launcher.${stats.hash}.js`);
        this.context.fs.writeFileSync(launcherFileName, launcherString);

        // Delete created files on exit
        process.on('exit', () => {
          console.log('exit');
          this.context.fs.unlinkSync(launcherFileName);
        });
        process.on('SIGINT', () => {
          console.log('SIGINT');
          this.context.fs.unlinkSync(launcherFileName);
        });

        return launcherFileName;
      }
    };

    // Execute built scripts
    const options = {
      cwd: process.cwd(),
      env: process.env,
    };
    if (process.getuid) {
      options.uid = process.getuid();
      options.gid = process.getgid();
    }
    this.context.serverProcess = fork(getLauncherFileName(), process.argv, options);
  };

  compilerDone = (stats) => {
    // We are now on valid state
    this.context.state = true;
    this.context.webpackStats = stats;

    // Do the stuff in nextTick, because bundle may be invalidated
    // if a change happened while compiling
    process.nextTick(() => {
      // check if still in valid state
      if (!this.context.state) return;

      // print webpack output
      this.context.options.reporter({
        state: true,
        stats,
        options: this.context.options,
      });

      if (this.context.serverProcess) {
        this.sendMessage('built');
      } else {
        // Start compiled files in child process.
        this.forkProcess(stats);
      }
    });
  };

  compilerInvalid = () => {
    this.sendMessage('compile');

    if (this.context.state && (!this.context.options.noInfo && !this.context.options.quiet)) {
      this.context.options.reporter({
        state: false,
        options: this.context.options,
      });
    }

    // We are now in invalid state
    this.context.state = false;
    // resolve async
    if (arguments.length === 2 && typeof arguments[1] === 'function') {
      const callback = arguments[1];
      callback();
    }
  };

  compilerWatch = (err) => {
    if (err) {
      this.context.options.error(err.stack || err);
      if (err.details) this.context.options.error(err.details);
    }
  };

  startWatch = () => {
    const options = this.context.options;
    const compiler = this.context.compiler;
    // start watching
    this.context.watching = compiler.watch(options.watchOptions, this.compilerWatch);
    console.info(LogColors.cyan('[HMR]'), 'Waiting webpack...');
  };

  run = () => {
    this.context.compiler.plugin('done', this.compilerDone);
    this.context.compiler.plugin('compile', this.compilerInvalid);
    this.startWatch();
    return this;
  }
}

export default HmrServer;
<|endoftext|>


<commit_before>((function (App) {
  'use strict';

  App.Router.ManagementPositionStep = Backbone.Router.extend({

    routes: {
      '(/)': 'index'
    },

    initialize: function (params) {
      this.slug = params[0] || null;
    },

    index: function () {
      this.structure = (window.gon && gon.structure) || null;

      this.treeContainer = document.querySelector('.js-tree');

      this.treeStructureView = new App.View.TreeStructureView({
        el: this.treeContainer,
        collection: new Backbone.Collection(this._getTreeStructure()),
        pageTemplate: this._getPageTemplate(),
        additionalPageTemplate: null
      });

      /* We add a listener for when the user clicks on "Continue" */
      $('.js-form').on('submit', this._onSubmit.bind(this));
    },

    /**
     * Event handler for when the user clicks the submit button
     * @param {object} e - event
     */
    _onSubmit: function () {
      // We retrieve the position and the parentId of the draggable node
      var position,
        parentId;

      var searchNode = function (currentNode, currentParentId, currentPosition) {
        // If the current node is the one we search for, we save its position and
        // parent ID and return true (meaning we found it)
        if (currentNode.id === 0) {
          position = currentPosition;
          parentId = currentParentId;
          return true;
        }

        // We search for the node in the children list
        for (var i = 0, j = (currentNode.children && currentNode.children.length) || 0; i < j; i++) {
          // If we found it, we return
          if (searchNode(currentNode.children[i], currentNode.id, i)) {
            return true;
          }
        }

        // If we couldn't find it, we return false
        return false;
      };

      if (!searchNode(this.treeStructureView.getTree(), null, 0)) {
        // eslint-disable-next-line no-console
        console.warn('Unable to find the dragged node in the tree');
        return;
      }

      // We save the value to the hidden fields
      $('.js-parent_id').val(parentId);
      $('.js-position').val(position);
    },

    /**
     * Return the tree structure with readonly nodes and a special
     * node that can be dragged
     */
    _getTreeStructure: function () {
      // Position of the "Drag this" item if editing a page
      var draggable = {
        position: (window.gon && gon.position) || null,
        parentId: (window.gon && gon.parentId) || null
      };

      /**
       * Recursively parse the nodes so they have the desired structure
       * @param {object} node - node/branch to parse
       * @param {number} level - nesting level of the node
       * @returns {object} tree
       */
      var parseNode = function (node, level) {
        if (level !== 0) node.readonly = true;

        for (var i = 0, j = (node.children && node.children.length) || 0; i < j; i++) {
          node.children[i] = parseNode(node.children[i], level + 1, node.id);

          // If the element is the draggable, we remove its readonly attribute
          if (node.id === draggable.parentId && i === draggable.position) {
            delete node.children[i].readonly;
            node.children[i].id = 0;
            node.children[i].name = 'Drag this';
            node.children[i].enabled = true;
            node.children[i].highlighted = true;
          }
        }

        // We insert as first page our draggable node if not editing
        if (!draggable.position && level === 0) {
          node.children.unshift({
            name: 'Drag this',
            id: 0,
            enabled: true,
            highlighted: true
          });
        }

        return node;
      };

      return parseNode(this.structure, 0);
    },

    /**
     * Return the template for a page in the tree
     * @returns {string} template
     */
    _getPageTemplate: function () {
      return '\

\
          {{name}}\
          {{#unless enabled}}\

\

Disabled
\

\
          {{/unless}}\

\
      ';
    }

  });
})(this.App));
<commit_msg>Fixes an issue with the tree step<commit_after>((function (App) {
  'use strict';

  App.Router.ManagementPositionStep = Backbone.Router.extend({

    routes: {
      '(/)': 'index'
    },

    initialize: function (params) {
      this.slug = params[0] || null;
    },

    index: function () {
      this.structure = (window.gon && gon.structure) || null;

      this.treeContainer = document.querySelector('.js-tree');

      this.treeStructureView = new App.View.TreeStructureView({
        el: this.treeContainer,
        collection: new Backbone.Collection(this._getTreeStructure()),
        pageTemplate: this._getPageTemplate(),
        additionalPageTemplate: null
      });

      /* We add a listener for when the user clicks on "Continue" */
      $('.js-form').on('submit', this._onSubmit.bind(this));
    },

    /**
     * Event handler for when the user clicks the submit button
     * @param {object} e - event
     */
    _onSubmit: function () {
      // We retrieve the position and the parentId of the draggable node
      var position,
        parentId;

      var searchNode = function (currentNode, currentParentId, currentPosition) {
        // If the current node is the one we search for, we save its position and
        // parent ID and return true (meaning we found it)
        if (currentNode.id === 0) {
          position = currentPosition;
          parentId = currentParentId;
          return true;
        }

        // We search for the node in the children list
        for (var i = 0, j = (currentNode.children && currentNode.children.length) || 0; i < j; i++) {
          // If we found it, we return
          if (searchNode(currentNode.children[i], currentNode.id, i)) {
            return true;
          }
        }

        // If we couldn't find it, we return false
        return false;
      };

      if (!searchNode(this.treeStructureView.getTree(), null, 0)) {
        // eslint-disable-next-line no-console
        console.warn('Unable to find the dragged node in the tree');
        return;
      }

      // We save the value to the hidden fields
      $('.js-parent_id').val(parentId);
      $('.js-position').val(position);
    },

    /**
     * Return the tree structure with readonly nodes and a special
     * node that can be dragged
     */
    _getTreeStructure: function () {
      // Position of the "Drag this" item if editing a page
      var draggable = {
        position: (window.gon && gon.position !== null && gon.position !== undefined) ? gon.position : null,
        parentId: (window.gon && gon.parentId !== null && gon.parentId !== undefined) ? gon.parentId : null
      };

      /**
       * Recursively parse the nodes so they have the desired structure
       * @param {object} node - node/branch to parse
       * @param {number} level - nesting level of the node
       * @returns {object} tree
       */
      var parseNode = function (node, level) {
        if (level !== 0) node.readonly = true;

        for (var i = 0, j = (node.children && node.children.length) || 0; i < j; i++) {
          node.children[i] = parseNode(node.children[i], level + 1, node.id);

          // If the element is the draggable, we remove its readonly attribute
          if (node.id === draggable.parentId && i === draggable.position) {
            delete node.children[i].readonly;
            node.children[i].id = 0;
            node.children[i].name = 'Drag this';
            node.children[i].enabled = true;
            node.children[i].highlighted = true;
          }
        }

        // We insert as first page our draggable node if not editing
        if (draggable.position === null && level === 0) {
          node.children.unshift({
            name: 'Drag this',
            id: 0,
            enabled: true,
            highlighted: true
          });
        }

        return node;
      };

      return parseNode(this.structure, 0);
    },

    /**
     * Return the template for a page in the tree
     * @returns {string} template
     */
    _getPageTemplate: function () {
      return '\

\
          {{name}}\
          {{#unless enabled}}\

\

Disabled
\

\
          {{/unless}}\

\
      ';
    }

  });
})(this.App));
<|endoftext|>


<commit_before>Ext.define('TM.model.Assignee', {
  extend: 'Ext.data.Model',

  fields: [
    { name: 'id', type: 'int' },
    { name: 'name' },
    { name: 'class_name' }
  ],

  proxy: {
    type: 'rest',
    url: '/assignees',
    reader: {
      root: 'assignees',
      totalProperty: 'total'
    }
  },
});<commit_msg>Model for get assignees<commit_after>Ext.define('TM.model.Assignee', {
  extend: 'Ext.data.Model',

  fields: [
    { name: 'id', type: 'int' },
    { name: 'name' },
    { name: 'class_name' },
    { name: 'parent_id', type: 'int' }
  ],

  proxy: {
    type: 'rest',
    url: '/assignees.json',
    reader: {
      root: 'assignees',
      totalProperty: 'total'
    }
  }
});
<|endoftext|>


<commit_before>(function(idbModules, undefined){
    /**
     * The IndexedDB Cursor Object
     * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBCursor
     * @param {Object} range
     * @param {Object} direction
     * @param {Object} idbObjectStore
     * @param {Object} cursorRequest
     */
    function IDBCursor(range, direction, idbObjectStore, cursorRequest, keyColumnName, valueColumnName){
        this.__range = range;
        this.source = this.__idbObjectStore = idbObjectStore;
        this.__req = cursorRequest;

        this.key = undefined;
        this.direction = direction;

        this.__keyColumnName = keyColumnName;
        this.__valueColumnName = valueColumnName;

        if (!this.source.transaction.__active) {
            idbModules.util.throwDOMException("TransactionInactiveError - The transaction this IDBObjectStore belongs to is not active.");
        }
        // Setting this to -1 as continue will set it to 0 anyway
        this.__offset = -1;
        this["continue"]();
    }

    IDBCursor.prototype.__find = function(key, tx, success, error){
        var me = this;
        var sql = ["SELECT * FROM ", idbModules.util.quote(me.__idbObjectStore.name)];
        var sqlValues = [];
        sql.push("WHERE ", me.__keyColumnName, " NOT NULL");
        if (me.__range && (me.__range.lower || me.__range.upper)) {
            sql.push("AND");
            if (me.__range.lower) {
                sql.push(me.__keyColumnName + (me.__range.lowerOpen ? " >=" : " >") + " ?");
                sqlValues.push(idbModules.Key.encode(me.__range.lower));
            }
            (me.__range.lower && me.__range.upper) && sql.push("AND");
            if (me.__range.upper) {
                sql.push(me.__keyColumnName + (me.__range.upperOpen ? " <= " : " < ") + " ?");
                sqlValues.push(idbModules.Key.encode(me.__range.upper));
            }
        }
        sql.push(" ORDER BY ", me.__keyColumnName);
        if (typeof key !== "undefined") {
            sql.push((me.__range && (me.__range.lower || me.__range.upper)) ? "AND" : "WHERE");
            sql.push("key = ?");
            sqlValues.push(idbModules.Key.encode(key));
            sql.push("LIMIT 1");
        }
        else {
            sql.push("LIMIT 1 OFFSET " + me.__offset);
        }
        logger.log(sql.join(" "), sqlValues);
        tx.executeSql(sql.join(" "), sqlValues, function(tx, data){
            if (data.rows.length === 1) {
                var key = idbModules.Key.decode(data.rows.item(0)[me.__keyColumnName]);
                var val = me.__valueColumnName === "value" ? idbModules.Sca.decode(data.rows.item(0)[me.__valueColumnName]) : idbModules.Key.decode(data.rows.item(0)[me.__valueColumnName]);
                success(key, val);
            }
            else {
                logger.log("Reached end of cursors");
                success(undefined, undefined);
            }
        }, function(tx, data){
            logger.log("Could not execute Cursor.continue");
            error(data);
        });
    };

    IDBCursor.prototype["continue"] = function(key){
        var me = this;
        this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__offset++;
            me.__find(key, tx, function(key, val){
                me.key = key;
                me.value = val;
                success(typeof me.key !== "undefined" ? me : undefined, me.__req);
            }, function(data){
                error(data);
            });
        });
    };

    IDBCursor.prototype.advance = function(count){
        if (count <= 0) {
            idbModules.util.throwDOMException("Type Error - Count is invalid - 0 or negative", count);
        }
        var me = this;
        this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__offset += count;
            me.__find(undefined, tx, function(key, value){
                me.__offset++;
                me.key = key;
                me.value = value;
                success(me, me.__req);
            }, function(data){
                error(data);
            });
        });
    };

    IDBCursor.prototype.update = function(valueToUpdate){
        var me = this;
        return this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__find(undefined, tx, function(key, value){
                var sql = "UPDATE " + idbModules.util.quote(me.__idbObjectStore.name) + " SET value = ? WHERE key = ?";
                logger.log(sql, valueToUpdate, key);
                tx.executeSql(sql, [idbModules.Sca.encode(valueToUpdate), idbModules.Key.encode(key)], function(tx, data){
                    if (data.rowsAffected === 1) {
                        success(key);
                    }
                    else {
                        error("No rowns with key found" + key);
                    }
                }, function(tx, data){
                    error(data);
                });
            }, function(data){
                error(data);
            });
        });
    };

    IDBCursor.prototype["delete"] = function(){
        var me = this;
        return this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__find(undefined, tx, function(key, value){
                var sql = "DELETE FROM  " + idbModules.util.quote(me.__idbObjectStore.name) + " WHERE key = ?";
                logger.log(sql, key);
                tx.executeSql(sql, [idbModules.Key.encode(key)], function(tx, data){
                    if (data.rowsAffected === 1) {
                        success(undefined);
                    }
                    else {
                        error("No rowns with key found" + key);
                    }
                }, function(tx, data){
                    error(data);
                });
            }, function(data){
                error(data);
            });
        });
    };

    idbModules.IDBCursor = IDBCursor;
}(idbModules));
<commit_msg>Fix #19 get continue working when providing key<commit_after>(function(idbModules, undefined){
    /**
     * The IndexedDB Cursor Object
     * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBCursor
     * @param {Object} range
     * @param {Object} direction
     * @param {Object} idbObjectStore
     * @param {Object} cursorRequest
     */
    function IDBCursor(range, direction, idbObjectStore, cursorRequest, keyColumnName, valueColumnName){
        this.__range = range;
        this.source = this.__idbObjectStore = idbObjectStore;
        this.__req = cursorRequest;

        this.key = undefined;
        this.direction = direction;

        this.__keyColumnName = keyColumnName;
        this.__valueColumnName = valueColumnName;

        if (!this.source.transaction.__active) {
            idbModules.util.throwDOMException("TransactionInactiveError - The transaction this IDBObjectStore belongs to is not active.");
        }
        // Setting this to -1 as continue will set it to 0 anyway
        this.__offset = -1;

        this.__lastKeyContinued = undefined; // Used when continuing with a key

        this["continue"]();
    }

    IDBCursor.prototype.__find = function(key, tx, success, error){
        var me = this;
        var sql = ["SELECT * FROM ", idbModules.util.quote(me.__idbObjectStore.name)];
        var sqlValues = [];
        sql.push("WHERE ", me.__keyColumnName, " NOT NULL");
        if (me.__range && (me.__range.lower || me.__range.upper)) {
            sql.push("AND");
            if (me.__range.lower) {
                sql.push(me.__keyColumnName + (me.__range.lowerOpen ? " >=" : " >") + " ?");
                sqlValues.push(idbModules.Key.encode(me.__range.lower));
            }
            (me.__range.lower && me.__range.upper) && sql.push("AND");
            if (me.__range.upper) {
                sql.push(me.__keyColumnName + (me.__range.upperOpen ? " <= " : " < ") + " ?");
                sqlValues.push(idbModules.Key.encode(me.__range.upper));
            }
        }
        if (typeof key !== "undefined") {
            me.__lastKeyContinued = key;
            me.__offset = 0;
        }
        if (me.__lastKeyContinued !== undefined) {
            sql.push("AND " + me.__keyColumnName + " >= ?");
            sqlValues.push(idbModules.Key.encode(me.__lastKeyContinued));
        }
        sql.push("ORDER BY ", me.__keyColumnName);
        sql.push("LIMIT 1 OFFSET " + me.__offset);
        logger.log(sql.join(" "), sqlValues);
        tx.executeSql(sql.join(" "), sqlValues, function(tx, data){
            if (data.rows.length === 1) {
                var key = idbModules.Key.decode(data.rows.item(0)[me.__keyColumnName]);
                var val = me.__valueColumnName === "value" ? idbModules.Sca.decode(data.rows.item(0)[me.__valueColumnName]) : idbModules.Key.decode(data.rows.item(0)[me.__valueColumnName]);
                success(key, val);
            }
            else {
                logger.log("Reached end of cursors");
                success(undefined, undefined);
            }
        }, function(tx, data){
            logger.log("Could not execute Cursor.continue");
            error(data);
        });
    };

    IDBCursor.prototype["continue"] = function(key){
        var me = this;
        this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__offset++;
            me.__find(key, tx, function(key, val){
                me.key = key;
                me.value = val;
                success(typeof me.key !== "undefined" ? me : undefined, me.__req);
            }, function(data){
                error(data);
            });
        });
    };

    IDBCursor.prototype.advance = function(count){
        if (count <= 0) {
            idbModules.util.throwDOMException("Type Error - Count is invalid - 0 or negative", count);
        }
        var me = this;
        this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__offset += count;
            me.__find(undefined, tx, function(key, value){
                me.__offset++;
                me.key = key;
                me.value = value;
                success(me, me.__req);
            }, function(data){
                error(data);
            });
        });
    };

    IDBCursor.prototype.update = function(valueToUpdate){
        var me = this;
        return this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__find(undefined, tx, function(key, value){
                var sql = "UPDATE " + idbModules.util.quote(me.__idbObjectStore.name) + " SET value = ? WHERE key = ?";
                logger.log(sql, valueToUpdate, key);
                tx.executeSql(sql, [idbModules.Sca.encode(valueToUpdate), idbModules.Key.encode(key)], function(tx, data){
                    if (data.rowsAffected === 1) {
                        success(key);
                    }
                    else {
                        error("No rowns with key found" + key);
                    }
                }, function(tx, data){
                    error(data);
                });
            }, function(data){
                error(data);
            });
        });
    };

    IDBCursor.prototype["delete"] = function(){
        var me = this;
        return this.__idbObjectStore.transaction.__addToTransactionQueue(function(tx, args, success, error){
            me.__find(undefined, tx, function(key, value){
                var sql = "DELETE FROM  " + idbModules.util.quote(me.__idbObjectStore.name) + " WHERE key = ?";
                logger.log(sql, key);
                tx.executeSql(sql, [idbModules.Key.encode(key)], function(tx, data){
                    if (data.rowsAffected === 1) {
                        success(undefined);
                    }
                    else {
                        error("No rowns with key found" + key);
                    }
                }, function(tx, data){
                    error(data);
                });
            }, function(data){
                error(data);
            });
        });
    };

    idbModules.IDBCursor = IDBCursor;
}(idbModules));
<|endoftext|>


<commit_before>//- JavaScript source code

//- defs-postgres.js ~~
//
//  These definitions assume Postgres 9.0 or later. They also need optimization
//  help from an RDBMS guru.
//
//  Known shortcomings:
//  -   The log storage definition assumes that hstore is available.
//
//                                                      ~~ (c) SRW, 25 Sep 2012
//                                                  ~~ last updated 24 Jan 2015

(function () {
    'use strict';

 // Pragmas

    /*jshint maxparams: 3, quotmark: single, strict: true */

    /*jslint indent: 4, maxlen: 80, node: true */

    /*properties
        api, avar_ttl, body, collect_garbage, connect, error, get_avar,
        get_list, hasOwnProperty, isMaster, join, key, length, log, map,
        native, persistent_storage, postgres, push, query, rows, set_avar,
        stringify, trafficlog_storage
    */

 // Declarations

    var cluster, pg;

 // Definitions

    cluster = require('cluster');

    try {
     // If the "pg-native" module is installed, use it for a 30% boost in
     // performance. QM lists "pg-native" as an optional dependency.
        pg = require('pg').native;
    } catch (err) {
     // Fall back to the JS (non-native) implementation of the module :-)
        pg = require('pg');
    }

 // Out-of-scope definitions

    exports.api = function (settings) {
     // This function needs documentation.

        var collect_garbage, connection_string, get_avar, get_list,
            set_avar;

        collect_garbage = function () {
         // This function is only a placeholder, now that QM uses an INSERT
         // trigger to evict old rows automatically.
            return;
        };

        connection_string = settings.persistent_storage.postgres;

        get_avar = function (params, callback) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    return callback(err, undefined);
                }
                var x = [
                    'UPDATE avars SET last_touch = NOW()',
                    'WHERE box_key = $1',
                    'RETURNING body'
                ].join(' ');
                client.query(x, [params.join('&')], function (err, results) {
                 // This function needs documentation.
                    done();
                    if (err !== null) {
                        return callback(err, undefined);
                    }
                    if (results.rows.length < 1) {
                        return callback(null, undefined);
                    }
                    return callback(null, results.rows[0].body);
                });
                return;
            });
            return;
        };

        get_list = function (params, callback) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    return callback(err, undefined);
                }
                var x = 'SELECT key FROM avars WHERE box_status = $1';
                client.query(x, [params.join('&')], function (err, results) {
                 // This function needs documentation.
                    done();
                    if (err !== null) {
                        return callback(err, undefined);
                    }
                    var y = (results === undefined) ? {rows: []} : results;
                    return callback(null, y.rows.map(function (row) {
                     // This function needs documentation.
                        return row.key;
                    }));
                });
                return;
            });
            return;
        };

        set_avar = function (params, callback) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    return callback(err, undefined);
                }
                var args, sql;
                if (params.length === 4) {
                    args = [
                        params[3],
                        params[0] + '&' + params[1],
                        params[0] + '&' + params[2],
                        params[1]
                    ];
                    sql = 'SELECT upsert_task($1, $2, $3, $4)';
                } else {
                    args = [
                        params[2],
                        params[0] + '&' + params[1]
                    ];
                    sql = 'SELECT upsert_avar($1, $2)';
                }
                client.query(sql, args, function (err, results) {
                 // This function needs documentation.
                    done();
                    return callback(err, results);
                });
                return;
            });
            return;
        };

        if (cluster.isMaster) {
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    throw err;
                }
                var lines = [

                    'CREATE TABLE IF NOT EXISTS avars (',
                    '   body TEXT NOT NULL,',
                    '   box_key TEXT NOT NULL,',
                    '   box_status TEXT,',
                    '   key TEXT,',     //- this doesn't need to be "NOT NULL"
                    '   last_touch TIMESTAMP NOT NULL DEFAULT NOW(),',
                    '   PRIMARY KEY (box_key)',
                    ');',

                    'DO',
                    '$$',
                    'BEGIN',
                    '   IF NOT EXISTS (',
                    '       SELECT  1',
                    '       FROM    pg_class c',
                    '       JOIN    pg_namespace n ON n.oid = c.relnamespace',
                    '       WHERE   c.relname = \'jobs\'',
                    '       AND     n.nspname = \'public\'',
                    '       ) THEN',
                    '       CREATE INDEX jobs ON public.avars (box_status);',
                    '   END IF;',
                    '   IF NOT EXISTS (',
                    '       SELECT  1',
                    '       FROM    pg_class c',
                    '       JOIN    pg_namespace n ON n.oid = c.relnamespace',
                    '       WHERE   c.relname = \'ltouch\'',
                    '       AND     n.nspname = \'public\'',
                    '       ) THEN',
                    '       CREATE INDEX ltouch ON public.avars (last_touch);',
                    '   END IF;',
                    'END',
                    '$$',
                    'language plpgsql;',

                    'CREATE OR REPLACE FUNCTION evict_old_avars() ' +
                        'RETURNS trigger AS',
                    '$$',
                    'BEGIN',
                    '   DELETE FROM avars',
                    '   WHERE last_touch < NOW() - INTERVAL \'' +
                            settings.avar_ttl + ' seconds\';',
                    '   RETURN NEW;',
                    'END;',
                    '$$',
                    'language plpgsql;',

                    'DROP TRIGGER IF EXISTS avar_gc ON avars;',
                    'CREATE TRIGGER avar_gc',
                    '   AFTER INSERT ON avars',
                    '   EXECUTE PROCEDURE evict_old_avars();',

                    'CREATE OR REPLACE FUNCTION upsert_avar' +
                        '(b2 TEXT, bk2 TEXT) RETURNS VOID AS',
                    '$$',
                    'BEGIN',
                    '   LOOP',
                    '       UPDATE avars',
                    '           SET body = b2,' +
                        '           box_status = NULL,' +
                        '           key = NULL,' +
                        '           last_touch = NOW()',
                    '           WHERE box_key = bk2;',
                    '       IF found THEN',
                    '           RETURN;',
                    '       END IF;',
                    '       BEGIN',
                    '           INSERT INTO avars (body, box_key)',
                    '               VALUES (b2, bk2);',
                    '           RETURN;',
                    '       EXCEPTION WHEN unique_violation THEN',
                    '       END;',
                    '   END LOOP;',
                    'END;',
                    '$$',
                    'LANGUAGE plpgsql;',

                    'CREATE OR REPLACE FUNCTION upsert_task' +
                        '(b2 TEXT, bk2 TEXT, bs2 TEXT, k2 TEXT)' +
                        'RETURNS VOID AS',
                    '$$',
                    'BEGIN',
                    '   LOOP',
                    '       UPDATE avars',
                    '           SET body = b2,' +
                        '           box_status = bs2,' +
                        '           key = k2,' +
                        '           last_touch = NOW()',
                    '           WHERE box_key = bk2;',
                    '       IF found THEN',
                    '           RETURN;',
                    '       END IF;',
                    '       BEGIN',
                    '           INSERT INTO avars ' +
                        '           (body, box_key, box_status, key)',
                    '               VALUES (b2, bk2, bs2, k2);',
                    '           RETURN;',
                    '       EXCEPTION WHEN unique_violation THEN',
                    '       END;',
                    '   END LOOP;',
                    'END;',
                    '$$',
                    'LANGUAGE plpgsql;'

                ];
                client.query(lines.join('\n'), function (err) {
                 // This function also accepts a second argument that contains
                 // the "results" of the query, but because I don't use it, I
                 // have omitted it to avoid irritating JSLint et al.
                    done();
                    if (err !== null) {
                        throw err;
                    }
                    console.log('API: Postgres storage is ready.');
                    return;
                });
                return;
            });
        }

        return {
            collect_garbage: collect_garbage,
            get_avar: get_avar,
            get_list: get_list,
            set_avar: set_avar
        };
    };

    exports.log = function (settings) {
     // This function needs documentation.
        var connection_string = settings.trafficlog_storage.postgres;
        pg.connect(connection_string, function (err, client, done) {
         // This function needs documentation.
            if (err !== null) {
                done();
                throw err;
            }
            var lines;
            lines = [
                'CREATE EXTENSION IF NOT EXISTS hstore;',
                'CREATE TABLE IF NOT EXISTS traffic (',
                '   id serial PRIMARY KEY,',
                '   doc hstore',
                ');'
            ];
            client.query(lines.join('\n'), function (err) {
             // This function needs documentation.
                if (err !== null) {
                    console.error('Error:', err);
                }
                done();
                return;
            });
            return;
        });
        return function (obj) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    throw err;
                }
                var doc, key, sql, temp;
                temp = [];
                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                     // Technically, this is a bad idea (SQL injection ...).
                        temp.push(key + ' => ' + JSON.stringify(obj[key]));
                    }
                }
                doc = temp.join(', ');
                sql = 'INSERT INTO traffic (doc) VALUES (\'' + doc + '\');';
                client.query(sql, function (err) {
                 // This function needs documentation.
                    if (err !== null) {
                        console.error('Error:', err);
                    }
                    done();
                    return;
                });
                return;
            });
            return;
        };
    };

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<commit_msg>Updated data model for Postgres<commit_after>//- JavaScript source code

//- defs-postgres.js ~~
//
//  These definitions assume Postgres 9.0 or later. They also need optimization
//  help from an RDBMS guru.
//
//  Known shortcomings:
//  -   The log storage definition assumes that hstore is available.
//
//                                                      ~~ (c) SRW, 25 Sep 2012
//                                                  ~~ last updated 24 Jan 2015

(function () {
    'use strict';

 // Pragmas

    /*jshint maxparams: 3, quotmark: single, strict: true */

    /*jslint indent: 4, maxlen: 80, node: true */

    /*properties
        api, avar_ttl, body, collect_garbage, connect, error, get_avar,
        get_list, hasOwnProperty, isMaster, join, key, length, log, map,
        native, persistent_storage, postgres, push, query, rows, set_avar,
        stringify, trafficlog_storage
    */

 // Declarations

    var cluster, pg;

 // Definitions

    cluster = require('cluster');

    try {
     // If the "pg-native" module is installed, use it for a 30% boost in
     // performance. QM lists "pg-native" as an optional dependency.
        pg = require('pg').native;
    } catch (err) {
     // Fall back to the JS (non-native) implementation of the module :-)
        pg = require('pg');
    }

 // Out-of-scope definitions

    exports.api = function (settings) {
     // This function needs documentation.

        var collect_garbage, connection_string, get_avar, get_list,
            set_avar;

        collect_garbage = function () {
         // This function is only a placeholder, now that QM uses an INSERT
         // trigger to evict old rows automatically.
            return;
        };

        connection_string = settings.persistent_storage.postgres;

        get_avar = function (params, callback) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    return callback(err, undefined);
                }
                var x = [
                    'UPDATE avars SET last_touch = NOW()',
                    'WHERE box = $1 AND key = $2',
                    'RETURNING body'
                ].join(' ');
                client.query(x, params, function (err, results) {
                 // This function needs documentation.
                    done();
                    if (err !== null) {
                        return callback(err, undefined);
                    }
                    if (results.rows.length < 1) {
                        return callback(null, undefined);
                    }
                    return callback(null, results.rows[0].body);
                });
                return;
            });
            return;
        };

        get_list = function (params, callback) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    return callback(err, undefined);
                }
                var x = [
                    'SELECT key FROM avars',
                    'WHERE box = $1 AND status = $2 AND ' +
                        'last_touch > NOW() - INTERVAL \'' +
                        settings.avar_ttl + ' seconds\''
                ].join(' ');
                client.query(x, params, function (err, results) {
                 // This function needs documentation.
                    done();
                    if (err !== null) {
                        return callback(err, undefined);
                    }
                    var y = (results === undefined) ? {rows: []} : results;
                    return callback(null, y.rows.map(function (row) {
                     // This function needs documentation.
                        return row.key;
                    }));
                });
                return;
            });
            return;
        };

        set_avar = function (params, callback) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    return callback(err, undefined);
                }
                var args, sql;
                args = [
                    params[params.length - 1],  // body
                    params[0],                  // box
                    params[1]                   // key
                ];
                sql = 'SELECT upsert_avar($1, $2, $3)';
                if (params.length === 4) {
                    args.push(params[2]);
                    sql = 'SELECT upsert_task($1, $2, $3, $4)';
                }
                client.query(sql, args, function (err, results) {
                 // This function needs documentation.
                    done();
                    return callback(err, results);
                });
                return;
            });
            return;
        };

        if (cluster.isMaster) {
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    throw err;
                }
                var lines = [

                    'CREATE TABLE IF NOT EXISTS avars (',
                    '   body TEXT NOT NULL,',
                    '   box TEXT NOT NULL,',
                    '   key TEXT NOT NULL,',
                    '   last_touch TIMESTAMP NOT NULL DEFAULT NOW(),',
                    '   status TEXT,',
                    '   PRIMARY KEY (box, key)',
                    ');',

                 /*
                    'DO',
                    '$$',
                    'BEGIN',
                    '   IF NOT EXISTS (',
                    '       SELECT  1',
                    '       FROM    pg_class c',
                    '       JOIN    pg_namespace n ON n.oid = c.relnamespace',
                    '       WHERE   c.relname = \'jobs\'',
                    '       AND     n.nspname = \'public\'',
                    '       ) THEN',
                    '       CREATE INDEX jobs ON public.avars (box, status);',
                    '   END IF;',
                    '   IF NOT EXISTS (',
                    '       SELECT  1',
                    '       FROM    pg_class c',
                    '       JOIN    pg_namespace n ON n.oid = c.relnamespace',
                    '       WHERE   c.relname = \'ltouch\'',
                    '       AND     n.nspname = \'public\'',
                    '       ) THEN',
                    '       CREATE INDEX ltouch ON public.avars (last_touch);',
                    '   END IF;',
                    'END',
                    '$$',
                    'language plpgsql;',
                 */

                    'CREATE OR REPLACE FUNCTION evict_old_avars() ' +
                        'RETURNS trigger AS',
                    '$$',
                    'BEGIN',
                    '   DELETE FROM avars',
                    '   WHERE last_touch < NOW() - INTERVAL \'' +
                            settings.avar_ttl + ' seconds\';',
                    '   RETURN NEW;',
                    'END;',
                    '$$',
                    'language plpgsql;',

                    'DROP TRIGGER IF EXISTS avar_gc ON avars;',
                    'CREATE TRIGGER avar_gc',
                    '   AFTER INSERT ON avars',
                    '   EXECUTE PROCEDURE evict_old_avars();',

                    'CREATE OR REPLACE FUNCTION upsert_avar' +
                        '(body2 TEXT, box2 TEXT, key2 TEXT) RETURNS VOID AS',
                    '$$',
                    'BEGIN',
                    '   LOOP',
                    '       UPDATE avars',
                    '           SET body = body2,' +
                        '           last_touch = NOW(),' +
                        '           status = NULL',
                    '           WHERE box = box2 AND key = key2;',
                    '       IF found THEN',
                    '           RETURN;',
                    '       END IF;',
                    '       BEGIN',
                    '           INSERT INTO avars (body, box, key)',
                    '               VALUES (body2, box2, key2);',
                    '           RETURN;',
                    '       EXCEPTION WHEN unique_violation THEN',
                    '       END;',
                    '   END LOOP;',
                    'END;',
                    '$$',
                    'LANGUAGE plpgsql;',

                    'CREATE OR REPLACE FUNCTION upsert_task' +
                        '(body2 TEXT, box2 TEXT, key2 TEXT, status2 TEXT) ' +
                        'RETURNS VOID AS',
                    '$$',
                    'BEGIN',
                    '   LOOP',
                    '       UPDATE avars',
                    '           SET body = body2,' +
                        '           last_touch = NOW(),' +
                        '           status = status2',
                    '           WHERE box = box2 AND key = key2;',
                    '       IF found THEN',
                    '           RETURN;',
                    '       END IF;',
                    '       BEGIN',
                    '           INSERT INTO avars (body, box, key, status)',
                    '               VALUES (body2, box2, key2, status2);',
                    '           RETURN;',
                    '       EXCEPTION WHEN unique_violation THEN',
                    '       END;',
                    '   END LOOP;',
                    'END;',
                    '$$',
                    'LANGUAGE plpgsql;'

                ];
                client.query(lines.join('\n'), function (err) {
                 // This function also accepts a second argument that contains
                 // the "results" of the query, but because I don't use it, I
                 // have omitted it to avoid irritating JSLint et al.
                    done();
                    if (err !== null) {
                        throw err;
                    }
                    console.log('API: Postgres storage is ready.');
                    return;
                });
                return;
            });
        }

        return {
            collect_garbage: collect_garbage,
            get_avar: get_avar,
            get_list: get_list,
            set_avar: set_avar
        };
    };

    exports.log = function (settings) {
     // This function needs documentation.
        var connection_string = settings.trafficlog_storage.postgres;
        pg.connect(connection_string, function (err, client, done) {
         // This function needs documentation.
            if (err !== null) {
                done();
                throw err;
            }
            var lines;
            lines = [
                'CREATE EXTENSION IF NOT EXISTS hstore;',
                'CREATE TABLE IF NOT EXISTS traffic (',
                '   id serial PRIMARY KEY,',
                '   doc hstore',
                ');'
            ];
            client.query(lines.join('\n'), function (err) {
             // This function needs documentation.
                if (err !== null) {
                    console.error('Error:', err);
                }
                done();
                return;
            });
            return;
        });
        return function (obj) {
         // This function needs documentation.
            pg.connect(connection_string, function (err, client, done) {
             // This function needs documentation.
                if (err !== null) {
                    done();
                    throw err;
                }
                var doc, key, sql, temp;
                temp = [];
                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                     // Technically, this is a bad idea (SQL injection ...).
                        temp.push(key + ' => ' + JSON.stringify(obj[key]));
                    }
                }
                doc = temp.join(', ');
                sql = 'INSERT INTO traffic (doc) VALUES (\'' + doc + '\');';
                client.query(sql, function (err) {
                 // This function needs documentation.
                    if (err !== null) {
                        console.error('Error:', err);
                    }
                    done();
                    return;
                });
                return;
            });
            return;
        };
    };

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<|endoftext|>


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

foam.INTERFACE({
  refines: 'foam.blob.Blob',

  methods: [
    {
      name: 'read',
      javaReturns: 'java.nio.Buffer',
      args: [
        {
          name: 'buffer',
          javaType: 'java.nio.Buffer'
        },
        {
          name: 'offset',
          javaType: 'long'
        }
      ]
    }
  ]
});

foam.INTERFACE({
  refines: 'foam.blob.BlobService',

  methods: [
    {
      name: 'put',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'put_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'find',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'id',
          javaType: 'String'
        }
      ]
    },
    {
      name: 'find_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'id',
          javaType: 'String'
        }
      ]
    },
    {
      name: 'urlFor',
      javaReturns: 'String',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    }
  ]
});<commit_msg>Added javaFactory<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.INTERFACE({
  refines: 'foam.blob.Blob',

  methods: [
    {
      name: 'read',
      javaReturns: 'java.nio.Buffer',
      args: [
        {
          name: 'buffer',
          javaType: 'java.nio.Buffer'
        },
        {
          name: 'offset',
          javaType: 'long'
        }
      ]
    }
  ]
});

foam.INTERFACE({
  refines: 'foam.blob.BlobService',

  methods: [
    {
      name: 'put',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'put_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'find',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'id',
          javaType: 'String'
        }
      ]
    },
    {
      name: 'find_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'id',
          javaType: 'String'
        }
      ]
    },
    {
      name: 'urlFor',
      javaReturns: 'String',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.IdentifiedBlob',

  properties: [
    {
      name: 'delegate',
      javaFactory: 'return ((BlobService) getBlobService()).find(getId());'
    }
  ]
});<|endoftext|>