<commit_before>var
    esPhinx,
    Promise;

(function($) {
    "use strict";

    $.extend({
        Deferment: {}
    });

    $.Extender.extend($.Deferment, true, {
        new: function(options, callbackUntil) {
            var
                _accomplishResponse,
                _rejectResponse,
                whenAccomplish,
                whenReject,
                status,
                promise,
                ConstructorReference = $.Deferment.new,

                accomplish = function(response) {
                    status = "fulfilled";
                    _accomplishResponse = response;
                },

                reject = function(response) {
                    status = "rejected";
                    _rejectResponse = response;
                },

                start = function(callbackUntil, options) {
                    if (typeof options.time != "number") {
                        options.time = 0;
                    }

                    var
                        loop = function(_accomplish, _reject, callbackUntil,
                                        options) {
                            window.setTimeout(function() {
                                options.time = 0;

                                // returns the control for the user
                                callbackUntil(accomplish, reject);
                                switch (status) {
                                    case "fulfilled": {
                                        _accomplish(_accomplishResponse);
                                    }
                                    break;
                                    case "rejected": {
                                        _reject(_rejectResponse);
                                    }
                                    break;
                                    default: {
                                        loop(_accomplish, _reject,
                                             callbackUntil, options);}
                                }
                            }, options.time);
                        };

                    promise = new Promise(function(_accomplish, _reject) {
                        loop(_accomplish, _reject, callbackUntil, options);
                    });

                    promise.then(
                        // response comes from original Deferment object
                        function(r) {
                            whenAccomplish(r);
                        },

                        function(r) {
                            whenReject(r);
                        }
                    );
                };

            if (!(this instanceof ConstructorReference)) {
                return new ConstructorReference(options, callbackUntil);
            }

            if (typeof options == "function") {
                callbackUntil = options;
                options = {};
            }

            start(callbackUntil, options);

            this.accomplish = function(run) {
                whenAccomplish = run;
            };

            this.reject = function(run) {
                whenReject = run;
            };

            this.catch = function(run) {
                promise.catch(run);
            };

            return this;
        }
    });

})(esPhinx);
<commit_msg>improves deferment to work with async function<commit_after>var
    esPhinx,
    Promise;

(function($) {
    "use strict";

    $.extend({
        Deferment: {}
    });

    $.Extender.extend($.Deferment, true, {
        new: function(options, callbackUntil) {
            var
                _accomplishResponse,
                _rejectResponse,
                whenReject,
                status,
                promise,
                whenAccomplish = function(){},
                ConstructorReference = $.Deferment.new,

                accomplish = function(response) {
                    status = "fulfilled";
                    _accomplishResponse = response;
                },

                reject = function(response) {
                    status = "rejected";
                    _rejectResponse = response;
                },

                start = function(callbackUntil, options) {
                    if (typeof options.time != "number") {
                        options.time = 0;
                    }

                    var
                        loop = function(_accomplish, _reject, callbackUntil,
                                        options) {
                            window.setTimeout(function() {
                                options.time = 0;

                                // returns the control for the user
                                callbackUntil(accomplish, reject);
                                switch (status) {
                                    case "fulfilled": {
                                        _accomplish(_accomplishResponse);
                                    }
                                    break;
                                    case "rejected": {
                                        _reject(_rejectResponse);
                                    }
                                    break;
                                    default: {
                                        loop(_accomplish, _reject,
                                             callbackUntil, options);}
                                }
                            }, options.time);
                        };

                    promise = new Promise(function(_accomplish, _reject) {
                        loop(_accomplish, _reject, callbackUntil, options);
                    });

                    promise.then(
                        // response comes from original Deferment object
                        function(r) {
                            whenAccomplish(r);
                        },

                        function(r) {
                            whenReject(r);
                        }
                    );
                };

            if (!(this instanceof ConstructorReference)) {
                return new ConstructorReference(options, callbackUntil);
            }

            if (typeof options == "function") {
                callbackUntil = options;
                options = {};
            }

            start(callbackUntil, options);

            this.accomplish = function(run) {
                if (typeof run != "function") {
                    run = function(){};
                }

                whenAccomplish = run;

                return promise;
            };

            this.reject = function(run) {
                if (typeof run != "function") {
                    run = function(){};
                }

                whenReject = run;
            };

            this.catch = function(run) {
                if (typeof run != "function") {
                    run = function(){};
                }

                promise.catch(run);

                return this;
            };

            return this;
        }
    });

})(esPhinx);
<|endoftext|>


<commit_before>/**
 * @module log
 * @summary: Provides comprehensive logging facilities.
 *
 * @description:
 *
 * Author: justin
 * Created On: 2015-03-27.
 * @license Apache-2.0
 */
'use strict';
var _ = require('lodash');

module.exports = function construct(config, logProvider, bunyan, PrettyStream, TrackedStream) {
  config = config || {};
  //config = _.defaults(config, );

  var bunyanConf = {
    src: config.debug,
    name: config.name,
    streams: config.streams
  };

  if (config.enableTrackedEvents) {
    bunyanConf.streams.push({
      level: 'info',
      type: 'raw',
      stream: TrackedStream(config)
    });
  }

  if (config.errorFile) {
    bunyanConf.streams.push({
      level: 'error',
      type: 'rotating-file',
      period: '1d',
      count: 14,
      path: config.errorFile
    });
  }

  if (config.logFile) {
    bunyanConf.streams.push({
      level: config.debug ? 'debug' : 'info',
      type: 'rotating-file',
      period: '1d',
      count: 3,
      path: config.logFile
    });
  }

  if (PrettyStream) {
    var prettyStdOut = new PrettyStream();
    prettyStdOut.pipe(process.stdout);
    if (config.debug) {
      bunyanConf.streams.push(
        {
          level: 'debug',
          type: 'raw',
          stream: prettyStdOut
        });
      console.warn('Debug Logging Is Enabled.  This is OK if it is not production');
    } else {
      bunyanConf.streams.push({
        level: 'info',
        stream: prettyStdOut           // log INFO and above to stdout
      });
    }
  }

  if (config.slackLoggingEnabled) {
    var BunyanSlack = require('bunyan-slack');
    bunyanConf.stream = new BunyanSlack(config.slackConfig, function (error) {
      console.log(error);
    });
  }

  var log = (logProvider && logProvider(bunyanConf)) || bunyan.createLogger(bunyanConf);
  log.on('error', function (err, stream) {
    console.error('Log Stream Error:', err, stream);
  });

  if (config.env) {
    log = log.child({env: config.env, app: config.app});
  }

  /**
   * Often you may be using external log rotation utilities like logrotate on Linux
   * or logadm on SmartOS/Illumos. In those cases, unless your are ensuring "copy and truncate"
   * sematics (via copytruncate with logrotate or -c with logadm) then the fd for your
   * 'file' stream will change. You can tell bunyan to reopen the file stream with code
   * like this in your app:
   */
  process.on('SIGUSR2', function () {
    log.reopenFileStreams();
  });

  return createEventLogger(log);
};

function createEventLogger(logger, context) {
  logger.observers = {};

  var enactObservers = function() {
    if (arguments[0][0] == '@') {
      if (logger.observers[arguments[0]]) {
        var event = {};
        p.map(logger.observers[arguments[0]] || [], function(cb) {
          if (!event.stopPropagation) cb(event, arguments[1]);
        }, {concurrency: 1});
      }
    }
  };

  function parseLogObject() {
    var logObject = {};

    if (_.isString(arguments[0])) {
      logObject.msg = arguments[0];
      if (_.isObject(arguments[1])) {
        _.extend(logObject, arguments[1]);
      }
      _.each(arguments, function(arg, idx) {
        if (idx != 0) {
          logObject.msg += ' ' + JSON.stringify(arg);
        }
      });
    } else if (!arguments[1]) {
      if (_.isObject(arguments[0])) return arguments[0];
    } else {
      _.each(arguments, function(arg, idx) {
        logObject.msg += ' ' + JSON.stringify(arg);
      });
    }
    return logObject;
  }

  // The log method itself is a little special.  It does 2 things:
  // 1. Calls bunyan info() log level logger.
  // 2. Checks for observers to this log event and fires their handlers.
  var log = function log() {
    var logObject = parseLogObject.apply(undefined,arguments);
    enactObservers.apply(logger, arguments);
    logger.info(logObject, logObject.msg);
  };

  log.watchFor = function(eventLabel, observerAction) {
    logger.observers[eventLabel] = logger.observers[eventLabel] || [];
    logger.observers[eventLabel].push(observerAction);
  };

  // make sure all the interfaces are wired up.
  log.error = function() {
    if (_.isString(arguments[0]) && _.isObject(arguments[1]) && arguments[1].message) {
      logger.error({err: arguments[1]}, arguments[0]);
    } else {
      var logObject = parseLogObject.apply(undefined,arguments);
      logger.error(logObject, logObject.msg);
    }
  };
  log.warn = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.warn(logObject, logObject.msg);
  };
  log.debug = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.debug(logObject, logObject.msg);
  };
  log.info = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.info(logObject, logObject.msg);
  };

  log.fatal = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.fatal(logObject, logObject.msg);
  };

  // log a goal completion.
  log.completion = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    if (!logObject.uid) { log.warn('Goal completion log failed due to no uid specified.'); }

    logObject.completeGoal = logObject.uid;
    logger.info(logObject, logObject.msg);
  };

  log.child = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.child(logObject);
  };

  // assign aliases:
  log.logFatal = log.fatal;
  log.log = log;
  log.logError = log.error;
  log.logWarn = log.warn;

  // bonus

  log.context = function(funcName, params, object) {
    return createEventLogger(log, {
      where: object? object.toString() + '->' +funcName: funcName,
      params: params
    })
  }

  log.rejectWithCode = function(code) {
    return function rejectWithCodeHandler(err) {
      var details = {
        what: code,
        context: context,
        err: err,
        why: _.isString(err) ? err : err.message
      };
      log.error(code, details)
      return p.reject(details)
    };
  }

  log.resolve = function(result) {
    if (context)
      log.log(context.what+' resolved.', {context: context, result: result});
    return result;
  }

  log.errorReport = function(what, details) {
    if (context) {
      details = _.extend(context, details)
    }
    log.error(what, details);
    return details;
  }

  return log;
}<commit_msg>bugfix<commit_after>/**
 * @module log
 * @summary: Provides comprehensive logging facilities.
 *
 * @description:
 *
 * Author: justin
 * Created On: 2015-03-27.
 * @license Apache-2.0
 */
'use strict';
var _ = require('lodash');

module.exports = function construct(config, logProvider, bunyan, PrettyStream, TrackedStream) {
  config = config || {};
  //config = _.defaults(config, );

  var bunyanConf = {
    src: config.debug,
    name: config.name,
    streams: config.streams
  };

  if (config.enableTrackedEvents) {
    bunyanConf.streams.push({
      level: 'info',
      type: 'raw',
      stream: TrackedStream(config)
    });
  }

  if (config.errorFile) {
    bunyanConf.streams.push({
      level: 'error',
      type: 'rotating-file',
      period: '1d',
      count: 14,
      path: config.errorFile
    });
  }

  if (config.logFile) {
    bunyanConf.streams.push({
      level: config.debug ? 'debug' : 'info',
      type: 'rotating-file',
      period: '1d',
      count: 3,
      path: config.logFile
    });
  }

  if (PrettyStream) {
    var prettyStdOut = new PrettyStream();
    prettyStdOut.pipe(process.stdout);
    if (config.debug) {
      bunyanConf.streams.push(
        {
          level: 'debug',
          type: 'raw',
          stream: prettyStdOut
        });
      console.warn('Debug Logging Is Enabled.  This is OK if it is not production');
    } else {
      bunyanConf.streams.push({
        level: 'info',
        stream: prettyStdOut           // log INFO and above to stdout
      });
    }
  }

  if (config.slackLoggingEnabled) {
    var BunyanSlack = require('bunyan-slack');
    bunyanConf.stream = new BunyanSlack(config.slackConfig, function (error) {
      console.log(error);
    });
  }

  var log = (logProvider && logProvider(bunyanConf)) || bunyan.createLogger(bunyanConf);
  log.on('error', function (err, stream) {
    console.error('Log Stream Error:', err, stream);
  });

  if (config.env) {
    log = log.child({env: config.env, app: config.app});
  }

  /**
   * Often you may be using external log rotation utilities like logrotate on Linux
   * or logadm on SmartOS/Illumos. In those cases, unless your are ensuring "copy and truncate"
   * sematics (via copytruncate with logrotate or -c with logadm) then the fd for your
   * 'file' stream will change. You can tell bunyan to reopen the file stream with code
   * like this in your app:
   */
  process.on('SIGUSR2', function () {
    log.reopenFileStreams();
  });

  return createEventLogger(log);
};

function createEventLogger(logger, context) {
  logger.observers = {};

  var enactObservers = function() {
    if (arguments[0][0] == '@') {
      if (logger.observers[arguments[0]]) {
        var event = {};
        p.map(logger.observers[arguments[0]] || [], function(cb) {
          if (!event.stopPropagation) cb(event, arguments[1]);
        }, {concurrency: 1});
      }
    }
  };

  function parseLogObject() {
    var logObject = {};

    if (_.isString(arguments[0])) {
      logObject.msg = arguments[0];
      if (_.isObject(arguments[1])) {
        _.extend(logObject, arguments[1]);
      }
      _.each(arguments, function(arg, idx) {
        if (idx != 0) {
          logObject.msg += ' ' + JSON.stringify(arg);
        }
      });
    } else if (!arguments[1]) {
      if (_.isObject(arguments[0])) return arguments[0];
    } else {
      _.each(arguments, function(arg, idx) {
        logObject.msg += ' ' + JSON.stringify(arg);
      });
    }
    return logObject;
  }

  // The log method itself is a little special.  It does 2 things:
  // 1. Calls bunyan info() log level logger.
  // 2. Checks for observers to this log event and fires their handlers.
  var log = function log() {
    var logObject = parseLogObject.apply(undefined,arguments);
    enactObservers.apply(logger, arguments);
    logger.info(logObject, logObject.msg);
  };

  log.watchFor = function(eventLabel, observerAction) {
    logger.observers[eventLabel] = logger.observers[eventLabel] || [];
    logger.observers[eventLabel].push(observerAction);
  };

  // make sure all the interfaces are wired up.
  log.error = function() {
    if (_.isString(arguments[0]) && _.isObject(arguments[1]) && arguments[1].message) {
      logger.error({err: arguments[1]}, arguments[0]);
    } else {
      var logObject = parseLogObject.apply(undefined,arguments);
      logger.error(logObject, logObject.msg);
    }
  };
  log.warn = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.warn(logObject, logObject.msg);
  };
  log.debug = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.debug(logObject, logObject.msg);
  };
  log.info = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.info(logObject, logObject.msg);
  };

  log.fatal = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.fatal(logObject, logObject.msg);
  };

  // log a goal completion.
  log.completion = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    if (!logObject.uid) { log.warn('Goal completion log failed due to no uid specified.'); }

    logObject.completeGoal = logObject.uid;
    logger.info(logObject, logObject.msg);
  };

  log.child = function() {
    var logObject = parseLogObject.apply(undefined,arguments);
    logger.child(logObject);
  };

  // assign aliases:
  log.logFatal = log.fatal;
  log.log = log;
  log.logError = log.error;
  log.logWarn = log.warn;

  // bonus

  log.context = function(funcName, params, object) {
    return createEventLogger(log, {
      where: object? object.constructor + '->' +funcName: funcName,
      params: params
    })
  }

  log.rejectWithCode = function(code) {
    return function rejectWithCodeHandler(err) {
      var details = {
        what: code,
        context: context,
        err: err,
        why: _.isString(err) ? err : err.message
      };
      log.error(code, details)
      return p.reject(details)
    };
  }

  log.resolve = function(result) {
    if (context)
      log.log(context.what+' resolved.', {context: context, result: result});
    return result;
  }

  log.errorReport = function(what, details) {
    if (context) {
      details = _.extend(context, details)
    }
    log.error(what, details);
    return details;
  }

  return log;
}<|endoftext|>


<commit_before>/*
 * grunt-contrib-watch
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var path = require('path');
  var fs = require('fs');
  var Gaze = require('gaze').Gaze;

  // Default options for the watch task
  var defaults = {
    interrupt: false
  };

  grunt.registerTask('watch', 'Run predefined tasks whenever watched files change.', function(target) {
    var name = this.name || 'watch';
    this.requiresConfig(name);

    // Build an array of files/tasks objects
    var watch = grunt.config(name);
    var targets = target ? [target] : Object.keys(watch).filter(function(key) {
      return typeof watch[key] !== 'string' && !Array.isArray(watch[key]);
    });

    targets = targets.map(function(target) {
      // Fail if any required config properties have been omitted
      target = [name, target];
      this.requiresConfig(target.concat('files'), target.concat('tasks'));
      return grunt.config(target);
    }, this);

    // Allow "basic" non-target format
    if (typeof watch.files === 'string' || Array.isArray(watch.files)) {
      targets.push({files: watch.files, tasks: watch.tasks});
    }

    // Message to display when waiting for changes
    var waiting = 'Waiting...';

    // File changes to be logged.
    var changedFiles = Object.create(null);

    // Keep track of spawns per tasks
    var spawned = Object.create(null);

    // List of changed / deleted file paths.
    grunt.file.watchFiles = {changed: [], deleted: [], added: []};

    // Get process.argv options without grunt.cli.tasks to pass to child processes
    var cliArgs = grunt.util._.without.apply(null, [[].slice.call(process.argv, 2)].concat(grunt.cli.tasks));

    // Call to close this task
    var done = this.async();
    grunt.log.write(waiting);

    // Run the tasks for the changed files
    var runTasks = grunt.util._.debounce(function runTasks(i, tasks, options) {
      // If interrupted, reset the spawned for a target
      if (options.interrupt && typeof spawned[i] === 'object') {
        grunt.log.writeln('').write('Previously spawned task has been interrupted...'.yellow);
        spawned[i].kill('SIGINT');
        delete spawned[i];
      }

      // Only spawn one at a time unless interrupt is specified
      if (!spawned[i]) {
        grunt.log.ok();

        var fileArray = Object.keys(changedFiles);
        fileArray.forEach(function(filepath) {
          // Log which file has changed, and how.
          grunt.log.ok('File "' + filepath + '" ' + changedFiles[filepath] + '.');
        });

        // Reset changedFiles
        changedFiles = Object.create(null);

        // Spawn the tasks as a child process
        spawned[i] = grunt.util.spawn({
          // Spawn with the grunt bin
          grunt: true,
          // Run from current working dir and inherit stdio from process
          opts: {cwd: process.cwd(), stdio: 'inherit'},
          // Run grunt this process uses, append the task to be run and any cli options
          args: grunt.util._.union(tasks, cliArgs)
        }, function(err, res, code) {
          // Spawn is done
          delete spawned[i];
          grunt.log.writeln('').write(waiting);
        });
      }
    }, 250);

    targets.forEach(function(target, i) {
      if (typeof target.files === 'string') {
        target.files = [target.files];
      }
      // Get patterns to glob for this target
      var patterns = grunt.util._.chain(target.files).flatten().uniq().value();

      // Default options per target
      var options = grunt.util._.defaults(target.options || {}, defaults);

      // Create watcher per target
      var gaze = new Gaze(patterns, options, function(err) {
        if (err) {
          grunt.log.error(err.message);
          return done();
        }

        // On changed/added/deleted
        this.on('all', function(status, filepath) {
          filepath = path.relative(process.cwd(), filepath);
          changedFiles[filepath] = status;
          runTasks(i, target.tasks, options);
        });

        // On watcher error
        this.on('error', function(err) { grunt.log.error(err); });
      });
    });

    // Keep the process alive
    setInterval(function() {}, 250);
  });
};
<commit_msg>Use grunt.file.expand to support exclusions. Closes GH-30.<commit_after>/*
 * grunt-contrib-watch
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var path = require('path');
  var fs = require('fs');
  var Gaze = require('gaze').Gaze;

  // Default options for the watch task
  var defaults = {
    interrupt: false
  };

  grunt.registerTask('watch', 'Run predefined tasks whenever watched files change.', function(target) {
    var name = this.name || 'watch';
    this.requiresConfig(name);

    // Build an array of files/tasks objects
    var watch = grunt.config(name);
    var targets = target ? [target] : Object.keys(watch).filter(function(key) {
      return typeof watch[key] !== 'string' && !Array.isArray(watch[key]);
    });

    targets = targets.map(function(target) {
      // Fail if any required config properties have been omitted
      target = [name, target];
      this.requiresConfig(target.concat('files'), target.concat('tasks'));
      return grunt.config(target);
    }, this);

    // Allow "basic" non-target format
    if (typeof watch.files === 'string' || Array.isArray(watch.files)) {
      targets.push({files: watch.files, tasks: watch.tasks});
    }

    // Message to display when waiting for changes
    var waiting = 'Waiting...';

    // File changes to be logged.
    var changedFiles = Object.create(null);

    // Keep track of spawns per tasks
    var spawned = Object.create(null);

    // List of changed / deleted file paths.
    grunt.file.watchFiles = {changed: [], deleted: [], added: []};

    // Get process.argv options without grunt.cli.tasks to pass to child processes
    var cliArgs = grunt.util._.without.apply(null, [[].slice.call(process.argv, 2)].concat(grunt.cli.tasks));

    // Call to close this task
    var done = this.async();
    grunt.log.write(waiting);

    // Run the tasks for the changed files
    var runTasks = grunt.util._.debounce(function runTasks(i, tasks, options) {
      // If interrupted, reset the spawned for a target
      if (options.interrupt && typeof spawned[i] === 'object') {
        grunt.log.writeln('').write('Previously spawned task has been interrupted...'.yellow);
        spawned[i].kill('SIGINT');
        delete spawned[i];
      }

      // Only spawn one at a time unless interrupt is specified
      if (!spawned[i]) {
        grunt.log.ok();

        var fileArray = Object.keys(changedFiles);
        fileArray.forEach(function(filepath) {
          // Log which file has changed, and how.
          grunt.log.ok('File "' + filepath + '" ' + changedFiles[filepath] + '.');
        });

        // Reset changedFiles
        changedFiles = Object.create(null);

        // Spawn the tasks as a child process
        spawned[i] = grunt.util.spawn({
          // Spawn with the grunt bin
          grunt: true,
          // Run from current working dir and inherit stdio from process
          opts: {cwd: process.cwd(), stdio: 'inherit'},
          // Run grunt this process uses, append the task to be run and any cli options
          args: grunt.util._.union(tasks, cliArgs)
        }, function(err, res, code) {
          // Spawn is done
          delete spawned[i];
          grunt.log.writeln('').write(waiting);
        });
      }
    }, 250);

    targets.forEach(function(target, i) {
      if (typeof target.files === 'string') {
        target.files = [target.files];
      }
      // Get patterns to glob for this target
      var patterns = grunt.file.expand(target.files);

      // Default options per target
      var options = grunt.util._.defaults(target.options || {}, defaults);

      // Create watcher per target
      var gaze = new Gaze(patterns, options, function(err) {
        if (err) {
          grunt.log.error(err.message);
          return done();
        }

        // On changed/added/deleted
        this.on('all', function(status, filepath) {
          filepath = path.relative(process.cwd(), filepath);
          changedFiles[filepath] = status;
          runTasks(i, target.tasks, options);
        });

        // On watcher error
        this.on('error', function(err) { grunt.log.error(err); });
      });
    });

    // Keep the process alive
    setInterval(function() {}, 250);
  });
};
<|endoftext|>


<commit_before>var shell = require("gl-now")()
var camera = require("game-shell-orbit-camera")(shell)
var createTileMap = require("gl-tile-map")
var createBuffer = require("gl-buffer")
var createVAO = require("gl-vao")
var ndarray = require("ndarray")
var fill = require("ndarray-fill")
var ops = require("ndarray-ops")
var terrain = require("isabella-texture-pack")
var createAOMesh = require("ao-mesher")
var createAOShader = require("../aoshader.js")
var glm = require("gl-matrix")
var mat4 = glm.mat4

//WebGL state
var shader, texture, vao, vertexCount

//Voxel resolution
var resolution = [32,32,32]

//Modify this to generate different terrains:
function generateVoxels(i,j,k) {
  var x = i - 16
  var y = j - 16
  var z = k - 16
  if(x*x+y*y+z*z < 30) {
    if(k < 16) {
      return 1<<15
    }
    return (1<<15)+1
  }
  return 0
}

shell.on("gl-init", function() {
  var gl = shell.gl

  //Create shader
  shader = createAOShader(gl)

  //Create some voxels
  var voxels = ndarray(new Int32Array(resolution[0]*resolution[1]*resolution[2]),
                      resolution)
  fill(voxels, generateVoxels)

  //Set up camera
  var c = [resolution[0]>>>1, resolution[1]>>>1, resolution[2]>>>1]
  camera.lookAt([c[0], c[1], c[2]+2*resolution[2]], c, [0,1,0])

  //Compute mesh
  var vert_data = createAOMesh(voxels)

  //Convert mesh to WebGL buffer
  vertexCount = vert_data.length>>3
  var vert_buf = createBuffer(gl, vert_data)
  vao = createVAO(gl, undefined, [
    { "buffer": vert_buf,
      "type": gl.UNSIGNED_BYTE,
      "size": 4,
      "offset": 0,
      "stride": 8,
      "normalized": false
    },
    { "buffer": vert_buf,
      "type": gl.UNSIGNED_BYTE,
      "size": 4,
      "offset": 4,
      "stride": 8,
      "normalized": false
    }
  ])

  //Load texture map
  var tiles = ndarray(terrain.data,
    [16,16,terrain.shape[0]>>4,terrain.shape[1]>>4,4],
    [terrain.stride[0]*16, terrain.stride[1]*16, terrain.stride[0], terrain.stride[1], terrain.stride[2]], 0)
  texture = createTileMap(gl, tiles, true)
  texture.mipSamples = 4
})

shell.on("gl-render", function(t) {
  var gl = shell.gl
  var A = mat4.create()

  //Set WebGL parameters
  gl.enable(gl.CULL_FACE)
  gl.enable(gl.DEPTH_TEST)

  //Bind the shader
  shader.bind()

  //Set shader attributes and uniforms
  shader.attributes.attrib0.location = 0
  shader.attributes.attrib1.location = 1
  shader.uniforms.projection = mat4.perspective(A,
                                                Math.PI/4.0,
                                                shell.width/shell.height,
                                                1.0,
                                                1000.0)
  shader.uniforms.view = camera.view()
	shader.uniforms.model = mat4.identity(A)
  shader.uniforms.tileMap = texture.bind()
  shader.uniforms.tileSize = 16.0

  //Draw object
  vao.bind()
  gl.drawArrays(gl.TRIANGLES, 0, vertexCount)
  vao.unbind()
})
<commit_msg>Add missing uniform<commit_after>var shell = require("gl-now")()
var camera = require("game-shell-orbit-camera")(shell)
var createTileMap = require("gl-tile-map")
var createBuffer = require("gl-buffer")
var createVAO = require("gl-vao")
var ndarray = require("ndarray")
var fill = require("ndarray-fill")
var ops = require("ndarray-ops")
var terrain = require("isabella-texture-pack")
var createAOMesh = require("ao-mesher")
var createAOShader = require("../aoshader.js")
var glm = require("gl-matrix")
var mat4 = glm.mat4

//WebGL state
var shader, texture, vao, vertexCount

//Voxel resolution
var resolution = [32,32,32]

//Modify this to generate different terrains:
function generateVoxels(i,j,k) {
  var x = i - 16
  var y = j - 16
  var z = k - 16
  if(x*x+y*y+z*z < 30) {
    if(k < 16) {
      return 1<<15
    }
    return (1<<15)+1
  }
  return 0
}

shell.on("gl-init", function() {
  var gl = shell.gl

  //Create shader
  shader = createAOShader(gl)

  //Create some voxels
  var voxels = ndarray(new Int32Array(resolution[0]*resolution[1]*resolution[2]),
                      resolution)
  fill(voxels, generateVoxels)

  //Set up camera
  var c = [resolution[0]>>>1, resolution[1]>>>1, resolution[2]>>>1]
  camera.lookAt([c[0], c[1], c[2]+2*resolution[2]], c, [0,1,0])

  //Compute mesh
  var vert_data = createAOMesh(voxels)

  //Convert mesh to WebGL buffer
  vertexCount = vert_data.length>>3
  var vert_buf = createBuffer(gl, vert_data)
  vao = createVAO(gl, undefined, [
    { "buffer": vert_buf,
      "type": gl.UNSIGNED_BYTE,
      "size": 4,
      "offset": 0,
      "stride": 8,
      "normalized": false
    },
    { "buffer": vert_buf,
      "type": gl.UNSIGNED_BYTE,
      "size": 4,
      "offset": 4,
      "stride": 8,
      "normalized": false
    }
  ])

  //Load texture map
  var tiles = ndarray(terrain.data,
    [16,16,terrain.shape[0]>>4,terrain.shape[1]>>4,4],
    [terrain.stride[0]*16, terrain.stride[1]*16, terrain.stride[0], terrain.stride[1], terrain.stride[2]], 0)
  texture = createTileMap(gl, tiles, true)
  texture.mipSamples = 4
})

shell.on("gl-render", function(t) {
  var gl = shell.gl
  var A = mat4.create()

  //Set WebGL parameters
  gl.enable(gl.CULL_FACE)
  gl.enable(gl.DEPTH_TEST)

  //Bind the shader
  shader.bind()

  //Set shader attributes and uniforms
  shader.attributes.attrib0.location = 0
  shader.attributes.attrib1.location = 1
  shader.uniforms.projection = mat4.perspective(A,
                                                Math.PI/4.0,
                                                shell.width/shell.height,
                                                1.0,
                                                1000.0)
  shader.uniforms.view = camera.view()
	shader.uniforms.model = mat4.identity(A)
  shader.uniforms.tileMap = texture.bind()
  shader.uniforms.tileSize = 16.0
  shader.uniforms.tileCount = 16.0

  //Draw object
  vao.bind()
  gl.drawArrays(gl.TRIANGLES, 0, vertexCount)
  vao.unbind()
})
<|endoftext|>


<commit_before>"use strict";

var domain = require("domain");
var url = require("url");
var _ = require("lodash");

plugin.consumes = ["raygun", "connect", "http", "connect.remote-address"];
plugin.provides = ["raygun.connect"];

module.exports = plugin;

function plugin(options, imports, register) {
    var raygun = imports.raygun;
    var errorClient = raygun.errorClient;
    var warningClient = raygun.warningClient;
    var connect = imports.connect;
    var server = imports.http.getServer();

    errorClient.user = warningClient.user = function(req) {
        return (req && req.user) ? req.user.name : "";
    };

    connect.useStart(function(req, res, next) {
        var d = domain.create();
        d.on("error", function(err) {
            sendRequestError(err, req);

            // from http://nodejs.org/api/domain.html
            try {
                // make sure we close down within 10 seconds
                console.error("Uncaught exception. Logging error and shutting down in 10 sec");
                console.error("Exception:", err);
                console.error("Exception stack:", err.stack);
                console.error("Our current stack: ", new Error().stack);
                var killtimer = setTimeout(function() {
                    console.error("Exiting after uncaught exception");
                    console.error(err.stack || err);
                    process.exit(1);
                }, 10000);
                // But don't keep the process open just for that!
                killtimer.unref();

                // stop taking new requests.
                server.close();
                next(err);
            } catch (er2) {
                console.error("Error sending 500!", er2.stack);
            }
        });
        d.add(req);
        d.add(res);
        d.run(next);
    });

    server.on("timeout", function(socket) {
        socket.destroy();

        var domain = socket._httpMessage && socket._httpMessage.domain;
        var req = domain && domain.members[0];
        if (req && req.url)
            sendRequestWarning(new Error("Request timed out: " + req.url), req);

    });

    function sendRequestError(err, req) {
        return _sendRequest(errorClient, err, req);
    }

    function sendRequestWarning(err, req) {
        return _sendRequest(warningClient, err, req);
    }

    function _sendRequest(raygunClient, err, req) {
        var parsedUrl = url.parse(req.url, false);
        var ip = req.remoteAddress;

        var customData = _.clone(raygun.customData || {});
        if (req.user) {
            customData.user = {
                id: req.user.id,
                name: req.user.name,
                email: req.user.email
            };
        }
        else if (req.session) {
            customData.user = {
                id: req.session.uid
            };
        }

        raygunClient.send(err, customData, function() {}, {
            host: parsedUrl.hostname,
            path: parsedUrl.pathname,
            method: req.method,
            ip: ip,
            query: parsedUrl.query,
            headers: req.headers,
            body: req.body,
            user: req.user
        });
    }

    register(null, {"raygun.connect": {
        sendRequestError: sendRequestError,
        sendRequestWarning: sendRequestWarning
    }});
}<commit_msg>Adding more custom data so we can track down server crashes<commit_after>"use strict";

var domain = require("domain");
var url = require("url");
var _ = require("lodash");

plugin.consumes = ["raygun", "connect", "http", "connect.remote-address"];
plugin.provides = ["raygun.connect"];

module.exports = plugin;

function plugin(options, imports, register) {
    var raygun = imports.raygun;
    var errorClient = raygun.errorClient;
    var warningClient = raygun.warningClient;
    var connect = imports.connect;
    var server = imports.http.getServer();

    errorClient.user = warningClient.user = function(req) {
        return (req && req.user) ? req.user.name : "";
    };

    connect.useStart(function(req, res, next) {
        var d = domain.create();
        d.on("error", function(err) {
            raygun.customData = raygun.customData || {};
            raygun.customData.serverCrashed = true;
            raygun.customData.exceptionStack = err.stack;
            raygun.customData.crashStack = new Error().stack;
            sendRequestError(err, req);

            // from http://nodejs.org/api/domain.html
            try {
                // make sure we close down within 10 seconds
                console.error("Uncaught exception. Logging error and shutting down in 10 sec");
                console.error("Exception:", err);
                console.error("Exception stack:", err.stack);
                console.error("Our current stack: ", new Error().stack);
                var killtimer = setTimeout(function() {
                    console.error("Exiting after uncaught exception");
                    console.error(err.stack || err);
                    process.exit(1);
                }, 10000);
                // But don't keep the process open just for that!
                killtimer.unref();

                // stop taking new requests.
                server.close();
                next(err);
            } catch (er2) {
                console.error("Error sending 500!", er2.stack);
            }
        });
        d.add(req);
        d.add(res);
        d.run(next);
    });

    server.on("timeout", function(socket) {
        socket.destroy();

        var domain = socket._httpMessage && socket._httpMessage.domain;
        var req = domain && domain.members[0];
        if (req && req.url)
            sendRequestWarning(new Error("Request timed out: " + req.url), req);

    });

    function sendRequestError(err, req) {
        return _sendRequest(errorClient, err, req);
    }

    function sendRequestWarning(err, req) {
        return _sendRequest(warningClient, err, req);
    }

    function _sendRequest(raygunClient, err, req) {
        var parsedUrl = url.parse(req.url, false);
        var ip = req.remoteAddress;

        var customData = _.clone(raygun.customData || {});
        if (req.user) {
            customData.user = {
                id: req.user.id,
                name: req.user.name,
                email: req.user.email
            };
        }
        else if (req.session) {
            customData.user = {
                id: req.session.uid
            };
        }

        raygunClient.send(err, customData, function() {}, {
            host: parsedUrl.hostname,
            path: parsedUrl.pathname,
            method: req.method,
            ip: ip,
            query: parsedUrl.query,
            headers: req.headers,
            body: req.body,
            user: req.user
        });
    }

    register(null, {"raygun.connect": {
        sendRequestError: sendRequestError,
        sendRequestWarning: sendRequestWarning
    }});
}<|endoftext|>


<commit_before>/*global $, initApp, XDomainRequest, ActiveXObject */
(function(document){
	var assetLocation = "http://rawgit.com/salbahra/Sprinklers/master/www/",
		isReady = false;

	function insertStyle(css) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    style = document.createElement("style");

		style.type = "text/css";
		if (style.styleSheet){
		  style.styleSheet.cssText = css;
		} else {
		  style.appendChild(document.createTextNode(css));
		}

		head.appendChild(style);
	}

	function insertStyleSheet(href) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    link = document.createElement("link");

		link.rel = "stylesheet";
		link.href = href;

		head.appendChild(link);
	}

	// Insert script into the DOM
	function insertScript(src,callback) {
		// Create callback if one is not provided
		callback = callback || function(){};

	    var a=document.createElement("script");
	    a.src=src;
	    document.getElementsByTagName("head")[0].appendChild(a);

	    // Start checking for script load completion and callback when done
	    var interval = setInterval(function(){
			if (document.readyState === "complete") {
				clearInterval(interval);
				callback();
			}
		},1);
	}

	// Insert loading icon
	insertStyle(".spinner{display:block;padding:.9375em;margin-left:-7.1875em;width:12.5em;filter:Alpha(Opacity=88);opacity:.88;box-shadow:0 1px 1px -1px #fff;margin-top:-2.6875em;height:auto;z-index:9999999;position:fixed;top:50%;left:50%;border:0;background-color:#2a2a2a;border-color:#1d1d1d;color:#fff;text-shadow:0 1px 0 #111;-webkit-border-radius:.3125em;border-radius:.3125em;}.spinner h1{font-size: 1em;margin:0;text-align:center;}.spinner form{margin-bottom:0}.spinner form{padding-top:.2em;}.spinner input[type='password']{border-radius:5px;padding:.3em;line-height:1.2em;display:block;width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;outline:0;}.spinner input[type=submit]{border-radius:5px;border: 0;font-family:Tahoma;background:#f4f4f4;margin-top:5px;width:100%;}");

	// Change title to reflect current state
	document.title = "Loading...";

	// Insert jQM stylesheet
	insertStyleSheet(assetLocation+"css/jquery.mobile.min.css");

	// Insert main application stylesheet
	insertStyleSheet(assetLocation+"css/main.css");

	// Insert jQuery and run init function on completion
	insertScript(assetLocation+"js/jquery.min.js",init);

	function init() {
		var body = $("body"),
			finishInit = function() {
			    // Start checking for script load completion and callback when done
			    var interval = setInterval(function(){
					if (isReady) {
						clearInterval(interval);
						// Load jQuery Mobile
						$.getScript(assetLocation+"js/jquery.mobile.min.js");
					}
				},1);
			},
			sites = JSON.parse(localStorage.getItem("sites")),
			loader;

		// Fix to allow CORS ajax requests to work on IE8 and 9
		(function(){if($.support.cors||!$.ajaxTransport||!window.XDomainRequest){return;}var b=/^https?:\/\//i;var c=/^get|post$/i;var a=new RegExp("^"+location.protocol,"i");$.ajaxTransport("* text html xml json",function(e,g){if(!e.crossDomain||!e.async||!c.test(e.type)||!b.test(e.url)||!a.test(e.url)){return;}var d=null;return{send:function(k,i){var h="";var j=(g.dataType||"").toLowerCase();d=new XDomainRequest();if(/^\d+$/.test(g.timeout)){d.timeout=g.timeout;}d.ontimeout=function(){i(500,"timeout");};d.onload=function(){var q="Content-Length: "+d.responseText.length+"\r\nContent-Type: "+d.contentType;var l={code:200,message:"success"};var n={text:d.responseText};try{if(j==="html"||/text\/html/i.test(d.contentType)){n.html=d.responseText;}else{if(j==="json"||(j!=="text"&&/\/json/i.test(d.contentType))){try{n.json=$.parseJSON(d.responseText);}catch(p){l.code=500;l.message="parseerror";}}else{if(j==="xml"||(j!=="text"&&/\/xml/i.test(d.contentType))){var o=new ActiveXObject("Microsoft.XMLDOM");o.async=false;try{o.loadXML(d.responseText);}catch(p){o=undefined;}if(!o||!o.documentElement||o.getElementsByTagName("parsererror").length){l.code=500;l.message="parseerror";throw"Invalid XML: "+d.responseText;}n.xml=o;}}}}catch(m){throw m;}finally{i(l.code,l.message,n,q);}};d.onprogress=function(){};d.onerror=function(){i(500,"error",{text:d.responseText});};if(g.data){h=($.type(g.data)==="string")?g.data:$.param(g.data);}d.open(e.type,e.url);d.send(h);},abort:function(){if(d){d.abort();}}};});}());

		if (sites) {
			// If device has been logged into before, use available settings
			loader = $("

Loading

");
			finishInit();
		} else {
			// If this is a new login, prompt for password
			loader = $("

Enter Device Password
<form><input type='password' id='os_pw' name='os_pw' value='' /><input type='submit' value='Submit' /></form>
"),
			loader.on("submit",function(){
				var sites = {
					"Local": {
						"os_ip": document.URL.match(/https?:\/\/(.*)\/.*?/)[1],
						// Still need to prompt for password
						"os_pw": $("#os_pw").val()
					}
				},
				current_site = "Local";

				// Show loading message and title
				body.html("

Loading

");
				document.title = "Loading...";

				// Inject site information to storage so Application loads current device
				localStorage.setItem("sites",JSON.stringify(sites));
				localStorage.setItem("current_site",current_site);

				finishInit();

				return false;
			});

			// Change title to reflect current state
			document.title = "OpenSprinkler: Login";
		}

		// Change viewport
		$("meta[name='viewport']").attr("content","width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no");

		// Hide the body while we modify the DOM
		body.html(loader);

		$.ajax({
			url: assetLocation+"index.html",
			cache: false,
			crossDomain: true,
			type: "GET"
		}).then(
			function(data){
				// Grab the pages from index.html (body content)
				var pages = data.match(/([.\s\S]*)<\/body>/)[1];

				// Disables site selection menu
				window.curr_local = true;

				// Load 3rd party libraries such as FastClick (loaded first to avoid conflicts)
				$.getScript(assetLocation+"js/libs.js",function(){

					// Load main application Javascript (loaded before jQM so binds trigger when jQM loads)
					$.getScript(assetLocation+"js/main.js",function(){

						// Show the body when jQM attempts first page transition
						$(document).one("mobileinit",function(){

							// Change title to reflect loading finished
							document.title = "Sprinkler System";

							// Inject pages into DOM
							body.html(pages);

							// Remove spinner code (no longer needed)
							$("head").find("style").remove();

							// Initialize environment (missed by main.js since body was added after)
							initApp();

							// Hide multi site features since using local device
							body.find(".multiSite").hide();
						});

						// Mark environment as loaded
						isReady = true;
					});
				});
			},
			function(){
				body.html("

Unable to load UI

");
			}
		);
	}
}(document));
<commit_msg>Injector: Add citation for plugin<commit_after>/*global $, initApp, XDomainRequest, ActiveXObject */
(function(document){
	var assetLocation = "http://rawgit.com/salbahra/Sprinklers/master/www/",
		isReady = false;

	function insertStyle(css) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    style = document.createElement("style");

		style.type = "text/css";
		if (style.styleSheet){
		  style.styleSheet.cssText = css;
		} else {
		  style.appendChild(document.createTextNode(css));
		}

		head.appendChild(style);
	}

	function insertStyleSheet(href) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    link = document.createElement("link");

		link.rel = "stylesheet";
		link.href = href;

		head.appendChild(link);
	}

	// Insert script into the DOM
	function insertScript(src,callback) {
		// Create callback if one is not provided
		callback = callback || function(){};

	    var a=document.createElement("script");
	    a.src=src;
	    document.getElementsByTagName("head")[0].appendChild(a);

	    // Start checking for script load completion and callback when done
	    var interval = setInterval(function(){
			if (document.readyState === "complete") {
				clearInterval(interval);
				callback();
			}
		},1);
	}

	// Insert loading icon
	insertStyle(".spinner{display:block;padding:.9375em;margin-left:-7.1875em;width:12.5em;filter:Alpha(Opacity=88);opacity:.88;box-shadow:0 1px 1px -1px #fff;margin-top:-2.6875em;height:auto;z-index:9999999;position:fixed;top:50%;left:50%;border:0;background-color:#2a2a2a;border-color:#1d1d1d;color:#fff;text-shadow:0 1px 0 #111;-webkit-border-radius:.3125em;border-radius:.3125em;}.spinner h1{font-size: 1em;margin:0;text-align:center;}.spinner form{margin-bottom:0}.spinner form{padding-top:.2em;}.spinner input[type='password']{border-radius:5px;padding:.3em;line-height:1.2em;display:block;width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;outline:0;}.spinner input[type=submit]{border-radius:5px;border: 0;font-family:Tahoma;background:#f4f4f4;margin-top:5px;width:100%;}");

	// Change title to reflect current state
	document.title = "Loading...";

	// Insert jQM stylesheet
	insertStyleSheet(assetLocation+"css/jquery.mobile.min.css");

	// Insert main application stylesheet
	insertStyleSheet(assetLocation+"css/main.css");

	// Insert jQuery and run init function on completion
	insertScript(assetLocation+"js/jquery.min.js",init);

	function init() {
		var body = $("body"),
			finishInit = function() {
			    // Start checking for script load completion and callback when done
			    var interval = setInterval(function(){
					if (isReady) {
						clearInterval(interval);
						// Load jQuery Mobile
						$.getScript(assetLocation+"js/jquery.mobile.min.js");
					}
				},1);
			},
			sites = JSON.parse(localStorage.getItem("sites")),
			loader;

		// Fix to allow CORS ajax requests to work on IE8 and 9
		/*!
		 * jQuery-ajaxTransport-XDomainRequest - v1.0.3 - 2014-06-06
		 * https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
		 * Copyright (c) 2014 Jason Moon (@JSONMOON)
		 * Licensed MIT (/blob/master/LICENSE.txt)
		 */
		(function(){if($.support.cors||!$.ajaxTransport||!window.XDomainRequest){return;}var b=/^https?:\/\//i;var c=/^get|post$/i;var a=new RegExp("^"+location.protocol,"i");$.ajaxTransport("* text html xml json",function(e,g){if(!e.crossDomain||!e.async||!c.test(e.type)||!b.test(e.url)||!a.test(e.url)){return;}var d=null;return{send:function(k,i){var h="";var j=(g.dataType||"").toLowerCase();d=new XDomainRequest();if(/^\d+$/.test(g.timeout)){d.timeout=g.timeout;}d.ontimeout=function(){i(500,"timeout");};d.onload=function(){var q="Content-Length: "+d.responseText.length+"\r\nContent-Type: "+d.contentType;var l={code:200,message:"success"};var n={text:d.responseText};try{if(j==="html"||/text\/html/i.test(d.contentType)){n.html=d.responseText;}else{if(j==="json"||(j!=="text"&&/\/json/i.test(d.contentType))){try{n.json=$.parseJSON(d.responseText);}catch(p){l.code=500;l.message="parseerror";}}else{if(j==="xml"||(j!=="text"&&/\/xml/i.test(d.contentType))){var o=new ActiveXObject("Microsoft.XMLDOM");o.async=false;try{o.loadXML(d.responseText);}catch(p){o=undefined;}if(!o||!o.documentElement||o.getElementsByTagName("parsererror").length){l.code=500;l.message="parseerror";throw"Invalid XML: "+d.responseText;}n.xml=o;}}}}catch(m){throw m;}finally{i(l.code,l.message,n,q);}};d.onprogress=function(){};d.onerror=function(){i(500,"error",{text:d.responseText});};if(g.data){h=($.type(g.data)==="string")?g.data:$.param(g.data);}d.open(e.type,e.url);d.send(h);},abort:function(){if(d){d.abort();}}};});}());

		if (sites) {
			// If device has been logged into before, use available settings
			loader = $("

Loading

");
			finishInit();
		} else {
			// If this is a new login, prompt for password
			loader = $("

Enter Device Password
<form><input type='password' id='os_pw' name='os_pw' value='' /><input type='submit' value='Submit' /></form>
"),
			loader.on("submit",function(){
				var sites = {
					"Local": {
						"os_ip": document.URL.match(/https?:\/\/(.*)\/.*?/)[1],
						// Still need to prompt for password
						"os_pw": $("#os_pw").val()
					}
				},
				current_site = "Local";

				// Show loading message and title
				body.html("

Loading

");
				document.title = "Loading...";

				// Inject site information to storage so Application loads current device
				localStorage.setItem("sites",JSON.stringify(sites));
				localStorage.setItem("current_site",current_site);

				finishInit();

				return false;
			});

			// Change title to reflect current state
			document.title = "OpenSprinkler: Login";
		}

		// Change viewport
		$("meta[name='viewport']").attr("content","width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no");

		// Hide the body while we modify the DOM
		body.html(loader);

		$.ajax({
			url: assetLocation+"index.html",
			cache: false,
			crossDomain: true,
			type: "GET"
		}).then(
			function(data){
				// Grab the pages from index.html (body content)
				var pages = data.match(/([.\s\S]*)<\/body>/)[1];

				// Disables site selection menu
				window.curr_local = true;

				// Load 3rd party libraries such as FastClick (loaded first to avoid conflicts)
				$.getScript(assetLocation+"js/libs.js",function(){

					// Load main application Javascript (loaded before jQM so binds trigger when jQM loads)
					$.getScript(assetLocation+"js/main.js",function(){

						// Show the body when jQM attempts first page transition
						$(document).one("mobileinit",function(){

							// Change title to reflect loading finished
							document.title = "Sprinkler System";

							// Inject pages into DOM
							body.html(pages);

							// Remove spinner code (no longer needed)
							$("head").find("style").remove();

							// Initialize environment (missed by main.js since body was added after)
							initApp();

							// Hide multi site features since using local device
							body.find(".multiSite").hide();
						});

						// Mark environment as loaded
						isReady = true;
					});
				});
			},
			function(){
				body.html("

Unable to load UI

");
			}
		);
	}
}(document));
<|endoftext|>


<commit_before>Ember.libraries.register('Ember Simple Auth', '1.1.0');
<commit_msg>upgrade version that shows in Ember inspector info tab (#1155)<commit_after>Ember.libraries.register('Ember Simple Auth', '1.2.0-beta.1');
<|endoftext|>


<commit_before>const BaseDataview = require('./base');
const debug = require('debug')('windshaft:dataview:numeric-histogram');

const columnCastTpl = ctx => `date_part('epoch', ${ctx.column})`;

const filterOutSpecialNumericValues = ctx => `
        ${ctx._column} != 'infinity'::float
    AND
        ${ctx._column} != '-infinity'::float
    AND
        ${ctx._column} != 'NaN'::float
`;

const filteredQueryTpl = ctx => `
    __cdb_filtered_source AS (
        SELECT *
        FROM (${ctx._query}) __cdb_filtered_source_query
        WHERE ${ctx._column} IS NOT NULL
        ${ctx._isFloatColumn ? `AND ${filterOutSpecialNumericValues(ctx)}` : ''}
    )
`;

const basicsQueryTpl = ctx => `
    __cdb_basics AS (
        SELECT
            max(${ctx._column}) AS __cdb_max_val, min(${ctx._column}) AS __cdb_min_val,
            avg(${ctx._column}) AS __cdb_avg_val, count(1) AS __cdb_total_rows
        FROM __cdb_filtered_source
    )
`;

const overrideBasicsQueryTpl = ctx => `
    __cdb_basics AS (
        SELECT
            max(${ctx._end}) AS __cdb_max_val, min(${ctx._start}) AS __cdb_min_val,
            avg(${ctx._column}) AS __cdb_avg_val, count(1) AS __cdb_total_rows
        FROM __cdb_filtered_source
    )
`;

const iqrQueryTpl = ctx => `
    __cdb_iqrange AS (
        SELECT max(quartile_max) - min(quartile_max) AS __cdb_iqr
        FROM (
            SELECT quartile, max(_cdb_iqr_column) AS quartile_max from (
                SELECT ${ctx._column} AS _cdb_iqr_column, ntile(4) over (order by ${ctx._column}
            ) AS quartile
            FROM __cdb_filtered_source) _cdb_quartiles
            WHERE quartile = 1 or quartile = 3
            GROUP BY quartile
        ) __cdb_iqr
    )
`;

const binsQueryTpl = ctx => `
    __cdb_bins AS (
        SELECT
            CASE WHEN __cdb_total_rows = 0 OR __cdb_iqr = 0
            THEN 1
            ELSE GREATEST(
                LEAST(${ctx._minBins}, CAST(__cdb_total_rows AS INT)),
                LEAST(
                    CAST(((__cdb_max_val - __cdb_min_val) / (2 * __cdb_iqr * power(__cdb_total_rows, 1/3))) AS INT),
                    ${ctx._maxBins}
                )
            )
        END AS __cdb_bins_number
        FROM __cdb_basics, __cdb_iqrange, __cdb_filtered_source
        LIMIT 1
    )
`;

const overrideBinsQueryTpl = ctx => `
    __cdb_bins AS (
        SELECT ${ctx._override.bins} AS __cdb_bins_number
    )
`;

const nullsQueryTpl = ctx => `
    __cdb_nulls AS (
        SELECT
            count(*) AS __cdb_nulls_count
        FROM (${ctx._query}) __cdb_histogram_nulls
        WHERE ${ctx._column} IS NULL
    )
`;

const infinitiesQueryTpl = ctx => `
    __cdb_infinities AS (
        SELECT
            count(*) AS __cdb_infinities_count
        FROM (${ctx._query}) __cdb_infinities_query
        WHERE
            ${ctx._column} = 'infinity'::float
        OR
            ${ctx._column} = '-infinity'::float
    )
`;

const nansQueryTpl = ctx => `
    __cdb_nans AS (
        SELECT
            count(*) AS __cdb_nans_count
        FROM (${ctx._query}) __cdb_nans_query
        WHERE ${ctx._column} = 'NaN'::float
    )
`;

const specialNumericValuesColumnDefinitionTpl = () => `
    __cdb_infinities_count AS infinities_count,
    __cdb_nans_count AS nans_count
`;

const specialNumericValuesCTETpl = () => `
    __cdb_infinities, __cdb_nans
`;

const specialNumericValuesColumnTpl = () => `
    infinities_count, nans_count
`;

const histogramQueryTpl = ctx => `
    SELECT
        (__cdb_max_val - __cdb_min_val) / cast(__cdb_bins_number as float) AS bin_width,
        __cdb_bins_number AS bins_number,
        __cdb_nulls_count AS nulls_count,
        ${ctx._isFloatColumn ? `${specialNumericValuesColumnDefinitionTpl()},` : ''}
        __cdb_avg_val AS avg_val,
        CASE WHEN __cdb_min_val = __cdb_max_val
            THEN 0
            ELSE GREATEST(
                1,
                LEAST(
                    WIDTH_BUCKET(${ctx._column}, __cdb_min_val, __cdb_max_val, __cdb_bins_number),
                    __cdb_bins_number
                )
            ) - 1
        END AS bin,
        min(${ctx._column})::numeric AS min,
        max(${ctx._column})::numeric AS max,
        avg(${ctx._column})::numeric AS avg,
        count(*) AS freq
    FROM __cdb_filtered_source, __cdb_basics, __cdb_nulls, __cdb_bins
        ${ctx._isFloatColumn ? `, ${specialNumericValuesCTETpl()}` : ''}
    GROUP BY bin, bins_number, bin_width, nulls_count, avg_val
        ${ctx._isFloatColumn ? `, ${specialNumericValuesColumnTpl()}` : ''}
    ORDER BY bin
`;

const BIN_MIN_NUMBER = 6;
const BIN_MAX_NUMBER = 48;

const TYPE = 'histogram';

/**
Numeric histogram:
{
    type: 'histogram',
    options: {
        column: 'name', // column data type: numeric
        bins: 10 // OPTIONAL
    }
}
*/
module.exports = class NumericHistogram extends BaseDataview {
    constructor (query, options, queries) {
        super();

        if (typeof options.column !== 'string') {
            throw new Error('Histogram expects `column` in widget options');
        }

        this.query = query;
        this.queries = queries;
        this.column = options.column;
        this.bins = options.bins;

        this._columnType = null;
    }

    sql (psql, override, callback) {
        var self = this;

        if (!callback) {
            callback = override;
            override = {};
        }

        if (this._columnType === null) {
            this.getColumnType(psql, this.column, this.queries.no_filters, function (err, type) {
                // assume numeric, will fail later
                self._columnType = 'numeric';
                if (!err && !!type) {
                    self._columnType = Object.keys(type).find(function (key) {
                        return type[key];
                    });
                }
                self.sql(psql, override, callback);
            }, true); // use read-only transaction
            return null;
        }

        this._buildQuery(psql, override, callback);
    }

    _buildQuery (psql, override, callback) {
        const histogramSql = this._buildQueryTpl({
            _override: override,
            _column: this._columnType === 'date' ? columnCastTpl({ column: this.column }) : this.column,
            _isFloatColumn: this._columnType === 'float',
            _query: this.query,
            _start: this._getBinStart(override),
            _end: this._getBinEnd(override),
            _minBins: BIN_MIN_NUMBER,
            _maxBins: BIN_MAX_NUMBER,
        });

        debug(histogramSql);

        return callback(null, histogramSql);
    }

    _buildQueryTpl (ctx) {
        return `
            WITH
                ${filteredQueryTpl(ctx)},
                ${this._shouldOverride(ctx._override) ? overrideBasicsQueryTpl(ctx) : basicsQueryTpl(ctx)},
                ${this._shouldOverrideRange(ctx._override) || this._shouldOverrideBins(ctx._override) ?
                    overrideBinsQueryTpl(ctx) :
                    `${iqrQueryTpl(ctx)}, ${binsQueryTpl(ctx)}`
                },
                ${nullsQueryTpl(ctx)}
                ${ctx._isFloatColumn ? `,${infinitiesQueryTpl(ctx)}, ${nansQueryTpl(ctx)}` : ''}
            ${histogramQueryTpl(ctx)}
        `;
    }

    _shouldOverride (override) {
        return this._shouldOverrideRange(override) && this._shouldOverrideBins(override);
    }

    _shouldOverrideRange (override) {
        return override && override.hasOwnProperty('start') && override.hasOwnProperty('end');
    }

    _shouldOverrideBins (override) {
        return override && override.hasOwnProperty('bins');
    }

    format (result, override) {
        override = override || {};
        var buckets = [];

        var binsCount = this._getBinsCount(override);
        var width = this._getWidth(override);
        var binsStart = this._getBinStart(override);
        var nulls = 0;
        var infinities = 0;
        var nans = 0;
        var avg;

        if (result.rows.length) {
            var firstRow = result.rows[0];
            binsCount = firstRow.bins_number;
            width = firstRow.bin_width || width;
            avg = firstRow.avg_val;
            nulls = firstRow.nulls_count;
            infinities = firstRow.infinities_count;
            nans = firstRow.nans_count;
            binsStart = this._populateBinStart(override, firstRow);

            buckets = result.rows.map(row => ({ bin, min, max, avg, freq } = row));
        }

        return {
            bin_width: width,
            bins_count: binsCount,
            bins_start: binsStart,
            nulls: nulls,
            infinities: infinities,
            nans: nans,
            avg: avg,
            bins: buckets
        };
    }

    getType () {
        return TYPE;
    }

    toString () {
        return JSON.stringify({
            _type: TYPE,
            _column: this.column,
            _query: this.query
        });
    }

    _getBinStart (override) {
        if (override.hasOwnProperty('start') && override.hasOwnProperty('end')) {
            return Math.min(override.start, override.end);
        }
        return override.start || 0;
    }

    _populateBinStart (override, firstRow) {
        var binStart;

        if (override.hasOwnProperty('start')) {
            binStart = this._getBinStart(override);
        } else {
            binStart = firstRow.min;
        }

        return binStart;
    }

    _getBinEnd (override) {
        if (override.hasOwnProperty('start') && override.hasOwnProperty('end')) {
            return Math.max(override.start, override.end);
        }
        return override.end || 0;
    }

    _getBinsCount (override) {
        return override.bins || 0;
    }

    _getWidth (override) {
        var width = 0;
        var binsCount = override.bins;

        if (binsCount && Number.isFinite(override.start) && Number.isFinite(override.end)) {
            width = (override.end - override.start) / binsCount;
        }

        return width;
    }
};
<commit_msg>Fix undefined while destructuring assignment<commit_after>const BaseDataview = require('./base');
const debug = require('debug')('windshaft:dataview:numeric-histogram');

const columnCastTpl = ctx => `date_part('epoch', ${ctx.column})`;

const filterOutSpecialNumericValues = ctx => `
        ${ctx._column} != 'infinity'::float
    AND
        ${ctx._column} != '-infinity'::float
    AND
        ${ctx._column} != 'NaN'::float
`;

const filteredQueryTpl = ctx => `
    __cdb_filtered_source AS (
        SELECT *
        FROM (${ctx._query}) __cdb_filtered_source_query
        WHERE ${ctx._column} IS NOT NULL
        ${ctx._isFloatColumn ? `AND ${filterOutSpecialNumericValues(ctx)}` : ''}
    )
`;

const basicsQueryTpl = ctx => `
    __cdb_basics AS (
        SELECT
            max(${ctx._column}) AS __cdb_max_val, min(${ctx._column}) AS __cdb_min_val,
            avg(${ctx._column}) AS __cdb_avg_val, count(1) AS __cdb_total_rows
        FROM __cdb_filtered_source
    )
`;

const overrideBasicsQueryTpl = ctx => `
    __cdb_basics AS (
        SELECT
            max(${ctx._end}) AS __cdb_max_val, min(${ctx._start}) AS __cdb_min_val,
            avg(${ctx._column}) AS __cdb_avg_val, count(1) AS __cdb_total_rows
        FROM __cdb_filtered_source
    )
`;

const iqrQueryTpl = ctx => `
    __cdb_iqrange AS (
        SELECT max(quartile_max) - min(quartile_max) AS __cdb_iqr
        FROM (
            SELECT quartile, max(_cdb_iqr_column) AS quartile_max from (
                SELECT ${ctx._column} AS _cdb_iqr_column, ntile(4) over (order by ${ctx._column}
            ) AS quartile
            FROM __cdb_filtered_source) _cdb_quartiles
            WHERE quartile = 1 or quartile = 3
            GROUP BY quartile
        ) __cdb_iqr
    )
`;

const binsQueryTpl = ctx => `
    __cdb_bins AS (
        SELECT
            CASE WHEN __cdb_total_rows = 0 OR __cdb_iqr = 0
            THEN 1
            ELSE GREATEST(
                LEAST(${ctx._minBins}, CAST(__cdb_total_rows AS INT)),
                LEAST(
                    CAST(((__cdb_max_val - __cdb_min_val) / (2 * __cdb_iqr * power(__cdb_total_rows, 1/3))) AS INT),
                    ${ctx._maxBins}
                )
            )
        END AS __cdb_bins_number
        FROM __cdb_basics, __cdb_iqrange, __cdb_filtered_source
        LIMIT 1
    )
`;

const overrideBinsQueryTpl = ctx => `
    __cdb_bins AS (
        SELECT ${ctx._override.bins} AS __cdb_bins_number
    )
`;

const nullsQueryTpl = ctx => `
    __cdb_nulls AS (
        SELECT
            count(*) AS __cdb_nulls_count
        FROM (${ctx._query}) __cdb_histogram_nulls
        WHERE ${ctx._column} IS NULL
    )
`;

const infinitiesQueryTpl = ctx => `
    __cdb_infinities AS (
        SELECT
            count(*) AS __cdb_infinities_count
        FROM (${ctx._query}) __cdb_infinities_query
        WHERE
            ${ctx._column} = 'infinity'::float
        OR
            ${ctx._column} = '-infinity'::float
    )
`;

const nansQueryTpl = ctx => `
    __cdb_nans AS (
        SELECT
            count(*) AS __cdb_nans_count
        FROM (${ctx._query}) __cdb_nans_query
        WHERE ${ctx._column} = 'NaN'::float
    )
`;

const specialNumericValuesColumnDefinitionTpl = () => `
    __cdb_infinities_count AS infinities_count,
    __cdb_nans_count AS nans_count
`;

const specialNumericValuesCTETpl = () => `
    __cdb_infinities, __cdb_nans
`;

const specialNumericValuesColumnTpl = () => `
    infinities_count, nans_count
`;

const histogramQueryTpl = ctx => `
    SELECT
        (__cdb_max_val - __cdb_min_val) / cast(__cdb_bins_number as float) AS bin_width,
        __cdb_bins_number AS bins_number,
        __cdb_nulls_count AS nulls_count,
        ${ctx._isFloatColumn ? `${specialNumericValuesColumnDefinitionTpl()},` : ''}
        __cdb_avg_val AS avg_val,
        CASE WHEN __cdb_min_val = __cdb_max_val
            THEN 0
            ELSE GREATEST(
                1,
                LEAST(
                    WIDTH_BUCKET(${ctx._column}, __cdb_min_val, __cdb_max_val, __cdb_bins_number),
                    __cdb_bins_number
                )
            ) - 1
        END AS bin,
        min(${ctx._column})::numeric AS min,
        max(${ctx._column})::numeric AS max,
        avg(${ctx._column})::numeric AS avg,
        count(*) AS freq
    FROM __cdb_filtered_source, __cdb_basics, __cdb_nulls, __cdb_bins
        ${ctx._isFloatColumn ? `, ${specialNumericValuesCTETpl()}` : ''}
    GROUP BY bin, bins_number, bin_width, nulls_count, avg_val
        ${ctx._isFloatColumn ? `, ${specialNumericValuesColumnTpl()}` : ''}
    ORDER BY bin
`;

const BIN_MIN_NUMBER = 6;
const BIN_MAX_NUMBER = 48;

const TYPE = 'histogram';

/**
Numeric histogram:
{
    type: 'histogram',
    options: {
        column: 'name', // column data type: numeric
        bins: 10 // OPTIONAL
    }
}
*/
module.exports = class NumericHistogram extends BaseDataview {
    constructor (query, options, queries) {
        super();

        if (typeof options.column !== 'string') {
            throw new Error('Histogram expects `column` in widget options');
        }

        this.query = query;
        this.queries = queries;
        this.column = options.column;
        this.bins = options.bins;

        this._columnType = null;
    }

    sql (psql, override, callback) {
        var self = this;

        if (!callback) {
            callback = override;
            override = {};
        }

        if (this._columnType === null) {
            this.getColumnType(psql, this.column, this.queries.no_filters, function (err, type) {
                // assume numeric, will fail later
                self._columnType = 'numeric';
                if (!err && !!type) {
                    self._columnType = Object.keys(type).find(function (key) {
                        return type[key];
                    });
                }
                self.sql(psql, override, callback);
            }, true); // use read-only transaction
            return null;
        }

        this._buildQuery(psql, override, callback);
    }

    _buildQuery (psql, override, callback) {
        const histogramSql = this._buildQueryTpl({
            _override: override,
            _column: this._columnType === 'date' ? columnCastTpl({ column: this.column }) : this.column,
            _isFloatColumn: this._columnType === 'float',
            _query: this.query,
            _start: this._getBinStart(override),
            _end: this._getBinEnd(override),
            _minBins: BIN_MIN_NUMBER,
            _maxBins: BIN_MAX_NUMBER,
        });

        debug(histogramSql);

        return callback(null, histogramSql);
    }

    _buildQueryTpl (ctx) {
        return `
            WITH
                ${filteredQueryTpl(ctx)},
                ${this._shouldOverride(ctx._override) ? overrideBasicsQueryTpl(ctx) : basicsQueryTpl(ctx)},
                ${this._shouldOverrideRange(ctx._override) || this._shouldOverrideBins(ctx._override) ?
                    overrideBinsQueryTpl(ctx) :
                    `${iqrQueryTpl(ctx)}, ${binsQueryTpl(ctx)}`
                },
                ${nullsQueryTpl(ctx)}
                ${ctx._isFloatColumn ? `,${infinitiesQueryTpl(ctx)}, ${nansQueryTpl(ctx)}` : ''}
            ${histogramQueryTpl(ctx)}
        `;
    }

    _shouldOverride (override) {
        return this._shouldOverrideRange(override) && this._shouldOverrideBins(override);
    }

    _shouldOverrideRange (override) {
        return override && override.hasOwnProperty('start') && override.hasOwnProperty('end');
    }

    _shouldOverrideBins (override) {
        return override && override.hasOwnProperty('bins');
    }

    format (result, override) {
        override = override || {};
        var buckets = [];

        var binsCount = this._getBinsCount(override);
        var width = this._getWidth(override);
        var binsStart = this._getBinStart(override);
        var nulls = 0;
        var infinities = 0;
        var nans = 0;
        var avg;

        if (result.rows.length) {
            var firstRow = result.rows[0];
            binsCount = firstRow.bins_number;
            width = firstRow.bin_width || width;
            avg = firstRow.avg_val;
            nulls = firstRow.nulls_count;
            infinities = firstRow.infinities_count;
            nans = firstRow.nans_count;
            binsStart = this._populateBinStart(override, firstRow);

            buckets = result.rows.map(row => {
                const { bin, min, max, avg, freq } = row;
                return { bin, min, max, avg, freq };
            });
        }

        return {
            bin_width: width,
            bins_count: binsCount,
            bins_start: binsStart,
            nulls: nulls,
            infinities: infinities,
            nans: nans,
            avg: avg,
            bins: buckets
        };
    }

    getType () {
        return TYPE;
    }

    toString () {
        return JSON.stringify({
            _type: TYPE,
            _column: this.column,
            _query: this.query
        });
    }

    _getBinStart (override) {
        if (override.hasOwnProperty('start') && override.hasOwnProperty('end')) {
            return Math.min(override.start, override.end);
        }
        return override.start || 0;
    }

    _populateBinStart (override, firstRow) {
        var binStart;

        if (override.hasOwnProperty('start')) {
            binStart = this._getBinStart(override);
        } else {
            binStart = firstRow.min;
        }

        return binStart;
    }

    _getBinEnd (override) {
        if (override.hasOwnProperty('start') && override.hasOwnProperty('end')) {
            return Math.max(override.start, override.end);
        }
        return override.end || 0;
    }

    _getBinsCount (override) {
        return override.bins || 0;
    }

    _getWidth (override) {
        var width = 0;
        var binsCount = override.bins;

        if (binsCount && Number.isFinite(override.start) && Number.isFinite(override.end)) {
            width = (override.end - override.start) / binsCount;
        }

        return width;
    }
};
<|endoftext|>


<commit_before>/* export Select */

/* globals $, jQuery */
class Select {

    /**
     * Construct Select
     * @return {Select}
     */
    constructor(adminController) {

        adminController
            .onRefreshUi((e, domElement) => {
                this.init(domElement);
            });

        return this;
    }

    // --------------------------------------------------------------------------

    /**
     * Inits Select
     * @param {HTMLElement} domElement
     * @returns {Select}
     */
    init(domElement) {

        //  @todo (Pablo - 2020-01-21) - Target all selects?
        $('select.select2:not(.select2-offscreen):not(.select2--processed)', domElement)
            .addClass('select2--processed')
            .select2();

        return this;
    }
}

export default Select;
<commit_msg>More flexible select2<commit_after>/* export Select */

/* globals $, jQuery */
class Select {

    /**
     * Construct Select
     * @return {Select}
     */
    constructor(adminController) {

        adminController
            .onRefreshUi((e, domElement) => {
                this.init(domElement);
            });

        return this;
    }

    // --------------------------------------------------------------------------

    /**
     * Inits Select
     * @param {HTMLElement} domElement
     * @returns {Select}
     */
    init(domElement) {

        $('select.select2:not(.select2-offscreen):not(.select2--processed)', domElement)
            .addClass('select2--processed')
            .each((index, element) => {
                $(element)
                    .data(
                        'select2',
                        new SelectInstance(
                            this.adminController,
                            element
                        )
                    );
            });

        return this;
    }
}

class SelectInstance {
    /**
     * Construct SearcherInstance
     *
     * @param {DOMElement} element
     */
    constructor(adminController, element) {

        this.adminController = adminController;
        this.$input = $(element);
        this.isMultiple = this.$input.data('multiple');
        this.isClearable = this.$input.data('clearable');
        this.placeholder = this.$input.data('placeholder') || 'Search for an item';

        this.$input
            .select2({
                placeholder: this.placeholder,
                multiple: this.isMultiple,
                allowClear: this.isClearable
            });
    }
}

export default Select;
<|endoftext|>


<commit_before>/* @flow */

import React, {PropTypes} from 'react';
import {
  View,
  Animated,
  Text,
  StyleSheet,
} from 'react-native';
import gql from 'graphql-tag';
import ProfilePic from '../../commons/ProfilePic';

import moment from 'moment';

type TaskHeaderStateType = {
  radius: Animated.Value,
  marginHorizontal: Animated.Value,
  blockDateTranslationY: Animated.Value,
  dateOpacity: Animated.Value,
  nbAnswersOpacity: Animated.Value,
}

type TaskHeaderPropsType = {
  title: string,
  date: ?Date,
  postedBy: {
    username: string,
  },
  nbAnswers: number,
}

const initialState = {
  radius: 3,
  marginHorizontal: 10,
  blockDateTranslationY: 15,
  dateOpacity: 0,
  nbAnswersOpacity: 1,
};

class TaskHeader extends React.Component {

  static propTypes = {
    title: PropTypes.string.isRequired,
    nbAnswers: PropTypes.number.isRequired,
    postedBy: PropTypes.shape({
      username: PropTypes.string.isRequired,
    }).isRequired,
  };

  state: TaskHeaderStateType = {
    radius: new Animated.Value(initialState.radius),
    marginHorizontal: new Animated.Value(initialState.marginHorizontal),
    blockDateTranslationY: new Animated.Value(initialState.blockDateTranslationY),
    dateOpacity: new Animated.Value(initialState.dateOpacity),
    nbAnswersOpacity: new Animated.Value(initialState.nbAnswersOpacity),
  }

  props: TaskHeaderPropsType;

  componentDidMount() {
    const {
      radius,
      marginHorizontal,
      blockDateTranslationY,
      dateOpacity,
      nbAnswersOpacity,
    } = this.state;

    if (this.props.full) {
      Animated.parallel([
        Animated.timing(marginHorizontal, {
          toValue: 0,
          duration: 1000,
        }),
        Animated.timing(radius, {
          toValue: 0,
          duration: 1000,
        }),

        Animated.timing(blockDateTranslationY, {
          toValue: 0,
          useNativeDriver: true,
        }),
      ]).start();
    }
  }
  componentWillReceiveProps(next: TaskHeaderPropsType) {
    const {
      radius,
      marginHorizontal,
      blockDateTranslationY,
    } = this.state;
    if (this.props.full !== next.full && !next.full) {
      Animated.parallel([
        Animated.timing(blockDateTranslationY, {
          toValue: initialState.blockDateTranslationY,
          useNativeDriver: true,
        }),
        Animated.timing(radius, {
          toValue: initialState.radius,
        }),
        Animated.timing(marginHorizontal, {
          toValue: initialState.marginHorizontal,
        }),
      ]).start();
    }
  }
  render(): React.Element<*> {
    const {title, date, postedBy} = this.props;
    return (
      <Animated.View style={[
        styles.questionContainer,
        {
          elevation: (date) ? 3 : 1,
          marginHorizontal: this.state.marginHorizontal,
          borderRadius: this.state.radius,
        }]} >
        <ProfilePic style={styles.pic} size={50} username={this.props.postedBy.username} />
        <View style={styles.leftColumn}>
          <Text style={styles.question} numberOfLines={2} ellipsizeMode='tail' >{title}</Text>
          <Text style={styles.postedBy} >
            {'Posted by: '}
            <Text style={styles.postedByUsername}>
              {postedBy.username}
            </Text>
          </Text>
        </View>
        <View style={styles.rightColumn}>
          <View style={styles.blockDate} >
            <Text>{moment(date).format('DD/MM/YY')}</Text>
          </View>
          <View style={styles.blockNbAnswers} >
            <Text>28 answers</Text>
          </View>
        </View>
      </Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  questionContainer: {
    flexDirection: 'row',
    height: 80,
    backgroundColor: 'white',
    elevation: 1,
    marginBottom: 0,
    paddingLeft: 5,
  },
  pic: {
    alignSelf: 'center',
  },
  leftColumn: {
    flex: 0.70,
    alignItems: 'flex-start',
    justifyContent: 'center',
  },
  question: {
    marginLeft: 5,
    textAlignVertical: 'center',
    fontSize: 16,
    fontWeight: '800',
    color: '#212121',
  },
  postedBy: {
    fontWeight: '100',
    fontSize: 12,
    marginLeft: 15,
  },
  postedByUsername: {
    color: '#020202',
    fontSize: 13,
  },
  rightColumn: {
    flex: 0.30,
    marginRight: 5,
    marginVertical: 5,
    alignItems: 'flex-end',
    justifyContent: 'space-between',
  },
  blockDate: {
    alignItems: 'flex-start',
  },
  blockNbAnswers: {
    alignItems: 'flex-end',
  },
});

TaskHeader.fragments = {
  task: gql`
    fragment Task on Task {
      _id
      title,
      nbAnswers,
      postedBy {
        username,
      }
    }
  `,
};

export default TaskHeader;
<commit_msg>:bug: Use real nbAnswers on task header<commit_after>/* @flow */

import React, {PropTypes} from 'react';
import {
  View,
  Animated,
  Text,
  StyleSheet,
} from 'react-native';
import gql from 'graphql-tag';
import ProfilePic from '../../commons/ProfilePic';

import moment from 'moment';

type TaskHeaderStateType = {
  radius: Animated.Value,
  marginHorizontal: Animated.Value,
  blockDateTranslationY: Animated.Value,
  dateOpacity: Animated.Value,
  nbAnswersOpacity: Animated.Value,
}

type TaskHeaderPropsType = {
  title: string,
  date: ?Date,
  postedBy: {
    username: string,
  },
  nbAnswers: number,
}

const initialState = {
  radius: 3,
  marginHorizontal: 10,
  blockDateTranslationY: 15,
  dateOpacity: 0,
  nbAnswersOpacity: 1,
};

class TaskHeader extends React.Component {

  static propTypes = {
    title: PropTypes.string.isRequired,
    nbAnswers: PropTypes.number.isRequired,
    postedBy: PropTypes.shape({
      username: PropTypes.string.isRequired,
    }).isRequired,
  };

  state: TaskHeaderStateType = {
    radius: new Animated.Value(initialState.radius),
    marginHorizontal: new Animated.Value(initialState.marginHorizontal),
    blockDateTranslationY: new Animated.Value(initialState.blockDateTranslationY),
    dateOpacity: new Animated.Value(initialState.dateOpacity),
    nbAnswersOpacity: new Animated.Value(initialState.nbAnswersOpacity),
  }

  props: TaskHeaderPropsType;

  componentDidMount() {
    const {
      radius,
      marginHorizontal,
      blockDateTranslationY,
      dateOpacity,
      nbAnswersOpacity,
    } = this.state;

    if (this.props.full) {
      Animated.parallel([
        Animated.timing(marginHorizontal, {
          toValue: 0,
          duration: 1000,
        }),
        Animated.timing(radius, {
          toValue: 0,
          duration: 1000,
        }),

        Animated.timing(blockDateTranslationY, {
          toValue: 0,
          useNativeDriver: true,
        }),
      ]).start();
    }
  }
  componentWillReceiveProps(next: TaskHeaderPropsType) {
    const {
      radius,
      marginHorizontal,
      blockDateTranslationY,
    } = this.state;
    if (this.props.full !== next.full && !next.full) {
      Animated.parallel([
        Animated.timing(blockDateTranslationY, {
          toValue: initialState.blockDateTranslationY,
          useNativeDriver: true,
        }),
        Animated.timing(radius, {
          toValue: initialState.radius,
        }),
        Animated.timing(marginHorizontal, {
          toValue: initialState.marginHorizontal,
        }),
      ]).start();
    }
  }
  render(): React.Element<*> {
    const {title, date, postedBy, nbAnswers = 0} = this.props;
    return (
      <Animated.View style={[
        styles.questionContainer,
        {
          elevation: (date) ? 3 : 1,
          marginHorizontal: this.state.marginHorizontal,
          borderRadius: this.state.radius,
        }]} >
        <ProfilePic style={styles.pic} size={50} username={this.props.postedBy.username} />
        <View style={styles.leftColumn}>
          <Text style={styles.question} numberOfLines={2} ellipsizeMode='tail' >{title}</Text>
          <Text style={styles.postedBy} >
            {'Posted by: '}
            <Text style={styles.postedByUsername}>
              {postedBy.username}
            </Text>
          </Text>
        </View>
        <View style={styles.rightColumn}>
          <View style={styles.blockDate} >
            <Text>{moment(date).format('DD/MM/YY')}</Text>
          </View>
          <View style={styles.blockNbAnswers} >
            <Text>{nbAnswers} answers</Text>
          </View>
        </View>
      </Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  questionContainer: {
    flexDirection: 'row',
    height: 80,
    backgroundColor: 'white',
    elevation: 1,
    marginBottom: 0,
    paddingLeft: 5,
  },
  pic: {
    alignSelf: 'center',
  },
  leftColumn: {
    flex: 0.70,
    alignItems: 'flex-start',
    justifyContent: 'center',
  },
  question: {
    marginLeft: 5,
    textAlignVertical: 'center',
    fontSize: 16,
    fontWeight: '800',
    color: '#212121',
  },
  postedBy: {
    fontWeight: '100',
    fontSize: 12,
    marginLeft: 15,
  },
  postedByUsername: {
    color: '#020202',
    fontSize: 13,
  },
  rightColumn: {
    flex: 0.30,
    marginRight: 5,
    marginVertical: 5,
    alignItems: 'flex-end',
    justifyContent: 'space-between',
  },
  blockDate: {
    alignItems: 'flex-start',
  },
  blockNbAnswers: {
    alignItems: 'flex-end',
  },
});

TaskHeader.fragments = {
  task: gql`
    fragment Task on Task {
      _id
      title,
      nbAnswers,
      postedBy {
        username,
      }
    }
  `,
};

export default TaskHeader;
<|endoftext|>


<commit_before>/*global $, initApp */
(function(document){
	var assetLocation = "http://rawgit.com/salbahra/Sprinklers/master/www/",
		isReady = false;

	function insertStyle(css) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    style = document.createElement("style");

		style.type = "text/css";
		if (style.styleSheet){
		  style.styleSheet.cssText = css;
		} else {
		  style.appendChild(document.createTextNode(css));
		}

		head.appendChild(style);
	}

	function insertStyleSheet(href) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    link = document.createElement("link");

		link.rel = "stylesheet";
		link.href = href;

		head.appendChild(link);
	}

	// Insert script into the DOM
	function insertScript(src,callback) {
		// Create callback if one is not provided
		callback = callback || function(){};

	    var a=document.createElement("script");
	    a.src=src;
	    document.getElementsByTagName("head")[0].appendChild(a);

	    // Start checking for script load completion and callback when done
	    var interval = setInterval(function(){
			if (document.readyState === "complete") {
				clearInterval(interval);
				callback();
			}
		},1);
	}

	// Insert loading icon
	insertStyle(".spinner{display:block;padding:.9375em;margin-left:-7.1875em;width:12.5em;filter:Alpha(Opacity=88);opacity:.88;box-shadow:0 1px 1px -1px #fff;margin-top:-2.6875em;height:auto;z-index:9999999;position:fixed;top:50%;left:50%;border:0;background-color:#2a2a2a;border-color:#1d1d1d;color:#fff;text-shadow:0 1px 0 #111;-webkit-border-radius:.3125em;border-radius:.3125em;}.spinner h1{padding-bottom:.2em;font-size: 1em;margin:0;text-align:center;}.spinner form{margin-bottom:0}.spinner input[type='password']{border-radius:5px;padding:.3em;line-height:1.2em;display:block;width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;outline:0;}.spinner input[type=submit]{border-radius:5px;border: 0;font-family:Tahoma;background:#f4f4f4;margin-top:5px;width:100%;}");

	// Change title to reflect current state
	document.title = "Loading...";

	// Insert jQM stylesheet
	insertStyleSheet(assetLocation+"css/jquery.mobile.min.css");

	// Insert main application stylesheet
	insertStyleSheet(assetLocation+"http://rawgit.com/salbahra/Sprinklers/master/www/css/main.css");

	// Insert jQuery and run init function on completion
	insertScript(assetLocation+"http://rawgit.com/salbahra/Sprinklers/master/www/js/jquery.min.js",init);

	function init() {
		var body = $("body"),
			finishInit = function() {
			    // Start checking for script load completion and callback when done
			    var interval = setInterval(function(){
					if (isReady) {
						clearInterval(interval);
						// Load jQuery Mobile
						$.getScript("http://rawgit.com/salbahra/Sprinklers/master/www/js/jquery.mobile.min.js");
					}
				},1);
			},
			sites = JSON.parse(localStorage.getItem("sites")),
			loader;

		if (sites) {
			// If device has been logged into before, use available settings
			loader = $("

Loading

");
			finishInit();
		} else {
			// If this is a new login, prompt for password
			loader = $("

Enter Device Password
<form><input type='password' id='os_pw' name='os_pw' value='' /><input type='submit' value='Submit' /></form>
"),
			loader.on("submit",function(){
				var sites = {
					"Local": {
						"os_ip": document.URL.match(/https?:\/\/(.*)\/.*?/)[1],
						// Still need to prompt for password
						"os_pw": $("#os_pw").val()
					}
				},
				current_site = "Local";

				// Show loading message and title
				body.html("

Loading

");
				document.title = "Loading...";

				// Inject site information to storage so Application loads current device
				localStorage.setItem("sites",JSON.stringify(sites));
				localStorage.setItem("current_site",current_site);

				finishInit();

				return false;
			});

			// Change title to reflect current state
			document.title = "OpenSprinkler: Login";
		}

		// Change viewport
		$("meta[name='viewport']").attr("content","width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no");

		// Hide the body while we modify the DOM
		body.html(loader);

		$.get("http://rawgit.com/salbahra/Sprinklers/master/www/index.html",function(data){
			// Grab the pages from index.html (body content)
			var pages = data.match(/([.\s\S]*)<\/body>/)[1];

			// Disables site selection menu
			window.curr_local = true;

			// Load 3rd party libraries such as FastClick (loaded first to avoid conflicts)
			$.getScript("http://rawgit.com/salbahra/Sprinklers/master/www/js/libs.js",function(){

				// Load main application Javascript (loaded before jQM so binds trigger when jQM loads)
				$.getScript("http://rawgit.com/salbahra/Sprinklers/master/www/js/main.js",function(){

					// Show the body when jQM attempts first page transition
					$(document).one("mobileinit",function(){

						// Change title to reflect loading finished
						document.title = "Sprinkler System";

						// Inject pages into DOM
						body.html(pages);

						// Remove spinner code (no longer needed)
						$("head").find("style").remove();

						// Initialize environment (missed by main.js since body was added after)
						initApp();

						// Hide multi site features since using local device
						body.find(".multiSite").hide();
					});

					// Mark environment as loaded
					isReady = true;

				});

			});

		});
	}
}(document));
<commit_msg>Base: Actually use assets location variable<commit_after>/*global $, initApp */
(function(document){
	var assetLocation = "http://rawgit.com/salbahra/Sprinklers/master/www/",
		isReady = false;

	function insertStyle(css) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    style = document.createElement("style");

		style.type = "text/css";
		if (style.styleSheet){
		  style.styleSheet.cssText = css;
		} else {
		  style.appendChild(document.createTextNode(css));
		}

		head.appendChild(style);
	}

	function insertStyleSheet(href) {
		var head = document.head || document.getElementsByTagName("head")[0],
		    link = document.createElement("link");

		link.rel = "stylesheet";
		link.href = href;

		head.appendChild(link);
	}

	// Insert script into the DOM
	function insertScript(src,callback) {
		// Create callback if one is not provided
		callback = callback || function(){};

	    var a=document.createElement("script");
	    a.src=src;
	    document.getElementsByTagName("head")[0].appendChild(a);

	    // Start checking for script load completion and callback when done
	    var interval = setInterval(function(){
			if (document.readyState === "complete") {
				clearInterval(interval);
				callback();
			}
		},1);
	}

	// Insert loading icon
	insertStyle(".spinner{display:block;padding:.9375em;margin-left:-7.1875em;width:12.5em;filter:Alpha(Opacity=88);opacity:.88;box-shadow:0 1px 1px -1px #fff;margin-top:-2.6875em;height:auto;z-index:9999999;position:fixed;top:50%;left:50%;border:0;background-color:#2a2a2a;border-color:#1d1d1d;color:#fff;text-shadow:0 1px 0 #111;-webkit-border-radius:.3125em;border-radius:.3125em;}.spinner h1{padding-bottom:.2em;font-size: 1em;margin:0;text-align:center;}.spinner form{margin-bottom:0}.spinner input[type='password']{border-radius:5px;padding:.3em;line-height:1.2em;display:block;width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;outline:0;}.spinner input[type=submit]{border-radius:5px;border: 0;font-family:Tahoma;background:#f4f4f4;margin-top:5px;width:100%;}");

	// Change title to reflect current state
	document.title = "Loading...";

	// Insert jQM stylesheet
	insertStyleSheet(assetLocation+"css/jquery.mobile.min.css");

	// Insert main application stylesheet
	insertStyleSheet(assetLocation+"css/main.css");

	// Insert jQuery and run init function on completion
	insertScript(assetLocation+"js/jquery.min.js",init);

	function init() {
		var body = $("body"),
			finishInit = function() {
			    // Start checking for script load completion and callback when done
			    var interval = setInterval(function(){
					if (isReady) {
						clearInterval(interval);
						// Load jQuery Mobile
						$.getScript(assetLocation+"js/jquery.mobile.min.js");
					}
				},1);
			},
			sites = JSON.parse(localStorage.getItem("sites")),
			loader;

		if (sites) {
			// If device has been logged into before, use available settings
			loader = $("

Loading

");
			finishInit();
		} else {
			// If this is a new login, prompt for password
			loader = $("

Enter Device Password
<form><input type='password' id='os_pw' name='os_pw' value='' /><input type='submit' value='Submit' /></form>
"),
			loader.on("submit",function(){
				var sites = {
					"Local": {
						"os_ip": document.URL.match(/https?:\/\/(.*)\/.*?/)[1],
						// Still need to prompt for password
						"os_pw": $("#os_pw").val()
					}
				},
				current_site = "Local";

				// Show loading message and title
				body.html("

Loading

");
				document.title = "Loading...";

				// Inject site information to storage so Application loads current device
				localStorage.setItem("sites",JSON.stringify(sites));
				localStorage.setItem("current_site",current_site);

				finishInit();

				return false;
			});

			// Change title to reflect current state
			document.title = "OpenSprinkler: Login";
		}

		// Change viewport
		$("meta[name='viewport']").attr("content","width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no");

		// Hide the body while we modify the DOM
		body.html(loader);

		$.get(assetLocation+"index.html",function(data){
			// Grab the pages from index.html (body content)
			var pages = data.match(/([.\s\S]*)<\/body>/)[1];

			// Disables site selection menu
			window.curr_local = true;

			// Load 3rd party libraries such as FastClick (loaded first to avoid conflicts)
			$.getScript(assetLocation+"js/libs.js",function(){

				// Load main application Javascript (loaded before jQM so binds trigger when jQM loads)
				$.getScript(assetLocation+"js/main.js",function(){

					// Show the body when jQM attempts first page transition
					$(document).one("mobileinit",function(){

						// Change title to reflect loading finished
						document.title = "Sprinkler System";

						// Inject pages into DOM
						body.html(pages);

						// Remove spinner code (no longer needed)
						$("head").find("style").remove();

						// Initialize environment (missed by main.js since body was added after)
						initApp();

						// Hide multi site features since using local device
						body.find(".multiSite").hide();
					});

					// Mark environment as loaded
					isReady = true;

				});

			});

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