<commit_before>var cp = require('child_process');
var util = require('util');
var os = require('os');
var fs = require('fs');
var fse = require('fs-extra2');
var config = require('../lib/config');
var colors = require('colors/safe');
var path = require('path');
/*eslint no-console: "off"*/
var CHECK_RUNNING_CMD = process.platform === 'win32' ?
  'tasklist /fi "PID eq %s" | findstr /i "node.exe"'
  : 'ps -f -p %s | grep "node"';
var isWin = process.platform === 'win32';

function isRunning(pid, callback) {
  pid ? cp.exec(util.format(CHECK_RUNNING_CMD, pid),
    function (err, stdout, stderr) {
      callback(!err && !!stdout.toString().trim());
    }) : callback();
}

exports.isRunning = isRunning;

function getIpList() {
  var ipList = [];
  var ifaces = os.networkInterfaces();
  Object.keys(ifaces).forEach(function(ifname) {
    ifaces[ifname].forEach(function (iface) {
      if (iface.family == 'IPv4') {
        ipList.push(iface.address);
      }
    });
  });
  var index = ipList.indexOf('127.0.0.1');
  if (index !== -1) {
    ipList.splice(index, 1);
  }
  ipList.unshift('127.0.0.1');
  return ipList;
}

function error(msg) {
  console.log(colors.red(msg));
}

function warn(msg) {
  console.log(colors.yellow(msg));
}

function info(msg) {
  console.log(colors.green(msg));
}
exports.error = error;
exports.warn = warn;
exports.info = info;

function showKillError() {
  error('[!] Cannot kill ' + config.name + ' owned by root');
  info('[i] Try to run command ' + (isWin ? 'as an administrator' : 'with `sudo`'));
}

exports.showKillError = showKillError;

function showUsage(isRunning, options, restart) {
  options = formatOptions(options);
  if (isRunning) {
    if (restart) {
      showKillError();
    } else {
      warn('[!] ' + config.name + '@' + config.version + ' is running');
    }
  } else {
    info('[i] ' + config.name + '@' + config.version + (restart ? ' restarted' : ' started'));
  }
  var port = /^\d+$/.test(options.port) && options.port > 0 ?  options.port : config.port;
  var list = options.host ? [options.host] : getIpList();
  info('[i] 1. use your device to visit the following URL list, gets the ' + colors.bold('IP') + ' of the URL you can access:');
  info(list.map(function(ip) {
    return '       http://' + colors.bold(ip) + (port ? ':' + port : '') + '/';
  }).join('\n'));

  warn('       Note: If all the above URLs are unable to access, check the firewall settings');
  warn('             For help see ' + colors.bold('https://github.com/avwo/whistle'));
  info('[i] 2. configure your device to use ' + config.name + ' as its HTTP and HTTPS proxy on ' + colors.bold('IP:') + port);
  info('[i] 3. use ' + colors.bold('Chrome') + ' to visit ' + colors.bold('http://' + (options.localUIHost || config.localUIHost) + '/') + ' to get started');

  if (parseInt(process.version.slice(1), 10) < 6) {
    warn(colors.bold('\nWarning: The current Node version is too low, access https://nodejs.org to install the latest version, or may not be able to Capture HTTPS CONNECTs\n'));
  }
}

exports.showUsage = showUsage;

function getDataDir() {
  return path.resolve(config.getHomedir(), '.startingAppData');
}

function formatOptions(options) {
  if (!options || !/^(?:([\w.-]+):)?([1-9]\d{0,4})$/.test(options.port)) {
    return options;
  }
  options.host = options.host || RegExp.$1;
  options.port = parseInt(RegExp.$2, 10);
  return options;
}

exports.formatOptions = formatOptions;

function readConfig(storage) {
  var dataDir = getDataDir();
  var configFile = path.join(dataDir, encodeURIComponent('#' + (storage ? storage + '#' : '')));
  if (!fs.existsSync(configFile)) {
    return;
  }
  try {
    var conf = fse.readJsonSync(configFile);
    conf && formatOptions(conf.options);
    return conf;
  } catch(e) {}
}

function readConfigList() {
  var dataDir = getDataDir();
  var result = [];
  try {
    fs.readdirSync(dataDir).forEach(function(dir) {
      try {
        dir = decodeURIComponent(dir);
        var lastIndex = dir.length - 1;
        if (dir[0] === '#' && dir[lastIndex] === '#') {
          dir = dir.substring(1, lastIndex || 1);
          var config = readConfig(dir);
          if (config && config.pid && config.options) {
            result.push(config);
          }
        }
      } catch(e) {}
    });
  } catch(e) {}
  return result;
}

exports.readConfig = readConfig;
exports.readConfigList = readConfigList;<commit_msg>chore: refine wording<commit_after>var cp = require('child_process');
var util = require('util');
var os = require('os');
var fs = require('fs');
var fse = require('fs-extra2');
var config = require('../lib/config');
var colors = require('colors/safe');
var path = require('path');
/*eslint no-console: "off"*/
var CHECK_RUNNING_CMD = process.platform === 'win32' ?
  'tasklist /fi "PID eq %s" | findstr /i "node.exe"'
  : 'ps -f -p %s | grep "node"';
var isWin = process.platform === 'win32';

function isRunning(pid, callback) {
  pid ? cp.exec(util.format(CHECK_RUNNING_CMD, pid),
    function (err, stdout, stderr) {
      callback(!err && !!stdout.toString().trim());
    }) : callback();
}

exports.isRunning = isRunning;

function getIpList() {
  var ipList = [];
  var ifaces = os.networkInterfaces();
  Object.keys(ifaces).forEach(function(ifname) {
    ifaces[ifname].forEach(function (iface) {
      if (iface.family == 'IPv4') {
        ipList.push(iface.address);
      }
    });
  });
  var index = ipList.indexOf('127.0.0.1');
  if (index !== -1) {
    ipList.splice(index, 1);
  }
  ipList.unshift('127.0.0.1');
  return ipList;
}

function error(msg) {
  console.log(colors.red(msg));
}

function warn(msg) {
  console.log(colors.yellow(msg));
}

function info(msg) {
  console.log(colors.green(msg));
}
exports.error = error;
exports.warn = warn;
exports.info = info;

function showKillError() {
  error('[!] Cannot kill ' + config.name + ' owned by root');
  info('[i] Try to run command ' + (isWin ? 'as an administrator' : 'with `sudo`'));
}

exports.showKillError = showKillError;

function showUsage(isRunning, options, restart) {
  options = formatOptions(options);
  if (isRunning) {
    if (restart) {
      showKillError();
    } else {
      warn('[!] ' + config.name + '@' + config.version + ' is running');
    }
  } else {
    info('[i] ' + config.name + '@' + config.version + (restart ? ' restarted' : ' started'));
  }
  var port = /^\d+$/.test(options.port) && options.port > 0 ?  options.port : config.port;
  var list = options.host ? [options.host] : getIpList();
  info('[i] 1. use your device to visit the following URL list, gets the ' + colors.bold('IP') + ' of the URL you can access:');
  info(list.map(function(ip) {
    return '       http://' + colors.bold(ip) + (port ? ':' + port : '') + '/';
  }).join('\n'));

  warn('       Note: If all the above URLs are unable to access, check the firewall settings');
  warn('             For help see ' + colors.bold('https://github.com/avwo/whistle'));
  info('[i] 2. set the HTTP proxy on your device with ' + colors.bold((list.length === 1 ? 'IP(' + list[0] + ')' : 'the above IP') + ' & PORT(' + port + ')'));
  info('[i] 3. use ' + colors.bold('Chrome') + ' to visit ' + colors.bold('http://' + (options.localUIHost || config.localUIHost) + '/') + ' to get started');

  if (parseInt(process.version.slice(1), 10) < 6) {
    warn(colors.bold('\nWarning: The current Node version is too low, access https://nodejs.org to install the latest version, or may not be able to Capture HTTPS CONNECTs\n'));
  }
}

exports.showUsage = showUsage;

function getDataDir() {
  return path.resolve(config.getHomedir(), '.startingAppData');
}

function formatOptions(options) {
  if (!options || !/^(?:([\w.-]+):)?([1-9]\d{0,4})$/.test(options.port)) {
    return options;
  }
  options.host = options.host || RegExp.$1;
  options.port = parseInt(RegExp.$2, 10);
  return options;
}

exports.formatOptions = formatOptions;

function readConfig(storage) {
  var dataDir = getDataDir();
  var configFile = path.join(dataDir, encodeURIComponent('#' + (storage ? storage + '#' : '')));
  if (!fs.existsSync(configFile)) {
    return;
  }
  try {
    var conf = fse.readJsonSync(configFile);
    conf && formatOptions(conf.options);
    return conf;
  } catch(e) {}
}

function readConfigList() {
  var dataDir = getDataDir();
  var result = [];
  try {
    fs.readdirSync(dataDir).forEach(function(dir) {
      try {
        dir = decodeURIComponent(dir);
        var lastIndex = dir.length - 1;
        if (dir[0] === '#' && dir[lastIndex] === '#') {
          dir = dir.substring(1, lastIndex || 1);
          var config = readConfig(dir);
          if (config && config.pid && config.options) {
            result.push(config);
          }
        }
      } catch(e) {}
    });
  } catch(e) {}
  return result;
}

exports.readConfig = readConfig;
exports.readConfigList = readConfigList;<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , join = path.join
  , dirname = path.dirname
  , exists = fs.existsSync || path.existsSync
  , arrow = process.platform == 'win32' ? '-' : '\u21B3'
  , defaults = {
        compiled: 'compiled'
      , platform: process.platform
      , arch: process.arch
      , version: parseVersion(process.versions.node)
      , bindings: 'bindings.node'
      , try: [
          // Debug files, for development
          [ 'module_root', 'out', 'Debug', 'bindings' ]
        , [ 'module_root', 'Debug', 'bindings' ]
          // Release files, but manually compiled
        , [ 'module_root', 'out', 'Release', 'bindings' ]
        , [ 'module_root', 'Release', 'bindings' ]
          // Production "Release" buildtype binary
        , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
          // Legacy from node-waf, node <= 0.4.x
        , [ 'module_root', 'build', 'Release', 'bindings' ]
        , [ 'module_root', 'build', 'default', 'bindings' ]
        ]
    }

/**
 * The main `bindings()` function loads the compiled bindings for a given module.
 * It uses V8's Error API to determine the parent filename that this function is
 * being invoked from, which is then used to find the root directory.
 */

function bindings (opts) {

  // Argument surgery
  if (typeof opts == 'string') {
    opts = { bindings: opts }
  } else if (!opts) {
    opts = {}
  }
  opts.__proto__ = defaults

  // Get the module root
  opts.module_root = exports.getRoot(exports.getFileName())

  // Ensure the given bindings name ends with .node
  if (path.extname(opts.bindings) != '.node') {
    opts.bindings += '.node'
  }

  var tries = []
    , i = 0
    , l = opts.try.length
    , n

  for (; i<l; i++) {
    n = join.apply(null, opts.try[i].map(function (p) {
      return opts[p] || p
    }))
    tries.push(n)
    try {
      var b = require(n)
      b.path = n
      return b
    } catch (e) {
      if (!/not find/i.test(e.message)) {
        throw e
      }
    }
  }

  var err = new Error('Could not load the bindings file. Tried:\n'
    + tries.map(function (a) { return ' ' + arrow + '  ' + a }).join('\n'))
  err.tries = tries
  throw err
}
module.exports = exports = bindings

/**
 * Gets the filename of the JavaScript file that invokes this function.
 * Used to help find the root directory of a module.
 */

exports.getFileName = function getFileName () {
  var origPST = Error.prepareStackTrace
    , dummy = {}
    , fileName

  Error.prepareStackTrace = function (e, st) {
    for (var i=0, l=st.length; i<l; i++) {
      fileName = st[i].getFileName()
      if (fileName !== __filename) {
        return
      }
    }
  }

  // run the 'prepareStackTrace' function above
  Error.captureStackTrace(dummy)
  dummy.stack

  // cleanup
  Error.prepareStackTrace = origPST

  return fileName
}

/**
 * Gets the root directory of a module, given an arbitrary filename
 * somewhere in the module tree. The "root directory" is the directory
 * containing the `package.json` file.
 *
 *   In:  /home/nate/node-native-module/lib/index.js
 *   Out: /home/nate/node-native-module
 */

exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    if (exists(join(dir, 'package.json'))) {
      // Found the 'package.json', we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: ' + file)
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}

/**
 * Accepts a String like "v0.10.4" and returns a String
 * containing the major and minor versions ("0.10").
 */

function parseVersion (str) {
  var m = String(str).match(/(\d+)\.(\d+)/)
  return m ? m[0] : null
}
exports.parseVersion = parseVersion
<commit_msg>Note that a `package.json` file is required if one is not found.<commit_after>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , join = path.join
  , dirname = path.dirname
  , exists = fs.existsSync || path.existsSync
  , arrow = process.platform == 'win32' ? '-' : '\u21B3'
  , defaults = {
        compiled: 'compiled'
      , platform: process.platform
      , arch: process.arch
      , version: parseVersion(process.versions.node)
      , bindings: 'bindings.node'
      , try: [
          // Debug files, for development
          [ 'module_root', 'out', 'Debug', 'bindings' ]
        , [ 'module_root', 'Debug', 'bindings' ]
          // Release files, but manually compiled
        , [ 'module_root', 'out', 'Release', 'bindings' ]
        , [ 'module_root', 'Release', 'bindings' ]
          // Production "Release" buildtype binary
        , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
          // Legacy from node-waf, node <= 0.4.x
        , [ 'module_root', 'build', 'Release', 'bindings' ]
        , [ 'module_root', 'build', 'default', 'bindings' ]
        ]
    }

/**
 * The main `bindings()` function loads the compiled bindings for a given module.
 * It uses V8's Error API to determine the parent filename that this function is
 * being invoked from, which is then used to find the root directory.
 */

function bindings (opts) {

  // Argument surgery
  if (typeof opts == 'string') {
    opts = { bindings: opts }
  } else if (!opts) {
    opts = {}
  }
  opts.__proto__ = defaults

  // Get the module root
  opts.module_root = exports.getRoot(exports.getFileName())

  // Ensure the given bindings name ends with .node
  if (path.extname(opts.bindings) != '.node') {
    opts.bindings += '.node'
  }

  var tries = []
    , i = 0
    , l = opts.try.length
    , n

  for (; i<l; i++) {
    n = join.apply(null, opts.try[i].map(function (p) {
      return opts[p] || p
    }))
    tries.push(n)
    try {
      var b = require(n)
      b.path = n
      return b
    } catch (e) {
      if (!/not find/i.test(e.message)) {
        throw e
      }
    }
  }

  var err = new Error('Could not load the bindings file. Tried:\n'
    + tries.map(function (a) { return ' ' + arrow + '  ' + a }).join('\n'))
  err.tries = tries
  throw err
}
module.exports = exports = bindings

/**
 * Gets the filename of the JavaScript file that invokes this function.
 * Used to help find the root directory of a module.
 */

exports.getFileName = function getFileName () {
  var origPST = Error.prepareStackTrace
    , dummy = {}
    , fileName

  Error.prepareStackTrace = function (e, st) {
    for (var i=0, l=st.length; i<l; i++) {
      fileName = st[i].getFileName()
      if (fileName !== __filename) {
        return
      }
    }
  }

  // run the 'prepareStackTrace' function above
  Error.captureStackTrace(dummy)
  dummy.stack

  // cleanup
  Error.prepareStackTrace = origPST

  return fileName
}

/**
 * Gets the root directory of a module, given an arbitrary filename
 * somewhere in the module tree. The "root directory" is the directory
 * containing the `package.json` file.
 *
 *   In:  /home/nate/node-native-module/lib/index.js
 *   Out: /home/nate/node-native-module
 */

exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    if (exists(join(dir, 'package.json'))) {
      // Found the 'package.json', we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: "' + file
                    + '". Do you have a `package.json` file? ')
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}

/**
 * Accepts a String like "v0.10.4" and returns a String
 * containing the major and minor versions ("0.10").
 */

function parseVersion (str) {
  var m = String(str).match(/(\d+)\.(\d+)/)
  return m ? m[0] : null
}
exports.parseVersion = parseVersion
<|endoftext|>


<commit_before>import DiffMatchPatch from 'diff-match-patch';
import TextPositionAnchor from 'dom-anchor-text-position'
import seek from 'dom-seek'

export default class TextQuoteAnchor {
  constructor(exact, context = {}) {
    if (exact === undefined) {
      throw new Error('missing required parameter "exact"');
    }
    this.exact = exact;
    this.prefix = context.prefix;
    this.suffix = context.suffix;
  }

  static fromRange(range) {
    if (range === undefined) {
      throw new Error('missing required parameter "range"');
    }

    let root = global.document.body;

    let {start, end} = TextPositionAnchor.fromRange(range);
    let exact = root.textContent.substr(start, end - start);

    let prefixStart = Math.max(0, start - 32);
    let prefix = root.textContent.substr(prefixStart, start - prefixStart);

    let suffixEnd = Math.min(root.textContent.length, end + 32);
    let suffix = root.textContent.substr(end, suffixEnd - end);

    return new TextQuoteAnchor(exact, {prefix, suffix});
  }

  static fromSelector(selector) {
    if (selector === undefined) {
      throw new Error('missing required parameter "selector"');
    }
    let {exact, prefix, suffix} = selector;
    return new TextQuoteSelector(exact, {prefix, suffix});
  }

  toRange() {
    return this.toPositionAnchor().toRange();
  }

  toSelector() {
    let selector = {
      type: 'TextQuoteSelector',
      exact: this.exact,
    };
    if (this.prefix !== undefined) selector.prefix = this.prefix;
    if (this.suffix !== undefined) selector.suffix = this.suffix;
    return selector;
  }

  toPositionAnchor() {
    let root = global.document.body;
    let dmp = new DiffMatchPatch();

    dmp.Match_Distance = root.textContent.length * 2;

    let foldSlices = (acc, slice) => {
      let result = dmp.match_main(root.textContent, slice, acc.loc);
      if (result === -1) {
        throw new Error('no match found');
      }
      acc.loc = result + slice.length;
      acc.start = Math.min(acc.start, result);
      acc.end = Math.max(acc.end, result + slice.length);
      return acc;
    };

    let slices = this.exact.match(/(.|[\r\n]){1,32}/g);
    let loc = root.textContent.length / 2;
    let start = -1;
    let end = -1;

    if (this.prefix !== undefined) {
      let result = dmp.match_main(root.textContent, this.prefix, loc);
      if (result > -1) loc = end = start = result + this.prefix.length;
    }

    if (start === -1) {
      let firstSlice = slices.shift();
      result = dmp.match_main(root.textContent, firstSlice, loc);
      if (result > -1) {
        start = result;
        loc = end = start + firstSlice.length;
      } else {
        throw new Error('no match found');
      }
    }

    dmp.Match_Distance = 64;
    let acc = slices.reduce(foldSlices, {
      start: start,
      end: end,
      loc: loc,
    });

    return new TextPositionAnchor(acc.start, acc.end);
  }
}
<commit_msg>Expose fromPositionAnchor<commit_after>import DiffMatchPatch from 'diff-match-patch';
import TextPositionAnchor from 'dom-anchor-text-position'
import seek from 'dom-seek'

export default class TextQuoteAnchor {
  constructor(exact, context = {}) {
    if (exact === undefined) {
      throw new Error('missing required parameter "exact"');
    }
    this.exact = exact;
    this.prefix = context.prefix;
    this.suffix = context.suffix;
  }

  static fromRange(range) {
    if (range === undefined) {
      throw new Error('missing required parameter "range"');
    }

    let position = TextPositionAnchor.fromRange(range);
    return this.fromPositionAnchor(position);
  }

  static fromSelector(selector) {
    if (selector === undefined) {
      throw new Error('missing required parameter "selector"');
    }
    let {exact, prefix, suffix} = selector;
    return new TextQuoteSelector(exact, {prefix, suffix});
  }

  static fromPositionAnchor(anchor) {
    let root = global.document.body;

    let {start, end} = anchor;
    let exact = root.textContent.substr(start, end - start);

    let prefixStart = Math.max(0, start - 32);
    let prefix = root.textContent.substr(prefixStart, start - prefixStart);

    let suffixEnd = Math.min(root.textContent.length, end + 32);
    let suffix = root.textContent.substr(end, suffixEnd - end);

    return new TextQuoteAnchor(exact, {prefix, suffix});
  }

  toRange() {
    return this.toPositionAnchor().toRange();
  }

  toSelector() {
    let selector = {
      type: 'TextQuoteSelector',
      exact: this.exact,
    };
    if (this.prefix !== undefined) selector.prefix = this.prefix;
    if (this.suffix !== undefined) selector.suffix = this.suffix;
    return selector;
  }

  toPositionAnchor() {
    let root = global.document.body;
    let dmp = new DiffMatchPatch();

    dmp.Match_Distance = root.textContent.length * 2;

    let foldSlices = (acc, slice) => {
      let result = dmp.match_main(root.textContent, slice, acc.loc);
      if (result === -1) {
        throw new Error('no match found');
      }
      acc.loc = result + slice.length;
      acc.start = Math.min(acc.start, result);
      acc.end = Math.max(acc.end, result + slice.length);
      return acc;
    };

    let slices = this.exact.match(/(.|[\r\n]){1,32}/g);
    let loc = root.textContent.length / 2;
    let start = -1;
    let end = -1;

    if (this.prefix !== undefined) {
      let result = dmp.match_main(root.textContent, this.prefix, loc);
      if (result > -1) loc = end = start = result + this.prefix.length;
    }

    if (start === -1) {
      let firstSlice = slices.shift();
      result = dmp.match_main(root.textContent, firstSlice, loc);
      if (result > -1) {
        start = result;
        loc = end = start + firstSlice.length;
      } else {
        throw new Error('no match found');
      }
    }

    dmp.Match_Distance = 64;
    let acc = slices.reduce(foldSlices, {
      start: start,
      end: end,
      loc: loc,
    });

    return new TextPositionAnchor(acc.start, acc.end);
  }
}
<|endoftext|>


<commit_before>module.exports = {
  config: {
    // Hyper configuration
    fontSize: 14,
    fontFamily: '"FuraCode Nerd Font", "DejaVu Sans Mono", Menlo, monospace',
    cursorColor: 'rgba(248,28,229,0.75)',
    cursorShape: 'BLOCK',
    borderColor: '#333',
    css: '',
    termCSS: '',
    padding: '12px 14px',
    // Plugin configurations
    hyperStatusLine: {
      dirtyColor: 'salmon',
    },
    tabIcons: {
      mapIcons: {
        nodejs: ['node'],
        vim: ['nvim', 'vim']
      },
      mapColors: { },
      processNameRegex: /: (.*?)$/
    },
    paneNavigation: {
      hotkeys: {
        navigation: {
          up: 'ctrl+alt+k',
          down: 'ctrl+alt+j',
          left: 'ctrl+alt+h',
          right: 'ctrl+alt+l'
        }
      },
      showIndicators: false
    },
    bell: false
  },
  plugins: [
    'hyperlinks',
    'hyper-tab-icons',
    'hyperterm-atom-dark'
  ]
};
<commit_msg>Update Hyper config<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'canary',

    // default font size in pixels for all tabs
    fontSize: 14,

    // font family with optional fallbacks
    fontFamily: '"FuraCode Nerd Font", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BLOCK',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // set to `true` (without backticks and without quotes) if you're using a
    // Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff',
    },
    materialBox: {
      scheme: 'material-palenight',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'false',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  plugins: ['hyper-material-box'],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<|endoftext|>


<commit_before>var Deferred = require('stupid-deferred');

/**
 * Image loader
 * @constructor
 */
function Loadimage(opts){
	/**
     * @define {object} Collection of public methods.
     */
    var self = {};

    /**
     * @define {object} Options for the constructor
     */
    var opts = opts || {};

    /**
     * @define {object} Cache for loaded images
     */
	var cache = {};

	/**
	 * Loading image
	 * @example imageload.load(src).success( // Do Something ).error( //Do something );
	 * @param {string} src Source of the image that should be loaded
	 * @config {object} def Deferred object to handle callbacks
	 * @return {object} Returns a promise
	 */
	function load(src){
		var def = Deferred();

		/**
		 * If image if cache returns the loaded image.
		 */
		if(cache[src]){
			/** resolve promise with cache image */
			def.resolve(cache[src], 'cached image');
		}else{
			/**
			 * Create new image
			 * Setup listeners for the image,
			 * and then set source.
			 */
			var img = new Image();
		    img.onload = function() {
		    	/** Cache image */
		        cache[src] = img;
		        /** Resolve promise */
		        def.resolve(img);
		    }
		    img.onerror = function(){
		    	def.reject('ERROR: ' + src);
		    }
		    img.src = src;
		}
		/**
		 * @return {object} Return promise
		 */
	    return def.promise;
	}

	/**
	 * Public methods
	 * @public {function}
	 */
	self.load = load;

	/**
	 * @return {object} Public object
	 */
	return self;
}

/** @export */
module.exports = Loadimage; <commit_msg>updated name<commit_after>var Deferred = require('stupid-deferred');

/**
 * Image loader
 * @constructor
 */
function Imageloader(opts){
	/**
     * @define {object} Collection of public methods.
     */
    var self = {};

    /**
     * @define {object} Options for the constructor
     */
    var opts = opts || {};

    /**
     * @define {object} Cache for loaded images
     */
	var cache = {};

	/**
	 * Loading image
	 * @example imageload.load(src).success( // Do Something ).error( //Do something );
	 * @param {string} src Source of the image that should be loaded
	 * @config {object} def Deferred object to handle callbacks
	 * @return {object} Returns a promise
	 */
	function load(src){
		var def = Deferred();

		/**
		 * If image if cache returns the loaded image.
		 */
		if(cache[src]){
			/** resolve promise with cache image */
			def.resolve(cache[src], 'cached image');
		}else{
			/**
			 * Create new image
			 * Setup listeners for the image,
			 * and then set source.
			 */
			var img = new Image();
		    img.onload = function() {
		    	/** Cache image */
		        cache[src] = img;
		        /** Resolve promise */
		        def.resolve(img);
		    }
		    img.onerror = function(){
		    	def.reject('ERROR: ' + src);
		    }
		    img.src = src;
		}
		/**
		 * @return {object} Return promise
		 */
	    return def.promise;
	}

	/**
	 * Public methods
	 * @public {function}
	 */
	self.load = load;

	/**
	 * @return {object} Public object
	 */
	return self;
}

/** @export */
module.exports = Imageloader; <|endoftext|>


<commit_before><commit_msg>Add Minified Version<commit_after>include=function(){function f(){var a=this.readyState;(!a||/ded|te/.test(a))&&(c--,!c&&e&&d())}var a=arguments,b=document,c=a.length,d=a[c-1],e=d.call;e&&c--;for(var g,h=0;c>h;h++)g=b.createElement("script"),g.src=arguments[h],g.async=!0,g.onload=g.onerror=g.onreadystatechange=f,(b.head||b.getElementsByTagName("head")[0]).appendChild(g)};
<|endoftext|>


<commit_before>var Integration = (function () {
  var _Integration = {};

  var iframeId = "integration";
  var userAgent = navigator.userAgent || "";
  var isIOS8 = /(os 8).*(applewebkit)/i.test(userAgent);
  var isSafari = /Version\/[\d\.]+.*Safari/.test(userAgent);

  var PageState = (function (argument) {
    var restoreObj = {
      bodyProp: {},
      bodyClass: [],
      eventListener: [],
      scroll: {
        x: 0,
        y: 0
      }
    };

    var _PageState = {};

    _PageState.changeBodyProp = function (key, value) {
      restoreObj.bodyProp[key] = document.body.value;
      document.body[key] = value;
    };

    _PageState.addBodyClass = function (value) {
      var elementClassList = document.body.classList;
      if (elementClassList.contains(value)) {
        return;
      }
      restoreObj.bodyClass.push(value);
      elementClassList.add(value);
    };

    _PageState.addEventListener = function (el, eventName, callback) {
      el.addEventListener("eventName", callback);
      restoreObj.eventListener.push({
        el: el,
        callback: callback
      });
    };

    _PageState.setScroll = function () {
      if (!window.scrollX && !window.scrollY) {
        return;
      }
      restoreObj.scroll.x = window.scrollX;
      restoreObj.scroll.y = window.scrollY;
    };

    _PageState.restore = function () {
      var i;
      var listener;
      var bodyClass;
      var scrollX = restoreObj.scroll.x;
      var scrollY = restoreObj.scroll.y;

      for (i in restoreObj.bodyProp) {
        document.body[i] = restoreObj.bodyProp[i];
        delete restoreObj.bodyProp[i];
      }

      for (i in restoreObj.bodyClass) {
        bodyClass = restoreObj.bodyClass.pop();
        document.body.classList.remove(bodyClass);
      }

      for (i in restoreObj.eventListener) {
        listener = restoreObj.eventListener.pop();
        listener.el.removeEventListener(listener.callback);
      }

      if (window.scroll && (!scrollX || !scrollY)) {
        window.scroll(scrollX, scrollY);
      }
    };

    return _PageState;
  })();

  _Integration.init = function (accessId) {
    var iframe = document.createElement("iframe");
    var props = {
      scrolling: "no",
      id: iframeId,
      src: "/iframe?accessId=" + accessId,
      frameborder: "0",
      allowtransparency: "true"
    };
    for (i in props) {
      iframe[i] = props[i];
    }

    PageState.setScroll(); // must be before adding body classes

    PageState.changeBodyProp("overflow", "hidden");
    PageState.addBodyClass("integration-noscroll");

    if (isIOS8) {
      PageState.addBodyClass("integration-ios8");
    }
    if (isSafari) {
      PageState.addBodyClass("integration-safari");
    }

    document.body.appendChild(iframe);

    return this;
  };

  _Integration.close = function () {
    PageState.restore();
    var iframe = document.getElementById(iframeId);
    var parent = iframe.parentNode;
    if (!parent) {
      return this;
    }
    parent.removeChild(iframe);
    return this;
  }

  return _Integration;
})();

<commit_msg>ie8 support on add event listener<commit_after>var Integration = (function () {
  var _Integration = {};

  var iframeId = "integration";
  var userAgent = navigator.userAgent || "";
  var isIOS8 = /(os 8).*(applewebkit)/i.test(userAgent);
  var isSafari = /Version\/[\d\.]+.*Safari/.test(userAgent);

  var PageState = (function (argument) {
    var restoreObj = {
      bodyProp: {},
      bodyClass: [],
      eventListener: [],
      scroll: {
        x: 0,
        y: 0
      }
    };

    var _PageState = {};

    _PageState.changeBodyProp = function (key, value) {
      restoreObj.bodyProp[key] = document.body.value;
      document.body[key] = value;
    };

    _PageState.addBodyClass = function (value) {
      var elementClassList = document.body.classList;
      if (elementClassList.contains(value)) {
        return;
      }
      restoreObj.bodyClass.push(value);
      elementClassList.add(value);
    };

    _PageState.addEventListener = function (el, eventName, callback) {
      if (window.addEventListener){
        el.addEventListener(eventName, callback, false);
      } else {
        attachEvent("on" + eventName, callback)
      }
      restoreObj.eventListener.push({
        el: el,
        eventName: eventName,
        callback: callback
      });
    };

    _PageState.setScroll = function () {
      if (!window.scrollX && !window.scrollY) {
        return;
      }
      restoreObj.scroll.x = window.scrollX;
      restoreObj.scroll.y = window.scrollY;
    };

    _PageState.restore = function () {
      var i;
      var listener;
      var bodyClass;
      var scrollX = restoreObj.scroll.x;
      var scrollY = restoreObj.scroll.y;

      for (i in restoreObj.bodyProp) {
        document.body[i] = restoreObj.bodyProp[i];
        delete restoreObj.bodyProp[i];
      }

      for (i in restoreObj.bodyClass) {
        bodyClass = restoreObj.bodyClass.pop();
        document.body.classList.remove(bodyClass);
      }

      for (i in restoreObj.eventListener) {
        listener = restoreObj.eventListener.pop();
        if (listener.el.removeEventListener) {
          listener.el.removeEventListener(listener.eventName, listener.callback);
        } else {
          listener.el.detachEvent("on" + listener.eventName, listener.callback);
        }
      }

      if (window.scroll && (!scrollX || !scrollY)) {
        window.scroll(scrollX, scrollY);
      }
    };

    return _PageState;
  })();

  _Integration.init = function (accessId) {
    var iframe = document.createElement("iframe");
    var props = {
      scrolling: "no",
      id: iframeId,
      src: "/iframe?accessId=" + accessId,
      frameborder: "0",
      allowtransparency: "true"
    };
    for (i in props) {
      iframe[i] = props[i];
    }

    PageState.setScroll(); // must be before adding body classes

    PageState.changeBodyProp("overflow", "hidden");
    PageState.addBodyClass("integration-noscroll");

    if (isIOS8) {
      PageState.addBodyClass("integration-ios8");
    }
    if (isSafari) {
      PageState.addBodyClass("integration-safari");
    }

    document.body.appendChild(iframe);

    return this;
  };

  _Integration.close = function () {
    PageState.restore();
    var iframe = document.getElementById(iframeId);
    var parent = iframe.parentNode;
    if (!parent) {
      return this;
    }
    parent.removeChild(iframe);
    return this;
  }

  return _Integration;
})();

<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var Mapbox = require('react-native-mapbox-gl');
var mapRef = 'mapRef';
var {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBarIOS,
  View
} = React;

var MapExample = React.createClass({
  mixins: [Mapbox.Mixin],
  getInitialState() {
    return {
      center: {
        latitude: 40.72052634,
        longitude: -73.97686958312988
      },
      zoom: 11,
      annotations: [{
        coordinates: [40.72052634, -73.97686958312988],
        'type': 'point',
        title: 'This is marker 1',
        subtitle: 'It has a rightCalloutAccessory too',
        rightCalloutAccessory: {
          url: 'https://cldup.com/9Lp0EaBw5s.png',
          height: 25,
          width: 25
        },
        annotationImage: {
          url: 'https://cldup.com/CnRLZem9k9.png',
          height: 25,
          width: 25
        },
        id: 'marker1'
      }, {
        coordinates: [40.714541341726175,-74.00579452514648],
        'type': 'point',
        title: 'Important!',
        subtitle: 'Neat, this is a custom annotation image',
        annotationImage: {
          url: 'https://cldup.com/7NLZklp8zS.png',
          height: 25,
          width: 25
        },
        id: 'marker2'
      }, {
        'coordinates': [[40.76572150042782,-73.99429321289062],[40.743485405490695, -74.00218963623047],[40.728266950429735,-74.00218963623047],[40.728266950429735,-73.99154663085938],[40.73633186448861,-73.98983001708984],[40.74465591168391,-73.98914337158203],[40.749337730454826,-73.9870834350586]],
        'type': 'polyline',
        'strokeColor': '#00FB00',
        'strokeWidth': 4,
        'strokeAlpha': .5,
        'id': 'foobar'
      }, {
        'coordinates': [[40.749857912194386, -73.96820068359375], [40.741924698522055,-73.9735221862793], [40.735681504432264,-73.97523880004883], [40.7315190495212,-73.97438049316406], [40.729177554196376,-73.97180557250975], [40.72345355209305,-73.97438049316406], [40.719290332250544,-73.97455215454102], [40.71369559554873,-73.97729873657227], [40.71200407096382,-73.97850036621094], [40.71031250340588,-73.98691177368163], [40.71031250340588,-73.99154663085938]],
        'type': 'polygon',
        'fillAlpha':1,
        'strokeColor': '#fffff',
        'fillColor': 'blue',
        'id': 'zap'
      }]
     };
  },
  onRegionChange(location) {
    this.setState({ currentZoom: location.zoom });
  },
  onRegionWillChange(location) {
    console.log(location);
  },
  onUpdateUserLocation(location) {
    console.log(location);
  },
  onOpenAnnotation(annotation) {
    console.log(annotation);
  },
  onRightAnnotationTapped(e) {
    console.log(e);
  },
  onLongPress(location) {
    console.log('long pressed', location);
  },
  render: function() {
    StatusBarIOS.setHidden(true);
    return (
      <View style={styles.container}>
        <Text style={styles.text} onPress={() => this.setDirectionAnimated(mapRef, 0)}>
          Set direction to 0
        </Text>
        <Text style={styles.text} onPress={() => this.setZoomLevelAnimated(mapRef, 6)}>
          Zoom out to zoom level 6
        </Text>
        <Text style={styles.text} onPress={() => this.setCenterCoordinateAnimated(mapRef, 48.8589, 2.3447)}>
          Go to Paris at current zoom level {parseInt(this.state.currentZoom)}
        </Text>
        <Text style={styles.text} onPress={() => this.setCenterCoordinateZoomLevelAnimated(mapRef, 35.68829, 139.77492, 14)}>
          Go to Tokyo at fixed zoom level 14
        </Text>
        <Text style={styles.text} onPress={() => this.addAnnotations(mapRef, [{
          coordinates: [40.73312,-73.989],
          type: 'point',
          title: 'This is a new marker',
          id: 'foo'
        }, {
          'coordinates': [[40.749857912194386, -73.96820068359375], [40.741924698522055,-73.9735221862793], [40.735681504432264,-73.97523880004883], [40.7315190495212,-73.97438049316406], [40.729177554196376,-73.97180557250975], [40.72345355209305,-73.97438049316406], [40.719290332250544,-73.97455215454102], [40.71369559554873,-73.97729873657227], [40.71200407096382,-73.97850036621094], [40.71031250340588,-73.98691177368163], [40.71031250340588,-73.99154663085938]],
          'type': 'polygon',
          'fillAlpha': 1,
          'fillColor': '#000',
          'strokeAlpha': 1,
          'id': 'new-black-polygon'
        }])}>
          Add new marker
        </Text>
        <Text style={styles.text} onPress={() => this.selectAnnotationAnimated(mapRef, 'marker1')}>
          Open marker1 popup
        </Text>
        <Text style={styles.text} onPress={() => this.removeAnnotation(mapRef, 'marker2')}>
          Remove marker2 annotation
        </Text>
        <Text style={styles.text} onPress={() => this.removeAllAnnotations(mapRef)}>
          Remove all annotations
        </Text>
        <Text style={styles.text} onPress={() => this.setVisibleCoordinateBoundsAnimated(mapRef, 40.712, -74.227, 40.774, -74.125, 100, 0, 0, 0)}>
          Set visible bounds to 40.7, -74.2, 40.7, -74.1
        </Text>
        <Text style={styles.text} onPress={() => this.setUserTrackingMode(mapRef, this.userTrackingMode.follow)}>
          Set userTrackingMode to follow
        </Text>
        <Mapbox
          style={styles.map}
          direction={0}
          rotateEnabled={true}
          scrollEnabled={true}
          zoomEnabled={true}
          showsUserLocation={true}
          ref={mapRef}
          accessToken={'your-mapbox.com-access-token'}
          styleURL={this.mapStyles.emerald}
          userTrackingMode={this.userTrackingMode.none}
          centerCoordinate={this.state.center}
          zoomLevel={this.state.zoom}
          onRegionChange={this.onRegionChange}
          onRegionWillChange={this.onRegionWillChange}
          annotations={this.state.annotations}
          onOpenAnnotation={this.onOpenAnnotation}
          onRightAnnotationTapped={this.onRightAnnotationTapped}
          onUpdateUserLocation={this.onUpdateUserLocation}
          onLongPress={this.onLongPress} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1
  },
  map: {
    flex: 1
  },
  text: {
    padding: 3
  }
});

AppRegistry.registerComponent('your-app-name', () => MapExample);
<commit_msg>Add example for updateAnnotation<commit_after>'use strict';

var React = require('react-native');
var Mapbox = require('react-native-mapbox-gl');
var mapRef = 'mapRef';
var {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBarIOS,
  View
} = React;

var MapExample = React.createClass({
  mixins: [Mapbox.Mixin],
  getInitialState() {
    return {
      center: {
        latitude: 40.72052634,
        longitude: -73.97686958312988
      },
      zoom: 11,
      annotations: [{
        coordinates: [40.72052634, -73.97686958312988],
        'type': 'point',
        title: 'This is marker 1',
        subtitle: 'It has a rightCalloutAccessory too',
        rightCalloutAccessory: {
          url: 'https://cldup.com/9Lp0EaBw5s.png',
          height: 25,
          width: 25
        },
        annotationImage: {
          url: 'https://cldup.com/CnRLZem9k9.png',
          height: 25,
          width: 25
        },
        id: 'marker1'
      }, {
        coordinates: [40.714541341726175,-74.00579452514648],
        'type': 'point',
        title: 'Important!',
        subtitle: 'Neat, this is a custom annotation image',
        annotationImage: {
          url: 'https://cldup.com/7NLZklp8zS.png',
          height: 25,
          width: 25
        },
        id: 'marker2'
      }, {
        'coordinates': [[40.76572150042782,-73.99429321289062],[40.743485405490695, -74.00218963623047],[40.728266950429735,-74.00218963623047],[40.728266950429735,-73.99154663085938],[40.73633186448861,-73.98983001708984],[40.74465591168391,-73.98914337158203],[40.749337730454826,-73.9870834350586]],
        'type': 'polyline',
        'strokeColor': '#00FB00',
        'strokeWidth': 4,
        'strokeAlpha': .5,
        'id': 'foobar'
      }, {
        'coordinates': [[40.749857912194386, -73.96820068359375], [40.741924698522055,-73.9735221862793], [40.735681504432264,-73.97523880004883], [40.7315190495212,-73.97438049316406], [40.729177554196376,-73.97180557250975], [40.72345355209305,-73.97438049316406], [40.719290332250544,-73.97455215454102], [40.71369559554873,-73.97729873657227], [40.71200407096382,-73.97850036621094], [40.71031250340588,-73.98691177368163], [40.71031250340588,-73.99154663085938]],
        'type': 'polygon',
        'fillAlpha':1,
        'strokeColor': '#fffff',
        'fillColor': 'blue',
        'id': 'zap'
      }]
     };
  },
  onRegionChange(location) {
    this.setState({ currentZoom: location.zoom });
  },
  onRegionWillChange(location) {
    console.log(location);
  },
  onUpdateUserLocation(location) {
    console.log(location);
  },
  onOpenAnnotation(annotation) {
    console.log(annotation);
  },
  onRightAnnotationTapped(e) {
    console.log(e);
  },
  onLongPress(location) {
    console.log('long pressed', location);
  },
  render: function() {
    StatusBarIOS.setHidden(true);
    return (
      <View style={styles.container}>
        <Text style={styles.text} onPress={() => this.setDirectionAnimated(mapRef, 0)}>
          Set direction to 0
        </Text>
        <Text style={styles.text} onPress={() => this.setZoomLevelAnimated(mapRef, 6)}>
          Zoom out to zoom level 6
        </Text>
        <Text style={styles.text} onPress={() => this.setCenterCoordinateAnimated(mapRef, 48.8589, 2.3447)}>
          Go to Paris at current zoom level {parseInt(this.state.currentZoom)}
        </Text>
        <Text style={styles.text} onPress={() => this.setCenterCoordinateZoomLevelAnimated(mapRef, 35.68829, 139.77492, 14)}>
          Go to Tokyo at fixed zoom level 14
        </Text>
        <Text style={styles.text} onPress={() => this.addAnnotations(mapRef, [{
          coordinates: [40.73312,-73.989],
          type: 'point',
          title: 'This is a new marker',
          id: 'foo'
        }, {
          'coordinates': [[40.749857912194386, -73.96820068359375], [40.741924698522055,-73.9735221862793], [40.735681504432264,-73.97523880004883], [40.7315190495212,-73.97438049316406], [40.729177554196376,-73.97180557250975], [40.72345355209305,-73.97438049316406], [40.719290332250544,-73.97455215454102], [40.71369559554873,-73.97729873657227], [40.71200407096382,-73.97850036621094], [40.71031250340588,-73.98691177368163], [40.71031250340588,-73.99154663085938]],
          'type': 'polygon',
          'fillAlpha': 1,
          'fillColor': '#000',
          'strokeAlpha': 1,
          'id': 'new-black-polygon'
        }])}>
          Add new marker
        </Text>
        <Text style={styles.text} onPress={() => this.updateAnnotation(mapRef, {
          coordinates: [40.714541341726175,-74.00579452514648],
          'type': 'point',
          title: 'New Title!',
          subtitle: 'New Subtitle',
          annotationImage: {
            url: 'https://cldup.com/7NLZklp8zS.png',
            height: 25,
            width: 25
          },
          id: 'marker2'
        })}>
          Update marker2
        </Text>
        <Text style={styles.text} onPress={() => this.selectAnnotationAnimated(mapRef, 'marker1')}>
          Open marker1 popup
        </Text>
        <Text style={styles.text} onPress={() => this.removeAnnotation(mapRef, 'marker2')}>
          Remove marker2 annotation
        </Text>
        <Text style={styles.text} onPress={() => this.removeAllAnnotations(mapRef)}>
          Remove all annotations
        </Text>
        <Text style={styles.text} onPress={() => this.setVisibleCoordinateBoundsAnimated(mapRef, 40.712, -74.227, 40.774, -74.125, 100, 0, 0, 0)}>
          Set visible bounds to 40.7, -74.2, 40.7, -74.1
        </Text>
        <Text style={styles.text} onPress={() => this.setUserTrackingMode(mapRef, this.userTrackingMode.follow)}>
          Set userTrackingMode to follow
        </Text>
        <Mapbox
          style={styles.map}
          direction={0}
          rotateEnabled={true}
          scrollEnabled={true}
          zoomEnabled={true}
          showsUserLocation={true}
          ref={mapRef}
          accessToken={'your-mapbox.com-access-token'}
          styleURL={this.mapStyles.emerald}
          userTrackingMode={this.userTrackingMode.none}
          centerCoordinate={this.state.center}
          zoomLevel={this.state.zoom}
          onRegionChange={this.onRegionChange}
          onRegionWillChange={this.onRegionWillChange}
          annotations={this.state.annotations}
          onOpenAnnotation={this.onOpenAnnotation}
          onRightAnnotationTapped={this.onRightAnnotationTapped}
          onUpdateUserLocation={this.onUpdateUserLocation}
          onLongPress={this.onLongPress} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1
  },
  map: {
    flex: 1
  },
  text: {
    padding: 3
  }
});

AppRegistry.registerComponent('your-app-name', () => MapExample);
<|endoftext|>


<commit_before>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testPathIgnorePatterns: ['<rootDir>/dist/']
};
<commit_msg>ci: renovate and coverage tweaks<commit_after>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testPathIgnorePatterns: ['<rootDir>/dist/'],
  collectCoverageFrom: ['src/*.ts']
};
<|endoftext|>


<commit_before>module.exports = {
    verbose: true,
    transform: { '\\.[jt]sx?$': 'babel-jest' },
    coveragePathIgnorePatterns: ['node_modules', '.storybook', 'relay/__generated__/', '.story.js'],
    moduleNameMapper: {
        '\\.(css|less|scss)$': 'identity-obj-proxy',
    },
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
};
<commit_msg>remove use of jsdom as jestTestEnvirontment<commit_after>module.exports = {
    verbose: true,
    transform: { '\\.[jt]sx?$': 'babel-jest' },
    coveragePathIgnorePatterns: ['node_modules', '.storybook', 'relay/__generated__/', '.story.js'],
    moduleNameMapper: {
        '\\.(css|less|scss)$': 'identity-obj-proxy',
    },
    preset: 'ts-jest',
};
<|endoftext|>


<commit_before>importScripts("node_modules/jimp/browser/lib/jimp.js");

self.addEventListener("message", function (message) {
    const data = JSON.parse(message.data);
    let presetName = data.presetName;
    const noImages = data.images.length;
    const width = data.sizes[0];
    const height = data.sizes[1];
    const quality = data.quality;
    const resizeMode = data.resizeMode;
    const autoSize = data.autosize;
    const halign = data.halign;
    const valign = data.valign;

    for (let i = 0; i < data.images.length; i++) {
        const imageName = data.images[i].split('\\').pop();

        if (resizeMode["resize"]) {
            Jimp.read(data.images[i]).then(function (img) {
                self.postMessage(i);
                // Auto size
                let aWidth;
                let aHeight;
                if (autoSize === 1) { // None
                    aWidth = width;
                    aHeight = height;
                } else if (autoSize === 2) { // Width
                    aWidth = Jimp.AUTO;
                    aHeight = height;
                } else { // Height
                    aWidth = width;
                    aHeight = Jimp.AUTO;
                }

                img.resize(aWidth, aHeight, halign | valign)
                    .quality(quality)
                    .getBase64(Jimp.AUTO, function (err, src) {
                        if (presetName) presetName = presetName.toLowerCase().trim();
                        let message = {
                            "presetName": presetName,
                            "name": imageName,
                            "src": src,
                            "type": 'resize'
                        };
                        self.postMessage(message);   // message the main thread
                    });
            }).catch(function (err) {
                console.error(err);
            });
        }

        if (resizeMode["cover"]) {
            Jimp.read(data.images[i]).then(function (img) {
                self.postMessage(i);
                img.cover(width, height, halign | valign)
                    .quality(quality)
                    .getBase64(Jimp.AUTO, function (err, src) {
                        if (presetName) presetName = presetName.toLowerCase().trim();
                        let message = {
                            "presetName": presetName,
                            "name": imageName,
                            "src": src,
                            "type": 'resize'
                        };
                        self.postMessage(message);   // message the main thread
                    });
            }).catch(function (err) {
                console.error(err);
            });
        }

        if (resizeMode["contain"]) {
            Jimp.read(data.images[i]).then(function (img) {
                self.postMessage(i);
                img.contain(width, height, halign | valign)
                    .quality(quality)
                    .getBase64(Jimp.AUTO, function (err, src) {
                        if (presetName) presetName = presetName.toLowerCase().trim();
                        let message = {
                            "presetName": presetName,
                            "name": imageName,
                            "src": src,
                            "type": 'resize'
                        };
                        self.postMessage(message);   // message the main thread
                    });
            }).catch(function (err) {
                console.error(err);
            });
        }
    }
});<commit_msg>Fixed output filename<commit_after>importScripts("node_modules/jimp/browser/lib/jimp.js");

self.addEventListener("message", function (message) {
    const data = JSON.parse(message.data);
    let presetName = data.presetName;
    const noImages = data.images.length;
    const width = data.sizes[0];
    const height = data.sizes[1];
    const quality = data.quality;
    const resizeMode = data.resizeMode;
    const autoSize = data.autosize;
    const halign = data.halign;
    const valign = data.valign;

    for (let i = 0; i < data.images.length; i++) {
        const imageName = data.images[i].split('\\').pop();

        if (resizeMode["resize"]) {
            Jimp.read(data.images[i]).then(function (img) {
                self.postMessage(i);
                // Auto size
                let aWidth;
                let aHeight;
                if (autoSize === 1) { // None
                    aWidth = width;
                    aHeight = height;
                } else if (autoSize === 2) { // Width
                    aWidth = Jimp.AUTO;
                    aHeight = height;
                } else { // Height
                    aWidth = width;
                    aHeight = Jimp.AUTO;
                }

                img.resize(aWidth, aHeight, halign | valign)
                    .quality(quality)
                    .getBase64(Jimp.AUTO, function (err, src) {
                        if (presetName) presetName = presetName.toLowerCase().trim();
                        let message = {
                            "presetName": presetName,
                            "name": imageName,
                            "src": src,
                            "type": 'resize'
                        };
                        self.postMessage(message);   // message the main thread
                    });
            }).catch(function (err) {
                console.error(err);
            });
        }

        if (resizeMode["cover"]) {
            Jimp.read(data.images[i]).then(function (img) {
                self.postMessage(i);
                img.cover(width, height, halign | valign)
                    .quality(quality)
                    .getBase64(Jimp.AUTO, function (err, src) {
                        if (presetName) presetName = presetName.toLowerCase().trim();
                        let message = {
                            "presetName": presetName,
                            "name": imageName,
                            "src": src,
                            "type": 'cover'
                        };
                        self.postMessage(message);   // message the main thread
                    });
            }).catch(function (err) {
                console.error(err);
            });
        }

        if (resizeMode["contain"]) {
            Jimp.read(data.images[i]).then(function (img) {
                self.postMessage(i);
                img.contain(width, height, halign | valign)
                    .quality(quality)
                    .getBase64(Jimp.AUTO, function (err, src) {
                        if (presetName) presetName = presetName.toLowerCase().trim();
                        let message = {
                            "presetName": presetName,
                            "name": imageName,
                            "src": src,
                            "type": 'contain'
                        };
                        self.postMessage(message);   // message the main thread
                    });
            }).catch(function (err) {
                console.error(err);
            });
        }
    }
});<|endoftext|>


<commit_before>

export function parseInt(value, defaultValue) {
   if (value) {
      try {
         return global.parseInt(value);
      } catch (err) {
         logger.debug('parseInt', value, defaultValue);
      }
   }
   return defaultValue;
}

export function isInteger(value) {
   return value && !isNaN(value) && /^[0-9]+$/.test(value.toString());
}
<commit_msg>logger<commit_after>
const logger = Loggers.create(module.filename);

export function parseInt(value, defaultValue) {
   if (value) {
      try {
         return global.parseInt(value);
      } catch (err) {
         logger.debug('parseInt', value, defaultValue);
      }
   }
   return defaultValue;
}

export function isInteger(value) {
   return value && !isNaN(value) && /^[0-9]+$/.test(value.toString());
}
<|endoftext|>


<commit_before>import Backbone from 'backbone';
import globals from 'globals';

export default Backbone.Model.extend({

    urlRoot: globals.TROPO_API_ROOT + "/help_links",

    idAttribute: "link_key",

    parse: function (attributes) {
        return attributes;
    },
});
<commit_msg>Correct root URL for HelpLink model<commit_after>import Backbone from 'backbone';
import globals from 'globals';

export default Backbone.Model.extend({

    urlRoot: globals.API_V2_ROOT + "/help_links",

    idAttribute: "link_key",

    parse: function (attributes) {
        return attributes;
    },
});
<|endoftext|>


<commit_before>// Great new taggable widget that requires jQuery UI to be loaded.
// Enhances an existing text field (progressive enhancement). See
// the README

function pkInlineTaggableWidget(selector, options)
{
	$(selector).each(function()
	{
		// Semi-global
		var typeaheadUrl = options['typeahead-url'];
		var tagsLabel = (options['tags-label']) ? options['tags-label'] : 'Existing Tags';
		var popularTagsLabel = (options['popular-tags-label']) ? options['popular-tags-label'] : 'Popular Tags';
		var popularTags = options['popular-tags'];
		var existingTags = {};
		var allTags = options['all-tags'];
		var commitSelector = options['commit-selector'];
		var commitEvent = (options['commit-event']) ? options['commit-event'] : 'click';
		var addLinkClass = (options['add-link-class']) ? options['add-link-class'] : 'a-popular-tags';
		var removeLinkClass = (options['remove-link-class']) ? options['remove-link-class'] : 'a-existing-tags';

		if (typeof(popularTags) == 'undefined')
		{
			popularTags = {};
		};
		if (typeof(allTags) == 'undefined')
		{
			allTags == {};
		};

		// populate existingTags
		if($.trim($(this).val()) != '')
		{
			var lp = $(this).val().split(',');
			for (x in lp)
			{
				existingTags[lp[x].trim()] = lp[x].trim();
			}
		}

		function makePopularLink(attributes, title, text)
		{
			var new_tag = $('');
			var new_link = $('');
			new_tag.attr({ title: title }).addClass('a-tag a-popular');
			new_tag.prepend(new_link);
			new_link.html(title + ""+text+"");
			new_link.attr(attributes).addClass('a-link');
			return new_tag;
		}

		function makeRemoveLink(attributes, title, text)
		{
			title = $.trim(title);

			var new_tag = $('');
			var new_link = $('');
			var tagTitle = title;

			if (typeof(allTags) != 'undefined')
			{
				if (typeof(allTags[title]) != 'undefined')
				{
					title = title + '' + allTags[title] + '';
				}
				else
				{
					title = title + '0';
				}
			}

			new_link.text(tagTitle);
			new_link.attr(attributes);
			new_link.attr({ title: 'Remove Tag' }).addClass('a-link icon a-close-small');
			new_link.prepend('');
			new_tag.attr({ title: tagTitle }).addClass('a-tag a-existing');
			new_tag.append(new_link);
			return new_tag;
		}

		function trimExcessCommas(string)
		{
			string = string.replace(/(^,)|(, ?$)/g, '');
			string = string.replace(/(,,)|(, ,)/, ',');
			string = $.trim(string);

			return string;
		}

		// For multiple word typeahead we need some helpers

		function split( val ) {
			return val.split( /,\s*/ );
		}

		function extractLast( term ) {
			return split( term ).pop();
		}

		function multipleSelect(event, ui)
		{
			var terms = split( this.value );
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push( ui.item.value );
			// add placeholder to get the comma-and-space at the end
			terms.push( "" );
			this.value = terms.join( ", " );
			return false;
		}

		function multipleFocus()
		{
			// prevent value inserted on focus
			return false;
		}

		function multipleSearch()
		{
			// custom minLength
			var term = extractLast( this.value );
			if ( term.length < 2 ) {
				return false;
			}
		}

		// We don't want to display popular tags that we're already using
		var unusedPopulars = {};
		for (x in popularTags)
		{
			if (typeof(existingTags[x]) == 'undefined')
			{
				unusedPopulars[x] = popularTags[x];
			}
		}

		var popularsAttributes = {};
		var existingTagsAttributes = {};
		var existingDiv = $('
');
		var popularsDiv = $('
');

		// Establish the quick enhancement
		var tagInput = $(this);
		var typeAheadContainer = $('
');
		var typeAheadBox = $('<input />');
		var typeAheadBoxId = 'inline-tag-ahead-box-' + Math.floor(Math.random() * 2000);
		typeAheadBox.attr('type', 'text');
		typeAheadBox.attr('id', typeAheadBoxId);
		if ((typeof(allTags) == 'undefined') && (typeof(typeaheadUrl) != 'undefined'))
		{
			typeAheadBox.autocomplete({
			  source: function (request, response) {
					$.getJSON(typeaheadUrl, {
						  term: extractLast(request.term)
					  }, response);
				},
				search: multipleSearch,
				focus: multipleFocus,
				select: multipleSelect
			});
		}
		else if (typeof(allTags) != 'undefined')
		{
			var allTagsReformat = new Array();
			for (x in allTags)
			{
				allTagsReformat.push(x);
			}
			typeAheadBox.autocomplete({
				source: function (request, response) {
					response( $.ui.autocomplete.filter(
										allTagsReformat, extractLast( request.term ) ) );
				},
				search: multipleSearch,
				focus: multipleFocus,
				select: multipleSelect
			});
		}

		var addButton = $('');
		addButton.html('Add');
		addButton.attr({'href' : '#', 'class' : 'a-btn icon a-add add-tags-link', 'title' : 'Add these tags'});

		typeAheadContainer.addClass('a-inline-taggable-widget').append(typeAheadBox).append(addButton);

		tagInput.hide();
		tagInput.parent().append(typeAheadContainer);

		// Add a list of popular tags to be added
		function addTagsToForm(link)
		{
			var tag = link.attr('title');
			var value = tagInput.val() + ', ' + tag;

			value = trimExcessCommas(value);
			tagInput.val(value);

			if (link.parent().children().length == 2)
				link.parent().children('h4').hide();
			link.remove();

			var new_link = makeRemoveLink(existingTagsAttributes, tag, tag + ' x');
			new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
			existingDiv.append(new_link);
			existingDiv.children('h4').show();
		}

		// Add a list of tags that may be removed
		function removeTagsFromForm(link)
		{
			var tag = link.attr('title');
			var value = tagInput.val();
			value = value.replace(tag, '');
			value = trimExcessCommas(value);
			tagInput.val(value);

			if (link.parent().children().length == 2)
				link.parent().children('h4').hide();
			link.remove();

			// As we have just removed it from the list, we want the real deal populars.
			if (typeof(popularTags[tag]) != 'undefined')
			{
				var linkLabel = popularTags[tag];
				var new_link = makePopularLink(existingTagsAttributes, tag, linkLabel);
				new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
				popularsDiv.children('h4').show();
				popularsDiv.append(new_link);
			}
		}

		// a maker function for tag containers
		function makeTagContainer(containerLabel, tagArray, linkAttributes, linkLabelType)
		{
			// Add a list of tags that may be removed
			var tagContainer = $('
');
			tagContainer.addClass('a-inline-taggable-widget-tag-container');
			var header = $('
');
			header.text(containerLabel);
			tagContainer.append(header);

			if (objEmpty(tagArray))
			{
				header.hide();
			}

			var attributes = {};
			for (x in tagArray)
			{
				var linkLabel = '';
				if (linkLabelType == 'add')
				{
					tagContainer.addClass(addLinkClass);
					linkLabel = tagArray[x];
					var new_link = makePopularLink(linkAttributes, x, linkLabel);
					new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
				}
				else if (linkLabelType == 'remove')
				{
					tagContainer.addClass(removeLinkClass);
					linkLabel = 'x ' + x;
					var new_link = makeRemoveLink(linkAttributes, x, linkLabel);
					new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
				}
				tagContainer.append(new_link);
			}
			return tagContainer;
		}

		// Add the new tags to the existing form input.
		// If the user doesn't click Save changes or add... tough?
		function commitTagsToForm()
		{
			if (typeAheadBox.val() != '')
			{
				var value = tagInput.val() + ',' + typeAheadBox.val();
				value = trimExcessCommas(value);
				tagInput.val(value);
				typeAheadBox.val('');

				existingTags = {};
				var lp = value.split(',');
				for (x in lp)
				{
					existingTags[lp[x]] = lp[x];
				}

				existingDiv.html(makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove').html());
				existingDiv.find('a').each(function() {
					$(this).bind('click', function() {
						removeTagsFromForm($(this).parent());
						return false;
					});
				});
			}
			return false;
		}
		addButton.bind('click', function() { commitTagsToForm(); return false; });
		if (commitSelector != 'undefined')
		{
			$(commitSelector).bind(commitEvent, function() {
				commitTagsToForm();
				return true;
			});
		}

		existingDiv = makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove');
		existingDiv.addClass(removeLinkClass).children('a').bind('click', function() { removeTagsFromForm($(this));  return false; });
		tagInput.parent().prepend(existingDiv);

		popularsDiv = makeTagContainer(popularTagsLabel, unusedPopulars, popularsAttributes, 'add');
		popularsDiv.children('a').bind('click', function() { addTagsToForm($(this));  return false; });
		tagInput.parent().append(popularsDiv);

		// Catch that enter key, baby!
		$(document).keyup(function(e)
			{
				if (e.keyCode == 13)
				{
					if (typeAheadBox.get(0) === $(document.activeElement).get(0))
					{
						e.preventDefault();
					}
				}
			});

		$(document).keypress(function(e)
			{
				if (e.keyCode == 13)
				{
					if (typeAheadBox.get(0) === $(document.activeElement).get(0))
					{
						e.preventDefault();
					}
				}
			});

		typeAheadBox.keyup(function(e)
			{
		 		if (e.keyCode == 13)
		 		{
					e.preventDefault();
		 			commitTagsToForm();
		 		}
		 	});

		function objEmpty(obj)
		{
			for (var prop in obj)
			{
				if (obj.hasOwnProperty(prop))
				{
					return false;
				}
			}

			return true;
		}
	});

}

// DEPRECATED. Requires the old sfJqueryReloadedPlugin and generally is not as cool.

// You need to bring in jQuery first in order for this to work
//
// Call it like this:
// pkTagahead(<?php echo json_encode(url_for("taggableComplete/complete")) ?>);
//
// Or similar. Now all of your input elements with the input-tag class
// automatically gain the typeahead suggestion feature.
//
// If you're not using Symfony and sfDoctrineActAsTaggablePlugin,
// pass your own URL that returns a
 containing
s with the
// FULL TEXT of what the ENTIRE tag string will be if the user takes
// that suggestion, with the new tag you're suggesting an  link
// to #. Then use CSS to hide (visibility: none) the part of the
//
 that is not in the . Don't introduce any extra whitespace.

function pkTagahead(tagaheadUrl)
{
  $(function() {
    function getKey(event)
    {
      // Portable keycodes sigh
      return event.keyCode ? event.keyCode : event.which;
    }
    function setClick(target)
    {
      $(target).find('a').click(function(event)
      {
        // span contains ul contains li contains a
        var span = this.parentNode.parentNode.parentNode;
        var input = $(span).data("tag-peer");
        // Get text from the li
        var parent = this.parentNode;
        $(input).val($(parent).text());
        $(input).focus();
        return false;
      });
    }
    // Add suggestions span (you'll need to style that)
    $('input.tag-input').after("

");
    // Each tag field remembers its suggestions span...
    $('input.tag-input').each(function()
    {
      $(this).data("tag-peer", $(this).next()[0]);
    });
    // And vice versa
    $('div.tag-suggestions').each(function()
    {
      $(this).data("tag-peer", $(this).prev()[0]);
    });
    // Now we can really throw down
    $('input.tag-input').keyup(function(event)
    {
      var key = getKey(event);
      // Tab key
      if (key == 9)
      {
        var peer = $(this).data("tag-peer");
        var suggestions = $(peer).find("li");
        if (suggestions.length)
        {
          $(this).val($(suggestions[0]).text());
          $(this).focus();
        }
        // In any case don't insert the tab
        return false;
      }
      else
      {
        // Trigger ajax update of suggestions
      }
    });
    $('input.tag-input').keypress(function(event)
    {
      // Firefox 2.0 mac is stubborn and only allows cancel here
      // (we will still get the keyup and do the real work there)
      var key = getKey(event);
      if (key == 9)
      {
        // Don't insert tabs, ever
        return false;
      }
    });
    var lastValues = {};
    setInterval(function()
    {
      // AJAX query for suggestions only when changes have taken place
      $('input.tag-input').each(function()
      {
        var last = $(this).data('tag-last');
        var value = $(this).val();
        var peer = $(this).data('tag-peer');
        if (last !== value)
        {
          $(this).data('tag-last', value);
          $.post(
            tagaheadUrl,
            {
              current: $(this).val()
            },
            function(data, textStatus)
            {
              $(peer).html(data);
              setClick(peer);
            }
          );
        }
      });
    }, 200);
  });
}
<commit_msg>added a class name to the tag heading<commit_after>// Great new taggable widget that requires jQuery UI to be loaded.
// Enhances an existing text field (progressive enhancement). See
// the README

function pkInlineTaggableWidget(selector, options)
{
	$(selector).each(function()
	{
		// Semi-global
		var typeaheadUrl = options['typeahead-url'];
		var tagsLabel = (options['tags-label']) ? options['tags-label'] : 'Existing Tags';
		var popularTagsLabel = (options['popular-tags-label']) ? options['popular-tags-label'] : 'Popular Tags';
		var popularTags = options['popular-tags'];
		var existingTags = {};
		var allTags = options['all-tags'];
		var commitSelector = options['commit-selector'];
		var commitEvent = (options['commit-event']) ? options['commit-event'] : 'click';
		var addLinkClass = (options['add-link-class']) ? options['add-link-class'] : 'a-popular-tags';
		var removeLinkClass = (options['remove-link-class']) ? options['remove-link-class'] : 'a-existing-tags';

		if (typeof(popularTags) == 'undefined')
		{
			popularTags = {};
		};
		if (typeof(allTags) == 'undefined')
		{
			allTags == {};
		};

		// populate existingTags
		if($.trim($(this).val()) != '')
		{
			var lp = $(this).val().split(',');
			for (x in lp)
			{
				existingTags[lp[x].trim()] = lp[x].trim();
			}
		}

		function makePopularLink(attributes, title, text)
		{
			var new_tag = $('');
			var new_link = $('');
			new_tag.attr({ title: title }).addClass('a-tag a-popular');
			new_tag.prepend(new_link);
			new_link.html(title + ""+text+"");
			new_link.attr(attributes).addClass('a-link');
			return new_tag;
		}

		function makeRemoveLink(attributes, title, text)
		{
			title = $.trim(title);

			var new_tag = $('');
			var new_link = $('');
			var tagTitle = title;

			if (typeof(allTags) != 'undefined')
			{
				if (typeof(allTags[title]) != 'undefined')
				{
					title = title + '' + allTags[title] + '';
				}
				else
				{
					title = title + '0';
				}
			}

			new_link.text(tagTitle);
			new_link.attr(attributes);
			new_link.attr({ title: 'Remove Tag' }).addClass('a-link icon a-close-small');
			new_link.prepend('');
			new_tag.attr({ title: tagTitle }).addClass('a-tag a-existing');
			new_tag.append(new_link);
			return new_tag;
		}

		function trimExcessCommas(string)
		{
			string = string.replace(/(^,)|(, ?$)/g, '');
			string = string.replace(/(,,)|(, ,)/, ',');
			string = $.trim(string);

			return string;
		}

		// For multiple word typeahead we need some helpers

		function split( val ) {
			return val.split( /,\s*/ );
		}

		function extractLast( term ) {
			return split( term ).pop();
		}

		function multipleSelect(event, ui)
		{
			var terms = split( this.value );
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push( ui.item.value );
			// add placeholder to get the comma-and-space at the end
			terms.push( "" );
			this.value = terms.join( ", " );
			return false;
		}

		function multipleFocus()
		{
			// prevent value inserted on focus
			return false;
		}

		function multipleSearch()
		{
			// custom minLength
			var term = extractLast( this.value );
			if ( term.length < 2 ) {
				return false;
			}
		}

		// We don't want to display popular tags that we're already using
		var unusedPopulars = {};
		for (x in popularTags)
		{
			if (typeof(existingTags[x]) == 'undefined')
			{
				unusedPopulars[x] = popularTags[x];
			}
		}

		var popularsAttributes = {};
		var existingTagsAttributes = {};
		var existingDiv = $('
');
		var popularsDiv = $('
');

		// Establish the quick enhancement
		var tagInput = $(this);
		var typeAheadContainer = $('
');
		var typeAheadBox = $('<input />');
		var typeAheadBoxId = 'inline-tag-ahead-box-' + Math.floor(Math.random() * 2000);
		typeAheadBox.attr('type', 'text');
		typeAheadBox.attr('id', typeAheadBoxId);
		if ((typeof(allTags) == 'undefined') && (typeof(typeaheadUrl) != 'undefined'))
		{
			typeAheadBox.autocomplete({
			  source: function (request, response) {
					$.getJSON(typeaheadUrl, {
						  term: extractLast(request.term)
					  }, response);
				},
				search: multipleSearch,
				focus: multipleFocus,
				select: multipleSelect
			});
		}
		else if (typeof(allTags) != 'undefined')
		{
			var allTagsReformat = new Array();
			for (x in allTags)
			{
				allTagsReformat.push(x);
			}
			typeAheadBox.autocomplete({
				source: function (request, response) {
					response( $.ui.autocomplete.filter(
										allTagsReformat, extractLast( request.term ) ) );
				},
				search: multipleSearch,
				focus: multipleFocus,
				select: multipleSelect
			});
		}

		var addButton = $('');
		addButton.html('Add');
		addButton.attr({'href' : '#', 'class' : 'a-btn icon a-add add-tags-link', 'title' : 'Add these tags'});

		typeAheadContainer.addClass('a-inline-taggable-widget').append(typeAheadBox).append(addButton);

		tagInput.hide();
		tagInput.parent().append(typeAheadContainer);

		// Add a list of popular tags to be added
		function addTagsToForm(link)
		{
			var tag = link.attr('title');
			var value = tagInput.val() + ', ' + tag;

			value = trimExcessCommas(value);
			tagInput.val(value);

			if (link.parent().children().length == 2)
				link.parent().children('h4').hide();
			link.remove();

			var new_link = makeRemoveLink(existingTagsAttributes, tag, tag + ' x');
			new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
			existingDiv.append(new_link);
			existingDiv.children('h4').show();
		}

		// Add a list of tags that may be removed
		function removeTagsFromForm(link)
		{
			var tag = link.attr('title');
			var value = tagInput.val();
			value = value.replace(tag, '');
			value = trimExcessCommas(value);
			tagInput.val(value);

			if (link.parent().children().length == 2)
				link.parent().children('h4').hide();
			link.remove();

			// As we have just removed it from the list, we want the real deal populars.
			if (typeof(popularTags[tag]) != 'undefined')
			{
				var linkLabel = popularTags[tag];
				var new_link = makePopularLink(existingTagsAttributes, tag, linkLabel);
				new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
				popularsDiv.children('h4').show();
				popularsDiv.append(new_link);
			}
		}

		// a maker function for tag containers
		function makeTagContainer(containerLabel, tagArray, linkAttributes, linkLabelType)
		{
			// Add a list of tags that may be removed
			var tagContainer = $('
');
			tagContainer.addClass('a-inline-taggable-widget-tag-container');
			var header = $('
');
			header.text(containerLabel).addClass('a-tag-heading');
			tagContainer.append(header);

			if (objEmpty(tagArray))
			{
				header.hide();
			}

			var attributes = {};
			for (x in tagArray)
			{
				var linkLabel = '';
				if (linkLabelType == 'add')
				{
					tagContainer.addClass(addLinkClass);
					linkLabel = tagArray[x];
					var new_link = makePopularLink(linkAttributes, x, linkLabel);
					new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
				}
				else if (linkLabelType == 'remove')
				{
					tagContainer.addClass(removeLinkClass);
					linkLabel = 'x ' + x;
					var new_link = makeRemoveLink(linkAttributes, x, linkLabel);
					new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
				}
				tagContainer.append(new_link);
			}
			return tagContainer;
		}

		// Add the new tags to the existing form input.
		// If the user doesn't click Save changes or add... tough?
		function commitTagsToForm()
		{
			if (typeAheadBox.val() != '')
			{
				var value = tagInput.val() + ',' + typeAheadBox.val();
				value = trimExcessCommas(value);
				tagInput.val(value);
				typeAheadBox.val('');

				existingTags = {};
				var lp = value.split(',');
				for (x in lp)
				{
					existingTags[lp[x]] = lp[x];
				}

				existingDiv.html(makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove').html());
				existingDiv.find('a').each(function() {
					$(this).bind('click', function() {
						removeTagsFromForm($(this).parent());
						return false;
					});
				});
			}
			return false;
		}
		addButton.bind('click', function() { commitTagsToForm(); return false; });
		if (commitSelector != 'undefined')
		{
			$(commitSelector).bind(commitEvent, function() {
				commitTagsToForm();
				return true;
			});
		}

		existingDiv = makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove');
		existingDiv.addClass(removeLinkClass).children('a').bind('click', function() { removeTagsFromForm($(this));  return false; });
		tagInput.parent().prepend(existingDiv);

		popularsDiv = makeTagContainer(popularTagsLabel, unusedPopulars, popularsAttributes, 'add');
		popularsDiv.children('a').bind('click', function() { addTagsToForm($(this));  return false; });
		tagInput.parent().append(popularsDiv);

		// Catch that enter key, baby!
		$(document).keyup(function(e)
			{
				if (e.keyCode == 13)
				{
					if (typeAheadBox.get(0) === $(document.activeElement).get(0))
					{
						e.preventDefault();
					}
				}
			});

		$(document).keypress(function(e)
			{
				if (e.keyCode == 13)
				{
					if (typeAheadBox.get(0) === $(document.activeElement).get(0))
					{
						e.preventDefault();
					}
				}
			});

		typeAheadBox.keyup(function(e)
			{
		 		if (e.keyCode == 13)
		 		{
					e.preventDefault();
		 			commitTagsToForm();
		 		}
		 	});

		function objEmpty(obj)
		{
			for (var prop in obj)
			{
				if (obj.hasOwnProperty(prop))
				{
					return false;
				}
			}

			return true;
		}
	});

}

// DEPRECATED. Requires the old sfJqueryReloadedPlugin and generally is not as cool.

// You need to bring in jQuery first in order for this to work
//
// Call it like this:
// pkTagahead(<?php echo json_encode(url_for("taggableComplete/complete")) ?>);
//
// Or similar. Now all of your input elements with the input-tag class
// automatically gain the typeahead suggestion feature.
//
// If you're not using Symfony and sfDoctrineActAsTaggablePlugin,
// pass your own URL that returns a
 containing
s with the
// FULL TEXT of what the ENTIRE tag string will be if the user takes
// that suggestion, with the new tag you're suggesting an  link
// to #. Then use CSS to hide (visibility: none) the part of the
//
 that is not in the . Don't introduce any extra whitespace.

function pkTagahead(tagaheadUrl)
{
  $(function() {
    function getKey(event)
    {
      // Portable keycodes sigh
      return event.keyCode ? event.keyCode : event.which;
    }
    function setClick(target)
    {
      $(target).find('a').click(function(event)
      {
        // span contains ul contains li contains a
        var span = this.parentNode.parentNode.parentNode;
        var input = $(span).data("tag-peer");
        // Get text from the li
        var parent = this.parentNode;
        $(input).val($(parent).text());
        $(input).focus();
        return false;
      });
    }
    // Add suggestions span (you'll need to style that)
    $('input.tag-input').after("

");
    // Each tag field remembers its suggestions span...
    $('input.tag-input').each(function()
    {
      $(this).data("tag-peer", $(this).next()[0]);
    });
    // And vice versa
    $('div.tag-suggestions').each(function()
    {
      $(this).data("tag-peer", $(this).prev()[0]);
    });
    // Now we can really throw down
    $('input.tag-input').keyup(function(event)
    {
      var key = getKey(event);
      // Tab key
      if (key == 9)
      {
        var peer = $(this).data("tag-peer");
        var suggestions = $(peer).find("li");
        if (suggestions.length)
        {
          $(this).val($(suggestions[0]).text());
          $(this).focus();
        }
        // In any case don't insert the tab
        return false;
      }
      else
      {
        // Trigger ajax update of suggestions
      }
    });
    $('input.tag-input').keypress(function(event)
    {
      // Firefox 2.0 mac is stubborn and only allows cancel here
      // (we will still get the keyup and do the real work there)
      var key = getKey(event);
      if (key == 9)
      {
        // Don't insert tabs, ever
        return false;
      }
    });
    var lastValues = {};
    setInterval(function()
    {
      // AJAX query for suggestions only when changes have taken place
      $('input.tag-input').each(function()
      {
        var last = $(this).data('tag-last');
        var value = $(this).val();
        var peer = $(this).data('tag-peer');
        if (last !== value)
        {
          $(this).data('tag-last', value);
          $.post(
            tagaheadUrl,
            {
              current: $(this).val()
            },
            function(data, textStatus)
            {
              $(peer).html(data);
              setClick(peer);
            }
          );
        }
      });
    }, 200);
  });
}
<|endoftext|>


<commit_before>// @flow
/**
 * All About Olaf
 * Individual row for inside a collapsible view
 */

import React from 'react'
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Dimensions,
} from 'react-native'

import * as c from '../components/colors'
import Collapsible from 'react-native-collapsible'
import MenuItem from './menuItem'

let width = Dimensions.get('window').width //full width

let styles = StyleSheet.create({
  container: {
    marginBottom: 10,
    alignItems: 'stretch',
    alignSelf: 'stretch',
  },
  collapsedContent: {
    alignSelf: 'center',
    backgroundColor: c.paleGreen,
    margin: 0,
    width: width,
  },
  headerText: {
    fontSize: 18,
    textAlign: 'center',
  },
  contentText: {
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 10,
    marginRight: 5,
    fontStyle: 'italic',
  },
  collapsedContainer: {
    marginBottom: 5,
  },
})

export default class MenuSection extends React.Component {
  static propTypes = {
    content: React.PropTypes.string.isRequired,
    header: React.PropTypes.string.isRequired,
    subText: React.PropTypes.string.isRequired,
  }

  state = {
    isCollapsed: true,
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          onPress={() => this.setState({isCollapsed: !this.state.isCollapsed})}
        >
          <Text style={styles.headerText}>{this.props.header}</Text>
          <Collapsible collapsed={this.state.isCollapsed} style={styles.collapsedContent}>
            <View style={styles.collapsedContainer}>
              <Text style={styles.contentText}>{this.props.subText}</Text>
              <MenuItem items={this.props.content} />
            </View>
          </Collapsible>
        </TouchableOpacity>
      </View>
    )
  }
}
<commit_msg>switch MenuSection to flow<commit_after>// @flow
/**
 * All About Olaf
 * Individual row for inside a collapsible view
 */

import React from 'react'
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Dimensions,
} from 'react-native'

import * as c from '../components/colors'
import Collapsible from 'react-native-collapsible'
import MenuItem from './menuItem'
import type { MenuItemType } from './types'

let width = Dimensions.get('window').width //full width

let styles = StyleSheet.create({
  container: {
    marginBottom: 10,
    alignItems: 'stretch',
    alignSelf: 'stretch',
  },
  collapsedContent: {
    alignSelf: 'center',
    backgroundColor: c.paleGreen,
    margin: 0,
    width: width,
  },
  headerText: {
    fontSize: 18,
    textAlign: 'center',
  },
  contentText: {
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 10,
    marginRight: 5,
    fontStyle: 'italic',
  },
  collapsedContainer: {
    marginBottom: 5,
  },
})

export default class MenuSection extends React.Component {
  state = {
    isCollapsed: true,
  }

  props: {
    content: MenuItemType[],
    header: string,
    subText: string,
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          onPress={() => this.setState({isCollapsed: !this.state.isCollapsed})}
        >
          <Text style={styles.headerText}>{this.props.header}</Text>
          <Collapsible collapsed={this.state.isCollapsed} style={styles.collapsedContent}>
            <View style={styles.collapsedContainer}>
              <Text style={styles.contentText}>{this.props.subText}</Text>
              <MenuItem items={this.props.content} />
            </View>
          </Collapsible>
        </TouchableOpacity>
      </View>
    )
  }
}
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

// NOTE: because vdates are timezone specific, this test will might only work in PST
// not sure about DST.  If you see a failure, that would be my first suspicion

var date = new Date(0);

var vdate = date.getVarDate();

// Test string concat both ways:
writeLine("Attempt string concat (string + vdate) and echo.");
var appendMe = "test concat: " + vdate;
writeLine(appendMe);

writeLine("Attempt string concat  (vdate + string) and echo.");
var appendMe = vdate + ": test concat2";
writeLine(appendMe);

// Test typeof
writeLine(typeof(date));
writeLine(typeof(vdate));
writeLine(typeof(new Object(vdate)));
writeLine(typeof(Object(vdate)));

// Test .toString (should fail)
try {
    var myVar = vdate.toString();
    writeLine("FAIL: we should have errored on .toString();");
} catch (e)
{
    writeLine("SUCCESS: vdate.toString() failed with error #" + e.number);
}

// Test assigning to a member
try {
    vdate.aMember = 3;
    writeLine("FAIL: we should have errored on vdate.aMember = 3;");
} catch (e)
{
    writeLine("SUCCESS: vdate.aMember = 3 failed with error #" + e.number);
}

// Test assigning to a member with []
try {
    vdate["aMember"] = 3;
    writeLine("FAIL: we should have errored on vdate[\"aMember\"] = 3;");
} catch (e)
{
    writeLine("SUCCESS: vdate[\"aMember\"] = 3 failed with error #" + e.number);
}

// Test accessing a member
try {
    var shouldNotWork = vdate.aMember;
} catch (e)
{
    writeLine("SUCCESS: var shouldNotWork = date.aMember failed with error #" + e.number);
}

// Try some more unusual or invalid uses of VarDate
writeLine("");
writeLine("Unusual cases:");
vdate = new Date(1234567890123).getVarDate();
safeCall(function() { writeLine(vdate ? true : false); });
safeCall(function() { writeLine([1, 2].indexOf(2, vdate)); }); // valid only in version 3
safeCall(function() { writeLine(parseInt("1", vdate)); });

// normalize Old GetNumberFormatEx exception
safeCall(function() {
    var result = [1, vdate, 2].toLocaleString();
    if (result == "1, [object Object], 2") {
        result = "1.00, [object Object], 2.00";
    }
    writeLine(result);
});

// Try some random dates to make sure we match the old engine
writeLine("");
writeLine("Pseudorandom cases:");
for (var i = 0; i < 1000; i++)
{
    var testDate = new Date(i*10373);
    var testVDate = testDate.getVarDate();
    writeLine("VT_DATE: '" + testVDate + "'");
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helpers

function writeLine(str)
{
    str = str.replace(/\(PDT\)/g, "(Pacific Daylight Time)")
             .replace(/\(PST\)/g, "(Pacific Standard Time)");
    WScript.Echo("" + str);
}

function safeCall(func)
{
    try
    {
        return func();
    }
    catch (ex)
    {
        writeLine(ex.name + " (" + ex.number + "): " + ex.message);
    }
}
<commit_msg>test: fix applying DST abbr. normalization to non-string<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

// NOTE: because vdates are timezone specific, this test will might only work in PST
// not sure about DST.  If you see a failure, that would be my first suspicion

var date = new Date(0);

var vdate = date.getVarDate();

// Test string concat both ways:
writeLine("Attempt string concat (string + vdate) and echo.");
var appendMe = "test concat: " + vdate;
writeLine(appendMe);

writeLine("Attempt string concat  (vdate + string) and echo.");
var appendMe = vdate + ": test concat2";
writeLine(appendMe);

// Test typeof
writeLine(typeof(date));
writeLine(typeof(vdate));
writeLine(typeof(new Object(vdate)));
writeLine(typeof(Object(vdate)));

// Test .toString (should fail)
try {
    var myVar = vdate.toString();
    writeLine("FAIL: we should have errored on .toString();");
} catch (e)
{
    writeLine("SUCCESS: vdate.toString() failed with error #" + e.number);
}

// Test assigning to a member
try {
    vdate.aMember = 3;
    writeLine("FAIL: we should have errored on vdate.aMember = 3;");
} catch (e)
{
    writeLine("SUCCESS: vdate.aMember = 3 failed with error #" + e.number);
}

// Test assigning to a member with []
try {
    vdate["aMember"] = 3;
    writeLine("FAIL: we should have errored on vdate[\"aMember\"] = 3;");
} catch (e)
{
    writeLine("SUCCESS: vdate[\"aMember\"] = 3 failed with error #" + e.number);
}

// Test accessing a member
try {
    var shouldNotWork = vdate.aMember;
} catch (e)
{
    writeLine("SUCCESS: var shouldNotWork = date.aMember failed with error #" + e.number);
}

// Try some more unusual or invalid uses of VarDate
writeLine("");
writeLine("Unusual cases:");
vdate = new Date(1234567890123).getVarDate();
safeCall(function() { writeLine(vdate ? true : false); });
safeCall(function() { writeLine([1, 2].indexOf(2, vdate)); }); // valid only in version 3
safeCall(function() { writeLine(parseInt("1", vdate)); });

// normalize Old GetNumberFormatEx exception
safeCall(function() {
    var result = [1, vdate, 2].toLocaleString();
    if (result == "1, [object Object], 2") {
        result = "1.00, [object Object], 2.00";
    }
    writeLine(result);
});

// Try some random dates to make sure we match the old engine
writeLine("");
writeLine("Pseudorandom cases:");
for (var i = 0; i < 1000; i++)
{
    var testDate = new Date(i*10373);
    var testVDate = testDate.getVarDate();
    writeLine("VT_DATE: '" + testVDate + "'");
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helpers

function writeLine(str)
{
    if (typeof str === "string") {
        str = str.replace(/\(PDT\)/g, "(Pacific Daylight Time)")
                 .replace(/\(PST\)/g, "(Pacific Standard Time)");
    }

    WScript.Echo("" + str);
}

function safeCall(func)
{
    try
    {
        return func();
    }
    catch (ex)
    {
        writeLine(ex.name + " (" + ex.number + "): " + ex.message);
    }
}
<|endoftext|>