<commit_before>Dionysus.module('DionysusApp.AdminHeader', function(Header, Dionysus, Backbone, Marionette, $) {
  var HeaderModel = Backbone.Model.extend({
    initialize: function() {
      Backbone.Select.Me.applyTo( this );
    }
  });

  var HeaderCollection = Backbone.Collection.extend({
    model: HeaderModel,
    initialize: function(models, options) {
      Backbone.Select.One.applyTo( this, models, options );
    }
  });

  var headers = new HeaderCollection([
    { name: "Home", href: "/admin", icon: "home" },
    { name: "Articles", href: "/admin/articles", icon: "edit" },
    { name: "Categories", href: "/admin/categories", icon: "inbox" },
    { name: "Tests", href: "/admin/tests", icon: "lab" }
  ]);

  var HeaderView = Marionette.ItemView.extend({
    template: "#admin-header-tpl",
    tagName: "li",
    className: "item",
    initialize: function() {
      this.model.on('selected', this.onRender, this);
      this.model.on('deselected', this.onRender, this);
    },
    events: {
      "click a" : "navigateMenu"
    },
    navigateMenu: function(e) {
      this.model.select();
    },
    onRender: function() {
      this.$el.toggleClass('active', !!this.model.selected);
    }
  });

  var HeadersView = Marionette.CompositeView.extend({
    template: '#admin-headers-tpl',
    childView: HeaderView,
    childViewContainer: '.menu',
    tagName: 'nav'
  });

  Dionysus.addInitializer(function() {
    Dionysus.headerRegion.show(new HeadersView({collection: headers}));
  });
});

Dionysus.start();<commit_msg>use Marionette modelEvent instead of Backbone.Model event<commit_after>Dionysus.module('DionysusApp.AdminHeader', function(Header, Dionysus, Backbone, Marionette, $) {
  var HeaderModel = Backbone.Model.extend({
    initialize: function() {
      Backbone.Select.Me.applyTo( this );
    }
  });

  var HeaderCollection = Backbone.Collection.extend({
    model: HeaderModel,
    initialize: function(models, options) {
      Backbone.Select.One.applyTo( this, models, options );
    }
  });

  var headers = new HeaderCollection([
    { name: "Home", href: "/admin", icon: "home" },
    { name: "Articles", href: "/admin/articles", icon: "edit" },
    { name: "Categories", href: "/admin/categories", icon: "inbox" },
    { name: "Tests", href: "/admin/tests", icon: "lab" }
  ]);

  var HeaderView = Marionette.ItemView.extend({
    template: "#admin-header-tpl",
    tagName: "li",
    className: "item",
    modelEvents: {
      "selected": "onRender",
      "deselected": "onRender"
    },
    events: {
      "click a" : "navigateMenu"
    },
    navigateMenu: function(e) {
      this.model.select();
    },
    onRender: function() {
      this.$el.toggleClass('active', !!this.model.selected);
    }
  });

  var HeadersView = Marionette.CompositeView.extend({
    template: '#admin-headers-tpl',
    childView: HeaderView,
    childViewContainer: '.menu',
    tagName: 'nav'
  });

  Dionysus.addInitializer(function() {
    Dionysus.headerRegion.show(new HeadersView({collection: headers}));
  });
});

Dionysus.start();<|endoftext|>


<commit_before>import createStyles from './styles';

const config = {
  maxWidth: 600,
  marginTop: 0,
  marginRight: 0,
  marginBottom: 0,
  marginLeft: 0
};

export default {
  ...config,
  styles: createStyles(config)
};
<commit_msg>update margin left to 50px<commit_after>import createStyles from './styles';

const config = {
  maxWidth: 600,
  marginTop: 0,
  marginRight: 0,
  marginBottom: 0,
  marginLeft: '50px'
};

export default {
  ...config,
  styles: createStyles(config)
};
<|endoftext|>


<commit_before>'use strict';

var winston = require('winston');
var Mail = require('winston-mail').Mail;
var Sentry = require('winston-sentry');
var connector;
var config;
var logger;
var throttle = function () {
    return Promise.resolve(false);
};

function initThrottle(config) {
    var throttleAdapter;
    if (!config) {
        return;
    }
    if (!config.adapter) {
        return;
    }
    if (typeof connector.getAdapter === 'function') {
        throttleAdapter = connector.getAdapter(config.adapter);
    } else {
        throttleAdapter = connector[config.adapter];
    }
    if (!throttleAdapter) {
        return;
    }
    if (typeof throttleAdapter.throttle !== 'function') {
        return;
    }

    throttle = function () {
        return Promise.resolve(throttleAdapter.throttle.apply(throttleAdapter, Array.prototype.slice.call(arguments)));
    }
}

module.exports = {
    initAdapter: (_connector, _config) => {
        connector = _connector;
        config = _config;

        logger = new winston.Logger({
            transports: [
                new winston.transports.Console({level: config.level})
            ],
            levels: {
                error: 0,
                warn: 1,
                info: 2,
                verbose: 3,
                debug: 4,
                silly: 5
            },
            colors: {
                error: 'red',
                warn: 'yellow',
                info: 'green',
                verbose: 'cyan',
                debug: 'blue',
                silly: 'magenta'
            }
        });

        if (config.enableMails) {
            logger.add(Mail, config.mailConfig);
        }

        if (config.enableSentry) {
            logger.add(Sentry, config.sentryConfig);
        }

        initThrottle(config.throttle);
    },

    log: function () {
        var argumentsArray = Array.prototype.slice.call(arguments);
        throttle.apply(null, argumentsArray)
            .then(isThrottled => {
                if (!isThrottled) {
                    logger.log.apply(logger, argumentsArray);
                }
            })
            .catch(err => {
                logger.log('error', err);
                logger.log.apply(logger, argumentsArray);
            });
    }
};
<commit_msg>patch the fact that winston doesnt handle error objects as msg parameter correctly<commit_after>'use strict';

var winston = require('winston');
var Mail = require('winston-mail').Mail;
var Sentry = require('winston-sentry');
var connector;
var config;
var logger;
var throttle = function () {
    return Promise.resolve(false);
};

function initThrottle(config) {
    var throttleAdapter;
    if (!config) {
        return;
    }
    if (!config.adapter) {
        return;
    }
    if (typeof connector.getAdapter === 'function') {
        throttleAdapter = connector.getAdapter(config.adapter);
    } else {
        throttleAdapter = connector[config.adapter];
    }
    if (!throttleAdapter) {
        return;
    }
    if (typeof throttleAdapter.throttle !== 'function') {
        return;
    }

    throttle = function () {
        return Promise.resolve(throttleAdapter.throttle.apply(throttleAdapter, Array.prototype.slice.call(arguments)));
    }
}

function convertErrorInsteadOfMsgArgToWinston(args) {
    var level = args.shift();
    var msg = args.shift();
    var meta = args.shift() || {};
    var message = msg;
    if (msg instanceof Error) {
        message = msg.message;
        meta = Object.assign(msg, meta);
    }
    return [level, message, meta];
}

module.exports = {
    initAdapter: (_connector, _config) => {
        connector = _connector;
        config = _config;

        logger = new winston.Logger({
            transports: [
                new winston.transports.Console({level: config.level})
            ],
            levels: {
                error: 0,
                warn: 1,
                info: 2,
                verbose: 3,
                debug: 4,
                silly: 5
            },
            colors: {
                error: 'red',
                warn: 'yellow',
                info: 'green',
                verbose: 'cyan',
                debug: 'blue',
                silly: 'magenta'
            }
        });

        if (config.enableMails) {
            logger.add(Mail, config.mailConfig);
        }

        if (config.enableSentry) {
            logger.add(Sentry, config.sentryConfig);
        }

        initThrottle(config.throttle);
    },

    log: function () {
        var args = convertErrorInsteadOfMsgArgToWinston([].slice.call(arguments));
        throttle.apply(null, args)
            .then(isThrottled => {
                if (!isThrottled) {
                    logger.log.apply(logger, args);
                }
            })
            .catch(err => {
                logger.log('error', err);
                logger.log.apply(logger, args);
            });
    }
};
<|endoftext|>


<commit_before>var logging = require("./logging");
var request = require("request");
var config = require("./config");
var fs = require("fs");

var session_url = "https://sessionserver.mojang.com/session/minecraft/profile/";
var skins_url = "https://skins.minecraft.net/MinecraftSkins/";
var capes_url = "https://skins.minecraft.net/MinecraftCloaks/";
var textures_url = "http://textures.minecraft.net/texture/";
var mojang_urls = [skins_url, capes_url];

var exp = {};

function extract_url(profile, property) {
  var url = null;
  if (profile && profile.properties) {
    profile.properties.forEach(function(prop) {
      if (prop.name === "textures") {
        var json = new Buffer(prop.value, "base64").toString();
        var props = JSON.parse(json);
        url = props && props.textures && props.textures[property] && props.textures[property].url || null;
      }
    });
  }
  return url;
}

// exracts the skin url of a +profile+ object
// returns null when no url found (user has no skin)
exp.extract_skin_url = function(profile) {
  return extract_url(profile, 'SKIN');
};

// exracts the cape url of a +profile+ object
// returns null when no url found (user has no cape)
exp.extract_cape_url = function(profile) {
  return extract_url(profile, 'CAPE');
};

// makes a GET request to the +url+
// +options+ hash includes various options for
// encoding and timeouts, defaults are already
// specified. +callback+ contains the body, response,
// and error buffer. get_from helper method is available
exp.get_from_options = function(rid, url, options, callback) {
  request.get({
    url: url,
    headers: {
      "User-Agent": "https://crafatar.com"
    },
    timeout: (options.timeout || config.http_timeout),
    encoding: (options.encoding || null),
    followRedirect: (options.folow_redirect || false),
  }, function(error, response, body) {
    // 200 or 301 depending on content type
    if (!error && (response.statusCode === 200 || response.statusCode === 301)) {
      // response received successfully
      logging.log(rid + url + " url received");
      callback(body, response, null);
    } else if (error) {
      callback(body || null, response, error);
    } else if (response.statusCode === 404 || response.statusCode === 204) {
      // page does not exist
      logging.log(rid + url + " url does not exist");
      callback(null, response, null);
    } else if (response.statusCode === 429) {
      // Too Many Requests exception - code 429
      logging.warn(rid + url + " Too many requests");
      callback(body || null, response, error);
    } else {
      logging.error(rid + url + " Unknown error:");
      logging.error(rid + JSON.stringify(response));
      callback(body || null, response, error);
    }
  });
};

// helper method for get_from_options, no options required
exp.get_from = function(rid, url, callback) {
  exp.get_from_options(rid, url, {}, function(body, response, err) {
    callback(body, response, err);
  });
};

// make a request to skins.miencraft.net
// the skin url is taken from the HTTP redirect
// type reference is above
exp.get_username_url = function(rid, name, type, callback) {
  exp.get_from(rid, mojang_urls[type] + name + ".png", function(body, response, err) {
    if (!err) {
      callback(err, response ? (response.statusCode === 404 ? null : response.headers.location) : null);
    } else {
      callback(err, null);
    }
  });
};

// gets the URL for a skin/cape from the profile
// +type+ specifies which to retrieve
exp.get_uuid_url = function(profile, type, callback) {
  var url = null;
  if (type === 0) {
    url = exp.extract_skin_url(profile);
  } else if (type === 1) {
    url = exp.extract_cape_url(profile);
  }
  callback(url || null);
};

// make a request to sessionserver
// profile is returned as json
exp.get_profile = function(rid, uuid, callback) {
  if (!uuid) {
    callback(null, null);
  } else {
    exp.get_from_options(rid, session_url + uuid, { encoding: "utf8" }, function(body, response, err) {
      callback(err || null, (body !== null ? JSON.parse(body) : null));
    });
  }
};

// +userId+ is likely a username and if so
// +userId+ is used to get the url, otherwise
// +profile+ will be used to get the url
exp.get_skin_url = function(rid, userId, profile, callback) {
  get_url(rid, userId, profile, 0, function(url) {
    callback(url);
  });
};

// +userId+ is likely a username and if so
// +userId+ is used to get the url, otherwise
// +profile+ will be used to get the url
exp.get_cape_url = function(rid, userId, profile, callback) {
  get_url(rid, userId, profile, 1, function(url) {
    callback(url);
  });
};

function get_url(rid, userId, profile, type, callback) {
  if (userId.length <= 16) {
    //username
    exp.get_username_url(rid, userId, type, function(err, url) {
      callback(url || null);
    });
  } else {
    exp.get_uuid_url(profile, type, function(url) {
      callback(url || null);
    });
  }
}

exp.save_texture = function(rid, tex_hash, outpath, callback) {
  if (tex_hash) {
    var textureurl = textures_url + tex_hash;
    exp.get_from(rid, textureurl, function(img, response, err) {
      if (err) {
        logging.error(rid + "error while downloading texture");
        callback(err, response, null);
      } else {
        fs.writeFile(outpath, img, "binary", function(err) {
          if (err) {
            logging.log(rid + "error: " + err.stack);
          }
          callback(err, response, img);
        });
      }
    });
  } else {
    callback(null, null, null);
  }
};

module.exports = exp;<commit_msg>remove unused options for GET requests<commit_after>var logging = require("./logging");
var request = require("request");
var config = require("./config");
var fs = require("fs");

var session_url = "https://sessionserver.mojang.com/session/minecraft/profile/";
var skins_url = "https://skins.minecraft.net/MinecraftSkins/";
var capes_url = "https://skins.minecraft.net/MinecraftCloaks/";
var textures_url = "http://textures.minecraft.net/texture/";
var mojang_urls = [skins_url, capes_url];

var exp = {};

function extract_url(profile, property) {
  var url = null;
  if (profile && profile.properties) {
    profile.properties.forEach(function(prop) {
      if (prop.name === "textures") {
        var json = new Buffer(prop.value, "base64").toString();
        var props = JSON.parse(json);
        url = props && props.textures && props.textures[property] && props.textures[property].url || null;
      }
    });
  }
  return url;
}

// exracts the skin url of a +profile+ object
// returns null when no url found (user has no skin)
exp.extract_skin_url = function(profile) {
  return extract_url(profile, 'SKIN');
};

// exracts the cape url of a +profile+ object
// returns null when no url found (user has no cape)
exp.extract_cape_url = function(profile) {
  return extract_url(profile, 'CAPE');
};

// makes a GET request to the +url+
// +options+ hash includes various options for
// encoding and timeouts, defaults are already
// specified. +callback+ contains the body, response,
// and error buffer. get_from helper method is available
exp.get_from_options = function(rid, url, options, callback) {
  request.get({
    url: url,
    headers: {
      "User-Agent": "https://crafatar.com"
    },
    timeout: config.http_timeout,
    followRedirect: false,
    encoding: (options.encoding || null),
  }, function(error, response, body) {
    // 200 or 301 depending on content type
    if (!error && (response.statusCode === 200 || response.statusCode === 301)) {
      // response received successfully
      logging.log(rid + url + " url received");
      callback(body, response, null);
    } else if (error) {
      callback(body || null, response, error);
    } else if (response.statusCode === 404 || response.statusCode === 204) {
      // page does not exist
      logging.log(rid + url + " url does not exist");
      callback(null, response, null);
    } else if (response.statusCode === 429) {
      // Too Many Requests exception - code 429
      logging.warn(rid + url + " Too many requests");
      callback(body || null, response, error);
    } else {
      logging.error(rid + url + " Unknown error:");
      logging.error(rid + JSON.stringify(response));
      callback(body || null, response, error);
    }
  });
};

// helper method for get_from_options, no options required
exp.get_from = function(rid, url, callback) {
  exp.get_from_options(rid, url, {}, function(body, response, err) {
    callback(body, response, err);
  });
};

// make a request to skins.miencraft.net
// the skin url is taken from the HTTP redirect
// type reference is above
exp.get_username_url = function(rid, name, type, callback) {
  exp.get_from(rid, mojang_urls[type] + name + ".png", function(body, response, err) {
    if (!err) {
      callback(err, response ? (response.statusCode === 404 ? null : response.headers.location) : null);
    } else {
      callback(err, null);
    }
  });
};

// gets the URL for a skin/cape from the profile
// +type+ specifies which to retrieve
exp.get_uuid_url = function(profile, type, callback) {
  var url = null;
  if (type === 0) {
    url = exp.extract_skin_url(profile);
  } else if (type === 1) {
    url = exp.extract_cape_url(profile);
  }
  callback(url || null);
};

// make a request to sessionserver
// profile is returned as json
exp.get_profile = function(rid, uuid, callback) {
  if (!uuid) {
    callback(null, null);
  } else {
    exp.get_from_options(rid, session_url + uuid, { encoding: "utf8" }, function(body, response, err) {
      callback(err || null, (body !== null ? JSON.parse(body) : null));
    });
  }
};

// +userId+ is likely a username and if so
// +userId+ is used to get the url, otherwise
// +profile+ will be used to get the url
exp.get_skin_url = function(rid, userId, profile, callback) {
  get_url(rid, userId, profile, 0, function(url) {
    callback(url);
  });
};

// +userId+ is likely a username and if so
// +userId+ is used to get the url, otherwise
// +profile+ will be used to get the url
exp.get_cape_url = function(rid, userId, profile, callback) {
  get_url(rid, userId, profile, 1, function(url) {
    callback(url);
  });
};

function get_url(rid, userId, profile, type, callback) {
  if (userId.length <= 16) {
    //username
    exp.get_username_url(rid, userId, type, function(err, url) {
      callback(url || null);
    });
  } else {
    exp.get_uuid_url(profile, type, function(url) {
      callback(url || null);
    });
  }
}

exp.save_texture = function(rid, tex_hash, outpath, callback) {
  if (tex_hash) {
    var textureurl = textures_url + tex_hash;
    exp.get_from(rid, textureurl, function(img, response, err) {
      if (err) {
        logging.error(rid + "error while downloading texture");
        callback(err, response, null);
      } else {
        fs.writeFile(outpath, img, "binary", function(err) {
          if (err) {
            logging.log(rid + "error: " + err.stack);
          }
          callback(err, response, img);
        });
      }
    });
  } else {
    callback(null, null, null);
  }
};

module.exports = exp;<|endoftext|>


<commit_before>'use strict';

/*!
 * Module dependencies.
 */
var fs = require('fs');
var util = require('util');
var events = require("events");
var path = require('path');
var glob = require('glob');
var colors = require('colors');
var spawn = require('child_process').spawn;
var _s = require('underscore.string');
var domain = require('domain').create();
/**
 * Exports
 */
module.exports = exports = helmsman;
exports.Helmsman = Helmsman;

/**
 * The Helmsman constructor
 *
 * Options:
 *
 *   * prefix: The prefix of the script files. eg: 'git-''
 *
 * @param  {object} options   config
 */
function Helmsman(options){
  var self = this;

  events.EventEmitter.call(self);

  if (!options) { options = {}; }

  if (!options.localDir) {
    this.localDir = path.dirname(module.parent.filename);
  } else {
    this.localDir = path.resolve(options.localDir);
  }

  // Guess the prefix. Assume if one isn't given and that executable doesn't equal
  // the root command filename, use the filename of the root command
  if (!options.prefix && path.basename(process.argv[1]) !== path.basename(require.main.filename)) {
    this.prefix = path.basename(require.main.filename)
  } else {
    this.prefix = options.prefix || path.basename(process.argv[1]);
  }

  this.availableCommands = {};
  this.commandMaxLength = 18; //For printing help later, 18 is help <sub-command>

  // Add a dash to the end if none was provided
  if (this.prefix.substr(-1) !== '-') {
    this.prefix += '-';
  }

  // Local files in files in the /bin folder for an application
  this.localFiles = glob.sync(self.prefix+"*", {cwd: self.localDir});

  this.localFiles.forEach(function(file){
    // Figure out the longest command name for printing --help
    var commandData = require(path.join(self.localDir, file)).command;

    if (!commandData) {
      util.error('The file ('+file+') did not export.command. Please ensure your commands are setup properly and your prefix is correct'.red);
      process.exit(1);
    }

    self.availableCommands[file.substr(self.prefix.length)] = commandData;

    var fullCommand = (commandData.options) ? file + ' ' + commandData.command : file

    if (fullCommand.length > self.commandMaxLength) { self.commandMaxLength = file.length; }
  });

  self.availableCommands['help'] = { // help is always available!
    arguments: '<sub-command>',
    description: 'Show the --help for a specific command'
  }
}

util.inherits(Helmsman, events.EventEmitter);

/**
 * Simplify creating a new Helmsman Object
 *
 * Example:
 *
 *   var helmsman = require('helmsman');
 *
 *   var cli = helmsman();
 *   cli.parse();
 *
 * @param  {Object} options   Contructor options
 * @return {Helmsman}         A new helmsman
 */

function helmsman(options){
  return new Helmsman(options);
}

/**
 * Determine the subcommand to run
 *
 *  Try:
 *    * Explicit match (status === status)
 *    * Shorthand (st === status)
 *    * Levenshtein of <=2 (sratus === status)
 *
 * @param  {String} cmd The command given to the script
 * @param  {[String]} availableCommands An array of all the available commands
 * @return {String}     The actual command that will be run
 */
Helmsman.prototype.getCommand = function(cmd, availableCommands){
  var self = this;

  if (!availableCommands) {
    availableCommands = Object.keys(self.availableCommands);
  }

  // If there is an exact match, return it
  if (~availableCommands.indexOf(cmd)) {
    return cmd;
  }

  // Detirmine how many commands match the iterator. Return one if command,
  function isOneOrMore(commands, iterator){
    var list = commands.filter(iterator)

    if (list.length === 1) {
      return list[0];
    } else if (list.length > 1) {
      return new Error(util.format('There are %d potential options for "%s": %s', list.length, cmd, list));
    } else {
      return false;
    }
  }

  // If there is a shorthand match, return it
  var shortHandCmd = isOneOrMore(availableCommands, function(command){
    return (command.indexOf(cmd) === 0);
  })
  if (shortHandCmd) { return shortHandCmd; }

  // If there is a close match, return it
  var similarCmd = isOneOrMore(availableCommands, function(command){
    return (_s.levenshtein(cmd, command) <= 2);
  })
  if (similarCmd) { return similarCmd; }

  // If nothing, then get outta here
  return new Error(util.format('There are no commands by the name of "%s"', cmd));
}

/**
 * GO!
 *
 * @param {[Object]} argv   The process arguments to parse. Defaults to process.argv
 */

Helmsman.prototype.parse = function(argv){
  var self = this;

  argv = argv || process.argv; // If no arguments are passed, assume process.argv

  var args = argv.slice(2);

  // Much of the following heavily inspired or simply taken from component/bin
  // https://github.com/component/component/blob/master/bin/component

  // Print the modules version number
  if (args[0] === '--version') {
    // BOLD assumption that the file is in ./bin
    var packagePath = path.join(path.dirname(require.main.filename), '..', 'package.json');
    var pkg = require(packagePath);
    return console.log(pkg.name + ": " + pkg.version)
  }

  // Print the command list if --help is called
  if (args[0] === '--help' || !args.length || args[0][0] === '-' || (args[0] === 'help' && args.length === 1)) {
    self.emit('--help');
    return self.showHelp();
  }

  var cmd = self.getCommand(args.shift());

  if ('Error' === typeof cmd) {
    util.error(e.message.red);
    self.showHelp();
    process.exit(1);
  }

  // Implicit help
  // If <command> help <sub-command> is entered, automatically run <command>-<sub-command> --help
  if (cmd === 'help') {
    cmd = args.shift();
    args = ['--help'];
  }

  var binPath = path.join(self.localDir, self.prefix + cmd);

  domain.on('error', function(err) {
    if (err.code === 'EACCES') {
      console.error('');
      console.error('Could not execute the subcommand: ' + self.prefix + cmd);
      console.error('');
      console.error('Consider running:\n chmod +x '+binPath);
    } else {
      console.error(err.stack.red);
    }
  });

  domain.run(function() {
    var subcommand = spawn(binPath, args, { stdio: 'inherit' });

    subcommand.on('close', function(code){
      process.exit(code);
    });
  });
};

/**
 * Show the help
 */

Helmsman.prototype.showHelp = function(){
  var self = this;
  var fullCommands = [];

  console.log('');
  console.log('Commands:');
  console.log('');

  for (var command in self.availableCommands) {
    var fullCommand = command;
    // console.log(command, self.availableCommands[command].options, "\n")
    if (self.availableCommands[command].arguments) {
      fullCommand += ' ' + self.availableCommands[command].arguments;
    }

    if (fullCommand.length > self.commandMaxLength) {
      self.commandMaxLength = fullCommand.length;
    }

    fullCommands.push([fullCommand, self.availableCommands[command].description]);
  }

  fullCommands.forEach(function(command){
    var diff = (self.commandMaxLength - command[0].length);
    // Pad spaces at the end of each command so help descriptions line up
    for (var i = 0; i < diff; i++) {
      command[0]+=' ';
    }
    console.log('   %s     %s', command[0], command[1]);
  })

  process.exit();
};<commit_msg>Catching non existant tasks now works<commit_after>'use strict';

/*!
 * Module dependencies.
 */
var fs = require('fs');
var util = require('util');
var events = require("events");
var path = require('path');
var glob = require('glob');
var colors = require('colors');
var spawn = require('child_process').spawn;
var _s = require('underscore.string');
var domain = require('domain').create();
/**
 * Exports
 */
module.exports = exports = helmsman;
exports.Helmsman = Helmsman;

/**
 * The Helmsman constructor
 *
 * Options:
 *
 *   * prefix: The prefix of the script files. eg: 'git-''
 *
 * @param  {object} options   config
 */
function Helmsman(options){
  var self = this;

  events.EventEmitter.call(self);

  if (!options) { options = {}; }

  if (!options.localDir) {
    this.localDir = path.dirname(module.parent.filename);
  } else {
    this.localDir = path.resolve(options.localDir);
  }

  // Guess the prefix. Assume if one isn't given and that executable doesn't equal
  // the root command filename, use the filename of the root command
  if (!options.prefix && path.basename(process.argv[1]) !== path.basename(require.main.filename)) {
    this.prefix = path.basename(require.main.filename)
  } else {
    this.prefix = options.prefix || path.basename(process.argv[1]);
  }

  this.availableCommands = {};
  this.commandMaxLength = 18; //For printing help later, 18 is help <sub-command>

  // Add a dash to the end if none was provided
  if (this.prefix.substr(-1) !== '-') {
    this.prefix += '-';
  }

  // Local files in files in the /bin folder for an application
  this.localFiles = glob.sync(self.prefix+"*", {cwd: self.localDir});

  this.localFiles.forEach(function(file){
    // Figure out the longest command name for printing --help
    var commandData = require(path.join(self.localDir, file)).command;

    if (!commandData) {
      util.error('The file ('+file+') did not export.command. Please ensure your commands are setup properly and your prefix is correct'.red);
      process.exit(1);
    }

    self.availableCommands[file.substr(self.prefix.length)] = commandData;

    var fullCommand = (commandData.options) ? file + ' ' + commandData.command : file

    if (fullCommand.length > self.commandMaxLength) { self.commandMaxLength = file.length; }
  });

  self.availableCommands['help'] = { // help is always available!
    arguments: '<sub-command>',
    description: 'Show the --help for a specific command'
  }
}

util.inherits(Helmsman, events.EventEmitter);

/**
 * Simplify creating a new Helmsman Object
 *
 * Example:
 *
 *   var helmsman = require('helmsman');
 *
 *   var cli = helmsman();
 *   cli.parse();
 *
 * @param  {Object} options   Contructor options
 * @return {Helmsman}         A new helmsman
 */

function helmsman(options){
  return new Helmsman(options);
}

/**
 * Determine the subcommand to run
 *
 *  Try:
 *    * Explicit match (status === status)
 *    * Shorthand (st === status)
 *    * Levenshtein of <=2 (sratus === status)
 *
 * @param  {String} cmd The command given to the script
 * @param  {[String]} availableCommands An array of all the available commands
 * @return {String}     The actual command that will be run
 */
Helmsman.prototype.getCommand = function(cmd, availableCommands){
  var self = this;

  if (!availableCommands) {
    availableCommands = Object.keys(self.availableCommands);
  }

  // If there is an exact match, return it
  if (~availableCommands.indexOf(cmd)) {
    return cmd;
  }

  // Detirmine how many commands match the iterator. Return one if command,
  function isOneOrMore(commands, iterator){
    var list = commands.filter(iterator)

    if (list.length === 1) {
      return list[0];
    } else if (list.length > 1) {
      return new Error(util.format('There are %d potential options for "%s": %s', list.length, cmd, list));
    } else {
      return false;
    }
  }

  // If there is a shorthand match, return it
  var shortHandCmd = isOneOrMore(availableCommands, function(command){
    return (command.indexOf(cmd) === 0);
  })
  if (shortHandCmd) { return shortHandCmd; }

  // If there is a close match, return it
  var similarCmd = isOneOrMore(availableCommands, function(command){
    return (_s.levenshtein(cmd, command) <= 2);
  })
  if (similarCmd) { return similarCmd; }

  // If nothing, then get outta here
  return new Error(util.format('There are no commands by the name of "%s"', cmd));
}

/**
 * GO!
 *
 * @param {[Object]} argv   The process arguments to parse. Defaults to process.argv
 */

Helmsman.prototype.parse = function(argv){
  var self = this;

  argv = argv || process.argv; // If no arguments are passed, assume process.argv

  var args = argv.slice(2);

  // Much of the following heavily inspired or simply taken from component/bin
  // https://github.com/component/component/blob/master/bin/component

  // Print the modules version number
  if (args[0] === '--version') {
    // BOLD assumption that the file is in ./bin
    var packagePath = path.join(path.dirname(require.main.filename), '..', 'package.json');
    var pkg = require(packagePath);
    return console.log(pkg.name + ": " + pkg.version)
  }

  // Print the command list if --help is called
  if (args[0] === '--help' || !args.length || args[0][0] === '-' || (args[0] === 'help' && args.length === 1)) {
    self.emit('--help');
    return self.showHelp();
  }

  var cmd = self.getCommand(args.shift());

  if ('object' === typeof cmd && cmd.name === "Error") {
    util.error(cmd.message.red);
    self.showHelp();
    process.exit(1);
  }

  // Implicit help
  // If <command> help <sub-command> is entered, automatically run <command>-<sub-command> --help
  if (cmd === 'help') {
    cmd = args.shift();
    args = ['--help'];
  }

  var binPath = path.join(self.localDir, self.prefix + cmd);

  domain.on('error', function(err) {
    if (err.code === 'EACCES') {
      console.error('');
      console.error('Could not execute the subcommand: ' + self.prefix + cmd);
      console.error('');
      console.error('Consider running:\n chmod +x '+binPath);
    } else {
      console.error(err.stack.red);
    }
  });

  domain.run(function() {
    var subcommand = spawn(binPath, args, { stdio: 'inherit' });

    subcommand.on('close', function(code){
      process.exit(code);
    });
  });
};

/**
 * Show the help
 */

Helmsman.prototype.showHelp = function(){
  var self = this;
  var fullCommands = [];

  console.log('');
  console.log('Commands:');
  console.log('');

  for (var command in self.availableCommands) {
    var fullCommand = command;
    // console.log(command, self.availableCommands[command].options, "\n")
    if (self.availableCommands[command].arguments) {
      fullCommand += ' ' + self.availableCommands[command].arguments;
    }

    if (fullCommand.length > self.commandMaxLength) {
      self.commandMaxLength = fullCommand.length;
    }

    fullCommands.push([fullCommand, self.availableCommands[command].description]);
  }

  fullCommands.forEach(function(command){
    var diff = (self.commandMaxLength - command[0].length);
    // Pad spaces at the end of each command so help descriptions line up
    for (var i = 0; i < diff; i++) {
      command[0]+=' ';
    }
    console.log('   %s     %s', command[0], command[1]);
  })

  process.exit();
};<|endoftext|>


<commit_before>var userid = null;

angular.module('ionicApp', ['ionic'])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('signin', {
      url: '/sign-in',
      templateUrl: 'templates/sign-in.html',
      controller: 'SignInCtrl'
    })
    .state('schedule', {
      url: '/schedule',
      templateUrl: 'templates/schedule.html',
      controller: 'ScheduleCtrl'
    })
    .state('form', {
      url: '/form',
      templateUrl: 'templates/app-form.html',
      controller: 'FormCtrl'
    })
    .state('signup', {
      url: '/sign-up',
      templateUrl: 'templates/sign-up.html',
      controller: 'SignUpCtrl'
    });
  $urlRouterProvider.otherwise('/sign-in');
})

.controller('ScheduleCtrl', function($scope, $http, $ionicPopup){
  $scope.stories = [];
  $scope.appointments = info;

  $scope.showAlert = function(title, body) {
   var alertPopup = $ionicPopup.alert({
     title: title,
     template: body
   });
   alertPopup.then(function(res) {
     console.log('Error');
   });
 };

  $scope.doRefresh = function() {
    console.log('called refresh!');
    $http.get('#/schedule')
     .success(function(/*newItems*/) {
      //  $scope.items = newItems;
      $scope.appointments = info;
     })
     .finally(function() {
       // Stop the ion-refresher from spinning
       $scope.$broadcast('scroll.refreshComplete');
     });
    };

  $scope.removeApp = function(id){
    //Works! Logs correct id :D
    console.log(id);
    $.ajax({
      //removed the /2 from url.
      url: ('https://api-us.clusterpoint.com//100600/Appointly/' + id),
      type: 'DELETE',
      dataType: 'json',
      // data: ("{'id'=" + id + "}"),
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      },
      success: function(data) {
        if (typeof success != 'undefined') {
          success(data);
        }
        $scope.showAlert("Success!", "Appointment has been delete!");
      },
        fail: function(data) {
          alert(data.error);
          console.log('Fail!');
          if (typeof fail != 'undefined') {
            fail(data);
          }
          $scope.showAlert("Error!", "Appointment could not be deleted!");
        }
      })

      setTimeout(function()
      {
          $scope.doRefresh();

      }, 2000);
  }

})

.controller('SignUpCtrl', function($http, $scope, $state, $ionicPopup) {
  $scope.showAlert = function(title, body) {
    var alertPopup = $ionicPopup.alert({
      title: title,
      template: body
    });
    alertPopup.then(function(res) {
      $state.go('signin');
    });
  };

  $scope.signup = function(name, email, phone, pass) {

    var send = {
        // "name"      : name,
        // "email"     : email,
        // "phone"     : phone,
        // "pass"      : pass,
        "id"            : phone,
        "password"      : pass,
    }

    console.log(JSON.stringify(send));

    $.ajax({
      url: 'https://api-us.clusterpoint.com/100600/User_Accounts/_insert',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(send),
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      },
      success: function(data) {
        if (typeof success != 'undefined') {
          success(data);
        }
        console.log(data);
        $scope.showAlert('Done!','You are in!');
      },
      fail: function(data) {
        alert('No!');
        alert(data.error);
        console.log('Fail!');
        if (typeof fail != 'undefined') {
          fail(data);
        }
      }
    })

    // users.done(function (data){
    //   var d = data.documents;
    //   //----------------------------------------------------------
    //   console.log(d);
    //   var result = $.grep(d, function(e) {
    //     return e.id == number && e.password == password;
    //   });
    //   console.log(result);
    //   if (result.length == 0) {
    //     $scope.showAlert('Error', 'Incorrect Number or Password!');
    //   } else if (result.length == 1) {
    //     $state.go('sign-in');
    //   } else {
    //     $scope.showAlert('Error', 'Duplicate Users Found!');
    //   }
    // })
  }

})

.controller('SignInCtrl', function($http, $scope, $state, $ionicPopup) {

  $scope.showAlert = function(title, body) {
    var alertPopup = $ionicPopup.alert({
      title: title,
      template: body
    });
    alertPopup.then(function(res) {
      console.log('Error');
    });
  };

  console.log('Enter SingInCtrl');
  $scope.url = '#';
  $scope.acc_number = '';
  $scope.acc_password = '';
  $scope.login = function(number, password) {
    console.log('Enter login function');
    console.log('number: ' + number);
    console.log('password: ' + password);
    var users = $.ajax({
      url: 'https://api-us.clusterpoint.com/100600/User_Accounts/_list_last',
      type: 'GET',
      dataType: 'json',
      // data      : '{"query": "<name>Test</name>"}',
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      },
      success: function(data) {
        console.log('Retrived Users!');
        if (typeof success != 'undefined') {
          // jQuery.parseJSON(doc.responseJSON.documents.toSource();
          success(data);
        }
      },
      fail: function(data) {
        alert(data.error);
        console.log('Fail!');
        if (typeof fail != 'undefined') {
          fail(data);
        }
      }
    });

    users.done(function(data) {
      var d = data.documents;
      //----------------------------------------------------------
      console.log(d);
      var result = $.grep(d, function(e) {
        return e.id == number && e.password == password;
      });
      console.log(result);
      if (result.length == 0) {
        $scope.showAlert('Error', 'Incorrect Number or Password!');
      } else if (result.length == 1) {
        userid = number;

        $state.go('schedule');
      } else {
        $scope.showAlert('Error', 'Duplicate Users Found!');
      }
    });

  }

  // $scope.signIn = function(user) {
  //   console.log('Sign-In', user);
  //   $state.go('schedule');
  // };

})

.controller('HomeTabCtrl', function($scope) {
  console.log('HomeTabCtrl');
})

.controller('FormCtrl', function($http, $scope, $state, $timeout, $ionicPopup, $filter) {

    $scope.app_numb;
    $scope.app_name;
    $scope.app_img_p = 'multicare.png';
    // ['multicare.png','hb.png','health.png','dental.png'];
    $scope.app_date = new Date();
    $scope.app_time = $scope.app_date;

    $scope.doRefresh = function() {
      console.log('called refresh!');
      $http.get('#/schedule')
       .success(function(/*newItems*/) {
        //  $scope.items = newItems;
        $scope.appointments = info;
       })
       .finally(function() {
         // Stop the ion-refresher from spinning
         $scope.$broadcast('scroll.refreshComplete');
       });
      };

    $scope.go = function(app_numb, app_date, app_name, app_time, app_location) {
      // app_date = app_date.toString();
      // app_time = app_time.toString();
      // console.log('Passed into function:');
      // console.log(app_id);
      // console.log(app_date);
      // console.log(app_name);
      // console.log(app_time);
      // var fullTime = app_time.split(" ");
      // app_time = fullTime[0];
      // var app_zone = fullTime[1];
      // app_date(new Date(), "mmmm dS, yyyy");

      // console.log('Fulltime: ');
      // console.log(fullTime);
      // console.log('Time: ');
      // console.log(app_time);
      // console.log('Zone: ');
      // console.log(app_zone);

      var id = userid + Date.now().toString();

      var send = {
        "id"      :   id,
        "numb"    :   app_numb,
        "name"    :   app_name,
        "date"    :   app_date.toString(),
        "time"    :   app_time.toString(),
        "location":   app_location
      }

      console.log(send);

      $scope.showAlert = function() {
        var alertPopup = $ionicPopup.alert({
          title: 'All done!',
          template: 'Appointment Requested'
        });
        alertPopup.then(function(res) {
          $state.go('schedule');
          console.log('Thank you for not eating my delicious ice cream cone');
          setTimeout(function()
          {
              $scope.doRefresh();

          }, 2000);
        });
      };

    var test_date = $filter('date')(app_date, "dd/MM/yyyy");
    var test_time = $filter('date')(app_time, "HH:mm a");

      // Simple GET request example :
    $http.get('http://appointly.mybluemix.net/twiliouth?number=+1' + app_numb + '&message=An appointment has been requested on ' + test_date + ' on ' + test_time + '.').
      success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log('MSG sent to phone!');
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

      // $.ajax({
      //   url: 'http://appointly.mybluemix.net/',
      //   type: 'GET',
      //   contentType: "text/plain; charset=utf-8",
      //   dataType: 'text',
      //   data: send.name + " scheduled an appoinment with you at " + send.time + " on " + send.date + ", location: " + send.location,
      //   // beforeSend: function(xhr) {
      //   //   xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      //   // },
      //   success: function(data) {
      //     alert("Submitted!");
      //     if (typeof success != 'undefined') {
      //       // jQuery.parseJSON(doc.responseJSON.documents.toSource());
      //       success(data);
      //     }
      //   },
      //   fail: function(data) {
      //     alert('No!');
      //     alert(data.error);
      //     console.log('Fail!');
      //     if (typeof fail != 'undefined') {
      //       fail(data);
      //     }
      //   }
      // })

      $.ajax({
        //removed the /2 from url.
        url: 'https://api-us.clusterpoint.com//100600/Appointly/_insert',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(send),
        beforeSend: function(xhr) {
          xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
        },
        success: function(data) {
          if (typeof success != 'undefined') {
            success(data);
          }
          $scope.showAlert();
        },
        fail: function(data) {
          alert('No!');
          alert(data.error);
          console.log('Fail!');
          if (typeof fail != 'undefined') {
            fail(data);
          }
        }
      })

    }
  })
  .controller('MainCtrl', function($http, $scope) {
    $scope.test = 'Scope Works!';

    // $scope.stories = [];
    //
    // $scope.appointments = info;

    // [{
    //   name: 'Green Valley Clinic',
    //   img_p: 'health.png',
    //   date: 'June 30th',
    //   time: 10,
    //   zone: 'am'
    // }, {
    //   name: 'Silver Point Dental',
    //   img_p: 'dental.png',
    //   date: 'July 16th',
    //   time: 2,
    //   zone: 'pm'
    // }, {
    //   name: 'Multicare',
    //   img_p: 'multicare.png',
    //   date: 'July 25th',
    //   time: 4,
    //   zone: 'pm'
    // }];

  });
<commit_msg>DELETE NOT FUCKING WORKgit status<commit_after>var userid = null;

angular.module('ionicApp', ['ionic'])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('signin', {
      url: '/sign-in',
      templateUrl: 'templates/sign-in.html',
      controller: 'SignInCtrl'
    })
    .state('schedule', {
      url: '/schedule',
      templateUrl: 'templates/schedule.html',
      controller: 'ScheduleCtrl'
    })
    .state('form', {
      url: '/form',
      templateUrl: 'templates/app-form.html',
      controller: 'FormCtrl'
    })
    .state('signup', {
      url: '/sign-up',
      templateUrl: 'templates/sign-up.html',
      controller: 'SignUpCtrl'
    });
  $urlRouterProvider.otherwise('/sign-in');
})

.controller('ScheduleCtrl', function($scope, $http, $ionicPopup){
  $scope.stories = [];
  $scope.appointments = info;

  $scope.showAlert = function(title, body) {
   var alertPopup = $ionicPopup.alert({
     title: title,
     template: body
   });
   alertPopup.then(function(res) {
     console.log('Error');
   });
 };

  $scope.doRefresh = function() {
    console.log('called refresh!');
    $http.get('#/schedule')
     .success(function(/*newItems*/) {
      //  $scope.items = newItems;
      $scope.appointments = info;
     })
     .finally(function() {
       // Stop the ion-refresher from spinning
       $scope.$broadcast('scroll.refreshComplete');
     });
    };

  $scope.removeApp = function(id){
    //Works! Logs correct id :D
    console.log(id);
    $.ajax({
      //removed the /2 from url.
      url: ('https://api-us.clusterpoint.com//100600/Appointly/' + id),
      type: 'DELETE',
      dataType: 'json',
      // data: ("{'id'=" + id + "}"),
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      },
      success: function(data) {
        if (typeof success != 'undefined') {
          success(data);
        }
        $scope.showAlert("Success!", "Appointment has been canceled!");
      },
        fail: function(data) {
          alert(data.error);
          console.log('Fail!');
          if (typeof fail != 'undefined') {
            fail(data);
          }
          $scope.showAlert("Error!", "Appointment could not be deleted!");
        }
      })

      setTimeout(function()
      {
          $scope.doRefresh();

      }, 2000);
  }

})

.controller('SignUpCtrl', function($http, $scope, $state, $ionicPopup) {
  $scope.showAlert = function(title, body) {
    var alertPopup = $ionicPopup.alert({
      title: title,
      template: body
    });
    alertPopup.then(function(res) {
      $state.go('signin');
    });
  };

  $scope.signup = function(name, email, phone, pass) {

    var send = {
        // "name"      : name,
        // "email"     : email,
        // "phone"     : phone,
        // "pass"      : pass,
        "id"            : phone,
        "password"      : pass,
    }

    console.log(JSON.stringify(send));

    $.ajax({
      url: 'https://api-us.clusterpoint.com/100600/User_Accounts/_insert',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(send),
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      },
      success: function(data) {
        if (typeof success != 'undefined') {
          success(data);
        }
        console.log(data);
        $scope.showAlert('Done!','You are in!');
      },
      fail: function(data) {
        alert('No!');
        alert(data.error);
        console.log('Fail!');
        if (typeof fail != 'undefined') {
          fail(data);
        }
      }
    })

    // users.done(function (data){
    //   var d = data.documents;
    //   //----------------------------------------------------------
    //   console.log(d);
    //   var result = $.grep(d, function(e) {
    //     return e.id == number && e.password == password;
    //   });
    //   console.log(result);
    //   if (result.length == 0) {
    //     $scope.showAlert('Error', 'Incorrect Number or Password!');
    //   } else if (result.length == 1) {
    //     $state.go('sign-in');
    //   } else {
    //     $scope.showAlert('Error', 'Duplicate Users Found!');
    //   }
    // })
  }

})

.controller('SignInCtrl', function($http, $scope, $state, $ionicPopup) {

  $scope.showAlert = function(title, body) {
    var alertPopup = $ionicPopup.alert({
      title: title,
      template: body
    });
    alertPopup.then(function(res) {
      console.log('Error');
    });
  };

  console.log('Enter SingInCtrl');
  $scope.url = '#';
  $scope.acc_number = '';
  $scope.acc_password = '';
  $scope.login = function(number, password) {
    console.log('Enter login function');
    console.log('number: ' + number);
    console.log('password: ' + password);
    var users = $.ajax({
      url: 'https://api-us.clusterpoint.com/100600/User_Accounts/_list_last',
      type: 'GET',
      dataType: 'json',
      // data      : '{"query": "<name>Test</name>"}',
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      },
      success: function(data) {
        console.log('Retrived Users!');
        if (typeof success != 'undefined') {
          // jQuery.parseJSON(doc.responseJSON.documents.toSource();
          success(data);
        }
      },
      fail: function(data) {
        alert(data.error);
        console.log('Fail!');
        if (typeof fail != 'undefined') {
          fail(data);
        }
      }
    });

    users.done(function(data) {
      var d = data.documents;
      //----------------------------------------------------------
      console.log(d);
      var result = $.grep(d, function(e) {
        return e.id == number && e.password == password;
      });
      console.log(result);
      if (result.length == 0) {
        $scope.showAlert('Error', 'Incorrect Number or Password!');
      } else if (result.length == 1) {
        userid = number;

        $state.go('schedule');
      } else {
        $scope.showAlert('Error', 'Duplicate Users Found!');
      }
    });

  }

  // $scope.signIn = function(user) {
  //   console.log('Sign-In', user);
  //   $state.go('schedule');
  // };

})

.controller('HomeTabCtrl', function($scope) {
  console.log('HomeTabCtrl');
})

.controller('FormCtrl', function($http, $scope, $state, $timeout, $ionicPopup, $filter) {

    $scope.app_numb;
    $scope.app_name;
    $scope.app_img_p = 'multicare.png';
    // ['multicare.png','hb.png','health.png','dental.png'];
    $scope.app_date = new Date();
    $scope.app_time = $scope.app_date;

    $scope.doRefresh = function() {
      console.log('called refresh!');
      $http.get('#/schedule')
       .success(function(/*newItems*/) {
        //  $scope.items = newItems;
        $scope.appointments = info;
       })
       .finally(function() {
         // Stop the ion-refresher from spinning
         $scope.$broadcast('scroll.refreshComplete');
       });
      };

    $scope.go = function(app_numb, app_date, app_name, app_time, app_location) {
      // app_date = app_date.toString();
      // app_time = app_time.toString();
      // console.log('Passed into function:');
      // console.log(app_id);
      // console.log(app_date);
      // console.log(app_name);
      // console.log(app_time);
      // var fullTime = app_time.split(" ");
      // app_time = fullTime[0];
      // var app_zone = fullTime[1];
      // app_date(new Date(), "mmmm dS, yyyy");

      // console.log('Fulltime: ');
      // console.log(fullTime);
      // console.log('Time: ');
      // console.log(app_time);
      // console.log('Zone: ');
      // console.log(app_zone);

      $scope.app_id = userid + Date.now().toString();

      var send = {
        "id"      :   app_id,
        "numb"    :   app_numb,
        "name"    :   app_name,
        "img_p"   :   $scope.app_img_p,
        "date"    :   app_date.toString(),
        "time"    :   app_time.toString(),
        "location":   app_location
      }

      console.log(send);

      $scope.showAlert = function() {
        var alertPopup = $ionicPopup.alert({
          title: 'All done!',
          template: 'Appointment Requested'
        });
        alertPopup.then(function(res) {
          $state.go('schedule');
          console.log('Thank you for not eating my delicious ice cream cone');
          setTimeout(function()
          {
              $scope.doRefresh();

          }, 2000);
        });
      };

    var test_date = $filter('date')(app_date, "dd/MM/yyyy");
    var test_time = $filter('date')(app_time, "HH:mm a");

      // Simple GET request example :
    $http.get('http://appointly.mybluemix.net/twiliouth?number=+1' + app_numb + '&message=An appointment has been requested on ' + test_date + ' at ' + test_time + '.').
      success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log('MSG sent to phone!');
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

      // $.ajax({
      //   url: 'http://appointly.mybluemix.net/',
      //   type: 'GET',
      //   contentType: "text/plain; charset=utf-8",
      //   dataType: 'text',
      //   data: send.name + " scheduled an appoinment with you at " + send.time + " on " + send.date + ", location: " + send.location,
      //   // beforeSend: function(xhr) {
      //   //   xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
      //   // },
      //   success: function(data) {
      //     alert("Submitted!");
      //     if (typeof success != 'undefined') {
      //       // jQuery.parseJSON(doc.responseJSON.documents.toSource());
      //       success(data);
      //     }
      //   },
      //   fail: function(data) {
      //     alert('No!');
      //     alert(data.error);
      //     console.log('Fail!');
      //     if (typeof fail != 'undefined') {
      //       fail(data);
      //     }
      //   }
      // })

      $.ajax({
        //removed the /2 from url.
        url: 'https://api-us.clusterpoint.com//100600/Appointly/_insert',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(send),
        beforeSend: function(xhr) {
          xhr.setRequestHeader('Authorization', 'Basic ' + btoa('bpshonyak@live.com:Password01'));
        },
        success: function(data) {
          if (typeof success != 'undefined') {
            success(data);
          }
          $scope.showAlert();
        },
        fail: function(data) {
          alert('No!');
          alert(data.error);
          console.log('Fail!');
          if (typeof fail != 'undefined') {
            fail(data);
          }
        }
      })

    }
  })
  .controller('MainCtrl', function($http, $scope) {
    $scope.test = 'Scope Works!';

    // $scope.stories = [];
    //
    // $scope.appointments = info;

    // [{
    //   name: 'Green Valley Clinic',
    //   img_p: 'health.png',
    //   date: 'June 30th',
    //   time: 10,
    //   zone: 'am'
    // }, {
    //   name: 'Silver Point Dental',
    //   img_p: 'dental.png',
    //   date: 'July 16th',
    //   time: 2,
    //   zone: 'pm'
    // }, {
    //   name: 'Multicare',
    //   img_p: 'multicare.png',
    //   date: 'July 25th',
    //   time: 4,
    //   zone: 'pm'
    // }];

  });
<|endoftext|>


<commit_before>/**
 * Created by kdban on 3/20/2016.
 */

var $ = require('jquery');
var PointerListener = require('polyball/client/hudbehaviors/PointerListener');
var Logger = require('polyball/shared/Logger');
var Util = require('polyball/shared/Util');

/**
 * @param config
 * @property {Number} config.accumulationInterval - The minimum time spane between successive mouse move registrations.
 * @property {Comms} config.comms - the game client comms module.
 * @property {Model} config.model - the game model.  FOR RENDERERING PURPOSES, not mutation.
 * @property {Synchronizer} config.synchronizer - the game synchronizer for passing mouse movement commands.
 * @constructor
 */
var HUD = function (config) {

    var comms = config.comms;
    var model = config.model;  // jshint ignore: line

    new PointerListener({
        accumulationInterval: config.accumulationInterval,
        synchronizer: config.synchronizer
    }).listenElement(document);

    $.get('hudcomponents/roundTimer.html', function (data) {
        Logger.debug('Injecting round timer.');

        $('#hudColumn').append(data);
    });

    // Inject and listen to queue-to-play button
    $.get('hudcomponents/addToQueueButton.html', function(data) {
        Logger.debug('Injecting add to queue button.');

        $('#hudColumn').append(data);
        $('#addToQueueButton').click(function (){
            comms.queueToPlay();
        });
    });

    $.get('hudcomponents/spectatorList.html', function (data) {
        Logger.debug('Injecting spectator list.');

        $('#hudColumn').append(data);
    });

    $.get('hudcomponents/playerQueue.html', function (data) {
        Logger.debug('Injecting player queue.');

        $('#hudColumn').append(data);
    });

    var appendNameToList = function (listElement) {

        return function (spectatorOrPlayer) {
            if (spectatorOrPlayer == null) {
                return;
            }

            var listItem = $('<li>').text(spectatorOrPlayer.client.name);

            if (spectatorOrPlayer.id === model.getLocalClientID()) {
                var localElement = $('<span>').addClass('localClient').text('  (you)');
                listItem.append(localElement);
            }
            listElement.append(listItem);
        };
    };

    this.render = function () {
        $('.roundTimer').text(Util.millisToCountDown(model.getRoundLength() - model.getCurrentRoundTime()));

        var spectatorList = $('.spectatorList');
        spectatorList.empty();
        model.getSpectators().forEach(appendNameToList(spectatorList));

        var playerQueueList = $('.playerQueue');
        playerQueueList.empty();

        if (model.getAllQueuedPlayers().length === 0) {
            playerQueueList.append(
                $('<li>').addClass('grayed').text('No players queued.')
            );
        }
        model.getAllQueuedPlayers().forEach(appendNameToList(playerQueueList));
    };
};

module.exports = HUD;<commit_msg>render waiting for players at round start.  (still needs to have #214 solved before full closure of #154<commit_after>/**
 * Created by kdban on 3/20/2016.
 */

var $ = require('jquery');
var PointerListener = require('polyball/client/hudbehaviors/PointerListener');
var Logger = require('polyball/shared/Logger');
var EngineStatus = require('polyball/shared/EngineStatus');
var Util = require('polyball/shared/Util');

/**
 * @param config
 * @property {Number} config.accumulationInterval - The minimum time spane between successive mouse move registrations.
 * @property {Comms} config.comms - the game client comms module.
 * @property {Model} config.model - the game model.  FOR RENDERERING PURPOSES, not mutation.
 * @property {Synchronizer} config.synchronizer - the game synchronizer for passing mouse movement commands.
 * @constructor
 */
var HUD = function (config) {

    var comms = config.comms;
    var model = config.model;  // jshint ignore: line

    new PointerListener({
        accumulationInterval: config.accumulationInterval,
        synchronizer: config.synchronizer
    }).listenElement(document);

    $.get('hudcomponents/roundTimer.html', function (data) {
        Logger.debug('Injecting round timer.');

        $('#hudColumn').append(data);
    });

    // Inject and listen to queue-to-play button
    $.get('hudcomponents/addToQueueButton.html', function(data) {
        Logger.debug('Injecting add to queue button.');

        $('#hudColumn').append(data);
        $('#addToQueueButton').click(function (){
            comms.queueToPlay();
        });
    });

    $.get('hudcomponents/spectatorList.html', function (data) {
        Logger.debug('Injecting spectator list.');

        $('#hudColumn').append(data);
    });

    $.get('hudcomponents/playerQueue.html', function (data) {
        Logger.debug('Injecting player queue.');

        $('#hudColumn').append(data);
    });

    $.get('hudcomponents/waitingForPlayers.html', function (data) {
        $('#hudColumn').append(data);
    });

    var appendNameToList = function (listElement) {

        return function (spectatorOrPlayer) {
            if (spectatorOrPlayer == null) {
                return;
            }

            var listItem = $('<li>').text(spectatorOrPlayer.client.name);

            if (spectatorOrPlayer.id === model.getLocalClientID()) {
                var localElement = $('<span>').addClass('localClient').text('  (you)');
                listItem.append(localElement);
            }
            listElement.append(listItem);
        };
    };

    this.render = function () {
        $('.roundTimer').text(Util.millisToCountDown(model.getRoundLength() - model.getCurrentRoundTime()));

        var spectatorList = $('.spectatorList');
        spectatorList.empty();
        model.getSpectators().forEach(appendNameToList(spectatorList));

        var playerQueueList = $('.playerQueue');
        playerQueueList.empty();

        if (model.getAllQueuedPlayers().length === 0) {
            playerQueueList.append(
                $('<li>').addClass('grayed').text('No players queued.')
            );
        }
        model.getAllQueuedPlayers().forEach(appendNameToList(playerQueueList));

        $('.statusMessage').hide();
        if (model.gameStatus === EngineStatus.gameInitializing) {
            $('.waitingForPlayers').show();
        }
    };
};

module.exports = HUD;<|endoftext|>


<commit_before>cordova.define("jp.wizcorp.phonegap.plugin.wizCanvasPlugin", function(require, exports, module) {
/* WizCanvas for cordova - Create a native canvas view.
*
 * @author Ally Ogilvie
 * @copyright Wizcorp Inc. [ Incorporated Wizards ] 2013
 * @file - wizCanvas.js
 * @about - JavaScript cordova bridge for canvas view management
 *
 *
*/

var exec = require("cordova/exec");

function propsToString(obj) {
    // stringify all vars
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            obj[i] = '' + obj[i];
        }
    }
}

var WizCanvas = function (name) {
	this.name = name;
	this.views = {};
};

// View for Cordova
var View = function (name) {
	this.name = name;
}

View.create = function (name, options, success, failure) {
	propsToString(options);
    exec(success, failure, "WizCanvasPlugin", "createView", [name, options]);
};

View.prototype.remove = function (success, failure) {
    exec(success, failure, "WizCanvasPlugin", "removeView", [this.name]);
};

View.prototype.show = function (animOptions, success, failure) {
    exec(success, failure, "WizCanvasPlugin", "showView", [this.name, animOptions]);
};

View.prototype.hide = function (animOptions, success, failure) {
    exec(success, failure, "WizCanvasPlugin", "hideView", [this.name, animOptions]);
};

View.prototype.load = function (source, success, failure) {
    exec(success, failure, "WizCanvasPlugin", "load", [this.name, { src: source }]);
};

View.prototype.setLayout = function (options, success, failure) {
	propsToString(options);
    exec(success, failure, "WizCanvasPlugin", "setLayout", [this.name, options]);
};

WizCanvas.prototype.throwError = function (cb, error) {
    if (cb) {
        cb(error);
    } else {
        throw error;
    }
};

WizCanvas.prototype.create = function (name, options, success, failure) {

	var views = this.views;
	// wrap around the success callback, so we can return a View instance
	function successWrapper() {

		var view = new View(name);
		views[name] = view;

		if (typeof(success) === 'function') {
            success(view);
		}

	}

    propsToString(options);
    View.create(name, options, successWrapper, failure);
};

WizCanvas.prototype.remove = function (name, success, failure) {
    this.views[name].remove(success, failure);
};

WizCanvas.prototype.show = function (name, animOptions, success, failure) {
    this.views[name].show(animOptions, success, failure);
};

WizCanvas.prototype.hide = function (name, animOptions, success, failure) {
    this.views[name].hide(animOptions, success, failure);
};

WizCanvas.prototype.load = function (name, source, success, failure) {
    this.views[name].load(source, success, failure);
};

WizCanvas.prototype.setLayout = function (name, options, success, failure) {
	propsToString(options);
    this.views[name].setLayout(options, success, failure);
};

WizCanvas.prototype.updateViewList = function (list) {

	// check for removed views
	for (var name in this.views) {
		if (list.indexOf(name) === -1) {
			delete this.views[name];
		}
	}

	// check for new views
	for (var i = 0; i < list.length; i++) {
		var name = list[i];

		if (!this.views[name]) {
			this.views[name] = new View(name);
		}
	}

};

// instantiate wizCanvas (passing "mainView" which is Cordova's window)
window.wizCanvas = new WizCanvas('mainView');
module.exports = wizCanvas;

var WizCanvasMessenger = function () {};

WizCanvasMessenger.prototype.postMessage = function (message, targetView) {
	// for more information on the MessageEvent API, see:
	// http://www.w3.org/TR/2008/WD-html5-20080610/comms.HTMLElement

	// wizPostMessage://origin?target?data

	// Check message type
    var type;
    if (Object.prototype.toString.call(message) === "[object Array]") {
        type = "Array";
        message = JSON.stringify(message);
    } else if (Object.prototype.toString.call(message) === "[object String]") {
        type = "String";
    } else if (Object.prototype.toString.call(message) === "[object Number]") {
        type = "Number";
        message = JSON.stringify(message);
    } else if (Object.prototype.toString.call(message) === "[object Boolean]") {
        type = "Boolean";
        message = message.toString();
    } else if (Object.prototype.toString.call(message) === "[object Function]") {
        type = "Function";
        message = message.toString();
    } else if (Object.prototype.toString.call(message) === "[object Object]") {
        type = "Object";
        message = JSON.stringify(message);
    } else {
    	console.error("WizCanvasMessenger posted unknown type!");
        return;
    }

	var iframe = document.createElement('IFRAME');
	iframe.setAttribute('src', 'wizPostMessage://'+ window.encodeURIComponent(window.name) + '?' + window.encodeURIComponent(targetView) + '?' + window.encodeURIComponent(message) + '?' + type );
	document.documentElement.appendChild(iframe);
	iframe.parentNode.removeChild(iframe);
	iframe = null;
};

WizCanvasMessenger.prototype.__triggerMessageEvent = function (origin, target, data, type) {
	// Trigger message event
	// Check message type
    if (type === "Array") {
        data = JSON.parse(data);
    } else if (type === "String") {
        // Stringy String String
    } else if (type === "Number") {
        data = JSON.parse(data);
    } else if (type === "Boolean") {
        data = Boolean(data);
    } else if (type === "Function") {
        // W3C says nothing about functions, will be returned as string.
    } else if (type === "Object") {
        data = JSON.parse(data);
    } else {
    	console.error("Message Event received unknown type!");
        return;
    }

	var event = document.createEvent("HTMLEvents");
	event.initEvent("message", true, true);
	event.eventName = "message";
	event.memo = { };
	event.origin = origin;
	event.source = target;
	event.data = data;
	dispatchEvent(event);
};

window.wizCanvasMessenger = new WizCanvasMessenger();

});<commit_msg>Updated JS file of wizCanvas example project.<commit_after>cordova.define("jp.wizcorp.phonegap.plugin.wizCanvasPlugin", function(require, exports, module) {/* WizCanvas for cordova - Create a native canvas view.
*
 * @author Ally Ogilvie
 * @copyright Wizcorp Inc. [ Incorporated Wizards ] 2013
 * @file - wizCanvas.js
 * @about - JavaScript cordova bridge for canvas view management
 *
 *
*/

var exec = require("cordova/exec");

function propsToString(obj) {
    // stringify all vars
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            obj[i] = '' + obj[i];
        }
    }
}

var WizCanvas = function (name) {
	this.name = name;
	this.views = {};
};

// View for Cordova
var View = function (name) {
	this.name = name;
};

View.create = function (name, options, success, failure) {
	propsToString(options);
    exec(success, failure, "WizCanvasPlugin", "createView", [name, options]);
};

View.prototype.remove = function (success, failure) {
    exec(success, failure, "WizCanvasPlugin", "removeView", [this.name]);
};

View.prototype.show = function (animOptions, success, failure) {
    exec(success, failure, "WizCanvasPlugin", "showView", [this.name, animOptions]);
};

View.prototype.hide = function (animOptions, success, failure) {
    exec(success, failure, "WizCanvasPlugin", "hideView", [this.name, animOptions]);
};

View.prototype.load = function (source, success, failure) {
    exec(success, failure, "WizCanvasPlugin", "load", [this.name, { src: source }]);
};

View.prototype.setLayout = function (options, success, failure) {
	propsToString(options);
    exec(success, failure, "WizCanvasPlugin", "setLayout", [this.name, options]);
};

WizCanvas.prototype.throwError = function (cb, error) {
    if (cb) {
        cb(error);
    } else {
        throw error;
    }
};

WizCanvas.prototype.create = function (name, options, success, failure) {

	var views = this.views;
	// wrap around the success callback, so we can return a View instance
	function successWrapper() {

		var view = new View(name);
		views[name] = view;

		if (typeof(success) === 'function') {
            success(view);
		}

	}

    propsToString(options);
    View.create(name, options, successWrapper, failure);
};

WizCanvas.prototype.remove = function (name, success, failure) {
    this.views[name].remove(success, failure);
};

WizCanvas.prototype.show = function (name, animOptions, success, failure) {
    this.views[name].show(animOptions, success, failure);
};

WizCanvas.prototype.hide = function (name, animOptions, success, failure) {
    this.views[name].hide(animOptions, success, failure);
};

WizCanvas.prototype.load = function (name, source, success, failure) {
    this.views[name].load(source, success, failure);
};

WizCanvas.prototype.setLayout = function (name, options, success, failure) {
	propsToString(options);
    this.views[name].setLayout(options, success, failure);
};

WizCanvas.prototype.updateViewList = function (list) {

	// check for removed views
	for (var name in this.views) {
		if (list.indexOf(name) === -1) {
			delete this.views[name];
		}
	}

	// check for new views
	for (var i = 0; i < list.length; i++) {
		name = list[i];

		if (!this.views[name]) {
			this.views[name] = new View(name);
		}
	}

};

// instantiate wizCanvas (passing "mainView" which is Cordova's window)
window.wizCanvas = new WizCanvas('mainView');
module.exports = wizCanvas;

var WizCanvasMessenger = function () {};

WizCanvasMessenger.prototype.postMessage = function (message, targetView) {
	// for more information on the MessageEvent API, see:
	// http://www.w3.org/TR/2008/WD-html5-20080610/comms.HTMLElement

	// wizPostMessage://origin?target?data

	// Check message type
    var type;
    if (Object.prototype.toString.call(message) === "[object Array]") {
        type = "Array";
        message = JSON.stringify(message);
    } else if (Object.prototype.toString.call(message) === "[object String]") {
        type = "String";
    } else if (Object.prototype.toString.call(message) === "[object Number]") {
        type = "Number";
        message = JSON.stringify(message);
    } else if (Object.prototype.toString.call(message) === "[object Boolean]") {
        type = "Boolean";
        message = message.toString();
    } else if (Object.prototype.toString.call(message) === "[object Function]") {
        type = "Function";
        message = message.toString();
    } else if (Object.prototype.toString.call(message) === "[object Object]") {
        type = "Object";
        message = JSON.stringify(message);
    } else {
        console.error("WizCanvasMessenger posted unknown type!");
        return;
    }

	var iframe = document.createElement('IFRAME');
	iframe.setAttribute('src', 'wizPostMessage://'+ window.encodeURIComponent(window.name) + '?' + window.encodeURIComponent(targetView) + '?' + window.encodeURIComponent(message) + '?' + type );
	// In case of heavy load or multiple views add a setTimeout
	setTimeout(function () {
        document.documentElement.appendChild(iframe);
        iframe.parentNode.removeChild(iframe);
        iframe = null;
	}, 1);

};

WizCanvasMessenger.prototype.__triggerMessageEvent = function (origin, target, data, type) {
	// Trigger message event
	// Check message type
    if (type === "Array") {
        data = JSON.parse(data);
    } else if (type === "String") {
        // Stringy String String
    } else if (type === "Number") {
        data = JSON.parse(data);
    } else if (type === "Boolean") {
        data = Boolean(data);
    } else if (type === "Function") {
        // W3C says nothing about functions, will be returned as string.
    } else if (type === "Object") {
        data = JSON.parse(data);
    } else {
        console.error("Message Event received unknown type!");
        return;
    }

	var event = document.createEvent("HTMLEvents");
	event.initEvent("message", true, true);
	event.eventName = "message";
	event.memo = { };
	event.origin = origin;
	event.source = target;
	event.data = data;
	dispatchEvent(event);
};

window.wizCanvasMessenger = new WizCanvasMessenger();});
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", // declare
	"dojo/mouse",
	"dojo/on",
	"dojo/touch",
	"./_ListBase"
], function(declare, mouse, on, touch, _ListBase){

// module:
//		dijit/form/_ListMouseMixin

return declare( "dijit.form._ListMouseMixin", _ListBase, {
	// summary:
	//		a Mixin to handle mouse or touch events for a focus-less menu
	//		Abstract methods that must be defined externally:
	//
	//		- onClick: item was chosen (mousedown somewhere on the menu and mouseup somewhere on the menu)
	// tags:
	//		private

	postCreate: function(){
		this.inherited(arguments);

		this.own(on(this.domNode, touch.press, function(evt){ evt.preventDefault(); })); // prevent focus shift on list scrollbar press

		this._listConnect(touch.press, "_onMouseDown");
		this._listConnect(touch.release, "_onMouseUp");
		this._listConnect(mouse.enter, "_onMouseOver");
		this._listConnect(mouse.leave, "_onMouseOut");
	},

	_onMouseDown: function(/*Event*/ evt, /*DomNode*/ target){
		if(this._hoveredNode){
			this.onUnhover(this._hoveredNode);
			this._hoveredNode = null;
		}
		this._isDragging = true;
		this._setSelectedAttr(target);
	},

	_onMouseUp: function(/*Event*/ evt, /*DomNode*/ target){
		this._isDragging = false;
		var selectedNode = this.selected;
		var hoveredNode = this._hoveredNode;
		if(selectedNode && target == selectedNode){
			this.onClick(selectedNode);
		}else if(hoveredNode && target == hoveredNode){ // drag to select
			this._setSelectedAttr(hoveredNode);
			this.onClick(hoveredNode);
		}
	},

	_onMouseOut: function(/*Event*/ evt, /*DomNode*/ target){
		if(this._hoveredNode){
			this.onUnhover(this._hoveredNode);
			this._hoveredNode = null;
		}
		if(this._isDragging){
			this._cancelDrag = (new Date()).getTime() + 1000; // cancel in 1 second if no _onMouseOver fires
		}
	},

	_onMouseOver: function(/*Event*/ evt, /*DomNode*/ target){
		if(this._cancelDrag){
			var time = (new Date()).getTime();
			if(time > this._cancelDrag){
				this._isDragging = false;
			}
			this._cancelDrag = null;
		}
		this._hoveredNode = target;
		this.onHover(target);
		if(this._isDragging){
			this._setSelectedAttr(target);
		}
	}
});

});
<commit_msg>Fixes #16730.  Have ComboBoxMenu trap mouse events and not touch events so that touch scrolling works.  Monitor click events and collapse redundant faux and real click events.<commit_after>define([
	"dojo/_base/declare", // declare
	"dojo/mouse",
	"dojo/on",
	"dojo/touch",
	"./_ListBase"
], function(declare, mouse, on, touch, _ListBase){

// module:
//		dijit/form/_ListMouseMixin

return declare( "dijit.form._ListMouseMixin", _ListBase, {
	// summary:
	//		a Mixin to handle mouse or touch events for a focus-less menu
	//		Abstract methods that must be defined externally:
	//
	//		- onClick: item was chosen (mousedown somewhere on the menu and mouseup somewhere on the menu)
	// tags:
	//		private

	postCreate: function(){
		this.inherited(arguments);

		this.own(on(this.domNode, "mousedown", function(evt){ evt.preventDefault(); })); // prevent focus shift on list scrollbar press
		this._listConnect("click", "_onClick");
		this._listConnect("mousedown", "_onMouseDown");
		this._listConnect("mouseup", "_onMouseUp");
		this._listConnect("mouseover", "_onMouseOver");
		this._listConnect("mouseout", "_onMouseOut");
	},

	_onClick: function(/*Event*/ evt, /*DomNode*/ target){
		this._setSelectedAttr(target);
		if(this._deferredClick){
			this._deferredClick.remove();
		}
		this._deferredClick = this.defer(function(){
			this._deferredClick = null;
			this.onClick(target);
		});
	},

	_onMouseDown: function(/*Event*/ evt, /*DomNode*/ target){
		if(this._hoveredNode){
			this.onUnhover(this._hoveredNode);
			this._hoveredNode = null;
		}
		this._isDragging = true;
		this._setSelectedAttr(target);
	},

	_onMouseUp: function(/*Event*/ evt, /*DomNode*/ target){
		this._isDragging = false;
		var selectedNode = this.selected;
		var hoveredNode = this._hoveredNode;
		if(selectedNode && target == selectedNode){
			this.defer(function(){ this._onClick(evt, selectedNode); });
		}else if(hoveredNode){ // drag to select
			this.defer(function(){ this._onClick(evt, hoveredNode); });
		}
	},

	_onMouseOut: function(/*Event*/ evt, /*DomNode*/ target){
		if(this._hoveredNode){
			this.onUnhover(this._hoveredNode);
			this._hoveredNode = null;
		}
		if(this._isDragging){
			this._cancelDrag = (new Date()).getTime() + 1000; // cancel in 1 second if no _onMouseOver fires
		}
	},

	_onMouseOver: function(/*Event*/ evt, /*DomNode*/ target){
		if(this._cancelDrag){
			var time = (new Date()).getTime();
			if(time > this._cancelDrag){
				this._isDragging = false;
			}
			this._cancelDrag = null;
		}
		this._hoveredNode = target;
		this.onHover(target);
		if(this._isDragging){
			this._setSelectedAttr(target);
		}
	}
});

});
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import RaisedButton from 'dist/RaisedButton';
import Popup from 'dist/Popup';

import 'sass/containers/app/modules/popup/PopupExamples.scss';

export default class PopupExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            popupVisible: false,
            triggerEl: null
        };

        this.togglePopup = this::this.togglePopup;
        this.closePopup = this::this.closePopup;

    }

    togglePopup(e) {

        // e.stopPropagation();

        this.setState({
            popupVisible: !this.state.popupVisible,
            triggerEl: e.currentTarget
        });

    }

    closePopup() {
        this.setState({
            popupVisible: false
        });
    }

    render() {

        const {popupVisible, triggerEl} = this.state;

        return (

Popup

                            <RaisedButton value="Toggle Popup"
                                          onTouchTap={this.togglePopup}/>

                            <Popup visible={popupVisible}
                                   triggerEl={triggerEl}
                                   onRequestClose={this.closePopup}>
                                123
                            </Popup>

        );
    }
};<commit_msg>update<commit_after>import React, {Component} from 'react';

import RaisedButton from 'dist/RaisedButton';
import Popup from 'dist/Popup';
import List from 'dist/List';

import 'sass/containers/app/modules/popup/PopupExamples.scss';

export default class PopupExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            popupVisible: false,
            triggerEl: null
        };

        this.togglePopup = this::this.togglePopup;
        this.closePopup = this::this.closePopup;

    }

    togglePopup(e) {

        // e.stopPropagation();

        this.setState({
            popupVisible: !this.state.popupVisible,
            triggerEl: e.currentTarget
        });

    }

    closePopup() {
        this.setState({
            popupVisible: false
        });
    }

    render() {

        const {popupVisible, triggerEl} = this.state;

        return (

Popup

                            <RaisedButton value="Toggle Popup"
                                          onTouchTap={this.togglePopup}/>

                            <Popup visible={popupVisible}
                                   triggerEl={triggerEl}
                                   onRequestClose={this.closePopup}>
                                <List items={[{
                                    iconCls: 'fa fa-facebook',
                                    value: 'Facebook'
                                }, {
                                    iconCls: 'fa fa-twitter',
                                    value: 'Twitter'
                                }, {
                                    iconCls: 'fa fa-google-plus',
                                    value: 'Google+'
                                }]}/>
                            </Popup>

        );
    }
};<|endoftext|>


<commit_before>import Orbit from 'orbit/core';

var Queue = function() {
  this.queue = [];
  this.processing = false;
};

Queue.prototype = {
  constructor: Queue,

  push: function(fn, binding) {
    var _this = this;

    binding = binding || this;

    if (this.processing) {
      debugger;
      var response = new Orbit.Promise(function(resolve) {
        _this.queue.push(function() {
          resolve(fn.call(binding));
        });
      });

      _this.process();

    } else {
      return fn.call(binding);
    }

    return response;
  },

  process: function() {
    if (!this.processing) {
      var _this = this;

      var settleEach = function() {
        if (_this.queue.length === 0) {
          _this.processing = false;

        } else {
          var fn = _this.queue.shift();
          var response = fn.call(_this);

          if (response) {
            return response.then(
              function(success) {
                settleEach();
              },
              function(error) {
                settleEach();
              }
            );
          } else {
            settleEach();
          }
        }
      };

      settleEach();
    }
  }
};

export default Queue;<commit_msg>Introduce `autoProcess` flag<commit_after>import Orbit from 'orbit/core';

var Queue = function() {
  this.queue = [];
  this.processing = false;
  this.autoProcess = true;
};

Queue.prototype = {
  constructor: Queue,

  push: function(fn, binding) {
    var _this = this;

    binding = binding || this;

    var response = new Orbit.Promise(function(resolve) {
      _this.queue.push(function() {
        resolve(fn.call(binding));
      });
    });

    if (this.autoProcess) this.process();

    return response;
  },

  process: function() {
    if (!this.processing) {
      var _this = this;

      var settleEach = function() {
        if (_this.queue.length === 0) {
          _this.processing = false;

        } else {
          var fn = _this.queue.shift();
          var response = fn.call(_this);

          if (response) {
            return response.then(
              function(success) {
                settleEach();
              },
              function(error) {
                settleEach();
              }
            );
          } else {
            settleEach();
          }
        }
      };

      settleEach();
    }
  }
};

export default Queue;<|endoftext|>