<commit_before>var jsend = require('jsend')
var httpify = require('httpify')

function jsendBatchedRequest(url, postParams, plural, callback) {
  httpify({
    url: url,
    method: 'POST',
    json: true,
    body: postParams
  }, function (err, res) {
    if (err) return callback(err)

    var body = res.body
    if (!jsend.isValid(body)) return callback(new Error('Invalid JSend response'))
    if (body.status === 'fail' || body.status === 'error') return callback(new Error(JSON.stringify(body.data)))

    return callback(undefined, plural ? body.data : body.data[0])
  })
}

module.exports = {
  jsendBatchedRequest: jsendBatchedRequest
}
<commit_msg>utils: avoid unnecessary stringify and handle .message<commit_after>var jsend = require('jsend')
var httpify = require('httpify')

function jsendBatchedRequest(url, postParams, plural, callback) {
  httpify({
    url: url,
    method: 'POST',
    json: true,
    body: postParams
  }, function (err, res) {
    if (err) return callback(err)

    var body = res.body
    if (!jsend.isValid(body)) return callback(new Error('Invalid JSend response'))
    if (body.status === 'fail' || body.status === 'error') {
      return callback(new Error(body.data || body.message))
    }

    return callback(undefined, plural ? body.data : body.data[0])
  })
}

module.exports = {
  jsendBatchedRequest: jsendBatchedRequest
}
<|endoftext|>


<commit_before>import { Dimensions } from 'react-native';
import * as animatable from 'react-native-animatable';

const { height, width } = Dimensions.get('window');

// Since react-native-animatable applies by default a margin of 100 to its
// sliding animation, we reset them here overriding the margin to 0.
export const initializeAnimations = () => {
  const makeSlideTranslation = (translationType, fromValue, toValue) => {
    return {
      from: {
        [translationType]: fromValue,
      },
      to: {
        [translationType]: toValue,
      },
    };
  };
  const animationDefinitions = {
    slideInDown: makeSlideTranslation('translateY', -height, 0),
    slideInUp: makeSlideTranslation('translateY', height, 0),
    slideInLeft: makeSlideTranslation('translateX', -width, 0),
    slideInRight: makeSlideTranslation('translateX', width, 0),
    slideOutDown: makeSlideTranslation('translateY', 0, height),
    slideOutUp: makeSlideTranslation('translateY', 0, -height),
    slideOutLeft: makeSlideTranslation('translateX', 0, -width),
    slideOutRight: makeSlideTranslation('translateX', 0, width),
  };
  animatable.initializeRegistryWithDefinitions(animationDefinitions);
};

// User can define custom react-native-animatable animations, see PR #72
// Utility for creating our own custom react-native-animatable animations
export const buildAnimations = ({ animationIn, animationOut }) => {
  let updatedAnimationIn = animationIn;
  let updatedAnimationOut = animationOut;

  if (isObject(animationIn)) {
    const animationName = JSON.stringify(animationIn);
    makeAnimation(animationName, animationIn);
    updatedAnimationIn = animationName;
  }

  if (isObject(animationOut)) {
    const animationName = JSON.stringify(animationOut);
    makeAnimation(animationName, animationOut);
    updatedAnimationOut = animationName;
  }

  return {
    animationIn: updatedAnimationIn,
    animationOut: updatedAnimationOut,
  };
};

const makeAnimation = (name, obj) => {
  animatable.registerAnimation(name, animatable.createAnimation(obj));
};

const isObject = obj => {
  return obj !== null && typeof obj === 'object';
};
<commit_msg>Moved comment<commit_after>import { Dimensions } from 'react-native';
import * as animatable from 'react-native-animatable';

const { height, width } = Dimensions.get('window');

export const initializeAnimations = () => {
  const makeSlideTranslation = (translationType, fromValue, toValue) => {
    return {
      from: {
        [translationType]: fromValue,
      },
      to: {
        [translationType]: toValue,
      },
    };
  };
  // Since react-native-animatable applies by default a margin of 100 to its
  // sliding animation, we reset them here overriding the margin to 0.
  const animationDefinitions = {
    slideInDown: makeSlideTranslation('translateY', -height, 0),
    slideInUp: makeSlideTranslation('translateY', height, 0),
    slideInLeft: makeSlideTranslation('translateX', -width, 0),
    slideInRight: makeSlideTranslation('translateX', width, 0),
    slideOutDown: makeSlideTranslation('translateY', 0, height),
    slideOutUp: makeSlideTranslation('translateY', 0, -height),
    slideOutLeft: makeSlideTranslation('translateX', 0, -width),
    slideOutRight: makeSlideTranslation('translateX', 0, width),
  };
  animatable.initializeRegistryWithDefinitions(animationDefinitions);
};

// User can define custom react-native-animatable animations, see PR #72
// Utility for creating our own custom react-native-animatable animations
export const buildAnimations = ({ animationIn, animationOut }) => {
  let updatedAnimationIn = animationIn;
  let updatedAnimationOut = animationOut;

  if (isObject(animationIn)) {
    const animationName = JSON.stringify(animationIn);
    makeAnimation(animationName, animationIn);
    updatedAnimationIn = animationName;
  }

  if (isObject(animationOut)) {
    const animationName = JSON.stringify(animationOut);
    makeAnimation(animationName, animationOut);
    updatedAnimationOut = animationName;
  }

  return {
    animationIn: updatedAnimationIn,
    animationOut: updatedAnimationOut,
  };
};

const makeAnimation = (name, obj) => {
  animatable.registerAnimation(name, animatable.createAnimation(obj));
};

const isObject = obj => {
  return obj !== null && typeof obj === 'object';
};
<|endoftext|>


<commit_before>export function addToMap(markers, {
  options, callbacks, map, useObjectManager, objectManagerClusterize, useHtmlInLayout,
}) {
  const defaultLayout = useHtmlInLayout ? `

  ` : `

{{ properties.balloonContentHeader }}

{{ properties.balloonContentBody }}

{{ properties.balloonContentFooter }}

  `;
  const defaultClusterLayout = 'cluster#balloonTwoColumns';

  const clusters = {};
  const unclastered = [];
  markers.forEach((marker) => {
    if (!marker.clusterName) unclastered.push(marker);
    else {
      clusters[marker.clusterName] = clusters[marker.clusterName]
        ? [...clusters[marker.clusterName], marker] : [marker];
    }
  });

  Object.keys(clusters).forEach((clusterName) => {
    const clusterOptions = { ...options[clusterName] } || {};
    const clusterCallbacks = callbacks[clusterName] || {};
    const layout = clusterOptions.layout || defaultLayout;
    clusterOptions.clusterBalloonItemContentLayout = ymaps.templateLayoutFactory
      .createClass(layout);

    const balloonLayout = clusterOptions.clusterBalloonLayout || clusterOptions.clusterLayout;
    delete clusterOptions.clusterBalloonLayout;

    const clusterBalloonLayout = balloonLayout
      ? ymaps.templateLayoutFactory.createClass(balloonLayout)
      : clusterOptions.clusterBalloonContentLayout || defaultClusterLayout;
    clusterOptions.clusterBalloonContentLayout = clusterBalloonLayout;

    const { clusterIconContentLayout } = clusterOptions;
    clusterOptions.clusterIconContentLayout = clusterIconContentLayout
      && ymaps.templateLayoutFactory.createClass(clusterIconContentLayout);

    if (useObjectManager) {
      const ObjectManager = new ymaps.ObjectManager(Object.assign(
        { clusterize: objectManagerClusterize },
        clusterOptions,
      ));
      Object.keys(clusterCallbacks).forEach((key) => {
        ObjectManager.clusters.events.add(key, clusterCallbacks[key]);
      });
      ObjectManager.add(clusters[clusterName]);
      map.geoObjects.add(ObjectManager);
    } else {
      const clusterer = new ymaps.Clusterer(clusterOptions);
      Object.keys(clusterCallbacks).forEach((key) => {
        clusterer.events.add(key, clusterCallbacks[key]);
      });

      if (clusterOptions.createCluster) {
        clusterer.createCluster = clusterOptions.createCluster;
      }

      clusterer.add(clusters[clusterName]);
      map.geoObjects.add(clusterer);
    }
  });
  if (unclastered.length) {
    const unclasteredMarkers = useObjectManager
      ? new ymaps.ObjectManager({ clusterize: false }) : new ymaps.GeoObjectCollection();
    unclastered.forEach(obj => unclasteredMarkers.add(obj));
    map.geoObjects.add(unclasteredMarkers);
  }
}

export function setFirstLetterToUppercase(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

export function getIconPreset(marker) {
  const firstPart = marker.icon.color || 'blue';
  let secondPart;
  if (marker.icon.glyph) {
    secondPart = setFirstLetterToUppercase(marker.icon.glyph);
  } else if (marker.icon.content) {
    secondPart = 'Stretchy';
  } else {
    secondPart = '';
  }
  return firstPart + secondPart;
}

export function setCoordsToNumeric(arr) {
  return arr.map(item => (Array.isArray(item) ? setCoordsToNumeric(item) : +item));
}

export function objectComparison(first, second) {
  const cache = []; // кеш обьектов, для избежания рекурсии

  function inCache(f, s) {
    let i = cache.length;
    while (i--) {
      if (
        (cache[i][0] === f || cache[i][0] === s) && (cache[i][1] === s || cache[i][1] === f)
      ) return true;
    }
    return false;
  }

  return (function eq(f, s) {
    if (f === s) return true; // сравниваем обычным образом
    if (f instanceof Date && s instanceof Date) return +f === +s; // время
    if (typeof f !== 'object' || typeof s !== 'object') return false; // если хотябы один из аргументов не объект (положительный случай для необъектов рассмотрен выше)
    if (inCache(f, s)) return true; // есть в кеше
    cache.push([f, s]); // кешируем

    const keys = Object.keys(f); let
      i = keys.length; // получаем ключи
    if (Object.keys(s).length !== i) return false; // если количество ключей не совпадает
    while (i--) if (!eq(f[keys[i]], s[keys[i]])) return false; // рекурсивный вызов

    return true;
  }(first, second));
}

class EventEmitter {
  constructor() {
    this.events = {};
    this.ymapReady = false;
    this.scriptIsNotAttached = true;
  }

  $on(eventName, fn) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }

    this.events[eventName].push(fn);

    return () => {
      this.events[eventName] = this.events[eventName].filter(eventFn => fn !== eventFn);
    };
  }

  $emit(eventName, data) {
    const event = this.events[eventName];
    if (event) {
      event.forEach(fn => fn(data));
    }
  }
}

export const emitter = new EventEmitter();

const CONTROL_TYPES = [
  'fullscreenControl',
  'geolocationControl',
  'routeEditor',
  'rulerControl',
  'searchControl',
  'trafficControl',
  'typeSelector',
  'zoomControl',
  'routeButtonControl',
  'routePanelControl',
];

export function controlsTypeValidator(val) {
  return val.filter(control => ![...CONTROL_TYPES, 'default'].includes(control)).length === 0;
}

export function createMarkerType(val, useObjectManager) {
  const type = setFirstLetterToUppercase(val);
  if (!useObjectManager) return type;
  switch (type) {
    case 'Placemark':
      return 'Point';
    case 'Polyline':
      return 'LineString';
    default:
      return type;
  }
}

export function createMarker(object, useObjectManager) {
  const marker = useObjectManager ? {
    type: 'Feature',
    id: object.properties.markerId,
    geometry: {
      type: object.markerType,
      coordinates: object.coords,
    },
    properties: object.properties,
    options: object.options,
  } : new ymaps[object.markerType](object.coords, object.properties, object.options);

  marker.clusterName = object.clusterName;

  return marker;
}

export function ymapLoader(settings = {}) {
  return new Promise((res, rej) => {
    if (window.ymaps) return res();

    if (document.getElementById('vue-yandex-maps')) {
      emitter.$on('scriptIsLoaded', res);
      return;
    }

    const yandexMapScript = document.createElement('SCRIPT');
    const {
      apiKey = '',
      lang = 'ru_RU',
      version = '2.1',
      coordorder = 'latlong',
      debug = false,
      enterprise = false,
    } = settings;
    const mode = debug ? 'debug' : 'release';
    const settingsPart = `lang=${lang}${apiKey && `&apikey=${apiKey}`}&mode=${mode}&coordorder=${coordorder}`;
    const link = `https://${enterprise ? 'enterprise.' : ''}api-maps.yandex.ru/${version}/?${settingsPart}`;
    yandexMapScript.setAttribute('src', link);
    yandexMapScript.setAttribute('async', '');
    yandexMapScript.setAttribute('defer', '');
    yandexMapScript.setAttribute('id', 'vue-yandex-maps');
    document.head.appendChild(yandexMapScript);
    emitter.scriptIsNotAttached = false;
    yandexMapScript.onload = () => {
      ymaps.ready(() => {
        emitter.ymapReady = true;
        emitter.$emit('scriptIsLoaded');
        res();
      });
    };
    yandexMapScript.onerror = rej;
  });
}

let idCounter = 1;
let VueBalloonClass;

export function setupBalloonClass(Vue) {
  if (typeof Vue.extend !== 'function') return;
  VueBalloonClass = Vue.extend({
    props: ['marker', 'component'],
    template: '<component :is="component" v-bind="{ marker, ...props.balloonComponentProps }" v-on="listeners" />',
  });
}

export function makeComponentBalloonTemplate(component) {
  let vueBalloon = null;
  const balloonId = `vue-balloon-${idCounter}`;

  idCounter += 1;

  return (markerComponent, markerData) => {
    const balloonContentLayout = ymaps.templateLayoutFactory.createClass(`<div id="${balloonId}"><div>`, {
      build() {
        balloonContentLayout.superclass.build.call(this);

        vueBalloon = new VueBalloonClass({
          parent: markerComponent.$root,
          data() {
            return {
              props: markerComponent.$props,
              listeners: markerComponent.$listeners,
            };
          },
          propsData: {
            marker: markerData,
            component,
          },
        });

        vueBalloon.$mount(`#${balloonId}`);
      },
      clear() {
        vueBalloon.$destroy();
        vueBalloon = null;
        balloonContentLayout.superclass.clear.call(this);
      },
    });

    return balloonContentLayout;
  };
}
<commit_msg>Added built-in control sets<commit_after>export function addToMap(markers, {
  options, callbacks, map, useObjectManager, objectManagerClusterize, useHtmlInLayout,
}) {
  const defaultLayout = useHtmlInLayout ? `

  ` : `

{{ properties.balloonContentHeader }}

{{ properties.balloonContentBody }}

{{ properties.balloonContentFooter }}

  `;
  const defaultClusterLayout = 'cluster#balloonTwoColumns';

  const clusters = {};
  const unclastered = [];
  markers.forEach((marker) => {
    if (!marker.clusterName) unclastered.push(marker);
    else {
      clusters[marker.clusterName] = clusters[marker.clusterName]
        ? [...clusters[marker.clusterName], marker] : [marker];
    }
  });

  Object.keys(clusters).forEach((clusterName) => {
    const clusterOptions = { ...options[clusterName] } || {};
    const clusterCallbacks = callbacks[clusterName] || {};
    const layout = clusterOptions.layout || defaultLayout;
    clusterOptions.clusterBalloonItemContentLayout = ymaps.templateLayoutFactory
      .createClass(layout);

    const balloonLayout = clusterOptions.clusterBalloonLayout || clusterOptions.clusterLayout;
    delete clusterOptions.clusterBalloonLayout;

    const clusterBalloonLayout = balloonLayout
      ? ymaps.templateLayoutFactory.createClass(balloonLayout)
      : clusterOptions.clusterBalloonContentLayout || defaultClusterLayout;
    clusterOptions.clusterBalloonContentLayout = clusterBalloonLayout;

    const { clusterIconContentLayout } = clusterOptions;
    clusterOptions.clusterIconContentLayout = clusterIconContentLayout
      && ymaps.templateLayoutFactory.createClass(clusterIconContentLayout);

    if (useObjectManager) {
      const ObjectManager = new ymaps.ObjectManager(Object.assign(
        { clusterize: objectManagerClusterize },
        clusterOptions,
      ));
      Object.keys(clusterCallbacks).forEach((key) => {
        ObjectManager.clusters.events.add(key, clusterCallbacks[key]);
      });
      ObjectManager.add(clusters[clusterName]);
      map.geoObjects.add(ObjectManager);
    } else {
      const clusterer = new ymaps.Clusterer(clusterOptions);
      Object.keys(clusterCallbacks).forEach((key) => {
        clusterer.events.add(key, clusterCallbacks[key]);
      });

      if (clusterOptions.createCluster) {
        clusterer.createCluster = clusterOptions.createCluster;
      }

      clusterer.add(clusters[clusterName]);
      map.geoObjects.add(clusterer);
    }
  });
  if (unclastered.length) {
    const unclasteredMarkers = useObjectManager
      ? new ymaps.ObjectManager({ clusterize: false }) : new ymaps.GeoObjectCollection();
    unclastered.forEach(obj => unclasteredMarkers.add(obj));
    map.geoObjects.add(unclasteredMarkers);
  }
}

export function setFirstLetterToUppercase(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

export function getIconPreset(marker) {
  const firstPart = marker.icon.color || 'blue';
  let secondPart;
  if (marker.icon.glyph) {
    secondPart = setFirstLetterToUppercase(marker.icon.glyph);
  } else if (marker.icon.content) {
    secondPart = 'Stretchy';
  } else {
    secondPart = '';
  }
  return firstPart + secondPart;
}

export function setCoordsToNumeric(arr) {
  return arr.map(item => (Array.isArray(item) ? setCoordsToNumeric(item) : +item));
}

export function objectComparison(first, second) {
  const cache = []; // кеш обьектов, для избежания рекурсии

  function inCache(f, s) {
    let i = cache.length;
    while (i--) {
      if (
        (cache[i][0] === f || cache[i][0] === s) && (cache[i][1] === s || cache[i][1] === f)
      ) return true;
    }
    return false;
  }

  return (function eq(f, s) {
    if (f === s) return true; // сравниваем обычным образом
    if (f instanceof Date && s instanceof Date) return +f === +s; // время
    if (typeof f !== 'object' || typeof s !== 'object') return false; // если хотябы один из аргументов не объект (положительный случай для необъектов рассмотрен выше)
    if (inCache(f, s)) return true; // есть в кеше
    cache.push([f, s]); // кешируем

    const keys = Object.keys(f); let
      i = keys.length; // получаем ключи
    if (Object.keys(s).length !== i) return false; // если количество ключей не совпадает
    while (i--) if (!eq(f[keys[i]], s[keys[i]])) return false; // рекурсивный вызов

    return true;
  }(first, second));
}

class EventEmitter {
  constructor() {
    this.events = {};
    this.ymapReady = false;
    this.scriptIsNotAttached = true;
  }

  $on(eventName, fn) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }

    this.events[eventName].push(fn);

    return () => {
      this.events[eventName] = this.events[eventName].filter(eventFn => fn !== eventFn);
    };
  }

  $emit(eventName, data) {
    const event = this.events[eventName];
    if (event) {
      event.forEach(fn => fn(data));
    }
  }
}

export const emitter = new EventEmitter();

const CONTROL_TYPES = [
  'fullscreenControl',
  'geolocationControl',
  'routeEditor',
  'rulerControl',
  'searchControl',
  'trafficControl',
  'typeSelector',
  'zoomControl',
  'routeButtonControl',
  'routePanelControl',
  'smallMapDefaultSet',
  'mediumMapDefaultSet',
  'largeMapDefaultSet',
];

export function controlsTypeValidator(val) {
  return val.filter(control => ![...CONTROL_TYPES, 'default'].includes(control)).length === 0;
}

export function createMarkerType(val, useObjectManager) {
  const type = setFirstLetterToUppercase(val);
  if (!useObjectManager) return type;
  switch (type) {
    case 'Placemark':
      return 'Point';
    case 'Polyline':
      return 'LineString';
    default:
      return type;
  }
}

export function createMarker(object, useObjectManager) {
  const marker = useObjectManager ? {
    type: 'Feature',
    id: object.properties.markerId,
    geometry: {
      type: object.markerType,
      coordinates: object.coords,
    },
    properties: object.properties,
    options: object.options,
  } : new ymaps[object.markerType](object.coords, object.properties, object.options);

  marker.clusterName = object.clusterName;

  return marker;
}

export function ymapLoader(settings = {}) {
  return new Promise((res, rej) => {
    if (window.ymaps) return res();

    if (document.getElementById('vue-yandex-maps')) {
      emitter.$on('scriptIsLoaded', res);
      return;
    }

    const yandexMapScript = document.createElement('SCRIPT');
    const {
      apiKey = '',
      lang = 'ru_RU',
      version = '2.1',
      coordorder = 'latlong',
      debug = false,
      enterprise = false,
    } = settings;
    const mode = debug ? 'debug' : 'release';
    const settingsPart = `lang=${lang}${apiKey && `&apikey=${apiKey}`}&mode=${mode}&coordorder=${coordorder}`;
    const link = `https://${enterprise ? 'enterprise.' : ''}api-maps.yandex.ru/${version}/?${settingsPart}`;
    yandexMapScript.setAttribute('src', link);
    yandexMapScript.setAttribute('async', '');
    yandexMapScript.setAttribute('defer', '');
    yandexMapScript.setAttribute('id', 'vue-yandex-maps');
    document.head.appendChild(yandexMapScript);
    emitter.scriptIsNotAttached = false;
    yandexMapScript.onload = () => {
      ymaps.ready(() => {
        emitter.ymapReady = true;
        emitter.$emit('scriptIsLoaded');
        res();
      });
    };
    yandexMapScript.onerror = rej;
  });
}

let idCounter = 1;
let VueBalloonClass;

export function setupBalloonClass(Vue) {
  if (typeof Vue.extend !== 'function') return;
  VueBalloonClass = Vue.extend({
    props: ['marker', 'component'],
    template: '<component :is="component" v-bind="{ marker, ...props.balloonComponentProps }" v-on="listeners" />',
  });
}

export function makeComponentBalloonTemplate(component) {
  let vueBalloon = null;
  const balloonId = `vue-balloon-${idCounter}`;

  idCounter += 1;

  return (markerComponent, markerData) => {
    const balloonContentLayout = ymaps.templateLayoutFactory.createClass(`<div id="${balloonId}"><div>`, {
      build() {
        balloonContentLayout.superclass.build.call(this);

        vueBalloon = new VueBalloonClass({
          parent: markerComponent.$root,
          data() {
            return {
              props: markerComponent.$props,
              listeners: markerComponent.$listeners,
            };
          },
          propsData: {
            marker: markerData,
            component,
          },
        });

        vueBalloon.$mount(`#${balloonId}`);
      },
      clear() {
        vueBalloon.$destroy();
        vueBalloon = null;
        balloonContentLayout.superclass.clear.call(this);
      },
    });

    return balloonContentLayout;
  };
}
<|endoftext|>


<commit_before>var opbeatSymbol = require('opbeat-js-core').patchUtils.opbeatSymbol

function isTopLevelWrapper (ReactMount, element) {
  // React 0.14.0+ exposes ReactMount.TopLevelWrapper
  var ReactTopLevelWrapper = ReactMount.TopLevelWrapper

  return element && element.type &&
  (
    element.type === ReactTopLevelWrapper ||
    element.type.isReactTopLevelWrapper
  )
}

function nodeName (ComponentTree, domNode) {
  if (ComponentTree) {
    var reactElem = ComponentTree.getClosestInstanceFromNode(domNode)

    if (!reactElem) {
      return DOMNodeName(domNode)
    }

    var elements = []
    var owner = reactElem._currentElement._owner

    reactElem = reactElem._hostParent

    while (reactElem && (owner === reactElem._currentElement._owner)) {
      elements.push(reactElem._tag)
      reactElem = reactElem._hostParent
    }

    if (owner !== null) {
      elements.push(owner.getName())
    } else if (reactElem && reactElem._currentElement && reactElem._currentElement._owner) {
      elements.push(reactElem._currentElement._owner.getName())
    }

    elements.unshift(DOMNodeName(domNode))

    // TODO: need a good way to get the name of the root component
    // (when both owner and reactElem._currentElement._owner is null)

    elements.reverse()
    return elements.join(' ')
  } else {
    return DOMNodeName(domNode)
  }
}

function DOMNodeName (domNode) {
  var tag = domNode.tagName ? domNode.tagName.toLowerCase() : ''
  if (domNode === document) {
    return 'document'
  }

  if (!domNode || !domNode.getAttribute) {
    return ''
  }
  var idName = domNode.getAttribute('id')
  idName = idName ? idName.trim() : ''

  var classes = (domNode.getAttribute('class') || '').trim().split(/\s+/).join('.')

  return tag + (idName ? '#' + idName : (classes ? '.' + classes : ''))
}

function RingBuffer (size) {
  var pointer = 0
  var buffer = []
  return {
    getAll: function getAll () {
      if (buffer.length < size) {
        return buffer
      }
      return buffer.slice(pointer, buffer.length).concat(buffer.slice(0, pointer))
    },
    push: function push (item) {
      buffer[pointer] = item
      pointer = (pointer + 1) % size
    }
  }
}

function opbeatGlobal (value) {
  if (!inBrowser()) {
    return
  }

  if (typeof value === 'undefined') {
    return window.__opbeat
  } else {
    window.__opbeat = value
  }
}

function inBrowser () {
  return typeof window !== 'undefined'
}

function createNamedFn (name, delegate) {
  try {
    return Function('f', 'return function ' + name + '(){return f(this, arguments)}')(delegate); // eslint-disable-line
  } catch (e) {
    // if we fail, we must be CSP, just return delegate.
    return function () {
      return delegate(this, arguments)
    }
  }
}

function patchObject (target, name, patchFn) {
  var delegateName = opbeatSymbol(name)
  var delegate = target[delegateName]
  if (!delegate) {
    delegate = target[delegateName] = target[name]
    target[name] = createNamedFn(name, patchFn(delegate, delegateName, name))
  }
  return delegate
}

module.exports = {
  nodeName: nodeName,
  isTopLevelWrapper: isTopLevelWrapper,
  RingBuffer: RingBuffer,
  DOMNodeName: DOMNodeName,
  opbeatGlobal: opbeatGlobal,
  inBrowser: inBrowser,
  patchObject: patchObject
}
<commit_msg>chore: Removing dead code.<commit_after>var opbeatSymbol = require('opbeat-js-core').patchUtils.opbeatSymbol

function isTopLevelWrapper (ReactMount, element) {
  // React 0.14.0+ exposes ReactMount.TopLevelWrapper
  var ReactTopLevelWrapper = ReactMount.TopLevelWrapper

  return element && element.type &&
  (
    element.type === ReactTopLevelWrapper ||
    element.type.isReactTopLevelWrapper
  )
}

function nodeName (ComponentTree, domNode) {
  if (ComponentTree) {
    var reactElem = ComponentTree.getClosestInstanceFromNode(domNode)

    if (!reactElem) {
      return DOMNodeName(domNode)
    }

    var elements = []
    var owner = reactElem._currentElement._owner

    reactElem = reactElem._hostParent

    while (reactElem && (owner === reactElem._currentElement._owner)) {
      elements.push(reactElem._tag)
      reactElem = reactElem._hostParent
    }

    if (owner !== null) {
      elements.push(owner.getName())
    } else if (reactElem && reactElem._currentElement && reactElem._currentElement._owner) {
      elements.push(reactElem._currentElement._owner.getName())
    }

    elements.unshift(DOMNodeName(domNode))

    // TODO: need a good way to get the name of the root component
    // (when both owner and reactElem._currentElement._owner is null)

    elements.reverse()
    return elements.join(' ')
  } else {
    return DOMNodeName(domNode)
  }
}

function DOMNodeName (domNode) {
  var tag = domNode.tagName ? domNode.tagName.toLowerCase() : ''
  if (domNode === document) {
    return 'document'
  }

  if (!domNode || !domNode.getAttribute) {
    return ''
  }
  var idName = domNode.getAttribute('id')
  idName = idName ? idName.trim() : ''

  var classes = (domNode.getAttribute('class') || '').trim().split(/\s+/).join('.')

  return tag + (idName ? '#' + idName : (classes ? '.' + classes : ''))
}

function RingBuffer (size) {
  var pointer = 0
  var buffer = []
  return {
    getAll: function getAll () {
      if (buffer.length < size) {
        return buffer
      }
      return buffer.slice(pointer, buffer.length).concat(buffer.slice(0, pointer))
    },
    push: function push (item) {
      buffer[pointer] = item
      pointer = (pointer + 1) % size
    }
  }
}

function inBrowser () {
  return typeof window !== 'undefined'
}

function createNamedFn (name, delegate) {
  try {
    return Function('f', 'return function ' + name + '(){return f(this, arguments)}')(delegate); // eslint-disable-line
  } catch (e) {
    // if we fail, we must be CSP, just return delegate.
    return function () {
      return delegate(this, arguments)
    }
  }
}

function patchObject (target, name, patchFn) {
  var delegateName = opbeatSymbol(name)
  var delegate = target[delegateName]
  if (!delegate) {
    delegate = target[delegateName] = target[name]
    target[name] = createNamedFn(name, patchFn(delegate, delegateName, name))
  }
  return delegate
}

module.exports = {
  nodeName: nodeName,
  isTopLevelWrapper: isTopLevelWrapper,
  RingBuffer: RingBuffer,
  DOMNodeName: DOMNodeName,
  inBrowser: inBrowser,
  patchObject: patchObject
}
<|endoftext|>


<commit_before>var debug = require('debug')('p3api-server:media');
var nodeExcel = require('excel-export');
module.exports=function(req,res,next){
	var rpcTypes = ["application/jsonrpc.result+json", "application/jsonrpc+json"];

	if (rpcTypes.some(function(t){
		return req.is(t);
	})){
		debug("RPC Request");
	}

	var fields;

	if (req.call_collection=="genome_feature"){
		fields = ["genome_name", "accession", "seed_id", "refseq_locus_tag", "alt_locus_tag", "feature_id",
				"annotation", "feature_type", "start", "end", "na_length", "strand", "protein_id", "aa_length", "gene", "product"
		];
	}else if (req.call_collection =="genome") {
		fields = ["genome_id", "genome_name", "organism_name", "taxon_id", "genome_status",
			"strain", "serovar", "biovar", "pathovar", "mlst", "other_typing",
			"culture_collection", "type_strain",
			"completion_date", "publication",
			"bioproject_accession", "biosample_accession", "assembly_accession", "genbank_accessions",
			"refseq_accessions",
			"sequencing_centers", "sequencing_status", "sequencing_platform", "sequencing_depth", "assembly_method",
			"chromosomes", "plasmids", "contigs", "sequences", "genome_length", "gc_content",
			"patric_cds", "brc1_cds", "refseq_cds",
			"isolation_site", "isolation_source", "isolation_comments", "collection_date",
			"isolation_country", "geographic_location", "latitude", "longitude", "altitude", "depth", "other_environmental",
			"host_name", "host_gender", "host_age", "host_health", "body_sample_site", "body_sample_subsite", "other_clinical",
			"antimicrobial_resistance", "antimicrobial_resistance_evidence",
			"gram_stain", "cell_shape", "motility", "sporulation", "temperature_range", "optimal_temperature", "salinity", "oxygen_requirement",
			"habitat",
			"disease", "comments", "additional_metadata"
		]
	}

	res.format({
		"text/csv": function(){
			debug("text/csv handler")
			if (req.isDownload){
				req.set("content-disposition", "attachment; filename=patric3_query.csv");
			}

			console.log("res.results: ", res.results);
			if (res.results && res.results.response && res.results.response.docs) {
				if (!fields) {
					fields = Object.keys(res.results.response.docs[0]);
				}

				res.write(fields.join(",") + "\n");
				console.log("Fields: ", fields);
				res.results.response.docs.forEach(function(o){
					var row = fields.map(function(field){
						return JSON.stringify(o[field]);
					});
					console.log("row: ", row);
					res.write(row.join(",") + "\n");
				});
			}

			res.end();
		},
		"text/tsv": function(){
			debug("text/tsv handler")
			if (req.isDownload){
				req.set("content-disposition", "attachment; filename=patric3_query.txt");
			}
			console.log("res.results: ", res.results);
			if (res.results && res.results.response && res.results.response.docs) {
				if (!fields) {
					fields = Object.keys(res.results.response.docs[0]);
				}
				res.write(fields.join("\t") + "\n");
				console.log("Fields: ", fields);
				res.results.response.docs.forEach(function(o){
					var row = fields.map(function(field){
						return o[field];
					});
					console.log("row: ", row);
					res.write(row.join("\t") + "\n");
				});
			}

			res.end();
		},
		"application/vnd.openxmlformats": function(){
			debug("Excel  handler")
			if (req.isDownload){
				req.set("content-disposition", "attachment; filename=patric3_query.xlsx");
			}
			var excelConf = {cols: []}

//			console.log("res.results: ", res.results);
			if (res.results && res.results.response && res.results.response.docs) {
				console.log("Build Excel Columns");
				if (!fields) {
					fields = Object.keys(res.results.response.docs[0]);
				}
				console.log("fields: ", fields);

				fields.forEach(function(field){
					if (res.results.response.docs[0] && res.results.response.docs[0][field]) {
						var fd = res.results.response.docs[0][field];
						if (typeof fd=="number"){
							excelConf.cols.push({caption: field, type: "number"});
						}else{
							excelConf.cols.push({caption: field, type: "string"});
						}
					}else{
						excelConf.cols.push({caption: field, type: "string"});
					}
				});

				console.log("excelconf: ", excelConf);
				excelConf.rows = res.results.response.docs.map(function(o){
					var row = fields.map(function(field){
						if (typeof o[field] == "object") {
							if (o[field] instanceof Array) {
								return o[field].join(";");
							}
							return JSON.stringify(o[field]);
						}
						return o[field] || "";
					});
					return row;
				});

				console.log("Excel Conf: ", excelConf);
				var d = nodeExcel.execute(excelConf);
				console.log("Node Excel Data Exported");
				res.set("Content-Type", "application/vnd.openxmlformats");
				res.end(d, "binary");
			}

			res.end();

		},

		"application/solr+json": function(){
			debug("application/json handler")
			res.send(JSON.stringify(res.results));
			res.end();
		},

		"application/json": function(){
			debug("application/json handler")
			if (req.call_method=="query"){
				if (res.results && res.results.response && res.results.response.docs){
					res.send(JSON.stringify(res.results.response.docs));
				}else{
					res.status(404);
				}
			} else{
					if (!res.results){
						res.status(404)
					}else{
						res.send(JSON.stringify(res.results));
					}
			}
			res.end();
		}
	})
}
<commit_msg>put facet_counts in the headers for application/json<commit_after>var debug = require('debug')('p3api-server:media');
var nodeExcel = require('excel-export');
module.exports=function(req,res,next){
	var rpcTypes = ["application/jsonrpc.result+json", "application/jsonrpc+json"];

	if (rpcTypes.some(function(t){
		return req.is(t);
	})){
		debug("RPC Request");
	}

	var fields;

	if (req.call_collection=="genome_feature"){
		fields = ["genome_name", "accession", "seed_id", "refseq_locus_tag", "alt_locus_tag", "feature_id",
				"annotation", "feature_type", "start", "end", "na_length", "strand", "protein_id", "aa_length", "gene", "product"
		];
	}else if (req.call_collection =="genome") {
		fields = ["genome_id", "genome_name", "organism_name", "taxon_id", "genome_status",
			"strain", "serovar", "biovar", "pathovar", "mlst", "other_typing",
			"culture_collection", "type_strain",
			"completion_date", "publication",
			"bioproject_accession", "biosample_accession", "assembly_accession", "genbank_accessions",
			"refseq_accessions",
			"sequencing_centers", "sequencing_status", "sequencing_platform", "sequencing_depth", "assembly_method",
			"chromosomes", "plasmids", "contigs", "sequences", "genome_length", "gc_content",
			"patric_cds", "brc1_cds", "refseq_cds",
			"isolation_site", "isolation_source", "isolation_comments", "collection_date",
			"isolation_country", "geographic_location", "latitude", "longitude", "altitude", "depth", "other_environmental",
			"host_name", "host_gender", "host_age", "host_health", "body_sample_site", "body_sample_subsite", "other_clinical",
			"antimicrobial_resistance", "antimicrobial_resistance_evidence",
			"gram_stain", "cell_shape", "motility", "sporulation", "temperature_range", "optimal_temperature", "salinity", "oxygen_requirement",
			"habitat",
			"disease", "comments", "additional_metadata"
		]
	}

	res.format({
		"text/csv": function(){
			debug("text/csv handler")
			if (req.isDownload){
				req.set("content-disposition", "attachment; filename=patric3_query.csv");
			}

			console.log("res.results: ", res.results);
			if (res.results && res.results.response && res.results.response.docs) {
				if (!fields) {
					fields = Object.keys(res.results.response.docs[0]);
				}

				res.write(fields.join(",") + "\n");
				console.log("Fields: ", fields);
				res.results.response.docs.forEach(function(o){
					var row = fields.map(function(field){
						return JSON.stringify(o[field]);
					});
					console.log("row: ", row);
					res.write(row.join(",") + "\n");
				});
			}

			res.end();
		},
		"text/tsv": function(){
			debug("text/tsv handler")
			if (req.isDownload){
				req.set("content-disposition", "attachment; filename=patric3_query.txt");
			}
			console.log("res.results: ", res.results);
			if (res.results && res.results.response && res.results.response.docs) {
				if (!fields) {
					fields = Object.keys(res.results.response.docs[0]);
				}
				res.write(fields.join("\t") + "\n");
				console.log("Fields: ", fields);
				res.results.response.docs.forEach(function(o){
					var row = fields.map(function(field){
						return o[field];
					});
					console.log("row: ", row);
					res.write(row.join("\t") + "\n");
				});
			}

			res.end();
		},
		"application/vnd.openxmlformats": function(){
			debug("Excel  handler")
			if (req.isDownload){
				req.set("content-disposition", "attachment; filename=patric3_query.xlsx");
			}
			var excelConf = {cols: []}

//			console.log("res.results: ", res.results);
			if (res.results && res.results.response && res.results.response.docs) {
				console.log("Build Excel Columns");
				if (!fields) {
					fields = Object.keys(res.results.response.docs[0]);
				}
				console.log("fields: ", fields);

				fields.forEach(function(field){
					if (res.results.response.docs[0] && res.results.response.docs[0][field]) {
						var fd = res.results.response.docs[0][field];
						if (typeof fd=="number"){
							excelConf.cols.push({caption: field, type: "number"});
						}else{
							excelConf.cols.push({caption: field, type: "string"});
						}
					}else{
						excelConf.cols.push({caption: field, type: "string"});
					}
				});

				console.log("excelconf: ", excelConf);
				excelConf.rows = res.results.response.docs.map(function(o){
					var row = fields.map(function(field){
						if (typeof o[field] == "object") {
							if (o[field] instanceof Array) {
								return o[field].join(";");
							}
							return JSON.stringify(o[field]);
						}
						return o[field] || "";
					});
					return row;
				});

				console.log("Excel Conf: ", excelConf);
				var d = nodeExcel.execute(excelConf);
				console.log("Node Excel Data Exported");
				res.set("Content-Type", "application/vnd.openxmlformats");
				res.end(d, "binary");
			}

			res.end();

		},

		"application/solr+json": function(){
			debug("application/json handler")
			res.send(JSON.stringify(res.results));
			res.end();
		},

		"application/json": function(){
			debug("application/json handler")
			if (req.call_method=="query"){
				if (res.results && res.results.response && res.results.facet_counts){
					res.set("facet_counts", JSON.stringify(res.results.facet_counts));
				}
				if (res.results && res.results.response && res.results.response.docs){
					res.send(JSON.stringify(res.results.response.docs));
				}else{
					res.status(404);
				}
			} else{
					if (!res.results){
						res.status(404)
					}else{
						res.send(JSON.stringify(res.results));
					}
			}
			res.end();
		}
	})
}
<|endoftext|>


<commit_before>'use strict';

import {hostname} from 'os';
import process from 'process';
import {name, version} from '../package.json';

/**
 * @returns current log level
 */
function getCurrentLogLevel() {
  return process.env.LOG_LEVEL || 'INFO'; // eslint-disable-line no-process-env
}

/**
 * Convert a log level name to a corresponding numerical value
 *
 * @param logLevel log level to convert
 * @returns numerical log level
 */

function getNumericalLogLevel(logLevel) {
  var logLevels = {
    OFF: 0,
    ERROR: 1,
    WARN: 2,
    WARNING: 2,
    INFO: 3,
    DEBUG: 4
  };

  var numericalLogLevel = logLevels[logLevel.toUpperCase()];
  return numericalLogLevel;
}

/**
 * Log as JSON to stdout
 *
 * @param level log level
 * @param msg message to log
 * @param args map of additional key/values to log
 */
function doLog(level, msg, args) {
  var currentNumericalLogLevel = getNumericalLogLevel(getCurrentLogLevel());
  var targetNumericalLogLevel = getNumericalLogLevel(level);
  if (currentNumericalLogLevel < targetNumericalLogLevel) {
    return; // level low, do nothing
  }

  var blob = {
    '@timestamp': (new Date()).toISOString(),
    '@version': 1,
    app: name,
    version: version,
    level: level.toUpperCase(),
    host: hostname(),
    pid: process.pid,
    msg: msg
  };
  console.log(JSON.stringify(Object.assign(blob, args))); // eslint-disable-line no-console
}

export const log = {
  log: doLog,
  info: (msg, args) => doLog('info', msg, args),
  warn: (msg, args) => doLog('warn', msg, args),
  error: (msg, args) => doLog('error', msg, args),
  debug: (msg, args) => doLog('debug', msg, args)
};

export function userEncode(libraryId, userId) {
  libraryId = libraryId || '';
  userId = userId || '';

  if (typeof libraryId !== 'string') {
    log.error('libraryId should be of type string, got ' + typeof libraryId, {libraryId: libraryId, userId: userId});
    return null;
  }

  if (typeof userId !== 'string') {
    log.error('userId should be of type string, got ' + typeof userId, {libraryId: libraryId, userId: userId});
    return null;
  }

  return userId + '@' + libraryId;
}

export function userDecode(username) {
  var splitPoint = username.lastIndexOf('@');
  var userId = username.substring(0, splitPoint);
  var libraryId = username.substring(splitPoint+1, username.length);
  var user = {libraryId: libraryId};

  if (userId) {
    user.id = userId;
  }

  return user;
}
<commit_msg>make msg optional when logging<commit_after>'use strict';

import {hostname} from 'os';
import process from 'process';
import {name, version} from '../package.json';

/**
 * @returns current log level
 */
function getCurrentLogLevel() {
  return process.env.LOG_LEVEL || 'INFO'; // eslint-disable-line no-process-env
}

/**
 * Convert a log level name to a corresponding numerical value
 *
 * @param logLevel log level to convert
 * @returns numerical log level
 */

function getNumericalLogLevel(logLevel) {
  var logLevels = {
    OFF: 0,
    ERROR: 1,
    WARN: 2,
    WARNING: 2,
    INFO: 3,
    DEBUG: 4
  };

  var numericalLogLevel = logLevels[logLevel.toUpperCase()];
  return numericalLogLevel;
}

/**
 * Log as JSON to stdout
 *
 * @param level log level
 * @param msg message to log
 * @param args map of additional key/values to log
 */
function doLog(level, msg, args) {
  var currentNumericalLogLevel = getNumericalLogLevel(getCurrentLogLevel());
  var targetNumericalLogLevel = getNumericalLogLevel(level);
  if (currentNumericalLogLevel < targetNumericalLogLevel) {
    return; // level low, do nothing
  }

  var blob = {
    '@timestamp': (new Date()).toISOString(),
    '@version': 1,
    app: name,
    version: version,
    level: level.toUpperCase(),
    host: hostname(),
    pid: process.pid
  };

  if (msg) {
    blob.msg = msg;
  }

  console.log(JSON.stringify(Object.assign(blob, args))); // eslint-disable-line no-console
}

export const log = {
  log: doLog,
  info: (msg, args) => doLog('info', msg, args),
  warn: (msg, args) => doLog('warn', msg, args),
  error: (msg, args) => doLog('error', msg, args),
  debug: (msg, args) => doLog('debug', msg, args)
};

export function userEncode(libraryId, userId) {
  libraryId = libraryId || '';
  userId = userId || '';

  if (typeof libraryId !== 'string') {
    log.error('libraryId should be of type string, got ' + typeof libraryId, {libraryId: libraryId, userId: userId});
    return null;
  }

  if (typeof userId !== 'string') {
    log.error('userId should be of type string, got ' + typeof userId, {libraryId: libraryId, userId: userId});
    return null;
  }

  return userId + '@' + libraryId;
}

export function userDecode(username) {
  var splitPoint = username.lastIndexOf('@');
  var userId = username.substring(0, splitPoint);
  var libraryId = username.substring(splitPoint+1, username.length);
  var user = {libraryId: libraryId};

  if (userId) {
    user.id = userId;
  }

  return user;
}
<|endoftext|>


<commit_before>const bot = require('./bot');
const RichEmbed = require('discord.js').RichEmbed;

exports.randomSelection = function () {
    return String(arguments[Math.floor(Math.random() * arguments.length)]);
};

exports.randomColor = function () {
    return [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
};

const randomFooter = function () {
    return exports.randomSelection(
        'just add water!',
        'Powered by squirrels!',
        'codeisluvcodeislife',
        'Where did you get that?',
        'WHAT DID YOU BREAK!?',
        'D-D-D-DROP THE BASS',
        'Eat, Sleep, Dubstep',
        '#BlameRayzr522'
    );
};

exports.embed = (title, description = '', fields = [], options = {}) => {
    let url = options.url || '';
    let color = options.color || this.randomColor();

    if (fields.length > 0) fields.push({ name: '\u200b', value: '\u200b' });
    if (options.inline) {
        fields = fields.map(obj => { obj.inline = true; return obj; });
        if (fields.length % 3 === 2)
            fields.push({ name: '\u200b', value: '\u200b' });
    }
    if (url !== '') description += '\n';

    return new RichEmbed({ fields, video: options.video || url })
        .setTitle(title)
        .setColor(color)
        .setDescription(description)
        .setImage(options.image || url)
        .setTimestamp(options.timestamp ? new Date() : null)
        .setFooter(options.footer === true ? randomFooter() : (options.footer ? options.footer : ''), options.footer ? bot.client.user.avatarURL : undefined);
};

exports.parseArgs = function (args, options) {
    if (!options)
        return args;
    if (typeof options === 'string')
        options = [options];

    var optionValues = {};

    var i;
    for (i = 0; i < args.length; i++) {
        var arg = args[i];
        if (!arg.startsWith('-')) {
            break;
        }

        var label = arg.substr(1);

        if (options.indexOf(label + ':') > -1) {
            var leftover = args.slice(i + 1).join(' ');
            var matches = leftover.match(/^"(.+)"/);
            if (matches) {
                optionValues[label] = matches[1];
                i += matches[0].split(' ').length;
            } else {
                i++;
                optionValues[label] = args[i];
            }
        } else if (options.indexOf(label) > -1) {
            optionValues[label] = true;
        } else {
            break;
        }
    }

    return {
        options: optionValues,
        leftover: args.slice(i)
    };
};

exports.multiSend = function (channel, messages, delay) {
    delay = delay || 100;
    messages.forEach((m, i) => {
        setTimeout(() => {
            channel.sendMessage(m);
        }, delay * i);
    });
};

exports.sendLarge = function (channel, largeMessage, options = {}) {
    var message = largeMessage;
    var messages = [];
    var prefix = options.prefix || '';
    var suffix = options.suffix || '';

    var max = 2000 - prefix.length - suffix.length;

    while (message.length >= max) {
        var part = message.substr(0, max);
        var cutTo = max;
        if (options.cutOn) {
            cutTo = part.lastIndexOf(options.cutOn);
            part = part.substr(0, cutTo);
        }
        messages.push(prefix + part + suffix);
        message = message.substr(cutTo);
    }

    if (message.length > 1) {
        messages.push(prefix + message + suffix);
    }

    this.multiSend(channel, messages, options.delay);
};

exports.now = () => {
    var now = process.hrtime();
    return now[0] * 1e3 + now[1] / 1e6;
};

exports.playAnimation = (msg, delay, list) => {
    if (list.length < 1)
        return;

    var next = list.shift();
    var start = this.now();

    msg.edit(next).then(() => {
        var elapsed = this.now() - start;

        setTimeout(() => {
            this.playAnimation(msg, delay, list);
        }, Math.max(50, delay - elapsed));
    }).catch(console.error);
};<commit_msg>Made quoted option regex lazy<commit_after>const bot = require('./bot');
const RichEmbed = require('discord.js').RichEmbed;

exports.randomSelection = function () {
    return String(arguments[Math.floor(Math.random() * arguments.length)]);
};

exports.randomColor = function () {
    return [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
};

const randomFooter = function () {
    return exports.randomSelection(
        'just add water!',
        'Powered by squirrels!',
        'codeisluvcodeislife',
        'Where did you get that?',
        'WHAT DID YOU BREAK!?',
        'D-D-D-DROP THE BASS',
        'Eat, Sleep, Dubstep',
        '#BlameRayzr522'
    );
};

exports.embed = (title, description = '', fields = [], options = {}) => {
    let url = options.url || '';
    let color = options.color || this.randomColor();

    if (fields.length > 0) fields.push({ name: '\u200b', value: '\u200b' });
    if (options.inline) {
        fields = fields.map(obj => { obj.inline = true; return obj; });
        if (fields.length % 3 === 2)
            fields.push({ name: '\u200b', value: '\u200b' });
    }
    if (url !== '') description += '\n';

    return new RichEmbed({ fields, video: options.video || url })
        .setTitle(title)
        .setColor(color)
        .setDescription(description)
        .setImage(options.image || url)
        .setTimestamp(options.timestamp ? new Date() : null)
        .setFooter(options.footer === true ? randomFooter() : (options.footer ? options.footer : ''), options.footer ? bot.client.user.avatarURL : undefined);
};

exports.parseArgs = function (args, options) {
    if (!options)
        return args;
    if (typeof options === 'string')
        options = [options];

    var optionValues = {};

    var i;
    for (i = 0; i < args.length; i++) {
        var arg = args[i];
        if (!arg.startsWith('-')) {
            break;
        }

        var label = arg.substr(1);

        if (options.indexOf(label + ':') > -1) {
            var leftover = args.slice(i + 1).join(' ');
            var matches = leftover.match(/^"(.+?)"/);
            if (matches) {
                optionValues[label] = matches[1];
                i += matches[0].split(' ').length;
            } else {
                i++;
                optionValues[label] = args[i];
            }
        } else if (options.indexOf(label) > -1) {
            optionValues[label] = true;
        } else {
            break;
        }
    }

    return {
        options: optionValues,
        leftover: args.slice(i)
    };
};

exports.multiSend = function (channel, messages, delay) {
    delay = delay || 100;
    messages.forEach((m, i) => {
        setTimeout(() => {
            channel.sendMessage(m);
        }, delay * i);
    });
};

exports.sendLarge = function (channel, largeMessage, options = {}) {
    var message = largeMessage;
    var messages = [];
    var prefix = options.prefix || '';
    var suffix = options.suffix || '';

    var max = 2000 - prefix.length - suffix.length;

    while (message.length >= max) {
        var part = message.substr(0, max);
        var cutTo = max;
        if (options.cutOn) {
            cutTo = part.lastIndexOf(options.cutOn);
            part = part.substr(0, cutTo);
        }
        messages.push(prefix + part + suffix);
        message = message.substr(cutTo);
    }

    if (message.length > 1) {
        messages.push(prefix + message + suffix);
    }

    this.multiSend(channel, messages, options.delay);
};

exports.now = () => {
    var now = process.hrtime();
    return now[0] * 1e3 + now[1] / 1e6;
};

exports.playAnimation = (msg, delay, list) => {
    if (list.length < 1)
        return;

    var next = list.shift();
    var start = this.now();

    msg.edit(next).then(() => {
        var elapsed = this.now() - start;

        setTimeout(() => {
            this.playAnimation(msg, delay, list);
        }, Math.max(50, delay - elapsed));
    }).catch(console.error);
};<|endoftext|>


<commit_before>export const centerGameObjects = (objects) => {
  objects.forEach(function (object) {
    object.anchor.setTo(0.5);
  });
};

export function centerOfObject(object, map) {
  return {
    x: object.x + (map.tileWidth / 2),
    y: object.y - (map.tileHeight / 2),
  };
}

export const findObjByKey = (array, key, value) => {
  for(let i = 0, len = array.length; i < len; i++) {
    let object = array[i];
    if (typeof object === 'object' && object.hasOwnProperty(key) && object[key] === value) {
      return object;
    }
  }
  return false;
}

export const clone = (obj) => JSON.parse(JSON.stringify(obj));
<commit_msg>Add utility function to convert direction name to WASD<commit_after>export const centerGameObjects = (objects) => {
  objects.forEach(function (object) {
    object.anchor.setTo(0.5);
  });
};

export function centerOfObject(object, map) {
  return {
    x: object.x + (map.tileWidth / 2),
    y: object.y - (map.tileHeight / 2),
  };
}

export const findObjByKey = (array, key, value) => {
  for(let i = 0, len = array.length; i < len; i++) {
    let object = array[i];
    if (typeof object === 'object' && object.hasOwnProperty(key) && object[key] === value) {
      return object;
    }
  }
  return false;
}

export const clone = (obj) => JSON.parse(JSON.stringify(obj));

export function directionToWASD(direction) {
  direction = direction.toLowerCase();

  switch (direction) {
    case 'up': {
      return 'w';
    }
    case 'left': {
      return 'a';
    }
    case 'down': {
      return 's';
    }
    case 'right': {
      return 'd';
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

exports.up = function (knex, Promise) {
    return Promise.all([
        knex.schema.createTableIfNotExists('users', function (table) {
            table.uuid('_id').notNullable().primary();
            table.string('email').notNullable().unique();
            table.string('password').notNullable().defaultTo('');
            table.string('fullname').notNullable().defaultTo('');
            table.string('slug').notNullable().defaultTo('').unique();
            table.string('url').notNullable().defaultTo('');
            table.string('location').notNullable().defaultTo('');
            table.text('description').notNullable().defaultTo('');
            table.string('role').notNullable().defaultTo('author');
            table.string('salt').notNull().defaultTo('');
            table.timestamps();
        })
    ]);
};

exports.down = function (knex, Promise) {
    return Promise.all([
        knex.schema.dropTable('users')
    ]);
};
<commit_msg>Eliminato users.js<commit_after><|endoftext|>


<commit_before>
/* global jQuery, Zepto, Pin */

(function ($) {
    'use strict';

    var defaults = {
        slide:           0,
        delay:           5000,
        preload:         true,
        timer:           true,
        overlay:         false,
        autoplay:        true,
        shuffle:         false,
        fill:            true,
        color:           null,
        align:           'center',
        valign:          'center',
        transition:      'fade',
        transitionDelay: 1000,
        init:  function () {},
        play:  function () {},
        pause: function () {},
        walk:  function () {},
        slides: [
            // {
            //  src:             null,
            //  color:           null,
            //  delay:           null,
            //  align:           null,
            //  valign:          null,
            //  transition:      null,
            //  transitiondelay: null,
            //  fill:            true,
            //  videos:          []
            // }
            // ...
        ]
    };

    var Vegas = function (elmt, options) {
        this.elmt         = elmt;
        this.settings     = $.extend({}, defaults, $.vegas.defaults, options);
        this.slide        = this.settings.slide;
        this.total        = this.settings.slides.length;
        this.noshow       = this.total < 2;
        this.paused       = !this.settings.autoplay || this.noshow;
        this.$elmt        = $(elmt);
        this.$timer       = null;
        this.$overlay     = null;
        this.$slide       = null;
        this.timeout      = null;
        this.transitions  = [];

        this.support = {
            objectFit:  'objectFit'  in document.body.style,
            transition: 'transition' in document.body.style || 'WebkitTransition' in document.body.style,
            video:      $.vegas.isVideoCompatible()
        };

        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i],
                rules = sheet.rules ? sheet.rules : sheet.cssRules;

            if (/vegas(\.min)?\.css$/.test(sheet.href)) {
                for (var j = 0; j < rules.length; j++) {
                    var rule  = rules[j],
                        match = /vegas\-transition\-(.*)-|\b/gi.exec(rule.selectorText);

                    if (match && match[1]) {
                        this.transitions.push(match[1]);
                    }
                }
            }
        }

        if (this.settings.shuffle === true) {
            this.shuffle();
        }

        this._init();
    };

    Vegas.prototype = {
        _init: function () {
            var $wrapper,
                $overlay,
                $timer,
                isBody    = this.elmt.tagName === 'BODY',
                timer     = this.settings.timer,
                overlay   = this.settings.overlay,
                preload   = this.settings.preload,
                position  = this.$elmt.css('position'),
                img,
                i;

            // Preloading
            if (preload) {
                for (i = 0; i < this.settings.slides.length; i++) {
                    img = new Image();
                    img.src = this.settings.slides[i].src;
                }
            }

            // Wrapper with content
            if (!isBody) {
                $wrapper = $('
')
                    .css('overflow', this.$elmt.css('overflow'))
                    .css('padding',  this.$elmt.css('padding'));

                // Some browsers don't compute padding shorthand
                if (!this.$elmt.css('padding')) {
                    $wrapper
                        .css('padding-top',    this.$elmt.css('padding-top'))
                        .css('padding-bottom', this.$elmt.css('padding-bottom'))
                        .css('padding-left',   this.$elmt.css('padding-left'))
                        .css('padding-right',  this.$elmt.css('padding-right'));
                }

                $wrapper[0].innerHTML = this.elmt.innerHTML;
                this.elmt.innerHTML = '';
            }

            // Timer
            if (timer && this.support.transition) {
                $timer = $('

');
                this.$timer = $timer;
                this.$elmt.prepend($timer);
            }

            // Overlay
            if (overlay) {
                $overlay = $('
');
                if (typeof overlay === 'string') {
                    $overlay.css('background-image', 'url(' + overlay + ')');
                }
                this.$overlay = $overlay;
                this.$elmt.prepend($overlay);
            }

            // Container
            this.$elmt.addClass('vegas-container');
            if (!isBody) {
                if (position === 'static') {
                    this.$elmt.css('position', 'relative');
                }
                this.$elmt.append($wrapper);
            }

            this.trigger('init');
            this._goto(this.slide);
        },

        _slideShow: function () {
            var self = this;

            if (this.paused || this.noshow) {
                clearTimeout(this.timeout);
            } else {
                clearTimeout(this.timeout);
                this.timeout = setTimeout(function () {
                    self.next();
                }, this._options('delay'));
            }
        },

        _timer: function (state) {
            var self = this;

            clearTimeout(this.timeout);

            if (!this.$timer || this.paused || this.noshow) {
                return;
            }

            this.$timer
                .removeClass('vegas-timer-running')
                    .find('div')
                        .css('transition-duration', '0ms');

            if (state) {
                setTimeout(function () {
                   self.$timer
                    .addClass('vegas-timer-running')
                        .find('div')
                            .css('transition-duration', self._options('delay') - 100 + 'ms');
                }, 100);
            }
        },

        _options: function (key, i) {
            if (i === undefined) {
                i = this.slide;
            }

            if (this.settings.slides[i][key] !== undefined) {
                return this.settings.slides[i][key];
            }

            return this.settings[key];
        },

        _goto: function (nb) {
            this.slide = nb;

            var $slide,
                $slides    = this.$elmt.children('.vegas-slide'),
                total      = $slides.length,
                self       = this,
                src        = this.settings.slides[nb].src,
                videos     = this.settings.slides[nb].video,
                delay      = this._options('delay'),
                duration   = this._options('transitionDelay'),
                align      = this._options('align'),
                valign     = this._options('valign'),
                color      = this._options('color') || this.$elmt.css('background-color'),
                fill       = this._options('fill') ? 'cover' : 'contain',
                transition = this._options('transition'),
                isRandom   = transition === 'random',
                video,
                source,
                img;

            if (isRandom) {
                transition = this.transitions[Math.floor(Math.random() * (this.transitions.length - 1))];
            }

            if (transition !== 'none' && this.transitions.indexOf(transition) < 0) {
                console.error("Vegas: Transition " + transition + " doesn't exist.");
            }

            if (duration > delay) {
                duration = delay;
            }

            if (this.support.video && videos) {
                if (videos instanceof Array === false) {
                    videos = [ videos ];
                }

                video = document.createElement('video');
                video.muted = true;
                video.loop = true;
                video.autoplay = true;

                videos.forEach(function (src) {
                    source = document.createElement('source');
                    source.src = src;
                    video.appendChild(source);
                });

                $slide = $(video)
                    .addClass('vegas-video')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-color', color);

                if (this.support.objectFit) {
                    $slide
                        .css('object-position', align + ' ' + valign)
                        .css('object-fit', fill)
                        .css('width',  '100%')
                        .css('height', '100%');
                } else if (fill === 'contain') {
                    $slide
                        .css('width',  '100%')
                        .css('height', '100%');
                }
            } else {
                img = new Image();
                img.src = src;

                $slide = $('

')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-image',    'url(' + src + ')')
                    .css('background-color',    color)
                    .css('background-position', align + ' ' + valign)
                    .css('background-size',     fill);
            }

            if (!self.support.transition) {
                $slide.css('display', 'none');
            }

            if (total) {
                $slides.eq(total - 1).after($slide);
            } else {
                this.$elmt.prepend($slide);
            }

            $slides
                .css('transition', 'all 0ms')
                .each(function () {
                    this.className  = ' vegas-slide';
                    this.className += ' vegas-transition-' +  transition;
                    this.className += ' vegas-transition-' +  transition + '-in';

                    if (video) {
                        this.className += ' vegas-video';
                    }
                }
            );

            self._timer(false);

            function go () {
                self._timer(true);

                setTimeout(function () {
                    if (self.support.transition) {
                        $slides
                            .css('transition', 'all ' + duration + 'ms')
                            .addClass('vegas-transition-' + transition + '-out');
                    }

                    $slide
                        .css('transition', 'all ' + duration + 'ms')
                        .addClass('vegas-transition-' + transition + '-in');

                    if (!self.support.transition) {
                        $slide.fadeIn(duration);
                    }

                    if ($slides.length >= 2) {
                         $slides.eq(0).remove();
                    }

                    self.trigger('walk');
                    self._slideShow();
                }, 100);
            }

            if (video) {
                // oncanplay is triggered every time when loop=true
                // so let's start the slide only once
                var played = false;

                video.play();
                video.oncanplay = function () {
                    if (!played) {
                        played = true;
                        go();
                    }
                };
            } else {
                img.onload = go;
            }
        },

        shuffle: function () {
            var temp,
                rand;

            for (var i = this.total - 1; i > 0; i--) {
                rand = Math.floor(Math.random() * (i + 1));
                temp = this.settings.slides[i];
                this.settings.slides[i] = this.settings.slides[rand];
                this.settings.slides[rand] = temp;
            }
        },

        play: function () {
            if (this.paused) {
                this.paused = false;
                this.next();
                this.trigger('play');
            }
        },

        pause: function () {
            this._timer(false);
            this.paused = true;
            this.trigger('pause');
        },

        toggle: function () {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        },

        playing: function () {
            return !this.paused && !this.noshow;
        },

        current: function (advanced) {
            if (advanced) {
                return {
                    slide: this.slide,
                    data:  this.settings.slides[this.slide]
                };
            }
            return this.slide;
        },

        jump: function (nb) {
            if (nb < 0 || nb > this.total - 1 || nb === this.slide) {
                return;
            }

            this.slide = nb;
            this._goto(this.slide);
        },

        next: function () {
            this.slide++;

            if (this.slide >= this.total) {
                this.slide = 0;
            }

            this._goto(this.slide);
        },

        previous: function () {
            this.slide--;

            if (this.slide < 0) {
                this.slide = this.total - 1;
            }

            this._goto(this.slide);
        },

        trigger: function (fn) {
            var params = [];

            if (fn !== 'init') {
                params = [
                    this.slide,
                    this.settings.slides[this.slide]
                ];
            }

            this.$elmt.trigger('vegas' + fn, params);

            if (typeof this.settings[fn] === 'function') {
                this.settings[fn].apply(this.$elmt, params);
            }
        },

        options: function (key, value) {
            if (typeof key === 'string') {
                if (value === undefined) {
                    return this.settings[key];
                }
                this.settings[key] = value;
            } else if (typeof key === 'object') {
                this.settings = key;
            } else {
                return this.settings;
            }
        }
    };

    $.fn.vegas = function(options) {
        var args = arguments,
            error = false,
            returns;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {
                if (!this._vegas) {
                    this._vegas = new Vegas(this, options);
                }
            });
        } else if (typeof options === 'string') {
            this.each(function () {
                var instance = this._vegas;

                if (!instance) {
                    throw new Error('No Vegas applied to this element.');
                }

                if (typeof instance[options] === 'function' && options[0] !== '_') {
                    returns = instance[options].apply(instance, [].slice.call(args, 1));
                } else {
                    error = true;
                }
            });

            if (error) {
                throw new Error('No method "' + options + '" in Vegas.');
            }

            return returns !== undefined ? returns : this;
        }
    };

    $.vegas = {};
    $.vegas.defaults = defaults;

    $.vegas.isVideoCompatible = function () {
        return !('ontouchstart' in window || 'onmsgesturechange' in window);
    };

})(typeof jQuery !== 'undefined' ? jQuery :
   typeof Zepto  !== 'undefined' ? Zepto  :
   typeof Pin    !== 'undefined' ? Pin    : null
);
<commit_msg>Don't try to preload a image without src<commit_after>
/* global jQuery, Zepto, Pin */

(function ($) {
    'use strict';

    var defaults = {
        slide:           0,
        delay:           5000,
        preload:         true,
        timer:           true,
        overlay:         false,
        autoplay:        true,
        shuffle:         false,
        fill:            true,
        color:           null,
        align:           'center',
        valign:          'center',
        transition:      'fade',
        transitionDelay: 1000,
        init:  function () {},
        play:  function () {},
        pause: function () {},
        walk:  function () {},
        slides: [
            // {
            //  src:             null,
            //  color:           null,
            //  delay:           null,
            //  align:           null,
            //  valign:          null,
            //  transition:      null,
            //  transitiondelay: null,
            //  fill:            true,
            //  videos:          []
            // }
            // ...
        ]
    };

    var Vegas = function (elmt, options) {
        this.elmt         = elmt;
        this.settings     = $.extend({}, defaults, $.vegas.defaults, options);
        this.slide        = this.settings.slide;
        this.total        = this.settings.slides.length;
        this.noshow       = this.total < 2;
        this.paused       = !this.settings.autoplay || this.noshow;
        this.$elmt        = $(elmt);
        this.$timer       = null;
        this.$overlay     = null;
        this.$slide       = null;
        this.timeout      = null;
        this.transitions  = [];

        this.support = {
            objectFit:  'objectFit'  in document.body.style,
            transition: 'transition' in document.body.style || 'WebkitTransition' in document.body.style,
            video:      $.vegas.isVideoCompatible()
        };

        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i],
                rules = sheet.rules ? sheet.rules : sheet.cssRules;

            if (/vegas(\.min)?\.css$/.test(sheet.href)) {
                for (var j = 0; j < rules.length; j++) {
                    var rule  = rules[j],
                        match = /vegas\-transition\-(.*)-|\b/gi.exec(rule.selectorText);

                    if (match && match[1]) {
                        this.transitions.push(match[1]);
                    }
                }
            }
        }

        if (this.settings.shuffle === true) {
            this.shuffle();
        }

        this._init();
    };

    Vegas.prototype = {
        _init: function () {
            var $wrapper,
                $overlay,
                $timer,
                isBody    = this.elmt.tagName === 'BODY',
                timer     = this.settings.timer,
                overlay   = this.settings.overlay,
                preload   = this.settings.preload,
                position  = this.$elmt.css('position'),
                img,
                i;

            // Preloading
            if (preload) {
                for (i = 0; i < this.settings.slides.length; i++) {
                    if (this.settings.slides[i].src) {
                        img = new Image();
                        img.src = this.settings.slides[i].src;
                    }
                }
            }

            // Wrapper with content
            if (!isBody) {
                $wrapper = $('
')
                    .css('overflow', this.$elmt.css('overflow'))
                    .css('padding',  this.$elmt.css('padding'));

                // Some browsers don't compute padding shorthand
                if (!this.$elmt.css('padding')) {
                    $wrapper
                        .css('padding-top',    this.$elmt.css('padding-top'))
                        .css('padding-bottom', this.$elmt.css('padding-bottom'))
                        .css('padding-left',   this.$elmt.css('padding-left'))
                        .css('padding-right',  this.$elmt.css('padding-right'));
                }

                $wrapper[0].innerHTML = this.elmt.innerHTML;
                this.elmt.innerHTML = '';
            }

            // Timer
            if (timer && this.support.transition) {
                $timer = $('

');
                this.$timer = $timer;
                this.$elmt.prepend($timer);
            }

            // Overlay
            if (overlay) {
                $overlay = $('
');
                if (typeof overlay === 'string') {
                    $overlay.css('background-image', 'url(' + overlay + ')');
                }
                this.$overlay = $overlay;
                this.$elmt.prepend($overlay);
            }

            // Container
            this.$elmt.addClass('vegas-container');
            if (!isBody) {
                if (position === 'static') {
                    this.$elmt.css('position', 'relative');
                }
                this.$elmt.append($wrapper);
            }

            this.trigger('init');
            this._goto(this.slide);
        },

        _slideShow: function () {
            var self = this;

            if (this.paused || this.noshow) {
                clearTimeout(this.timeout);
            } else {
                clearTimeout(this.timeout);
                this.timeout = setTimeout(function () {
                    self.next();
                }, this._options('delay'));
            }
        },

        _timer: function (state) {
            var self = this;

            clearTimeout(this.timeout);

            if (!this.$timer || this.paused || this.noshow) {
                return;
            }

            this.$timer
                .removeClass('vegas-timer-running')
                    .find('div')
                        .css('transition-duration', '0ms');

            if (state) {
                setTimeout(function () {
                   self.$timer
                    .addClass('vegas-timer-running')
                        .find('div')
                            .css('transition-duration', self._options('delay') - 100 + 'ms');
                }, 100);
            }
        },

        _options: function (key, i) {
            if (i === undefined) {
                i = this.slide;
            }

            if (this.settings.slides[i][key] !== undefined) {
                return this.settings.slides[i][key];
            }

            return this.settings[key];
        },

        _goto: function (nb) {
            this.slide = nb;

            var $slide,
                $slides    = this.$elmt.children('.vegas-slide'),
                total      = $slides.length,
                self       = this,
                src        = this.settings.slides[nb].src,
                videos     = this.settings.slides[nb].video,
                delay      = this._options('delay'),
                duration   = this._options('transitionDelay'),
                align      = this._options('align'),
                valign     = this._options('valign'),
                color      = this._options('color') || this.$elmt.css('background-color'),
                fill       = this._options('fill') ? 'cover' : 'contain',
                transition = this._options('transition'),
                isRandom   = transition === 'random',
                video,
                source,
                img;

            if (isRandom) {
                transition = this.transitions[Math.floor(Math.random() * (this.transitions.length - 1))];
            }

            if (transition !== 'none' && this.transitions.indexOf(transition) < 0) {
                console.error("Vegas: Transition " + transition + " doesn't exist.");
            }

            if (duration > delay) {
                duration = delay;
            }

            if (this.support.video && videos) {
                if (videos instanceof Array === false) {
                    videos = [ videos ];
                }

                video = document.createElement('video');
                video.muted = true;
                video.loop = true;
                video.autoplay = true;

                videos.forEach(function (src) {
                    source = document.createElement('source');
                    source.src = src;
                    video.appendChild(source);
                });

                $slide = $(video)
                    .addClass('vegas-video')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-color', color);

                if (this.support.objectFit) {
                    $slide
                        .css('object-position', align + ' ' + valign)
                        .css('object-fit', fill)
                        .css('width',  '100%')
                        .css('height', '100%');
                } else if (fill === 'contain') {
                    $slide
                        .css('width',  '100%')
                        .css('height', '100%');
                }
            } else {
                img = new Image();
                img.src = src;

                $slide = $('

')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-image',    'url(' + src + ')')
                    .css('background-color',    color)
                    .css('background-position', align + ' ' + valign)
                    .css('background-size',     fill);
            }

            if (!self.support.transition) {
                $slide.css('display', 'none');
            }

            if (total) {
                $slides.eq(total - 1).after($slide);
            } else {
                this.$elmt.prepend($slide);
            }

            $slides
                .css('transition', 'all 0ms')
                .each(function () {
                    this.className  = ' vegas-slide';
                    this.className += ' vegas-transition-' +  transition;
                    this.className += ' vegas-transition-' +  transition + '-in';

                    if (video) {
                        this.className += ' vegas-video';
                    }
                }
            );

            self._timer(false);

            function go () {
                self._timer(true);

                setTimeout(function () {
                    if (self.support.transition) {
                        $slides
                            .css('transition', 'all ' + duration + 'ms')
                            .addClass('vegas-transition-' + transition + '-out');
                    }

                    $slide
                        .css('transition', 'all ' + duration + 'ms')
                        .addClass('vegas-transition-' + transition + '-in');

                    if (!self.support.transition) {
                        $slide.fadeIn(duration);
                    }

                    if ($slides.length >= 2) {
                         $slides.eq(0).remove();
                    }

                    self.trigger('walk');
                    self._slideShow();
                }, 100);
            }

            if (video) {
                // oncanplay is triggered every time when loop=true
                // so let's start the slide only once
                var played = false;

                video.play();
                video.oncanplay = function () {
                    if (!played) {
                        played = true;
                        go();
                    }
                };
            } else {
                img.onload = go;
            }
        },

        shuffle: function () {
            var temp,
                rand;

            for (var i = this.total - 1; i > 0; i--) {
                rand = Math.floor(Math.random() * (i + 1));
                temp = this.settings.slides[i];
                this.settings.slides[i] = this.settings.slides[rand];
                this.settings.slides[rand] = temp;
            }
        },

        play: function () {
            if (this.paused) {
                this.paused = false;
                this.next();
                this.trigger('play');
            }
        },

        pause: function () {
            this._timer(false);
            this.paused = true;
            this.trigger('pause');
        },

        toggle: function () {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        },

        playing: function () {
            return !this.paused && !this.noshow;
        },

        current: function (advanced) {
            if (advanced) {
                return {
                    slide: this.slide,
                    data:  this.settings.slides[this.slide]
                };
            }
            return this.slide;
        },

        jump: function (nb) {
            if (nb < 0 || nb > this.total - 1 || nb === this.slide) {
                return;
            }

            this.slide = nb;
            this._goto(this.slide);
        },

        next: function () {
            this.slide++;

            if (this.slide >= this.total) {
                this.slide = 0;
            }

            this._goto(this.slide);
        },

        previous: function () {
            this.slide--;

            if (this.slide < 0) {
                this.slide = this.total - 1;
            }

            this._goto(this.slide);
        },

        trigger: function (fn) {
            var params = [];

            if (fn !== 'init') {
                params = [
                    this.slide,
                    this.settings.slides[this.slide]
                ];
            }

            this.$elmt.trigger('vegas' + fn, params);

            if (typeof this.settings[fn] === 'function') {
                this.settings[fn].apply(this.$elmt, params);
            }
        },

        options: function (key, value) {
            if (typeof key === 'string') {
                if (value === undefined) {
                    return this.settings[key];
                }
                this.settings[key] = value;
            } else if (typeof key === 'object') {
                this.settings = key;
            } else {
                return this.settings;
            }
        }
    };

    $.fn.vegas = function(options) {
        var args = arguments,
            error = false,
            returns;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {
                if (!this._vegas) {
                    this._vegas = new Vegas(this, options);
                }
            });
        } else if (typeof options === 'string') {
            this.each(function () {
                var instance = this._vegas;

                if (!instance) {
                    throw new Error('No Vegas applied to this element.');
                }

                if (typeof instance[options] === 'function' && options[0] !== '_') {
                    returns = instance[options].apply(instance, [].slice.call(args, 1));
                } else {
                    error = true;
                }
            });

            if (error) {
                throw new Error('No method "' + options + '" in Vegas.');
            }

            return returns !== undefined ? returns : this;
        }
    };

    $.vegas = {};
    $.vegas.defaults = defaults;

    $.vegas.isVideoCompatible = function () {
        return !('ontouchstart' in window || 'onmsgesturechange' in window);
    };

})(typeof jQuery !== 'undefined' ? jQuery :
   typeof Zepto  !== 'undefined' ? Zepto  :
   typeof Pin    !== 'undefined' ? Pin    : null
);
<|endoftext|>


<commit_before>// $Id$

// Global Killswitch
if (Drupal.jsEnabled) {
  // Keep track of all header cells.
  var cells = [];

  // Attach to all headers.
  $(document).ready(function() {
    var z = 0;
    $('table thead').each(function () {
      // Find table height.
      var table = $(this).parent('table')[0];
      var height = $(table).addClass('sticky-table').height();
      var i = 0;

      // Find all header cells.
      $('th', this).each(function () {

        // Ensure each cell has an element in it.
        var html = $(this).html();
        if (html == ' ') {
          html = ' ';
        }
        if ($(this).children().size() == 0) {
          html = ''+ html +'';
        }

        // Clone and wrap cell contents in sticky wrapper that overlaps the cell's padding.
        $('
'+ html +'
').prependTo(this);
        var div = $('div.sticky-header', this).css({
          'marginLeft': '-'+ $(this).css('paddingLeft'),
          'marginRight': '-'+ $(this).css('paddingRight'),
          'paddingLeft': $(this).css('paddingLeft'),
          'paddingTop': $(this).css('paddingTop'),
          'paddingBottom': $(this).css('paddingBottom'),
          'z-index': ++z
        })[0];
        cells.push(div);

        // Adjust width to fit cell/table.
        var ref = this;
        if (!i++) {
          // The first cell is as wide as the table to prevent gaps.
          ref = table;
          div.wide = true;
        }
        $(div).css('width', parseInt($(ref).width())
                          - parseInt($(div).css('paddingLeft')) +'px');

        // Get position and store.
        div.cell = this;
        div.table = table;
        div.stickyMax = height;
        div.stickyPosition = Drupal.absolutePosition(this).y;
      });
    });
  });

  // Track scrolling.
  var scroll = function() {
    $(cells).each(function () {
      // Fetch scrolling position.
      var scroll = document.documentElement.scrollTop || document.body.scrollTop;
      var offset = scroll - this.stickyPosition - 4;
      if (offset > 0 && offset < this.stickyMax - 100) {
        $(this).css('visibility', 'visible');
      }
      else {
        $(this).css('visibility', 'hidden');
      }
    });
  };
  $(window).scroll(scroll);
  $(document.documentElement).scroll(scroll);

  // Track resizing.
  var time = null;
  var resize = function () {
    // Ensure minimum time between adjustments.
    if (time) {
      clearTimeout(time);
      time = null;
    }
    time = setTimeout(function () {

      // Precalculate table heights
      $('table.sticky-table').each(function () {
        this.height = $(this).height();
      })

      $(cells).each(function () {
        // Get position.
        this.stickyPosition = Drupal.absolutePosition(this.cell).y;
        this.stickyMax = this.table.height;

        // Reflow the cell.
        var ref = this.cell;
        if (this.wide) {
          // Resize the first cell to fit the table.
          ref = this.table;
        }
        $(this).css('width', parseInt($(ref).width())
                           - parseInt($(this).css('paddingLeft')) +'px');
      });
    }, 250);
  };
  $(window).resize(resize);
}
<commit_msg>Slightly tweak the JS timing for sticky tableheader resizing.<commit_after>// $Id$

// Global Killswitch
if (Drupal.jsEnabled) {
  // Keep track of all header cells.
  var cells = [];

  // Attach to all headers.
  $(document).ready(function() {
    var z = 0;
    $('table thead').each(function () {
      // Find table height.
      var table = $(this).parent('table')[0];
      var height = $(table).addClass('sticky-table').height();
      var i = 0;

      // Find all header cells.
      $('th', this).each(function () {

        // Ensure each cell has an element in it.
        var html = $(this).html();
        if (html == ' ') {
          html = ' ';
        }
        if ($(this).children().size() == 0) {
          html = ''+ html +'';
        }

        // Clone and wrap cell contents in sticky wrapper that overlaps the cell's padding.
        $('
'+ html +'
').prependTo(this);
        var div = $('div.sticky-header', this).css({
          'marginLeft': '-'+ $(this).css('paddingLeft'),
          'marginRight': '-'+ $(this).css('paddingRight'),
          'paddingLeft': $(this).css('paddingLeft'),
          'paddingTop': $(this).css('paddingTop'),
          'paddingBottom': $(this).css('paddingBottom'),
          'z-index': ++z
        })[0];
        cells.push(div);

        // Adjust width to fit cell/table.
        var ref = this;
        if (!i++) {
          // The first cell is as wide as the table to prevent gaps.
          ref = table;
          div.wide = true;
        }
        $(div).css('width', parseInt($(ref).width())
                          - parseInt($(div).css('paddingLeft')) +'px');

        // Get position and store.
        div.cell = this;
        div.table = table;
        div.stickyMax = height;
        div.stickyPosition = Drupal.absolutePosition(this).y;
      });
    });
  });

  // Track scrolling.
  var scroll = function() {
    $(cells).each(function () {
      // Fetch scrolling position.
      var scroll = document.documentElement.scrollTop || document.body.scrollTop;
      var offset = scroll - this.stickyPosition - 4;
      if (offset > 0 && offset < this.stickyMax - 100) {
        $(this).css('visibility', 'visible');
      }
      else {
        $(this).css('visibility', 'hidden');
      }
    });
  };
  $(window).scroll(scroll);
  $(document.documentElement).scroll(scroll);

  // Track resizing.
  var time = null;
  var resize = function () {
    // Ensure minimum time between adjustments.
    if (time) {
      return;
    }
    time = setTimeout(function () {

      // Precalculate table heights
      $('table.sticky-table').each(function () {
        this.height = $(this).height();
      })

      $(cells).each(function () {
        // Get position.
        this.stickyPosition = Drupal.absolutePosition(this.cell).y;
        this.stickyMax = this.table.height;

        // Reflow the cell.
        var ref = this.cell;
        if (this.wide) {
          // Resize the first cell to fit the table.
          ref = this.table;
        }
        $(this).css('width', parseInt($(ref).width())
                           - parseInt($(this).css('paddingLeft')) +'px');
      });

      // Reset timer
      time = null;
    }, 250);
  };
  $(window).resize(resize);
}
<|endoftext|>