<commit_before>var Parsimmon = require('./../index');
var string = Parsimmon.string;
var regex = Parsimmon.regex;
var succeed = Parsimmon.succeed;
var seq = Parsimmon.seq;
var lazy = Parsimmon.lazy;

var json = (function() {
  var json = lazy(function() {
    return alt([
      object,
      array,
      stringLiteral,
      numberLiteral,
      nullLiteral,
      trueLiteral,
      falseLiteral
    ]).skip(regex(/^\s*/m));
  });

  var escapes = {
    b: '\b',
    f: '\f',
    n: '\n',
    r: '\r',
    t: '\t'
  }

  var stringLiteral = regex(/^"(\\.|.)*?"/).map(function(str) {
    return str.slice(1, -1).replace(/\\u(\d{4})/, function(_, hex) {
      return String.fromCharCode(parseInt(hex, 16));
    }).replace(/\\(.)/, function(_, ch) {
      return escapes.hasOwnProperty(ch) ? escapes[ch] : ch
    });
  });

  var numberLiteral = regex(/^\d+(([.]|e[+-]?)\d+)?/i).map(parseFloat)

  function commaSep(parser) {
    var commaParser = regex(/^,\s*/m).then(parser).many()
    return seq([parser, commaParser]).map(function(results) {
      return [results[0]].concat(results[1]);
    }).or(succeed([]));
  }

  var array = seq([regex(/^\[\s*/m), commaSep(json), string(']')]).map(function(results) {
    return results[1];
  });

  var pair = seq([stringLiteral.skip(regex(/^\s*:\s*/m)), json]);

  var object = seq([regex(/^[{]\s*/m), commaSep(pair), string('}')]).map(function(results) {
    var pairs = results[1];
    var out = {};
    for (var i = pairs.length-1; i >= 0; i -= 1) {
      out[pairs[i][0]] = pairs[i][1];
    }
    return out;
  });

  var nullLiteral = string('null').result(null);
  var trueLiteral = string('true').result(true);
  var falseLiteral = string('false').result(false);

  return json;
})();

var source = process.argv[2] || __dirname+'/../package.json';
var result = json.parse(require('fs').readFileSync(source, 'utf-8'));

console.log(result);
<commit_msg>fix the json example to use alt/seq correctly<commit_after>var Parsimmon = require('./../index');
var string = Parsimmon.string;
var regex = Parsimmon.regex;
var succeed = Parsimmon.succeed;
var seq = Parsimmon.seq;
var alt = Parsimmon.alt;
var lazy = Parsimmon.lazy;

var json = (function() {
  var json = lazy(function() {
    return alt(
      object,
      array,
      stringLiteral,
      numberLiteral,
      nullLiteral,
      trueLiteral,
      falseLiteral
    ).skip(regex(/^\s*/m));
  });

  var escapes = {
    b: '\b',
    f: '\f',
    n: '\n',
    r: '\r',
    t: '\t'
  }

  var stringLiteral = regex(/"(\\.|.)*?"/).map(function(str) {
    return str.slice(1, -1).replace(/\\u(\d{4})/, function(_, hex) {
      return String.fromCharCode(parseInt(hex, 16));
    }).replace(/\\(.)/, function(_, ch) {
      return escapes.hasOwnProperty(ch) ? escapes[ch] : ch
    });
  });

  var numberLiteral = regex(/\d+(([.]|e[+-]?)\d+)?/i).map(parseFloat)

  function commaSep(parser) {
    var commaParser = regex(/^,\s*/m).then(parser).many()
    return seq(parser, commaParser).map(function(results) {
      return [results[0]].concat(results[1]);
    }).or(succeed([]));
  }

  var array = seq(regex(/\[\s*/m), commaSep(json), string(']')).map(function(results) {
    return results[1];
  });

  var pair = seq(stringLiteral.skip(regex(/^\s*:\s*/m)), json);

  var object = seq(regex(/^[{]\s*/m), commaSep(pair), string('}')).map(function(results) {
    var pairs = results[1];
    var out = {};
    for (var i = pairs.length-1; i >= 0; i -= 1) {
      out[pairs[i][0]] = pairs[i][1];
    }
    return out;
  });

  var nullLiteral = string('null').result(null);
  var trueLiteral = string('true').result(true);
  var falseLiteral = string('false').result(false);

  return json;
})();

var source = process.argv[2] || __dirname+'/../package.json';
var result = json.parse(require('fs').readFileSync(source, 'utf-8'));

console.log(result);
<|endoftext|>


<commit_before>import Immutable, { List, Map, Set } from 'immutable';
import { isSmallScreen } from '../utils/media_utils';
import * as d from './i18n/index';
import t from './i18n/t';
import trim from 'trim';
import * as gp from '../avatar/gravatar_provider';
import { dataFns } from '../utils/data_utils';

const {
  get,
  init,
  remove,
  reset,
  set,
  tget,
  tset,
  tremove
} = dataFns(["core"]);

export function setup(id, clientID, domain, options, logInCallback, hookRunner, emitEventFn) {
  return init(id, Immutable.fromJS({
    auth: extractAuthOptions(options),
    clientID: clientID,
    domain: domain,
    emitEventFn: emitEventFn,
    hookRunner: hookRunner,
    mode: options.mode,
    logInCallback: logInCallback,
    allowedConnections: Immutable.fromJS(options.allowedConnections || []),
    ui: extractUIOptions(id, options.mode, options)
  }));
}

export function id(m) {
  return m.get("id");
}

export function clientID(m) {
  return get(m, "clientID");
}

export function domain(m) {
  return get(m, "domain");
}

export function modeName(m) {
  return get(m, "mode");
}

export function setSubmitting(m, value, error = "") {
  m = tset(m, "submitting", value);
  m = error && !value ? setGlobalError(m, error) : clearGlobalError(m);
  return m;
}

export function submitting(m) {
  return tget(m, "submitting", false);
}

export function setGlobalError(m, str) {
  return tset(m, "globalError", str);
}

export function globalError(m) {
  return tget(m, "globalError", "");
}

export function clearGlobalError(m) {
  return tremove(m, "globalError");
}

export function setGlobalSuccess(m, str) {
  return tset(m, "globalSuccess", str);
}

export function globalSuccess(m) {
  return tget(m, "globalSuccess", "");
}

export function clearGlobalSuccess(m) {
  return tremove(m, "globalSuccess");
}

export function rendering(m) {
  return tget(m, "render", false);
}

export function stopRendering(m) {
  return tremove(m, "render");
}

function extractUIOptions(id, modeName, options) {
  const closable = options.container ? false : undefined === options.closable ? true : !!options.closable;
  const theme = options.theme || {};
  const { logo, primaryColor } = theme;

  const avatar = options.avatar !== null;
  const customAvatarProvider = options.avatar
    && typeof options.avatar.url === "function"
    && typeof options.avatar.displayName === "function"
    && options.avatar;
  const avatarProvider = customAvatarProvider || gp;

  return new Map({
    containerID: options.container || `auth0-lock-container-${id}`,
    appendContainer: !options.container,
    autoclose: undefined === options.autoclose ? false : closable && options.autoclose,
    autofocus: undefined === options.autofocus ? !(options.container || isSmallScreen()) : !!options.autofocus,
    avatar: avatar,
    avatarProvider: avatarProvider,
    logo: typeof logo === "string" ? logo : undefined,
    closable: closable,
    dict: d.buildDict(modeName, typeof options.languageDictionary === "object" ? options.languageDictionary : {}),
    disableWarnings: options.disableWarnings === undefined ? false : !!options.disableWarnings,
    mobile: undefined === options.mobile ? false : !!options.mobile,
    popupOptions: new Map(undefined === options.popupOptions ? {} : options.popupOptions),
    primaryColor: typeof primaryColor === "string" ? primaryColor : undefined,
    rememberLastLogin: undefined === options.rememberLastLogin ? true : !!options.rememberLastLogin
  });
}

const { get: getUIAttribute } = dataFns(["core", "ui"]);

export const ui = {
  containerID: lock => getUIAttribute(lock, "containerID"),
  appendContainer: lock => getUIAttribute(lock, "appendContainer"),
  autoclose: lock => getUIAttribute(lock, "autoclose"),
  autofocus: lock => getUIAttribute(lock, "autofocus"),
  avatar: lock => getUIAttribute(lock, "avatar"),
  avatarProvider: lock => getUIAttribute(lock, "avatarProvider"),
  closable: lock => getUIAttribute(lock, "closable"),
  dict: lock => getUIAttribute(lock, "dict"),
  disableWarnings: lock => getUIAttribute(lock, "disableWarnings"),
  t: (lock, keyPath, params) => t(ui.dict(lock), keyPath, params),
  logo: lock => getUIAttribute(lock, "logo"),
  mobile: lock => getUIAttribute(lock, "mobile"),
  popupOptions: lock => getUIAttribute(lock, "popupOptions"),
  primaryColor: lock => getUIAttribute(lock, "primaryColor"),
  rememberLastLogin: lock => getUIAttribute(lock, "rememberLastLogin")
};

const { get: getAuthAttribute } = dataFns(["core", "auth"]);

export const auth = {
  params: lock => getAuthAttribute(lock, "params"),
  redirect: lock => getAuthAttribute(lock, "redirect"),
  redirectUrl: lock => getAuthAttribute(lock, "redirectUrl"),
  responseType: lock => getAuthAttribute(lock, "responseType"),
  sso: lock => getAuthAttribute(lock, "sso")
};

function extractAuthOptions(options) {
  // TODO: shouldn't all options be namespased in authentication?
  let {
    params,
    redirect,
    redirectUrl,
    responseType,
    sso
  } = options.auth || {};

  params = typeof params === "object" ? params : {};
  redirectUrl = typeof redirectUrl === "string" && redirectUrl ? redirectUrl : undefined;
  redirect = typeof redirect === "boolean" ? redirect : true;
  responseType = typeof responseType === "string" ? responseType : redirectUrl ? "code" : "token";
  sso = typeof sso === "boolean" ? sso : true;

  if (trim(params.scope || "") === "openid profile") {
    warn(options, "Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details.");
  }

  return Immutable.fromJS({
    params,
    redirect,
    redirectUrl,
    responseType,
    sso
  });
}

export function withAuthOptions(m, opts) {
  return Immutable.fromJS(opts)
    .merge(get(m, "auth"))
    .toJS();
}

export function invokeLogInCallback(m, ...args) {
  get(m, "logInCallback").apply(undefined, args);
}

export function render(m) {
  return tset(m, "render", true);
}

export { reset };

export function setSignedIn(m, value) {
  return tset(m, "signedIn", value);
}

export function signedIn(m) {
  return tget(m, "signedIn", false);
}

export function warn(x, str) {
  const shouldOutput = Map.isMap(x)
    ? !ui.disableWarnings(x)
    : !x.disableWarnings;

  if (shouldOutput && console && console.warn) {
    console.warn(str);
  }
}

export function allowedConnections(m) {
  return get(m, "allowedConnections");
}

export function connections(m, type = undefined, ...strategies) {
  if (arguments.length === 1) {
    return get(m, "connections", Map())
      .filter((v, k) => k !== "unknown")
      .valueSeq()
      .flatten(true);
  }

  const xs = get(m, ["connections", type], List());
  return strategies.length > 0
    ? xs.filter(x => ~strategies.indexOf(x.get("strategy")))
    : xs;
}

export function connection(m, type = undefined, ...strategies) {
  return connections(m, type, ...strategies).get(0);
}

export function hasOneConnection(m, type = undefined) {
  const xs = connections(m);
  return xs.count() === 1 && (!type || xs.getIn([0, "type"]) === type);
}

export function hasOnlyConnections(m, type = undefined, ...strategies) {
  const all = connections(m).count();
  const filtered = connections(m, type, ...strategies).count();
  return all > 0 && all === filtered;
}

export function hasSomeConnections(m, type = undefined, ...strategies) {
  return connections(m, type, ...strategies).count() > 0;
}

export function findConnection(m, name) {
  return connections(m).find(m1 => m1.get("name") === name);
}

export function hasConnection(m, name) {
  return !!findConnection(m, name);
}

export function runHook(m, str, ...args) {
  get(m, "hookRunner")(str, ...args);
}

export function emitEvent(m, str, ...args) {
  get(m, "emitEventFn")(str, ...args);
}

export function loginErrorMessage(m, error) {
  // NOTE: previous version of lock checked for status codes and, at
  // some point, if the status code was 401 it defaults to an
  // "invalid_user_password" error (actually the
  // "wrongEmailPasswordErrorText" dict entry) instead of checking
  // explicitly. We should figure out if there was a reason for that.

  if (error.status === 0) {
    return ui.t(m, ["error", "login", "lock.network"], {__textOnly: true});
  }

  // Custom rule error (except blocked_user)
  if (error.error === "rule_error") {
    return error.description
      || ui.t(m, ["error", "login", "lock.fallback"], {__textOnly: true});
  }

  return ui.t(m, ["error", "login", error.error], {__textOnly: true})
    || ui.t(m, ["error", "login", "lock.fallback"], {__textOnly: true});
}

export function stop(m) {
  return set(m, "stopped", true);
}

export function hasStopped(m) {
  return get(m, "stopped");
}
<commit_msg>Log errors to the console not just warnings<commit_after>import Immutable, { List, Map, Set } from 'immutable';
import { isSmallScreen } from '../utils/media_utils';
import * as d from './i18n/index';
import t from './i18n/t';
import trim from 'trim';
import * as gp from '../avatar/gravatar_provider';
import { dataFns } from '../utils/data_utils';

const {
  get,
  init,
  remove,
  reset,
  set,
  tget,
  tset,
  tremove
} = dataFns(["core"]);

export function setup(id, clientID, domain, options, logInCallback, hookRunner, emitEventFn) {
  return init(id, Immutable.fromJS({
    auth: extractAuthOptions(options),
    clientID: clientID,
    domain: domain,
    emitEventFn: emitEventFn,
    hookRunner: hookRunner,
    mode: options.mode,
    logInCallback: logInCallback,
    allowedConnections: Immutable.fromJS(options.allowedConnections || []),
    ui: extractUIOptions(id, options.mode, options)
  }));
}

export function id(m) {
  return m.get("id");
}

export function clientID(m) {
  return get(m, "clientID");
}

export function domain(m) {
  return get(m, "domain");
}

export function modeName(m) {
  return get(m, "mode");
}

export function setSubmitting(m, value, error = "") {
  m = tset(m, "submitting", value);
  m = error && !value ? setGlobalError(m, error) : clearGlobalError(m);
  return m;
}

export function submitting(m) {
  return tget(m, "submitting", false);
}

export function setGlobalError(m, str) {
  return tset(m, "globalError", str);
}

export function globalError(m) {
  return tget(m, "globalError", "");
}

export function clearGlobalError(m) {
  return tremove(m, "globalError");
}

export function setGlobalSuccess(m, str) {
  return tset(m, "globalSuccess", str);
}

export function globalSuccess(m) {
  return tget(m, "globalSuccess", "");
}

export function clearGlobalSuccess(m) {
  return tremove(m, "globalSuccess");
}

export function rendering(m) {
  return tget(m, "render", false);
}

export function stopRendering(m) {
  return tremove(m, "render");
}

function extractUIOptions(id, modeName, options) {
  const closable = options.container ? false : undefined === options.closable ? true : !!options.closable;
  const theme = options.theme || {};
  const { logo, primaryColor } = theme;

  const avatar = options.avatar !== null;
  const customAvatarProvider = options.avatar
    && typeof options.avatar.url === "function"
    && typeof options.avatar.displayName === "function"
    && options.avatar;
  const avatarProvider = customAvatarProvider || gp;

  return new Map({
    containerID: options.container || `auth0-lock-container-${id}`,
    appendContainer: !options.container,
    autoclose: undefined === options.autoclose ? false : closable && options.autoclose,
    autofocus: undefined === options.autofocus ? !(options.container || isSmallScreen()) : !!options.autofocus,
    avatar: avatar,
    avatarProvider: avatarProvider,
    logo: typeof logo === "string" ? logo : undefined,
    closable: closable,
    dict: d.buildDict(modeName, typeof options.languageDictionary === "object" ? options.languageDictionary : {}),
    disableWarnings: options.disableWarnings === undefined ? false : !!options.disableWarnings,
    mobile: undefined === options.mobile ? false : !!options.mobile,
    popupOptions: new Map(undefined === options.popupOptions ? {} : options.popupOptions),
    primaryColor: typeof primaryColor === "string" ? primaryColor : undefined,
    rememberLastLogin: undefined === options.rememberLastLogin ? true : !!options.rememberLastLogin
  });
}

const { get: getUIAttribute } = dataFns(["core", "ui"]);

export const ui = {
  containerID: lock => getUIAttribute(lock, "containerID"),
  appendContainer: lock => getUIAttribute(lock, "appendContainer"),
  autoclose: lock => getUIAttribute(lock, "autoclose"),
  autofocus: lock => getUIAttribute(lock, "autofocus"),
  avatar: lock => getUIAttribute(lock, "avatar"),
  avatarProvider: lock => getUIAttribute(lock, "avatarProvider"),
  closable: lock => getUIAttribute(lock, "closable"),
  dict: lock => getUIAttribute(lock, "dict"),
  disableWarnings: lock => getUIAttribute(lock, "disableWarnings"),
  t: (lock, keyPath, params) => t(ui.dict(lock), keyPath, params),
  logo: lock => getUIAttribute(lock, "logo"),
  mobile: lock => getUIAttribute(lock, "mobile"),
  popupOptions: lock => getUIAttribute(lock, "popupOptions"),
  primaryColor: lock => getUIAttribute(lock, "primaryColor"),
  rememberLastLogin: lock => getUIAttribute(lock, "rememberLastLogin")
};

const { get: getAuthAttribute } = dataFns(["core", "auth"]);

export const auth = {
  params: lock => getAuthAttribute(lock, "params"),
  redirect: lock => getAuthAttribute(lock, "redirect"),
  redirectUrl: lock => getAuthAttribute(lock, "redirectUrl"),
  responseType: lock => getAuthAttribute(lock, "responseType"),
  sso: lock => getAuthAttribute(lock, "sso")
};

function extractAuthOptions(options) {
  // TODO: shouldn't all options be namespased in authentication?
  let {
    params,
    redirect,
    redirectUrl,
    responseType,
    sso
  } = options.auth || {};

  params = typeof params === "object" ? params : {};
  redirectUrl = typeof redirectUrl === "string" && redirectUrl ? redirectUrl : undefined;
  redirect = typeof redirect === "boolean" ? redirect : true;
  responseType = typeof responseType === "string" ? responseType : redirectUrl ? "code" : "token";
  sso = typeof sso === "boolean" ? sso : true;

  if (trim(params.scope || "") === "openid profile") {
    warn(options, "Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details.");
  }

  return Immutable.fromJS({
    params,
    redirect,
    redirectUrl,
    responseType,
    sso
  });
}

export function withAuthOptions(m, opts) {
  return Immutable.fromJS(opts)
    .merge(get(m, "auth"))
    .toJS();
}

export function invokeLogInCallback(m, ...args) {
  get(m, "logInCallback").apply(undefined, args);
}

export function render(m) {
  return tset(m, "render", true);
}

export { reset };

export function setSignedIn(m, value) {
  return tset(m, "signedIn", value);
}

export function signedIn(m) {
  return tget(m, "signedIn", false);
}

export function warn(x, str) {
  const shouldOutput = Map.isMap(x)
    ? !ui.disableWarnings(x)
    : !x.disableWarnings;

  if (shouldOutput && console && console.warn) {
    console.warn(str);
  }
}

export function error(x, str) {
  const shouldOutput = Map.isMap(x)
    ? !ui.disableWarnings(x)
    : !x.disableWarnings;

  if (shouldOutput && console && console.error) {
    console.error(str);
  }
}

export function allowedConnections(m) {
  return get(m, "allowedConnections");
}

export function connections(m, type = undefined, ...strategies) {
  if (arguments.length === 1) {
    return get(m, "connections", Map())
      .filter((v, k) => k !== "unknown")
      .valueSeq()
      .flatten(true);
  }

  const xs = get(m, ["connections", type], List());
  return strategies.length > 0
    ? xs.filter(x => ~strategies.indexOf(x.get("strategy")))
    : xs;
}

export function connection(m, type = undefined, ...strategies) {
  return connections(m, type, ...strategies).get(0);
}

export function hasOneConnection(m, type = undefined) {
  const xs = connections(m);
  return xs.count() === 1 && (!type || xs.getIn([0, "type"]) === type);
}

export function hasOnlyConnections(m, type = undefined, ...strategies) {
  const all = connections(m).count();
  const filtered = connections(m, type, ...strategies).count();
  return all > 0 && all === filtered;
}

export function hasSomeConnections(m, type = undefined, ...strategies) {
  return connections(m, type, ...strategies).count() > 0;
}

export function findConnection(m, name) {
  return connections(m).find(m1 => m1.get("name") === name);
}

export function hasConnection(m, name) {
  return !!findConnection(m, name);
}

export function runHook(m, str, ...args) {
  get(m, "hookRunner")(str, ...args);
}

export function emitEvent(m, str, ...args) {
  get(m, "emitEventFn")(str, ...args);
}

export function loginErrorMessage(m, error) {
  // NOTE: previous version of lock checked for status codes and, at
  // some point, if the status code was 401 it defaults to an
  // "invalid_user_password" error (actually the
  // "wrongEmailPasswordErrorText" dict entry) instead of checking
  // explicitly. We should figure out if there was a reason for that.

  if (error.status === 0) {
    return ui.t(m, ["error", "login", "lock.network"], {__textOnly: true});
  }

  // Custom rule error (except blocked_user)
  if (error.error === "rule_error") {
    return error.description
      || ui.t(m, ["error", "login", "lock.fallback"], {__textOnly: true});
  }

  return ui.t(m, ["error", "login", error.error], {__textOnly: true})
    || ui.t(m, ["error", "login", "lock.fallback"], {__textOnly: true});
}

export function stop(m) {
  return set(m, "stopped", true);
}

export function hasStopped(m) {
  return get(m, "stopped");
}
<|endoftext|>


<commit_before>/**
 * @namespace PIXI
 */
export * from './const';
export * from './math';

import * as utils from './utils';
import * as ticker from './ticker';
import settings from './settings';
import CanvasRenderer from './renderers/canvas/CanvasRenderer';
import WebGLRenderer from './renderers/webgl/WebGLRenderer';

export { settings, utils, ticker, CanvasRenderer, WebGLRenderer };

export { default as glCore } from 'pixi-gl-core';

export { default as Bounds } from './display/Bounds';
export { default as DisplayObject } from './display/DisplayObject';
export { default as Container } from './display/Container';
export { default as Transform } from './display/Transform';
export { default as TransformStatic } from './display/TransformStatic';
export { default as TransformBase } from './display/TransformBase';
export { default as Sprite } from './sprites/Sprite';
export { default as CanvasSpriteRenderer } from './sprites/canvas/CanvasSpriteRenderer';
export { default as CanvasTinter } from './sprites/canvas/CanvasTinter';
export { default as SpriteRenderer } from './sprites/webgl/SpriteRenderer';
export { default as Text } from './text/Text';
export { default as TextStyle } from './text/TextStyle';
export { default as TextMetrics } from './text/TextMetrics';
export { default as Graphics } from './graphics/Graphics';
export { default as GraphicsData } from './graphics/GraphicsData';
export { default as GraphicsRenderer } from './graphics/webgl/GraphicsRenderer';
export { default as CanvasGraphicsRenderer } from './graphics/canvas/CanvasGraphicsRenderer';
export { default as Spritesheet } from './textures/Spritesheet';
export { default as FrameBuffer } from './textures/FrameBuffer';
export { default as CubeTexture } from './textures/CubeTexture';
export { default as BaseTexture } from './textures/BaseTexture';
export { default as ArrayTexture } from './textures/ArrayTexture';
export { default as Texture } from './textures/Texture';
export { default as RenderTexture } from './textures/RenderTexture';
export { default as BaseRenderTexture } from './textures/BaseRenderTexture';
export { default as VideoBaseTexture } from './textures/VideoBaseTexture';
export { default as TextureUvs } from './textures/TextureUvs';
export { default as CanvasRenderTarget } from './renderers/canvas/utils/CanvasRenderTarget';
export { default as WebGLSystem } from './renderers/webgl/systems/WebGLSystem';
export { default as State } from './renderers/webgl/State';
export { default as ObjectRenderer } from './renderers/webgl/utils/ObjectRenderer';
export { default as RenderTarget } from './renderers/webgl/utils/RenderTarget';
export { default as Quad } from './renderers/webgl/utils/Quad';
export { default as Shader } from './shader/Shader';
export { default as Program } from './shader/Program';
export { default as UniformGroup } from './shader/UniformGroup';
export { default as SpriteMaskFilter } from './renderers/webgl/filters/spriteMask/SpriteMaskFilter';
export { default as Filter } from './renderers/webgl/filters/Filter';
export { default as Application } from './Application';
export { autoDetectRenderer } from './autoDetectRenderer';
<commit_msg>Expose image resource to public API<commit_after>/**
 * @namespace PIXI
 */
import ImageResource from './textures/resources/ImageResource';

export * from './const';
export * from './math';

import * as utils from './utils';
import * as ticker from './ticker';
import settings from './settings';
import CanvasRenderer from './renderers/canvas/CanvasRenderer';
import WebGLRenderer from './renderers/webgl/WebGLRenderer';

export { settings, utils, ticker, CanvasRenderer, WebGLRenderer };

export { default as glCore } from 'pixi-gl-core';

export { default as Bounds } from './display/Bounds';
export { default as DisplayObject } from './display/DisplayObject';
export { default as Container } from './display/Container';
export { default as Transform } from './display/Transform';
export { default as TransformStatic } from './display/TransformStatic';
export { default as TransformBase } from './display/TransformBase';
export { default as Sprite } from './sprites/Sprite';
export { default as CanvasSpriteRenderer } from './sprites/canvas/CanvasSpriteRenderer';
export { default as CanvasTinter } from './sprites/canvas/CanvasTinter';
export { default as SpriteRenderer } from './sprites/webgl/SpriteRenderer';
export { default as Text } from './text/Text';
export { default as TextStyle } from './text/TextStyle';
export { default as TextMetrics } from './text/TextMetrics';
export { default as Graphics } from './graphics/Graphics';
export { default as GraphicsData } from './graphics/GraphicsData';
export { default as GraphicsRenderer } from './graphics/webgl/GraphicsRenderer';
export { default as CanvasGraphicsRenderer } from './graphics/canvas/CanvasGraphicsRenderer';
export { default as Spritesheet } from './textures/Spritesheet';
export { default as FrameBuffer } from './textures/FrameBuffer';
export { default as CubeTexture } from './textures/CubeTexture';
export { default as BaseTexture } from './textures/BaseTexture';

// image resource
export { default as ImageResource } from './textures/resources/ImageResource';

export { default as ArrayTexture } from './textures/ArrayTexture';
export { default as Texture } from './textures/Texture';
export { default as RenderTexture } from './textures/RenderTexture';
export { default as BaseRenderTexture } from './textures/BaseRenderTexture';
export { default as VideoBaseTexture } from './textures/VideoBaseTexture';
export { default as TextureUvs } from './textures/TextureUvs';
export { default as CanvasRenderTarget } from './renderers/canvas/utils/CanvasRenderTarget';
export { default as WebGLSystem } from './renderers/webgl/systems/WebGLSystem';
export { default as State } from './renderers/webgl/State';
export { default as ObjectRenderer } from './renderers/webgl/utils/ObjectRenderer';
export { default as RenderTarget } from './renderers/webgl/utils/RenderTarget';
export { default as Quad } from './renderers/webgl/utils/Quad';
export { default as Shader } from './shader/Shader';
export { default as Program } from './shader/Program';
export { default as UniformGroup } from './shader/UniformGroup';
export { default as SpriteMaskFilter } from './renderers/webgl/filters/spriteMask/SpriteMaskFilter';
export { default as Filter } from './renderers/webgl/filters/Filter';
export { default as Application } from './Application';
export { autoDetectRenderer } from './autoDetectRenderer';
<|endoftext|>


<commit_before>'use strict';

import {toCamel, syncObjects} from './utils';
import storage from './storage';
import q from 'q';
import clone from 'lodash/lang/clone';

const original = {};
var Defer = q.defer;

export default class Model {
  constructor(type, id, attr, adapter) {
    var models = [],
      p = new Defer(),
      self = this;

    // Check if resource or collection
    this.address = (id) ? type + '/' + id : type;
    this.type = type;
    this.__adapter = adapter;

    if (!attr) {
      /**
       * GET request case
       * Either fetching a collection
       * Either fetching a resource
       */
      this.__adapter.onDone((model) => {
        if (model.length) {
          /**
           * GET Collection case
           */
          model.forEach((item) => {
            models.push( new Model(type, item.id, item, self.__adapter) );
          });
          p.resolve(models);
        }
        else {
          /**
           * GET Resource case
           */
          self.attr = toCamel(clone(model, true));
          storage.store(self);
          original[self.type + self.__unique] = model;

          p.resolve(self);
        }
      }).onFail(() => {
        p.reject('GET HTTP request failed for the resource: [' + self.type +']');
      }).ajax('get', this.address, false);

    }
    else {
      /**
       * Create a new Model based on an given ATTR
       * NO REQUEST here
       */
      this.attr = toCamel(clone(attr, true));
      storage.store(this);
      original[this.type + this.__unique] = attr;

      if(!this.attr.id) {
        this.attr.id = id;
      }
    }

    /**
     * return collection
     */
    if (models.length) {
      return p.promise;
    }

    /**
     * return resource
     */
    if (!attr) {
      return p.promise;
    }
  }

  /**
   * The update method, sends all attributes via API and if the request was a success it recieves them back
   * also syncs the same models
   * @return {Promise}
   */
  update() {
    var self = this,
      defer = new Defer(),
      originalObj = original[this.type + this.__unique],
      syncedOriginal= {};

    syncedOriginal = syncObjects(originalObj, this.attr);

    this.__adapter.onDone((attr) => {
      self.attr = toCamel(clone(attr, true));
      storage.store(self);
      original[self.type + self.__unique] = attr;

      defer.resolve(self);
    })
    .onFail(() => {
      defer.reject('A problem has accoured while trying to update the [' + self.type + '] model');
    })
    .ajax('put', this.address, false, syncedOriginal);

    return defer.promise;
  }

  get() {
    var self = this,
        defer = new Defer();

    this.__adapter.onDone((attr) => {
      /**
       * GET Resource case
       */
      self.attr = toCamel(clone(attr, true));
      storage.store(self);
      original[self.type + self.__unique] = attr;

      defer.resolve(self);
    }).ajax('get', this.address, false);

    return defer.promise;
  }

  delete() {
    var defer = new Defer();

    this.__adapter.onDone(() => {
      defer.resolve();
    }).onFail(() => {
      defer.reject();
    }).ajax('delete', this.address, false);

    delete original[this.type + this.__unique];

    storage.delete(this);

    this.attr = {};

    return defer.promise;
  }
}

/**
* Creates a new model of the type given with the specified attr, if the attr aren't matched the model will not be created
* @param  {String} type The model type
* @param  {Object} attr The model's attributes
*/
Model.create = function(type, attr, __adapter) {
  var defer = new Defer();

  __adapter.onDone((newAttr) => {
    defer.resolve(new Model(type, newAttr.id, newAttr, __adapter));
  }).onFail(() => {
    defer.reject('A problem has accoured while trying to create a [' + this.type + '] model');
  }).ajax('post', type, false, attr);

  return defer.promise;
};
<commit_msg>Small changes<commit_after>'use strict';

import {toCamel, syncObjects} from './utils';
import storage from './storage';
import q from 'q';
import clone from 'lodash/lang/clone';

const original = {};
const Defer = q.defer;

export default class Model {
  constructor(type, id, attr, adapter) {
    var models = [],
      p = new Defer(),
      self = this;

    // Check if resource or collection
    this.address = (id) ? type + '/' + id : type;
    this.type = type;
    this.__adapter = adapter;

    if (!attr) {
      /**
       * GET request case
       * Either fetching a collection
       * Either fetching a resource
       */
      this.__adapter.onDone((model) => {
        if (model.length) {
          /**
           * GET Collection case
           */
          model.forEach((item) => {
            models.push( new Model(type, item.id, item, self.__adapter) );
          });
          p.resolve(models);
        }
        else {
          /**
           * GET Resource case
           */
          self.attr = toCamel(clone(model, true));
          storage.store(self);
          original[self.type + self.__unique] = model;

          p.resolve(self);
        }
      }).onFail(() => {
        p.reject('GET HTTP request failed for the resource: [' + self.type +']');
      }).ajax('get', this.address, false);

    }
    else {
      /**
       * Create a new Model based on an given ATTR
       * NO REQUEST here
       */
      this.attr = toCamel(clone(attr, true));
      storage.store(this);
      original[this.type + this.__unique] = attr;

      if(!this.attr.id) {
        this.attr.id = id;
      }
    }

    /**
     * return collection
     */
    if (models.length) {
      return p.promise;
    }

    /**
     * return resource
     */
    if (!attr) {
      return p.promise;
    }
  }

  /**
   * The update method, sends all attributes via API and if the request was a success it recieves them back
   * also syncs the same models
   * @return {Promise}
   */
  update() {
    var self = this,
      defer = new Defer(),
      originalObj = original[this.type + this.__unique],
      syncedOriginal= {};

    syncedOriginal = syncObjects(originalObj, this.attr);

    this.__adapter.onDone((attr) => {
      self.attr = toCamel(clone(attr, true));
      storage.store(self);
      original[self.type + self.__unique] = attr;

      defer.resolve(self);
    })
    .onFail(() => {
      defer.reject('A problem has accoured while trying to update the [' + self.type + '] model');
    })
    .ajax('put', this.address, false, syncedOriginal);

    return defer.promise;
  }

  get() {
    var self = this,
        defer = new Defer();

    this.__adapter.onDone((attr) => {
      /**
       * GET Resource case
       */
      self.attr = toCamel(clone(attr, true));
      storage.store(self);
      original[self.type + self.__unique] = attr;

      defer.resolve(self);
    }).ajax('get', this.address, false);

    return defer.promise;
  }

  delete() {
    var defer = new Defer();

    this.__adapter.onDone(() => {
      defer.resolve();
    }).onFail(() => {
      defer.reject();
    }).ajax('delete', this.address, false);

    delete original[this.type + this.__unique];

    storage.delete(this);

    this.attr = {};

    return defer.promise;
  }
}

/**
* Creates a new model of the type given with the specified attr, if the attr aren't matched the model will not be created
* @param  {String} type The model type
* @param  {Object} attr The model's attributes
*/
Model.create = function(type, attr, __adapter) {
  var defer = new Defer();

  __adapter.onDone((newAttr) => {
    defer.resolve(new Model(type, newAttr.id, newAttr, __adapter));
  }).onFail(() => {
    defer.reject('A problem has accoured while trying to create a [' + this.type + '] model');
  }).ajax('post', type, false, attr);

  return defer.promise;
};
<|endoftext|>


<commit_before>// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/*********************************************
This basic RFID example listens for an RFID
device to come within range of the module,
then logs its UID to the console.
*********************************************/

var tessel = require('tessel');

var rfid = require('../').use(tessel.port['A']); // Replace '../' with 'rfid-pn532' in your own code

rfid.on('ready', function (version) {
  console.log('Ready to read RFID card');

  rfid.on('data', function(uid) {
    console.log('UID:', uid);
  });
});
<commit_msg>added back error handling code<commit_after>/*********************************************
This basic RFID example listens for an RFID
device to come within range of the module,
then logs its UID to the console.
*********************************************/

// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

var tessel = require('tessel');

var rfid = require('../').use(tessel.port['A']); // Replace '../' with 'rfid-pn532' in your own code

rfid.on('ready', function (version) {
  console.log('Ready to read RFID card');

  rfid.on('data', function(uid) {
    console.log('UID:', uid);
  });
});

rfid.on('error', function (err) {
  console.error(err);
});
<|endoftext|>


<commit_before>import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import { rootReducer } from './root'

export default (initialState = {}) => {
  const logger = createLogger({
    collapsed: true,
  })
  let middleware = applyMiddleware(thunk, logger)

  if (process.env.NODE_ENV !== 'production') {
    // configure redux-devtools-extension
    // @see https://github.com/zalmoxisus/redux-devtools-extension
    const devToolsExtension = window.devToolsExtension
    if (typeof devToolsExtension === 'function') {
      middleware = compose(middleware, devToolsExtension())
    }
  }

  const store = createStore(rootReducer, initialState, middleware)

  if (module.hot) {
    module.hot.accept('./root', () => {
      store.replaceReducer(rootReducer.default)
    })
  }

  return store
}
<commit_msg>Remove logger from prod<commit_after>import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import { rootReducer } from './root'

export default (initialState = {}) => {
  const logger = createLogger({
    collapsed: true,
  })
  let middleware = applyMiddleware(thunk)

  if (process.env.NODE_ENV !== 'production') {
    middleware = middleware.compose(logger)
    // configure redux-devtools-extension
    // @see https://github.com/zalmoxisus/redux-devtools-extension
    const devToolsExtension = window.devToolsExtension
    if (typeof devToolsExtension === 'function') {
      middleware = compose(middleware, devToolsExtension())
    }
  }

  const store = createStore(rootReducer, initialState, middleware)

  if (module.hot) {
    module.hot.accept('./root', () => {
      store.replaceReducer(rootReducer.default)
    })
  }

  return store
}
<|endoftext|>


<commit_before>export const patterns = [{
	name:"Date in format dd/mm/yyyy",
	regex:/^(0?[1-9]|[12][0-9]|3[01])([ /\-])(0?[1-9]|1[012])\2(19[0-9][0-9]|20[0-9][0-9])$/,
	description:"Will match dates with dashes, slashes or with spaces dd-mm-yyyy dd/mm/yyyy dd mm yyyy",
	tags:"date,time"
},
{
	name: "Time in 24-hour format",
	regex: /([01]?[0-9]|2[0-3]):[0-5][0-9]/,
	description: "Match times in 24 hour format",
	tags: "date,time"
},
{
	name:"HTML tags",
	regex:/^<([a-z1-6]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/,
	description:"Match opening and closing HTML tags with content between",
	tags:"markup,xml,html"
},
{
	name:"Username",
	regex:/^[a-zA-Z0-9_-]{3,16}$/,
	description:"A string between 3 and 16 characters, allowing alphanumeric characters and hyphens and underscores",
	tags:"username,validation"
},
{
	name:"Hex Color Value",
	regex:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
	description:"RGB hex colors",
	tags:"hex,color"
},
{
	name:"URL Slug",
	regex:/^[a-z0-9-]+$/,
	description:"Match valid URL slugs",
	tags:"URL"
},
{
	name:"Email",
	regex:/^([a-z0-9+_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,24})$/,
	description:"Match standards complient email addresses",
	tags:"email,validation"
},
{
	name:"SRC of image tag",
	regex:/\< *[img][^\>]*[src] *= *[\"\']{0,1}([^\"\'\ >]*)/,
	description:"Match the src attribute of an HTML image tag",
	tags:"html,tag,image"
},
{
	name:"URL",
	regex:/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
	description:"Match URL with optional protocal",
	tags:"url,address,http"
},
{
	name:"IPv4 Address",
	regex:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
	description:"Match IP v4 addresses",
	tags:"tcpip,internet,address"
},
{
	name: "IPv6 Address",
	regex: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,
	description: "Match IP v6 addresses",
	tags: "tcpip,internet,address"
},
{
	name:"Positive Integer",
	regex:/^\d+$/,
	descriptions:"Match whole numbers above zero",
	tags:"number"
},
{
	name:"Negative Integer",
	regex:/^-\d+$/,
	description:"Match whole numbers below zero",
	tags:"number"
},
{
	name:"Integer",
	regex:/^-?\d+$/,
	description:"Match whole numbers, above or below zero",
	tags:"number"
},
{
	name:"Positive number",
	regex:/^\d*\.?\d+$/,
	description:"Match integers or floats that are positive",
	tags:"float"
},
{
	name:"Negative number",
	regex:/^-\d*\.?\d+$/,
	description:"Match integers or floats that are negative",
	tags:"float"
},
{
	name:"Positive or negative number",
	regex:/^-?\d*\.?\d+$/,
	description:"Match integers or floats that are positive or negative",
	tags:"float"
},
{
	name:"Phone number",
	regex:/^\+?[\d\s]{3,}$/,
	description:"Match phone numbers at least 3 digits long",
	tags:"validation"
},
{
	name:"New line",
	regex:/[\r\n]|$/,
	description:"Match new lines within text",
	tags:"text"
},
{
	name:"ID of Youtube video",
	regex:/https?:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/gi,
	description:"Match the ID of a youtube video URL",
	tags:"video,youtube,url"
},
{
	name:"ID of Youtube Channel",
	regex: /https?:\/\/(www\.)?youtube.com\/channel\/UC([-_a-z0-9]{22})/i,
	description:"Match the ID of a youtube channel URL",
	tags:"channel,youtube,url"
},
{
	name:"CSS comment",
	regex:/\/\*[^*]*\*+([^/*][^*]*\*+)*\//,
	description:"Match standard CSS comments",
	tags:"css,comment,code"
},
{
	name:"Wordpress shortcodes",
	regex:/^\[([a-z-_0-9]+)([^\[]+)*(?:\](.*)\[\/\1\]|\s+\/\])$/,
	description:"Matches opening and closing shortcode tags with content in-between them.",
	tags:"wordpress,shortcodes,markup"
}
/*,
{
	name:"Word exception",
	regex:/\bTarzan\b|\bJane\b|\bSuperman\b|(\w+)/,
	description:"Match all words apart from the ones listed",
	tags:"words,sentence,blacklist"
}*/
];
<commit_msg>Amend email regex<commit_after>export const patterns = [{
	name:"Date in format dd/mm/yyyy",
	regex:/^(0?[1-9]|[12][0-9]|3[01])([ /\-])(0?[1-9]|1[012])\2(19[0-9][0-9]|20[0-9][0-9])$/,
	description:"Will match dates with dashes, slashes or with spaces dd-mm-yyyy dd/mm/yyyy dd mm yyyy",
	tags:"date,time"
},
{
	name: "Time in 24-hour format",
	regex: /([01]?[0-9]|2[0-3]):[0-5][0-9]/,
	description: "Match times in 24 hour format",
	tags: "date,time"
},
{
	name:"HTML tags",
	regex:/^<([a-z1-6]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/,
	description:"Match opening and closing HTML tags with content between",
	tags:"markup,xml,html"
},
{
	name:"Username",
	regex:/^[a-zA-Z0-9_-]{3,16}$/,
	description:"A string between 3 and 16 characters, allowing alphanumeric characters and hyphens and underscores",
	tags:"username,validation"
},
{
	name:"Hex Color Value",
	regex:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
	description:"RGB hex colors",
	tags:"hex,color"
},
{
	name:"URL Slug",
	regex:/^[a-z0-9-]+$/,
	description:"Match valid URL slugs",
	tags:"URL"
},
{
	name:"Email",
	regex:/^.+@.+$/,
	description:"Match standards complient email addresses. A stricter regex fully compliant with the standards is considered too complex to maintain. To actually verify an email address sending a conformation email is the only valid test.",
	tags:"email,validation"
},
{
	name:"SRC of image tag",
	regex:/\< *[img][^\>]*[src] *= *[\"\']{0,1}([^\"\'\ >]*)/,
	description:"Match the src attribute of an HTML image tag",
	tags:"html,tag,image"
},
{
	name:"URL",
	regex:/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
	description:"Match URL with optional protocal",
	tags:"url,address,http"
},
{
	name:"IPv4 Address",
	regex:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
	description:"Match IP v4 addresses",
	tags:"tcpip,internet,address"
},
{
	name: "IPv6 Address",
	regex: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,
	description: "Match IP v6 addresses",
	tags: "tcpip,internet,address"
},
{
	name:"Positive Integer",
	regex:/^\d+$/,
	descriptions:"Match whole numbers above zero",
	tags:"number"
},
{
	name:"Negative Integer",
	regex:/^-\d+$/,
	description:"Match whole numbers below zero",
	tags:"number"
},
{
	name:"Integer",
	regex:/^-?\d+$/,
	description:"Match whole numbers, above or below zero",
	tags:"number"
},
{
	name:"Positive number",
	regex:/^\d*\.?\d+$/,
	description:"Match integers or floats that are positive",
	tags:"float"
},
{
	name:"Negative number",
	regex:/^-\d*\.?\d+$/,
	description:"Match integers or floats that are negative",
	tags:"float"
},
{
	name:"Positive or negative number",
	regex:/^-?\d*\.?\d+$/,
	description:"Match integers or floats that are positive or negative",
	tags:"float"
},
{
	name:"Phone number",
	regex:/^\+?[\d\s]{3,}$/,
	description:"Match phone numbers at least 3 digits long",
	tags:"validation"
},
{
	name:"New line",
	regex:/[\r\n]|$/,
	description:"Match new lines within text",
	tags:"text"
},
{
	name:"ID of Youtube video",
	regex:/https?:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/gi,
	description:"Match the ID of a youtube video URL",
	tags:"video,youtube,url"
},
{
	name:"ID of Youtube Channel",
	regex: /https?:\/\/(www\.)?youtube.com\/channel\/UC([-_a-z0-9]{22})/i,
	description:"Match the ID of a youtube channel URL",
	tags:"channel,youtube,url"
},
{
	name:"CSS comment",
	regex:/\/\*[^*]*\*+([^/*][^*]*\*+)*\//,
	description:"Match standard CSS comments",
	tags:"css,comment,code"
},
{
	name:"Wordpress shortcodes",
	regex:/^\[([a-z-_0-9]+)([^\[]+)*(?:\](.*)\[\/\1\]|\s+\/\])$/,
	description:"Matches opening and closing shortcode tags with content in-between them.",
	tags:"wordpress,shortcodes,markup"
}
/*,
{
	name:"Word exception",
	regex:/\bTarzan\b|\bJane\b|\bSuperman\b|(\w+)/,
	description:"Match all words apart from the ones listed",
	tags:"words,sentence,blacklist"
}*/
];
<|endoftext|>


<commit_before>// adopted from: ilog <https://github.com/teambition/ilog>
// Copyright (c) 2015 Teambition (License: MIT)

'use strict'

const format = require('util').format
const nano   = require('../time/nano')
const slice  = require('../array/slice')
const jlog   = require('../util/jcolorz')
const apply  = require('../function/apply')

const levels = [
  'FATAL',    // level 0
  'CRITICAL', // level 1
  'ERROR',    // level 2
  'WARNING',  // level 3
  'ALERT',    // level 4
  'NOTICE',   // level 5
  'INFO',     // level 6
  'DEBUG'     // level 7
]

const clrs = {
  black   : 30,
  gray    : 90,
  grey    : 90,
  red     : 31,
  green   : 32,
  yellow  : 33,
  blue    : 34,
  magenta : 35,
  cyan    : 36,
  white   : 37
}

// Original version
function ilog () {
  if (arguments.length) {
    ilog._stdout.write(ilog._assembleLog(apply(format, null, slice(arguments))))
  }
}

// Own version: meant for raw string output to log
function logr () {
  // don't penalize a single string/template being passed as a param
  arguments.length > 1
    ? ilog._stdout.write(ilog._assembleLog(slice(arguments).join(' ')))
    : ilog._stdout.write(ilog._assembleLog(arguments[0]))
}

// options for display, preserving the original functionality by reversing values.
ilog.dates = false
ilog.colors = true
ilog.verbose = true

// ilog.level === -1 turns off all levels
// ilog.level === -2 turns on debug and trace logging
// ilog.level === -3 adds notice and info logging
ilog.level = 7
ilog.levels = levels.slice()

// ilog.fatal, ilog.critical, ilog.error, ilog.warning, ilog.alert
map(levels.slice(0, 5), (level, index) => {
  ilog[level.toLowerCase()] = function (error, stack) {
    if (error != null && index <= ilog.level) {
      // allow the ability to pass debugging messages as strings
      if (typeof error === 'string') error = {message: error}
      if (stack) error.stack = ilog._errorify(stack)

      error.name = level.charAt(0) + level.slice(1).toLowerCase()

      error = ilog.colors && ilog.verbose
        ? ilog._errorify(error)
        : ilog._stringify(ilog._errorify(error))

      let type = function (obj) {
        return typeof obj === 'string'
          ? obj
          : obj.message
      }

      ilog._outputDisplay(type(error), {name: level, color: 'red'})

      if (ilog.colors) ilog.inspect(error)
    }
  }
})

// ilog.notice, ilog.info
map(levels.slice(5, 7), (level, index) => {
  index += 5
  ilog[level.toLowerCase()] = function (message) {
    if (message != null && (index <= ilog.level || ilog.level <= -4)) {
      message = ilog._stringify(message)

      ilog._outputDisplay(message, {name: level, color: 'grey'})
    }
  }
})

ilog.debug = function () {
  if (arguments.length && (ilog.level >= 7 || ilog.level <= -3)) {
    let messages
    let stack = false

    if (arguments.length === 1) {
      messages = ilog._stringify(arguments[0])
    }

    else  {
      messages = arguments[0]
      stack = true
    }

    if (!ilog.colors || !ilog.verbose) messages = apply(format, null, slice(arguments))

    ilog._outputDisplay(messages, {name: 'DEBUG', color: 'cyan'})

    if (stack && ilog.colors) {
      forEach(slice(arguments, 1), (view) => {
        ilog.inspect(ilog._inspectify(view))
      })
    }
  }
}

ilog.assert = function (expression, label) {
  if (ilog.level >= 7 || ilog.level <= -3) {
    let result = !!expression
    let stack = {
      name: 'Assertion Test',
      message: label,
      actual: result,
      expected: true
    }

    let msg = ilog.colors && ilog.verbose
      ? label
      : ilog._stringify(stack)

    ilog._outputDisplay(msg, {name: 'ASERT', color: 'cyan'})
    if (ilog.colors) ilog.inspect(stack)
  }
}

// trace logging [level 8]
ilog.trace = function () {
  if (arguments.length && (ilog.level >= 8 || ilog.level <= -2)) {
    let messages = apply(format, null, slice(arguments))

    ilog._outputDisplay(messages, {name: 'TRACE', color: 'yellow'})
  }
}

ilog.tracer = function (prefix, prompt) {
  if (prompt == null) prompt = `${ilog._pointer.double}`
  if (prefix == null) prefix = 'LOGGR'

  return (nsp, clrs) => {
    return function () {
      if (arguments.length && (ilog.level >= 8 || ilog.level <= -2)) {
        let messages = apply(format, null, slice(arguments))

        ilog._outputDisplay(messages, {prefix: prefix, prompt: prompt, name: nsp, color: clrs})
      }
    }
  }
}

ilog.auto = function (error) {
  if (error instanceof Error) return ilog.error(error)

  let args = slice(arguments, +(error == null))

  if (args.length === 1) ilog.info(args[0])
  else apply(ilog.debug, null, args)
}

ilog.inspect = function () {
  if (ilog.verbose && ilog.level !== -1) {
    if (arguments.length > 1 && typeof arguments[0] === 'string') {
      ilog._outputDisplay(`Inspecting ${arguments[0]}: `, {name: 'LOGGR', color: 'white'})
      map(slice(arguments, 1), (arg) => {
        ilog._inspector(arg)
      })
    }

    else {
      map(slice(arguments), (arg) => {
        ilog._inspector(arg)
      })
    }
  }
}

// implement base start and stop times
// adopted from debug-logger
ilog.timeTables = {}

ilog.strt = function time (label) {
  if (Array.isArray(label)) {
    map(label, (lab) => {
      ilog.timeTables[lab] = process.hrtime()
    })
  }

  else {
    ilog.timeTables[label] = process.hrtime()
  }
}

ilog.stop = function timeEnd (label) {
  let diff = process.hrtime(ilog.timeTables[label])
  let diffMs = nano(diff, 'ms', 3)
  let msg = `${label} took: ${ilog._color(diffMs, 'grey')} ms`

  if (ilog.level !== -1) {
    ilog._outputDisplay(msg, {name: 'TIMER', color: 'white'})
  }

  return diffMs
}

ilog.log = logr
ilog._inspector = jlog // expose json-colorz
ilog._stdout = process.stdout
ilog._stderr = process.stderr
ilog._procname = process.argv[1].split('/').pop()
ilog._pointer = {
  tick       : '✔',
  check      : '√',
  cross      : '✖',
  star       : '★',
  bullet     : '*',
  dot        : '․',
  line       : '─',
  dash       : '-',
  ellipsis   : '…',
  info       : 'i',
  info2      : 'ℹ',
  warning    : '‼',
  warning2   : '⚠',
  flag       : '⚑',
  mark       : '✗',
  tilde      : '~',
  clip       : '❯',
  single     : '›',
  double     : '»',
  arrowUp    : '↑',
  arrowDown  : '↓',
  arrowLeft  : '←',
  arrowRight : '→',
  radioOn    : '◉',
  radioOff   : '◯'
}

ilog._outputDisplay = function (logMsg, levelObj, labelDisp) {
  // contruct components
  let level = ilog.colors ? ilog._color(levelObj.name, levelObj.color) : levelObj.name
  let label = ilog.dates ? ilog._label(new Date()) : ilog._label()

  // compose and log message
  ilog._stdout.write(ilog._assembleLog(logMsg, level, label))
}

ilog._color = function (label, color) {
  return `\u001b[${clrs[color]}m${label}\u001b[39m`
}

ilog._label = function () {
  return `${ilog._procname} ${ilog._pointer.double}`
}

ilog._assembleLog = function (log, level, label) {
  if (level) log = `${level} ${log}`
  if (label) log = `${label} ${log}\n`
  else log = `${ilog._label()} ${log}\n`

  return log
}

ilog._stringify = function (obj) {
  try {
    return JSON.stringify(obj)
  } catch (e) {
    return format(obj)
  }
}

ilog._inspectify = function (obj) {
  return new Inspectified(obj)
}

function Inspectified (obj) {
  let type = Object.prototype.toString.call(obj)
  this.type = type.replace(/^\[object |\]$/g, '').toLowerCase()
  this.inspector = {}
  if (type !== '[object Object]') {
    this.inspector[this.type] = obj
  } else if (type === '[object Object]'){
    this.inspector[this.type] = {}
    Object.keys(obj).map((key) => {
      if (!this.inspector[this.type][key]) this.inspector[this.type][key] = obj[key]
    })
  }
}

ilog._errorify = function (error) {
  return new Errorify(error)
}

function Errorify (error) {
  this.name = error.name || 'Error'
  this.message = error.message || format(error)

  if (error.code) this.code = error.code
  if (error.errno) this.errno = error.errno
  if (error.status) this.status = error.status
  if (error.syscall) this.syscall = error.syscall
  if (!Array.isArray(error)) {
    Object.keys(error).map((key) => {
      if (!this[key]) this[key] = error[key]
    })
  }
  if (error.stack) this.stack = error.stack
}

// ilog._standardize () {
//   return new Standardize()
// }

// function Standardize (level, msg) {
//   const os       = require('os')
//   const pid      = process.pid
//   const hostname = os.hostname()

//   this.pid = pid
//   this.hostname = hostname
//   this.name = name
//   this.level = level
//   this.msg = msg && msg.toString()
//   this.time = new Date()
//   this.v = 0
// }

function forEach (array, iterator) {
  var i = -1
  var len = array >= 0 ? array : array.length

  while (++i < len) iterator(array[i], i)
}

function map (arr, fn) {
  var results = []
  if (arr == null) return results

  var i = -1
  var len = arr.length

  while (++i < len) {
    results[i] = fn(arr[i], i, arr)
  }
  return results
}

module.exports = ilog
<commit_msg>update debug/ilog — assemblelvl function allowing the customization of level labels also add check for ilog._color function to check if colors is enable globally<commit_after>// adopted from: ilog <https://github.com/teambition/ilog>
// Copyright (c) 2015 Teambition (License: MIT)

'use strict'

const format = require('util').format
const nano   = require('../time/nano')
const slice  = require('../array/slice')
const jlog   = require('../util/jcolorz')
const apply  = require('../function/apply')

const levels = [
  'FATAL',    // level 0
  'CRITICAL', // level 1
  'ERROR',    // level 2
  'WARNING',  // level 3
  'ALERT',    // level 4
  'NOTICE',   // level 5
  'INFO',     // level 6
  'DEBUG'     // level 7
]

const clrs = {
  black   : 30,
  gray    : 90,
  grey    : 90,
  red     : 31,
  green   : 32,
  yellow  : 33,
  blue    : 34,
  magenta : 35,
  cyan    : 36,
  white   : 37
}

// Original version
function ilog () {
  if (arguments.length) {
    ilog._stdout.write(ilog._assembleLog(apply(format, null, slice(arguments))))
  }
}

// Own version: meant for raw string output to log
function logr () {
  // don't penalize a single string/template being passed as a param
  arguments.length > 1
    ? ilog._stdout.write(ilog._assembleLog(slice(arguments).join(' ')))
    : ilog._stdout.write(ilog._assembleLog(arguments[0]))
}

// options for display, preserving the original functionality by reversing values.
ilog.dates = false
ilog.colors = true
ilog.verbose = true

// ilog.level === -1 turns off all levels
// ilog.level === -2 turns on debug and trace logging
// ilog.level === -3 adds notice and info logging
ilog.level = 7
ilog.levels = levels.slice()

// ilog.fatal, ilog.critical, ilog.error, ilog.warning, ilog.alert
map(levels.slice(0, 5), (level, index) => {
  ilog[level.toLowerCase()] = function (error, stack) {
    if (error != null && index <= ilog.level) {
      // allow the ability to pass debugging messages as strings
      if (typeof error === 'string') error = {message: error}
      if (stack) error.stack = ilog._errorify(stack)

      error.name = level.charAt(0) + level.slice(1).toLowerCase()

      error = ilog.colors && ilog.verbose
        ? ilog._errorify(error)
        : ilog._stringify(ilog._errorify(error))

      let type = function (obj) {
        return typeof obj === 'string'
          ? obj
          : obj.message
      }

      ilog._outputDisplay(type(error), {name: level, color: 'red'})

      if (ilog.colors) ilog.inspect(error)
    }
  }
})

// ilog.notice, ilog.info
map(levels.slice(5, 7), (level, index) => {
  index += 5
  ilog[level.toLowerCase()] = function (message) {
    if (message != null && (index <= ilog.level || ilog.level <= -4)) {
      message = ilog._stringify(message)

      ilog._outputDisplay(message, {name: level, color: 'grey'})
    }
  }
})

ilog.debug = function () {
  if (arguments.length && (ilog.level >= 7 || ilog.level <= -3)) {
    let messages
    let stack = false

    if (arguments.length === 1) {
      messages = ilog._stringify(arguments[0])
    }

    else  {
      messages = arguments[0]
      stack = true
    }

    if (!ilog.colors || !ilog.verbose) messages = apply(format, null, slice(arguments))

    ilog._outputDisplay(messages, {name: 'DEBUG', color: 'cyan'})

    if (stack && ilog.colors) {
      forEach(slice(arguments, 1), (view) => {
        ilog.inspect(ilog._inspectify(view))
      })
    }
  }
}

ilog.assert = function (expression, label) {
  if (ilog.level >= 7 || ilog.level <= -3) {
    let result = !!expression
    let stack = {
      name: 'Assertion Test',
      message: label,
      actual: result,
      expected: true
    }

    let msg = ilog.colors && ilog.verbose
      ? label
      : ilog._stringify(stack)

    ilog._outputDisplay(msg, {name: 'ASERT', color: 'cyan'})
    if (ilog.colors) ilog.inspect(stack)
  }
}

// trace logging [level 8]
ilog.trace = function () {
  if (arguments.length && (ilog.level >= 8 || ilog.level <= -2)) {
    let messages = apply(format, null, slice(arguments))

    ilog._outputDisplay(messages, {name: 'TRACE', color: 'yellow'})
  }
}

ilog.tracer = function (prefix, prompt) {
  if (prompt == null) prompt = `${ilog._pointer.double}`
  if (prefix == null) prefix = 'LOGGR'

  return (nsp, clrs) => {
    return function () {
      if (arguments.length && (ilog.level >= 8 || ilog.level <= -2)) {
        let messages = apply(format, null, slice(arguments))

        ilog._outputDisplay(messages, {prefix: prefix, prompt: prompt, name: nsp, color: clrs})
      }
    }
  }
}

ilog.auto = function (error) {
  if (error instanceof Error) return ilog.error(error)

  let args = slice(arguments, +(error == null))

  if (args.length === 1) ilog.info(args[0])
  else apply(ilog.debug, null, args)
}

ilog.inspect = function () {
  if (ilog.verbose && ilog.level !== -1) {
    if (arguments.length > 1 && typeof arguments[0] === 'string') {
      ilog._outputDisplay(`Inspecting ${arguments[0]}: `, {name: 'LOGGR', color: 'white'})
      map(slice(arguments, 1), (arg) => {
        ilog._inspector(arg)
      })
    }

    else {
      map(slice(arguments), (arg) => {
        ilog._inspector(arg)
      })
    }
  }
}

// implement base start and stop times
// adopted from debug-logger
ilog.timeTables = {}

ilog.strt = function time (label) {
  if (Array.isArray(label)) {
    map(label, (lab) => {
      ilog.timeTables[lab] = process.hrtime()
    })
  }

  else {
    ilog.timeTables[label] = process.hrtime()
  }
}

ilog.stop = function timeEnd (label) {
  let diff = process.hrtime(ilog.timeTables[label])
  let diffMs = nano(diff, 'ms', 3)
  let msg = `${label} took: ${ilog._color(diffMs, 'grey')} ms`

  if (ilog.level !== -1) {
    ilog._outputDisplay(msg, {name: 'TIMER', color: 'white'})
  }

  return diffMs
}

ilog.log = logr
ilog._inspector = jlog // expose json-colorz
ilog._stdout = process.stdout
ilog._stderr = process.stderr
ilog._procname = process.argv[1].split('/').pop()
ilog._pointer = {
  tick       : '✔',
  check      : '√',
  cross      : '✖',
  star       : '★',
  bullet     : '*',
  dot        : '․',
  line       : '─',
  dash       : '-',
  ellipsis   : '…',
  info       : 'i',
  info2      : 'ℹ',
  warning    : '‼',
  warning2   : '⚠',
  flag       : '⚑',
  mark       : '✗',
  tilde      : '~',
  clip       : '❯',
  single     : '›',
  double     : '»',
  arrowUp    : '↑',
  arrowDown  : '↓',
  arrowLeft  : '←',
  arrowRight : '→',
  radioOn    : '◉',
  radioOff   : '◯'
}

ilog._outputDisplay = function (logMsg, levelObj, labelDisp) {
  // contruct components
  let level = ilog.colors ? ilog._color(levelObj.name, levelObj.color) : levelObj.name
  let label = ilog.dates ? ilog._label(new Date()) : ilog._label()

  // compose and log message
  ilog._stdout.write(ilog._assembleLog(logMsg, level, label))
}

ilog._assembleLvl = function (lvlo) {
  let construct
  let prefix
  let prompt

  if (lvlo.prompt) {
    if (Array.isArray(lvlo.prompt)) {
      prompt = `${ilog._color(lvlo.prompt[0], lvlo.prompt[1])}`
    } else {
      prompt = `${ilog._color(lvlo.prompt)}`
    }
  } else {
    prompt = ''
  }
  if (lvlo.prefix) {
    if (Array.isArray(lvlo.prefix)) {
      prefix = `${ilog._color(lvlo.prefix[0], lvlo.prefix[1])}` + ' '+prompt + ' '
    }
    else {
      prefix = `${ilog._color(lvlo.prefix, 'black')}` + ' '+prompt + ' '
    }
  } else {
    prefix = ''
  }

  if (Array.isArray(lvlo.name)) {
    construct = map(lvlo.name, (lvlname, idx) => {
      let prompto = ' '+prompt+' '
      if (idx === lvlo.name.length - 1) prompto = ' '+prompt

      return ilog._color(lvlname, lvlo.color[idx]) + (prefix ? prompto : prompt)
    }).join('')
  } else {
    construct = `${ilog._color(lvlo.name, lvlo.color)}` + ' ' +  prompt
  }

  let construction = prefix + construct

  return construction
}

ilog._color = function (label, color) {
  if (!color || !ilog.colors) return label
  return `\u001b[${clrs[color]}m${label}\u001b[39m`
}

ilog._label = function () {
  return `${ilog._procname} ${ilog._pointer.double}`
}

ilog._assembleLog = function (log, level, label) {
  if (level) log = `${level} ${log}`
  if (label) log = `${label} ${log}\n`
  else log = `${ilog._label()} ${log}\n`

  return log
}

ilog._stringify = function (obj) {
  try {
    return JSON.stringify(obj)
  } catch (e) {
    return format(obj)
  }
}

ilog._inspectify = function (obj) {
  return new Inspectified(obj)
}

function Inspectified (obj) {
  let type = Object.prototype.toString.call(obj)
  this.type = type.replace(/^\[object |\]$/g, '').toLowerCase()
  this.inspector = {}
  if (type !== '[object Object]') {
    this.inspector[this.type] = obj
  } else if (type === '[object Object]'){
    this.inspector[this.type] = {}
    Object.keys(obj).map((key) => {
      if (!this.inspector[this.type][key]) this.inspector[this.type][key] = obj[key]
    })
  }
}

ilog._errorify = function (error) {
  return new Errorify(error)
}

function Errorify (error) {
  this.name = error.name || 'Error'
  this.message = error.message || format(error)

  if (error.code) this.code = error.code
  if (error.errno) this.errno = error.errno
  if (error.status) this.status = error.status
  if (error.syscall) this.syscall = error.syscall
  if (!Array.isArray(error)) {
    Object.keys(error).map((key) => {
      if (!this[key]) this[key] = error[key]
    })
  }
  if (error.stack) this.stack = error.stack
}

// ilog._standardize () {
//   return new Standardize()
// }

// function Standardize (level, msg) {
//   const os       = require('os')
//   const pid      = process.pid
//   const hostname = os.hostname()

//   this.pid = pid
//   this.hostname = hostname
//   this.name = name
//   this.level = level
//   this.msg = msg && msg.toString()
//   this.time = new Date()
//   this.v = 0
// }

function forEach (array, iterator) {
  var i = -1
  var len = array >= 0 ? array : array.length

  while (++i < len) iterator(array[i], i)
}

function map (arr, fn) {
  var results = []
  if (arr == null) return results

  var i = -1
  var len = arr.length

  while (++i < len) {
    results[i] = fn(arr[i], i, arr)
  }
  return results
}

module.exports = ilog
<|endoftext|>


<commit_before>Element.Dimensions = Class.create({
  // TODO: Add method for getting offsets (cumulative, viewport, scroll)
  initialize: function(element, options) {
    this.element = $(element);
    this.options = options;

    this.dimensions = new Hash();

    this.getDimensions();
  },

  getDimensions: function() {
    var element = this.element,
        display = element.getStyle('display'),
        noOffsetWidth;

    // The style object is inaccessible in Safari <= 2.0 when the element
    // is hidden.
    var isNotShown = display === "none" || display === null;
    var isTable = element.tagName.toUpperCase() == 'TABLE';

    // If the element is hidden, we show it for an instant
    // to grab its dimensions.
    if (isNotShown) {
      var style = element.style;
      var originalStyle = {
        visibility: style.visibility,
        position:   style.position,
        display:    style.display
      };

      Object.extend(style, {
        visibility: 'hidden',
        position:   'absolute',
        display:    'block'
      });
    }

    // clientWidth includes margin offsets of a table in Mozilla,
    // set offsets to 0, get width value, then revert back
    if (isTable) {
      var originalLeft = element.style.marginLeft;
      var originalRight = element.style.marginRight;
      element.style.marginLeft = '0px';
      element.style.marginRight = '0px';
      noOffsetWidth = element.clientWidth;
      element.style.marginLeft = originalLeft;
      element.style.marginRight = originalRight;
    }

    var paddingBox = {
      width:  noOffsetWidth || element.clientWidth,
      height: element.clientHeight
    };

    // For backwards-compatibility, the returned object will have
    // width and height equal to the padding-box values.
    this.dimensions.update(paddingBox);

    this.dimensions.set('paddingBox', paddingBox);

    var padding = this.getStyleValuesFor('padding', 'trbl');
    this.dimensions.set('padding', padding);

    var contentBox = {
      width:  paddingBox.width  - padding.left - padding.right,
      height: paddingBox.height - padding.top  - padding.bottom
    };

    this.dimensions.set('contentBox', contentBox);

    var border = this.getStyleValuesFor('border', 'trbl');
    this.dimensions.set('border', border);

    var borderBox = {
      width:  paddingBox.width  + border.left + border.right,
      height: paddingBox.height + border.top  + border.bottom
    };

    this.dimensions.set('borderBox', border);

    // If we altered the element's styles, return them to their
    // original values.
    if (isNotShown) {
      Object.extend(style, originalStyle);
    }

    return this.dimensions;
  },

  // Converts a raw CSS value like '9px' or '1em' to
  // a number (in pixels).
  // IE: Redefined below
  cssToNumber: function(property) {
    return window.parseFloat(this.element.getStyle(property));
  },

  // sidesNeeded argument is a string.
  // "trbl" = top, right, bottom, left
  // "tb"   = top, bottom
  getStyleValuesFor: function(property, sidesNeeded) {
    var sides = $w('top bottom left right');
    var propertyNames = sides.map( function(s) {
      return property + s.capitalize();
    });

    if (property === 'border') {
      propertyNames = propertyNames.map( function(p) {
        return p + 'Width';
      });
    }

    var values = {};

    sides.each( function(side, index) {
      if (!sidesNeeded.include(side.charAt(0))) return;
      values[side] = this.cssToNumber(propertyNames[index]);
    }, this);

    return values;
  },

  toObject: function() {
    return this.dimensions.toObject();
  },

  toHash: function() {
    return this.dimensions;
  },

  toJSON: function() {
    return this.dimensions.toJSON();
  }
});

if (Prototype.Browser.IE) {
  Element.Dimensions.addMethods({
    // IE gives the literal cascaded style, not the computed style.
    // We need to ensure pixel values are returned.
    cssToNumber: function(property) {
      var value = this.element.getStyle(property);

      if ((/^\d+(px)?$/i).test(value))
        return window.parseFloat(value);

      // If the unit is something other than a pixel (em, pt, %), set it on
      // something we can grab a pixel value from.
      var element = this.element;

      var sl = element.style.left, rsl = element.runtimeStyle.left;

      element.runtimeStyle.left = element.currentStyle.left;
      element.style.left = value || 0;

      value = element.style.pixelLeft;

      element.style.left = sl;
      element.runtimeStyle.left = rsl;

      return value;
    }
  });
}

// Acts like an array for backwards-compatibility.
Element.Dimensions.normalize = function(obj) {
  obj[0] = obj.left || obj.width;
  obj[1] = obj.top  || obj.height;
  return obj;
};

Object.extend(Element.Methods, {
  getDimensions: function(element, options) {
    return new Element.Dimensions(element, options).toObject();
  },

  viewportOffset: function(forElement) {
    forElement = $(forElement);

    // IE and FF >= 3 provide getBoundingClientRect, a much quicker path
    // to retrieving viewport offset.
    if (element.getBoundingClientRect) {
      var d = element.getBoundingClientRect();
      return Element.Dimensions.normalize({ left: d.left, top: d.top });
    }

    var valueT = 0, valueL = 0, element = forElement;

    // First collect cumulative offsets
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body &&
        Element.getStyle(element, 'position') === 'absolute') break;

    } while (element = element.offsetParent);

    // Then subtract cumulative scroll offsets
    element = forElement;
    do {
      if (!Prototype.Browser.Opera || element.tagName.toUpperCase() == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  cumulativeScrollOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName.toUpperCase() == 'BODY') break;
        if (Element.getStyle(element, 'position') !== 'static') break;
      }
    } while (element);
    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  absolutize: function(element) {
    element = $(element);
    if (element.getStyle('position') === 'absolute') return element;

    var offsets = element.positionedOffset();
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    Object.extend(element, {
      _originalLeft:   left - parseFloat(element.style.left || 0),
      _originalTop:    top  - parseFloat(element.style.top  || 0),
      _originalWidth:  element.style.width,
      _originalHeight: element.style.height
    });

    element.setStyle({
      position: 'absolute',
      top:      top + 'px',
      left:     left + 'px',
      width:    width + 'px',
      height:   height + 'px'
    });

    return element;
  },

  relativize: function(element) {
    element = $(element);
    if (element.getStyle('position') === 'relative') return element;

    if (Object.isUndefined(element._originalTop)) {
      throw "Element#absolutize must be called first.";
    }

    element.setStyle({ position: 'relative' });

    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.setStyle({
      top:      top + 'px',
      left:     left + 'px',
      width:    element._originalHeight + 'px',
      height:   element._originalWidth  + 'px'
    });

    return element;
  },

  getOffsetParent: function(element) {
    if (element.offsetParent) return $(element.offsetParent);
    if (element == document.body) return $(element);

    while ((element = element.parentNode) && element !== document.body)
      if (Element.getStyle(element, 'position') !== 'static')
        return element;

    return $(document.body);
  }
});

document.viewport = {
  getDimensions: function() {
    var dimensions = { };
    var B = Prototype.Browser;
    $w('width height').each(function(d) {
      var D = d.capitalize();
      dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
        (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
    });
    return dimensions;
  },

  getWidth: function() {
    return this.getDimensions().width;
  },

  getHeight: function() {
    return this.getDimensions().height;
  },

  getScrollOffsets: function() {
    return Element._returnOffset(
      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
};
<commit_msg>Add/subtract various offsets when using getBoundingClientRect<commit_after>Element.Dimensions = Class.create({
  // TODO: Add method for getting offsets (cumulative, viewport, scroll)
  initialize: function(element, options) {
    this.element = $(element);
    this.options = options;

    this.dimensions = new Hash();

    this.getDimensions();
  },

  getDimensions: function() {
    var element = this.element,
        display = element.getStyle('display'),
        noOffsetWidth;

    // The style object is inaccessible in Safari <= 2.0 when the element
    // is hidden.
    var isNotShown = display === "none" || display === null;
    var isTable = element.tagName.toUpperCase() == 'TABLE';

    // If the element is hidden, we show it for an instant
    // to grab its dimensions.
    if (isNotShown) {
      var style = element.style;
      var originalStyle = {
        visibility: style.visibility,
        position:   style.position,
        display:    style.display
      };

      Object.extend(style, {
        visibility: 'hidden',
        position:   'absolute',
        display:    'block'
      });
    }

    // clientWidth includes margin offsets of a table in Mozilla,
    // set offsets to 0, get width value, then revert back
    if (isTable) {
      var originalLeft = element.style.marginLeft;
      var originalRight = element.style.marginRight;
      element.style.marginLeft = '0px';
      element.style.marginRight = '0px';
      noOffsetWidth = element.clientWidth;
      element.style.marginLeft = originalLeft;
      element.style.marginRight = originalRight;
    }

    var paddingBox = {
      width:  noOffsetWidth || element.clientWidth,
      height: element.clientHeight
    };

    // For backwards-compatibility, the returned object will have
    // width and height equal to the padding-box values.
    this.dimensions.update(paddingBox);

    this.dimensions.set('paddingBox', paddingBox);

    var padding = this.getStyleValuesFor('padding', 'trbl');
    this.dimensions.set('padding', padding);

    var contentBox = {
      width:  paddingBox.width  - padding.left - padding.right,
      height: paddingBox.height - padding.top  - padding.bottom
    };

    this.dimensions.set('contentBox', contentBox);

    var border = this.getStyleValuesFor('border', 'trbl');
    this.dimensions.set('border', border);

    var borderBox = {
      width:  paddingBox.width  + border.left + border.right,
      height: paddingBox.height + border.top  + border.bottom
    };

    this.dimensions.set('borderBox', border);

    // If we altered the element's styles, return them to their
    // original values.
    if (isNotShown) {
      Object.extend(style, originalStyle);
    }

    return this.dimensions;
  },

  // Converts a raw CSS value like '9px' or '1em' to
  // a number (in pixels).
  // IE: Redefined below
  cssToNumber: function(property) {
    return window.parseFloat(this.element.getStyle(property));
  },

  // sidesNeeded argument is a string.
  // "trbl" = top, right, bottom, left
  // "tb"   = top, bottom
  getStyleValuesFor: function(property, sidesNeeded) {
    var sides = $w('top bottom left right');
    var propertyNames = sides.map( function(s) {
      return property + s.capitalize();
    });

    if (property === 'border') {
      propertyNames = propertyNames.map( function(p) {
        return p + 'Width';
      });
    }

    var values = {};

    sides.each( function(side, index) {
      if (!sidesNeeded.include(side.charAt(0))) return;
      values[side] = this.cssToNumber(propertyNames[index]);
    }, this);

    return values;
  },

  toObject: function() {
    return this.dimensions.toObject();
  },

  toHash: function() {
    return this.dimensions;
  },

  toJSON: function() {
    return this.dimensions.toJSON();
  }
});

if (Prototype.Browser.IE) {
  Element.Dimensions.addMethods({
    // IE gives the literal cascaded style, not the computed style.
    // We need to ensure pixel values are returned.
    cssToNumber: function(property) {
      var value = this.element.getStyle(property);

      if ((/^\d+(px)?$/i).test(value))
        return window.parseFloat(value);

      // If the unit is something other than a pixel (em, pt, %), set it on
      // something we can grab a pixel value from.
      var element = this.element;

      var sl = element.style.left, rsl = element.runtimeStyle.left;

      element.runtimeStyle.left = element.currentStyle.left;
      element.style.left = value || 0;

      value = element.style.pixelLeft;

      element.style.left = sl;
      element.runtimeStyle.left = rsl;

      return value;
    }
  });
}

// Acts like an array for backwards-compatibility.
Element.Dimensions.normalize = function(obj) {
  obj[0] = obj.left || obj.width;
  obj[1] = obj.top  || obj.height;
  return obj;
};

Object.extend(Element.Methods, {
  getDimensions: function(element, options) {
    return new Element.Dimensions(element, options).toObject();
  },

  viewportOffset: function(forElement) {
    forElement = $(forElement);

    // IE and FF >= 3 provide getBoundingClientRect, a much quicker path
    // to retrieving viewport offset.
    if (forElement.getBoundingClientRect) {
      var d = forElement.getBoundingClientRect(),
          doc = document.documentElement,
          body = document.body;
      var offset = {
        left: Math.max(doc.scrollLeft, body.scrollLeft) - (doc.clientLeft || 0),
        top: Math.max(doc.scrollTop, body.scrollTop) - (doc.clientTop || 0)
      }
      return Element.Dimensions.normalize({
        left: d.left + offset.left,
        top: d.top + offset.top
      });
    }

    var valueT = 0, valueL = 0, element = forElement;

    // First collect cumulative offsets
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body &&
        Element.getStyle(element, 'position') === 'absolute') break;

    } while (element = element.offsetParent);

    // Then subtract cumulative scroll offsets
    element = forElement;
    do {
      if (!Prototype.Browser.Opera || element.tagName.toUpperCase() == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  cumulativeScrollOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName.toUpperCase() == 'BODY') break;
        if (Element.getStyle(element, 'position') !== 'static') break;
      }
    } while (element);
    return Element.Dimensions.normalize({ left: valueL, top: valueT });
  },

  absolutize: function(element) {
    element = $(element);
    if (element.getStyle('position') === 'absolute') return element;

    var offsets = element.positionedOffset();
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    Object.extend(element, {
      _originalLeft:   left - parseFloat(element.style.left || 0),
      _originalTop:    top  - parseFloat(element.style.top  || 0),
      _originalWidth:  element.style.width,
      _originalHeight: element.style.height
    });

    element.setStyle({
      position: 'absolute',
      top:      top + 'px',
      left:     left + 'px',
      width:    width + 'px',
      height:   height + 'px'
    });

    return element;
  },

  relativize: function(element) {
    element = $(element);
    if (element.getStyle('position') === 'relative') return element;

    if (Object.isUndefined(element._originalTop)) {
      throw "Element#absolutize must be called first.";
    }

    element.setStyle({ position: 'relative' });

    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.setStyle({
      top:      top + 'px',
      left:     left + 'px',
      width:    element._originalHeight + 'px',
      height:   element._originalWidth  + 'px'
    });

    return element;
  },

  getOffsetParent: function(element) {
    if (element.offsetParent) return $(element.offsetParent);
    if (element == document.body) return $(element);

    while ((element = element.parentNode) && element !== document.body)
      if (Element.getStyle(element, 'position') !== 'static')
        return element;

    return $(document.body);
  }
});

document.viewport = {
  getDimensions: function() {
    var dimensions = { };
    var B = Prototype.Browser;
    $w('width height').each(function(d) {
      var D = d.capitalize();
      dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
        (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
    });
    return dimensions;
  },

  getWidth: function() {
    return this.getDimensions().width;
  },

  getHeight: function() {
    return this.getDimensions().height;
  },

  getScrollOffsets: function() {
    return Element.Dimensions.normalize({
      left: window.pageXOffset
        || document.documentElement.scrollLeft
        || document.body.scrollLeft,
      top: window.pageYOffset
        || document.documentElement.scrollTop
        || document.body.scrollTop
    });
  }
};
<|endoftext|>


<commit_before>var dom = {
  createElement: function(tagName, opt) {
    var node = document.createElement(tagName);
    if (opt.class) node.className = opt.class;
    if (opt.text) {
      var textNode = document.createTextNode(opt.text);
      node.appendChild(textNode);
    }
    return node;
  },
  insertAfter: function(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  },
  renderTo: function(newChild, oldChild) {
    oldChild.parentNode.replaceChild(newChild, oldChild);
  },
  getTextNodeFromElement: function(elem) {
    if (!elem) throw new Error('Unable to set UUID, element not exist.');
    if (!elem.childNodes || elem.childNodes.length <= 0)
      throw new Error('Unable to get text node.');
    return elem.childNodes[0].nodeValue;
  },
  /** Generate a UUID for current page */
  generateUUID: function() {
    var w = window || {};
    w.uuidCounter = w.uuidCounter || 0;
    w.uuidCounter++;
    return 'e.' + w.uuidCounter;
  },
  /** Set UUID onto element by manual */
  setElementUUID: function(elem, uuid) {
    if (!elem) throw new Error('Unable to set UUID, element not exist.');
    if (!elem.dataset)
      throw new Error('Unable to set UUID, element have no dataset attribute.');
    elem.dataset.uuid = uuid;
  },
  /** Get UUID onto element by manual */
  getElementUUID: function(elem) {
    if (!elem) throw new Error('Unable to get UUID, element not exist.');
    if (!elem.dataset)
      throw new Error('Unable to get UUID, element have no dataset attribute.');
    return elem.dataset.uuid;
  },
  /** Attach UUID onto element by auto-generated UUID */
  autoAttachUUID: function(elem) {
    var uuid = dom.generateUUID();
    dom.setElementUUID(elem, uuid);
    return uuid;
  },
  /** Find a element by given UUID */
  findElementByUUID: function(uuid) {
    return document.querySelector('[data-uuid="' + uuid + '"]');
  },
  removeElementByUUID: function(uuid) {
    var elem = dom.findElementByUUID(uuid);
    if (elem) elem.parentNode.removeChild(elem);
  }
};

module.exports = dom;
<commit_msg>Fix the issue when option is not given<commit_after>var dom = {
  createElement: function(tagName, opt) {
    var node = document.createElement(tagName);
    if (opt && opt.class) node.className = opt.class;
    if (opt && opt.text) {
      var textNode = document.createTextNode(opt.text);
      node.appendChild(textNode);
    }
    return node;
  },
  insertAfter: function(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  },
  renderTo: function(newChild, oldChild) {
    oldChild.parentNode.replaceChild(newChild, oldChild);
  },
  getTextNodeFromElement: function(elem) {
    if (!elem) throw new Error('Unable to set UUID, element not exist.');
    if (!elem.childNodes || elem.childNodes.length <= 0)
      throw new Error('Unable to get text node.');
    return elem.childNodes[0].nodeValue;
  },
  /** Generate a UUID for current page */
  generateUUID: function() {
    var w = window || {};
    w.uuidCounter = w.uuidCounter || 0;
    w.uuidCounter++;
    return 'e.' + w.uuidCounter;
  },
  /** Set UUID onto element by manual */
  setElementUUID: function(elem, uuid) {
    if (!elem) throw new Error('Unable to set UUID, element not exist.');
    if (!elem.dataset)
      throw new Error('Unable to set UUID, element have no dataset attribute.');
    elem.dataset.uuid = uuid;
  },
  /** Get UUID onto element by manual */
  getElementUUID: function(elem) {
    if (!elem) throw new Error('Unable to get UUID, element not exist.');
    if (!elem.dataset)
      throw new Error('Unable to get UUID, element have no dataset attribute.');
    return elem.dataset.uuid;
  },
  /** Attach UUID onto element by auto-generated UUID */
  autoAttachUUID: function(elem) {
    var uuid = dom.generateUUID();
    dom.setElementUUID(elem, uuid);
    return uuid;
  },
  /** Find a element by given UUID */
  findElementByUUID: function(uuid) {
    return document.querySelector('[data-uuid="' + uuid + '"]');
  },
  removeElementByUUID: function(uuid) {
    var elem = dom.findElementByUUID(uuid);
    if (elem) elem.parentNode.removeChild(elem);
  }
};

module.exports = dom;
<|endoftext|>


<commit_before>/*
 *  Init code for legacy compatibility.
 *
 *  Compatibility properties / wrapper functions here allow Duktape to remain
 *  compatible for user code when core features are changed, without burdening
 *  the main C code with compatibility stuff.
 *
 *  This file goes through UglifyJS to minify it.  UglifyJS renames variables,
 *  removes comments, and is clever enough to drop any "if (false) { ... }"
 *  blocks altogether, so that's an effective way to disable currently unneeded
 *  code.
 */

(function(D) {
    'use strict';

    function def(name, value) {
        Object.defineProperty(D, name, {
            value: value,
            writable: true,
            enumerable: false,
            configurable: true
        });
    }

    // legacy properties
    if (true) {
        // removed in Duktape 0.9.0
        def('build', '');
        def('setFinalizer', function(o,v) { Duktape.fin(o,v); });
        def('getFinalizer', function(o) { return Duktape.fin(o); });
        def('addr', function(v) { return D.info(v)[1]; });
        def('refc', function(v) { return D.info(v)[2]; });
    }

    // JSONX/JSONC convenience
    if (false) {
        def('jxEnc', function(a,b,c) { return D.enc('jsonx', a, b, c); });
        def('jxDec', function(a,b) { return D.dec('jsonx', a, b); });
        def('jcEnc', function(a,b,c) { return D.enc('jsonc', a, b, c); });
        def('jcDec', function(a,b) { return D.dec('jsonc', a, b); });
    }

    // info convenience
    if (false) {
        def('infox', function (v) {
            var t = D.info(v);
            if (!t) { return t; }
            return { type: t[0], addr: t[1], refc: t[2], hdrsize: t[3], addsize: t[4], bcsize: t[5] };
        });
    }
})(Duktape);
<commit_msg>add a __duk__ compatibility property for now<commit_after>/*
 *  Init code for legacy compatibility.
 *
 *  Compatibility properties / wrapper functions here allow Duktape to remain
 *  compatible for user code when core features are changed, without burdening
 *  the main C code with compatibility stuff.
 *
 *  This file goes through UglifyJS to minify it.  UglifyJS renames variables,
 *  removes comments, and is clever enough to drop any "if (false) { ... }"
 *  blocks altogether, so that's an effective way to disable currently unneeded
 *  code.
 */

(function(G, D) {
    'use strict';

    function def(name, value) {
        Object.defineProperty(D, name, {
            value: value,
            writable: true,
            enumerable: false,
            configurable: true
        });
    }

    // __duk__, renamed to Duktape in 0.9.0
    Object.defineProperty(G, '__duk__', {
        value: D,
        writable: true,
        enumerable: false,
        configurable: true
    });

    // legacy properties
    if (true) {
        // removed in Duktape 0.9.0
        def('build', '');
        def('setFinalizer', function(o,v) { Duktape.fin(o,v); });
        def('getFinalizer', function(o) { return Duktape.fin(o); });
        def('addr', function(v) { return D.info(v)[1]; });
        def('refc', function(v) { return D.info(v)[2]; });
    }

    // JSONX/JSONC convenience
    if (false) {
        def('jxEnc', function(a,b,c) { return D.enc('jsonx', a, b, c); });
        def('jxDec', function(a,b) { return D.dec('jsonx', a, b); });
        def('jcEnc', function(a,b,c) { return D.enc('jsonc', a, b, c); });
        def('jcDec', function(a,b) { return D.dec('jsonc', a, b); });
    }

    // info convenience
    if (false) {
        def('infox', function (v) {
            var t = D.info(v);
            if (!t) { return t; }
            return { type: t[0], addr: t[1], refc: t[2], hdrsize: t[3], addsize: t[4], bcsize: t[5] };
        });
    }
})(this, Duktape);
<|endoftext|>