<commit_before>var PacketHeader = require('./PacketHeader');

module.exports = Parser;
function Parser(options) {
  options = options || {};

  this._buffer        = null;
  this._offset        = 0;
  this._packetEnd     = null;
  this._packetHeader  = null;
  this._packetHandler = null;
}

Parser.prototype.write = function(buffer) {
  this.append(buffer);

  while (true) {
    if (!this._packetHeader) {
      if (this._bytesRemaining() < 4) {
        break;
      }

      this._packetHeader = new PacketHeader(
        this.parseUnsignedNumber(3),
        this.parseUnsignedNumber(1)
      );
    }

    if (this._bytesRemaining() < this._packetHeader.length) {
      break;
    }

    this._packetEnd = this._offset + this._packetHeader.length;

    this._packetHandler(this._packetHeader, this);

    this._offset       = this._packetEnd;
    this._packetHeader = null;
    this._packetEnd    = null;
  }
};

Parser.prototype.append = function(newBuffer) {
  var oldBuffer = this._buffer;
  if (!oldBuffer) {
    this._buffer = newBuffer;
    return;
  }

  var bytesRemaining = this._bytesRemaining();
  var newLength = bytesRemaining + newBuffer.length;

  var combinedBuffer = (newLength < this._offset)
    ? oldBuffer.slice(0, newLength)
    : new Buffer(newLength);

  oldBuffer.copy(combinedBuffer, 0, this._offset);
  newBuffer.copy(combinedBuffer, bytesRemaining);

  this._buffer = combinedBuffer;
  this._offset = 0;
};

Parser.prototype.setPacketHandler = function(handler) {
  this._packetHandler = handler;
};

Parser.prototype.peak = function() {
  return this._buffer[this._offset];
};

Parser.prototype.parseUnsignedNumber = function(bytes) {
  var bytesRead = 0;
  var value     = 0;

  while (bytesRead < bytes) {
    var byte = this._buffer[this._offset++];

    value += byte * Math.pow(256, bytesRead);

    bytesRead++;
  }

  return value;
};

Parser.prototype.parseLengthCodedString = function() {
  var length = this.parseLengthCodedNumber();

  if (length === null) {
    return null;
  }

  return this.parseString(length);
};

Parser.prototype.parseLengthCodedNumber = function() {
  var byte = this._buffer[this._offset++];

  if (byte <= 251) {
    return (byte === 251)
      ? null
      : byte;
  }

  if (byte === 252) {
    var length = 2;
  } else {
    throw new Error('not implemented');
  }

  var value = 0;
  for (var bytesRead = 0; bytesRead < length; bytesRead++) {
    var byte = this._buffer[this._offset++];
    value += Math.pow(256, bytesRead) * byte;
  }

  return value;
};

Parser.prototype.parseFiller = function(length) {
  return this.parseBuffer(length);
};

Parser.prototype.parseNullTerminated = function(encoding) {
  var end = this._offset;
  while (this._buffer[end] !== 0x00) {
    end++;
  }

  var value = (encoding)
    ? this._buffer.toString(encoding, this._offset, end)
    : this._buffer.slice(this._offset, end - 1);

  this._offset = end + 1;
  return value;
};

Parser.prototype.parsePacketTerminatedString = function() {
  var length = this._packetEnd - this._offset;
  return this.parseString(length);
};

Parser.prototype.parseBuffer = function(length) {
  var buffer = this._buffer.slice(this._offset, this._offset + length);

  this._offset += length;
  return buffer;
};

Parser.prototype.parseString = function(length) {
  var offset = this._offset;
  var end = offset + length;
  var value = this._buffer.toString('utf-8', offset, end);

  this._offset = end;
  return value;
};

Parser.prototype.reachedPacketEnd = function() {
  return this._offset === this._packetEnd;
};

Parser.prototype._bytesRemaining = function() {
  return this._buffer.length - this._offset;
};
<commit_msg>Prepare parser for future encodings<commit_after>var PacketHeader = require('./PacketHeader');

module.exports = Parser;
function Parser(options) {
  options = options || {};

  this._buffer        = null;
  this._offset        = 0;
  this._packetEnd     = null;
  this._packetHeader  = null;
  this._packetHandler = null;
  this._encoding      = 'utf-8';
}

Parser.prototype.write = function(buffer) {
  this.append(buffer);

  while (true) {
    if (!this._packetHeader) {
      if (this._bytesRemaining() < 4) {
        break;
      }

      this._packetHeader = new PacketHeader(
        this.parseUnsignedNumber(3),
        this.parseUnsignedNumber(1)
      );
    }

    if (this._bytesRemaining() < this._packetHeader.length) {
      break;
    }

    this._packetEnd = this._offset + this._packetHeader.length;

    this._packetHandler(this._packetHeader, this);

    this._offset       = this._packetEnd;
    this._packetHeader = null;
    this._packetEnd    = null;
  }
};

Parser.prototype.append = function(newBuffer) {
  var oldBuffer = this._buffer;
  if (!oldBuffer) {
    this._buffer = newBuffer;
    return;
  }

  var bytesRemaining = this._bytesRemaining();
  var newLength = bytesRemaining + newBuffer.length;

  var combinedBuffer = (newLength < this._offset)
    ? oldBuffer.slice(0, newLength)
    : new Buffer(newLength);

  oldBuffer.copy(combinedBuffer, 0, this._offset);
  newBuffer.copy(combinedBuffer, bytesRemaining);

  this._buffer = combinedBuffer;
  this._offset = 0;
};

Parser.prototype.setPacketHandler = function(handler) {
  this._packetHandler = handler;
};

Parser.prototype.peak = function() {
  return this._buffer[this._offset];
};

Parser.prototype.parseUnsignedNumber = function(bytes) {
  var bytesRead = 0;
  var value     = 0;

  while (bytesRead < bytes) {
    var byte = this._buffer[this._offset++];

    value += byte * Math.pow(256, bytesRead);

    bytesRead++;
  }

  return value;
};

Parser.prototype.parseLengthCodedString = function() {
  var length = this.parseLengthCodedNumber();

  if (length === null) {
    return null;
  }

  return this.parseString(length);
};

Parser.prototype.parseLengthCodedNumber = function() {
  var byte = this._buffer[this._offset++];

  if (byte <= 251) {
    return (byte === 251)
      ? null
      : byte;
  }

  if (byte === 252) {
    var length = 2;
  } else {
    throw new Error('not implemented');
  }

  var value = 0;
  for (var bytesRead = 0; bytesRead < length; bytesRead++) {
    var byte = this._buffer[this._offset++];
    value += Math.pow(256, bytesRead) * byte;
  }

  return value;
};

Parser.prototype.parseFiller = function(length) {
  return this.parseBuffer(length);
};

Parser.prototype.parseNullTerminated = function(encoding) {
  var end = this._offset;
  while (this._buffer[end] !== 0x00) {
    end++;
  }

  var value = (encoding)
    ? this._buffer.toString(encoding, this._offset, end)
    : this._buffer.slice(this._offset, end - 1);

  this._offset = end + 1;
  return value;
};

Parser.prototype.parsePacketTerminatedString = function() {
  var length = this._packetEnd - this._offset;
  return this.parseString(length);
};

Parser.prototype.parseBuffer = function(length) {
  var buffer = this._buffer.slice(this._offset, this._offset + length);

  this._offset += length;
  return buffer;
};

Parser.prototype.parseString = function(length) {
  var offset = this._offset;
  var end = offset + length;
  var value = this._buffer.toString(this._encoding, offset, end);

  this._offset = end;
  return value;
};

Parser.prototype.reachedPacketEnd = function() {
  return this._offset === this._packetEnd;
};

Parser.prototype._bytesRemaining = function() {
  return this._buffer.length - this._offset;
};
<|endoftext|>


<commit_before>// @flow weak

/**
 * A layout component using the following libs as inspiration.
 *
 * For the implementation:
 * - http://v4-alpha.getbootstrap.com/layout/flexbox-grid/
 * - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css
 * - https://github.com/roylee0704/react-flexbox-grid
 * - https://material.angularjs.org/latest/layout/introduction
 *
 * Follow this flexbox Guide to better understand the underlying model:
 * - https://css-tricks.com/snippets/css/a-guide-to-flexbox/
 */
import React, { PropTypes } from 'react';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from '../utils/customPropTypes';

const GUTTERS = [0, 8, 16, 24, 40];
const GRID_SIZES = [true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

function generateGrid(globalStyles, theme, breakpoint) {
  // For the auto layouting
  const styles = {
    [`grid-${breakpoint}`]: {
      flexBasis: 0,
      flexGrow: 1,
      maxWidth: '100%',
    },
  };

  GRID_SIZES.forEach((size, index) => {
    if (index === 0) { // Skip the first one as handle above.
      return;
    }

    // Only keep 6 significant numbers.
    const width = `${Math.round((size / 12) * Math.pow(10, 6)) / Math.pow(10, 4)}%`;

    /* eslint-disable max-len */
    // Close to the bootstrap implementation:
    // https://github.com/twbs/bootstrap/blob/b0508a975d711d6b24c01f57dd5445c22699fac4/scss/mixins/_grid.scss#L69
    /* eslint-enable max-len */
    styles[`grid-${breakpoint}-${size}`] = {
      flexBasis: width,
      maxWidth: width,
    };
  });

  // No need for a media query for the first size.
  if (breakpoint === 'xs') {
    Object.assign(globalStyles, styles);
  } else {
    globalStyles[theme.breakpoints.up(breakpoint)] = styles;
  }
}

function generateGutter(theme, breakpoint) {
  const styles = {};

  GUTTERS.forEach((gutter, index) => {
    if (index === 0) { // Skip the default style.
      return;
    }

    styles[`gutter-${breakpoint}-${gutter}`] = {
      margin: -gutter / 2,
      '& > $typeItem': {
        padding: gutter / 2,
      },
    };
  });

  return styles;
}

export const styleSheet = createStyleSheet('MuiLayout', (theme) => {
  // Default CSS values
  // flex: '0 1 auto',
  // flexDirection: 'row',
  // alignItems: 'flex-start',
  // flexWrap: 'nowrap',
  // justifyContent: 'flex-start',

  return {
    typeContainer: {
      boxSizing: 'border-box',
      display: 'flex',
      flexWrap: 'wrap',
    },
    typeItem: {
      boxSizing: 'border-box',
      flex: '0 0 auto',
    },
    'direction-xs-column': {
      flexDirection: 'column',
    },
    'direction-xs-column-reverse': {
      flexDirection: 'column-reverse',
    },
    'direction-xs-row-reverse': {
      flexDirection: 'row-reverse',
    },
    'wrap-xs-nowrap': {
      flexWrap: 'nowrap',
    },
    'align-xs-center': {
      alignItems: 'center',
    },
    'align-xs-flex-start': {
      alignItems: 'flex-start',
    },
    'align-xs-flex-end': {
      alignItems: 'flex-end',
    },
    'justify-xs-center': {
      justifyContent: 'center',
    },
    'justify-xs-flex-end': {
      justifyContent: 'flex-end',
    },
    'justify-xs-space-between': {
      justifyContent: 'space-between',
    },
    'justify-xs-space-around': {
      justifyContent: 'space-around',
    },
    ...generateGutter(theme, 'xs'),
    ...theme.breakpoints.keys.reduce((styles, key) => {
      // Use side effect for performance.
      generateGrid(styles, theme, key);

      return styles;
    }, {}),
  };
});

function Layout(props, context) {
  const {
    children,
    className,
    component: ComponentProp,
    container,
    item,
    align,
    direction,
    xs,
    sm,
    md,
    lg,
    xl,
    gutter,
    justify,
    wrap,
    ...other
  } = props;

  const classes = context.styleManager.render(styleSheet);

  return (
    <ComponentProp
      className={classNames({
        [classes.typeContainer]: container,
        [classes.typeItem]: item,
        [classes[`gutter-xs-${gutter}`]]: container && gutter !== 0,
        [classes[`direction-xs-${direction}`]]: direction !== Layout.defaultProps.direction,
        [classes[`wrap-xs-${wrap}`]]: wrap !== Layout.defaultProps.wrap,
        [classes[`align-xs-${align}`]]: align !== Layout.defaultProps.align,
        [classes[`justify-xs-${justify}`]]: justify !== Layout.defaultProps.justify,
        [classes['grid-xs']]: xs === true,
        [classes[`grid-xs-${xs}`]]: xs && xs !== true,
        [classes['grid-sm']]: sm === true,
        [classes[`grid-sm-${sm}`]]: sm && sm !== true,
        [classes['grid-md']]: md === true,
        [classes[`grid-md-${md}`]]: md && md !== true,
        [classes['grid-lg']]: lg === true,
        [classes[`grid-lg-${lg}`]]: lg && lg !== true,
        [classes['grid-xl']]: xl === true,
        [classes[`grid-xl-${xl}`]]: xl && xl !== true,
      }, className)}
      {...other}
    >
      {children}
    </ComponentProp>
  );
}

Layout.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * The CSS class name of the root element.
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a ReactElement.
   */
  component: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.func,
  ]),
  /**
   * It true, the component will have the flex *container* behavior.
   * You should be wrapping *items* with a *container*.
   */
  container: PropTypes.bool,
  /**
   * It true, the component will have the flex *item* behavior.
   * You should be wrapping *items* with a *container*.
   */
  item: PropTypes.bool,
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for all the screen sizes with the lowest priority.
   */
  xs: PropTypes.oneOf(GRID_SIZES),
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `sm` breakpoint and wider screens if not overridden.
   */
  sm: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `md` breakpoint and wider screens if not overridden.
   */
  md: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `lg` breakpoint and wider screens if not overridden.
   */
  lg: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `xl` breakpoint and wider screens.
   */
  xl: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the `align-items` style property.
   * It's applied for all the screen sizes.
   */
  align: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'flex-start',
    'center',
    'flex-end',
    'stretch',
  ]),
  /**
   * Defines the `flex-direction` style property.
   * It's applied for all the screen sizes.
   */
  direction: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'row',
    'row-reverse',
    'column',
    'column-reverse',
  ]),
  /**
   * Defines the space between the type `item` component.
   * It can only be used on a type `container` component.
   */
  gutter: PropTypes.oneOf(GUTTERS), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the `justify-content` style property.
   * It's applied for all the screen sizes.
   */
  justify: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'flex-start',
    'center',
    'flex-end',
    'space-between',
    'space-around',
  ]),
  /**
   * Defines the `flex-wrap` style property.
   * It's applied for all the screen sizes.
   */
  wrap: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'nowrap',
    'wrap',
    'wrap-reverse',
  ]),
};

Layout.defaultProps = {
  component: 'div',
  container: false,
  item: false,
  align: 'stretch',
  direction: 'row',
  gutter: 16,
  justify: 'flex-start',
  wrap: 'wrap',
};

Layout.contextTypes = {
  styleManager: customPropTypes.muiRequired,
};

/**
 * Add a wrapper component to generate some helper messages in the development
 * environment.
 */
let LayoutWrapper = Layout; // eslint-disable-line import/no-mutable-exports

if (process.env.NODE_ENV !== 'production') {
  const requireProp = (requiredProp) =>
    (props, propName, componentName, location, propFullName) => {
      const propFullNameSafe = propFullName || propName;

      if (typeof props[propName] !== 'undefined' && !props[requiredProp]) {
        return new Error(
          `The property \`${propFullNameSafe}\` of ` +
          `\`Layout\` must be used on \`${requiredProp}\`.`,
        );
      }

      return null;
    };

  LayoutWrapper = (props) => <Layout {...props} />;

  LayoutWrapper.propTypes = {
    align: requireProp('container'),
    direction: requireProp('container'),
    gutter: requireProp('container'),
    justify: requireProp('container'),
    lg: requireProp('item'),
    md: requireProp('item'),
    sm: requireProp('item'),
    wrap: requireProp('container'),
    xs: requireProp('item'),
  };
}

export default LayoutWrapper;
<commit_msg>[Layout] Backport a fix at Doctolib for Chrome (#6376)<commit_after>// @flow weak

/**
 * A layout component using the following libs as inspiration.
 *
 * For the implementation:
 * - http://v4-alpha.getbootstrap.com/layout/flexbox-grid/
 * - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css
 * - https://github.com/roylee0704/react-flexbox-grid
 * - https://material.angularjs.org/latest/layout/introduction
 *
 * Follow this flexbox Guide to better understand the underlying model:
 * - https://css-tricks.com/snippets/css/a-guide-to-flexbox/
 */
import React, { PropTypes } from 'react';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from '../utils/customPropTypes';

const GUTTERS = [0, 8, 16, 24, 40];
const GRID_SIZES = [true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

function generateGrid(globalStyles, theme, breakpoint) {
  // For the auto layouting
  const styles = {
    [`grid-${breakpoint}`]: {
      flexBasis: 0,
      flexGrow: 1,
      maxWidth: '100%',
    },
  };

  GRID_SIZES.forEach((size, index) => {
    if (index === 0) { // Skip the first one as handle above.
      return;
    }

    // Only keep 6 significant numbers.
    const width = `${Math.round((size / 12) * Math.pow(10, 6)) / Math.pow(10, 4)}%`;

    /* eslint-disable max-len */
    // Close to the bootstrap implementation:
    // https://github.com/twbs/bootstrap/blob/b0508a975d711d6b24c01f57dd5445c22699fac4/scss/mixins/_grid.scss#L69
    /* eslint-enable max-len */
    styles[`grid-${breakpoint}-${size}`] = {
      flexBasis: width,
      maxWidth: width,
    };
  });

  // No need for a media query for the first size.
  if (breakpoint === 'xs') {
    Object.assign(globalStyles, styles);
  } else {
    globalStyles[theme.breakpoints.up(breakpoint)] = styles;
  }
}

function generateGutter(theme, breakpoint) {
  const styles = {};

  GUTTERS.forEach((gutter, index) => {
    if (index === 0) { // Skip the default style.
      return;
    }

    styles[`gutter-${breakpoint}-${gutter}`] = {
      margin: -gutter / 2,
      width: `calc(100% + ${gutter}px)`,
      '& > $typeItem': {
        padding: gutter / 2,
      },
    };
  });

  return styles;
}

export const styleSheet = createStyleSheet('MuiLayout', (theme) => {
  // Default CSS values
  // flex: '0 1 auto',
  // flexDirection: 'row',
  // alignItems: 'flex-start',
  // flexWrap: 'nowrap',
  // justifyContent: 'flex-start',

  return {
    typeContainer: {
      boxSizing: 'border-box',
      display: 'flex',
      flexWrap: 'wrap',
      width: '100%',
    },
    typeItem: {
      boxSizing: 'border-box',
      flex: '0 0 auto',
    },
    'direction-xs-column': {
      flexDirection: 'column',
    },
    'direction-xs-column-reverse': {
      flexDirection: 'column-reverse',
    },
    'direction-xs-row-reverse': {
      flexDirection: 'row-reverse',
    },
    'wrap-xs-nowrap': {
      flexWrap: 'nowrap',
    },
    'align-xs-center': {
      alignItems: 'center',
    },
    'align-xs-flex-start': {
      alignItems: 'flex-start',
    },
    'align-xs-flex-end': {
      alignItems: 'flex-end',
    },
    'justify-xs-center': {
      justifyContent: 'center',
    },
    'justify-xs-flex-end': {
      justifyContent: 'flex-end',
    },
    'justify-xs-space-between': {
      justifyContent: 'space-between',
    },
    'justify-xs-space-around': {
      justifyContent: 'space-around',
    },
    ...generateGutter(theme, 'xs'),
    ...theme.breakpoints.keys.reduce((styles, key) => {
      // Use side effect for performance.
      generateGrid(styles, theme, key);

      return styles;
    }, {}),
  };
});

function Layout(props, context) {
  const {
    children,
    className,
    component: ComponentProp,
    container,
    item,
    align,
    direction,
    xs,
    sm,
    md,
    lg,
    xl,
    gutter,
    justify,
    wrap,
    ...other
  } = props;

  const classes = context.styleManager.render(styleSheet);

  return (
    <ComponentProp
      className={classNames({
        [classes.typeContainer]: container,
        [classes.typeItem]: item,
        [classes[`gutter-xs-${gutter}`]]: container && gutter !== 0,
        [classes[`direction-xs-${direction}`]]: direction !== Layout.defaultProps.direction,
        [classes[`wrap-xs-${wrap}`]]: wrap !== Layout.defaultProps.wrap,
        [classes[`align-xs-${align}`]]: align !== Layout.defaultProps.align,
        [classes[`justify-xs-${justify}`]]: justify !== Layout.defaultProps.justify,
        [classes['grid-xs']]: xs === true,
        [classes[`grid-xs-${xs}`]]: xs && xs !== true,
        [classes['grid-sm']]: sm === true,
        [classes[`grid-sm-${sm}`]]: sm && sm !== true,
        [classes['grid-md']]: md === true,
        [classes[`grid-md-${md}`]]: md && md !== true,
        [classes['grid-lg']]: lg === true,
        [classes[`grid-lg-${lg}`]]: lg && lg !== true,
        [classes['grid-xl']]: xl === true,
        [classes[`grid-xl-${xl}`]]: xl && xl !== true,
      }, className)}
      {...other}
    >
      {children}
    </ComponentProp>
  );
}

Layout.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * The CSS class name of the root element.
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a ReactElement.
   */
  component: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.func,
  ]),
  /**
   * It true, the component will have the flex *container* behavior.
   * You should be wrapping *items* with a *container*.
   */
  container: PropTypes.bool,
  /**
   * It true, the component will have the flex *item* behavior.
   * You should be wrapping *items* with a *container*.
   */
  item: PropTypes.bool,
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for all the screen sizes with the lowest priority.
   */
  xs: PropTypes.oneOf(GRID_SIZES),
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `sm` breakpoint and wider screens if not overridden.
   */
  sm: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `md` breakpoint and wider screens if not overridden.
   */
  md: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `lg` breakpoint and wider screens if not overridden.
   */
  lg: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the number of grids the component is going to use.
   * It's applied for the `xl` breakpoint and wider screens.
   */
  xl: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the `align-items` style property.
   * It's applied for all the screen sizes.
   */
  align: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'flex-start',
    'center',
    'flex-end',
    'stretch',
  ]),
  /**
   * Defines the `flex-direction` style property.
   * It's applied for all the screen sizes.
   */
  direction: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'row',
    'row-reverse',
    'column',
    'column-reverse',
  ]),
  /**
   * Defines the space between the type `item` component.
   * It can only be used on a type `container` component.
   */
  gutter: PropTypes.oneOf(GUTTERS), // eslint-disable-line react/sort-prop-types
  /**
   * Defines the `justify-content` style property.
   * It's applied for all the screen sizes.
   */
  justify: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'flex-start',
    'center',
    'flex-end',
    'space-between',
    'space-around',
  ]),
  /**
   * Defines the `flex-wrap` style property.
   * It's applied for all the screen sizes.
   */
  wrap: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
    'nowrap',
    'wrap',
    'wrap-reverse',
  ]),
};

Layout.defaultProps = {
  component: 'div',
  container: false,
  item: false,
  align: 'stretch',
  direction: 'row',
  gutter: 16,
  justify: 'flex-start',
  wrap: 'wrap',
};

Layout.contextTypes = {
  styleManager: customPropTypes.muiRequired,
};

/**
 * Add a wrapper component to generate some helper messages in the development
 * environment.
 */
let LayoutWrapper = Layout; // eslint-disable-line import/no-mutable-exports

if (process.env.NODE_ENV !== 'production') {
  const requireProp = (requiredProp) =>
    (props, propName, componentName, location, propFullName) => {
      const propFullNameSafe = propFullName || propName;

      if (typeof props[propName] !== 'undefined' && !props[requiredProp]) {
        return new Error(
          `The property \`${propFullNameSafe}\` of ` +
          `\`Layout\` must be used on \`${requiredProp}\`.`,
        );
      }

      return null;
    };

  LayoutWrapper = (props) => <Layout {...props} />;

  LayoutWrapper.propTypes = {
    align: requireProp('container'),
    direction: requireProp('container'),
    gutter: requireProp('container'),
    justify: requireProp('container'),
    lg: requireProp('item'),
    md: requireProp('item'),
    sm: requireProp('item'),
    wrap: requireProp('container'),
    xs: requireProp('item'),
  };
}

export default LayoutWrapper;
<|endoftext|>


<commit_before>'use strict';

//GetAttribute() returns "boolean" values and will return either "true" or null
describe('Import-Export', function(){

    var Reports = require('../../app/reports/reports-page');
    var reports = new Reports();

    var path = require('path');
    var invalidReportFile = path.resolve(__dirname, './data/invalid-report.json');
    var validReportFile = path.resolve(__dirname, './data/Fundamental_Accounting_Concepts.xbrlb');
    var reportsCount;
    var reportName = 'Import test';

    it('Should list reports', function() {
        reports.visitPage();
        reports.list.count().then(function(count){
          reportsCount = count;
          expect(count).toBeGreaterThan(1);
        });
    });

    it('Should not import invalid report', function() {
        reports.fillInImportReport(invalidReportFile);
        expect(reports.import.errorMsg.isDisplayed()).toBe(true);
        reports.import.btn.cancel.click();
        expect(reports.list.count()).toBe(reportsCount);
    });

    it('Should allow importing valid report', function() {
        reports.fillInImportReport(validReportFile);
        expect(reports.import.errorMsg.isDisplayed()).toBe(false);
        reports.import.btn.cancel.click();
        expect(reports.list.count()).toBe(reportsCount);
    });

/*    it('Should import valid report', function() {
        reports.fillInImportReport(validReportFile);
        expect(reports.import.errorMsg.isDisplayed()).toBe(false);
        reports.import.btn.ok.click();
        reports.findReport(reportName).then(function(found){
          expect(found.length).toBeGreaterThan(0);
        });
        expect(reports.list.count()).toBe(reportsCount+1);
    });*/

    it('Should not display export button', function() {
        expect(reports.exportBtn.isDisplayed()).toBe(false);
    });

    it('Should display export button', function() {
        reports.selectReport('Disclosures');
        expect(reports.exportBtn.isDisplayed()).toBe(true);
    });

    it('Should not display export button in case more than one report', function() {
        reports.selectReport('Fundamental Accounting Concepts');
        expect(reports.exportBtn.isDisplayed()).toBe(false);
    });

    // reset
/*    it('Should remove imported report', function() {
        reports.visitPage();
        reports.deleteReport(reportName);
        expect(reports.list.count()).toBe(reportsCount);
        // export button should disappear after deletion
        expect(reports.exportBtn.isDisplayed()).toBe(false);
    });*/

});
<commit_msg>fixed unused variable.<commit_after>'use strict';

//GetAttribute() returns "boolean" values and will return either "true" or null
describe('Import-Export', function(){

    var Reports = require('../../app/reports/reports-page');
    var reports = new Reports();

    var path = require('path');
    var invalidReportFile = path.resolve(__dirname, './data/invalid-report.json');
    var validReportFile = path.resolve(__dirname, './data/Fundamental_Accounting_Concepts.xbrlb');
    var reportsCount;
    //var reportName = 'Import test';

    it('Should list reports', function() {
        reports.visitPage();
        reports.list.count().then(function(count){
          reportsCount = count;
          expect(count).toBeGreaterThan(1);
        });
    });

    it('Should not import invalid report', function() {
        reports.fillInImportReport(invalidReportFile);
        expect(reports.import.errorMsg.isDisplayed()).toBe(true);
        reports.import.btn.cancel.click();
        expect(reports.list.count()).toBe(reportsCount);
    });

    it('Should allow importing valid report', function() {
        reports.fillInImportReport(validReportFile);
        expect(reports.import.errorMsg.isDisplayed()).toBe(false);
        reports.import.btn.cancel.click();
        expect(reports.list.count()).toBe(reportsCount);
    });

/*    it('Should import valid report', function() {
        reports.fillInImportReport(validReportFile);
        expect(reports.import.errorMsg.isDisplayed()).toBe(false);
        reports.import.btn.ok.click();
        reports.findReport(reportName).then(function(found){
          expect(found.length).toBeGreaterThan(0);
        });
        expect(reports.list.count()).toBe(reportsCount+1);
    });*/

    it('Should not display export button', function() {
        expect(reports.exportBtn.isDisplayed()).toBe(false);
    });

    it('Should display export button', function() {
        reports.selectReport('Disclosures');
        expect(reports.exportBtn.isDisplayed()).toBe(true);
    });

    it('Should not display export button in case more than one report', function() {
        reports.selectReport('Fundamental Accounting Concepts');
        expect(reports.exportBtn.isDisplayed()).toBe(false);
    });

    // reset
/*    it('Should remove imported report', function() {
        reports.visitPage();
        reports.deleteReport(reportName);
        expect(reports.list.count()).toBe(reportsCount);
        // export button should disappear after deletion
        expect(reports.exportBtn.isDisplayed()).toBe(false);
    });*/

});
<|endoftext|>


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

var keys = require('./keys');
var sliceBuffer = require('arraybuffer.slice');
var base64encoder = require('base64-arraybuffer');
var after = require('after');
var utf8 = require('utf8');

/**
 * Check if we are running an android browser. That requires us to use
 * ArrayBuffer with polling transports...
 *
 * http://ghinda.net/jpeg-blob-ajax-android/
 */

var isAndroid = navigator.userAgent.match(/Android/i);

/**
 * Current protocol version.
 */

exports.protocol = 2;

/**
 * Packet types.
 */

var packets = exports.packets = {
    open:     0    // non-ws
  , close:    1    // non-ws
  , ping:     2
  , pong:     3
  , message:  4
  , upgrade:  5
  , noop:     6
};

var packetslist = keys(packets);

/**
 * Premade error packet.
 */

var err = { type: 'error', data: 'parser error' };

/**
 * Create a blob api even for blob builder when vendor prefixes exist
 */

var Blob = require('blob');

/**
 * Encodes a packet.
 *
 *     <packet type id> [ <data> ]
 *
 * Example:
 *
 *     5hello world
 *     3
 *     4
 *
 * Binary is encoded in an identical principle
 *
 * @api private
 */

exports.encodePacket = function (packet, supportsBinary, callback) {
  if (typeof supportsBinary == 'function') {
    callback = supportsBinary;
    supportsBinary = false;
  }

  var data = (packet.data === undefined)
    ? undefined
    : packet.data.buffer || packet.data;

  if (global.ArrayBuffer && data instanceof ArrayBuffer) {
    return encodeArrayBuffer(packet, supportsBinary, callback);
  } else if (Blob && data instanceof global.Blob) {
    return encodeBlob(packet, supportsBinary, callback);
  }

  // Sending data as a utf-8 string
  var encoded = packets[packet.type];

  // data fragment is optional
  if (undefined !== packet.data) {
    encoded += utf8.encode(String(packet.data));
  }

  return callback('' + encoded);

};

/**
 * Encode packet helpers for binary types
 */

function encodeArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var data = packet.data;
  var contentArray = new Uint8Array(data);
  var resultBuffer = new Uint8Array(1 + data.byteLength);

  resultBuffer[0] = packets[packet.type];
  for (var i = 0; i < contentArray.length; i++) {
    resultBuffer[i+1] = contentArray[i];
  }

  return callback(resultBuffer.buffer);
}

function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var fr = new FileReader();
  fr.onload = function() {
    packet.data = fr.result;
    exports.encodePacket(packet, supportsBinary, callback);
  };
  return fr.readAsArrayBuffer(packet.data);
}

function encodeBlob(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  if (isAndroid) {
    return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  }

  var length = new Uint8Array(1);
  length[0] = packets[packet.type];
  var blob = new Blob([length.buffer, packet.data]);

  return callback(blob);
}

/**
 * Encodes a packet with binary data in a base64 string
 *
 * @param {Object} packet, has `type` and `data`
 * @return {String} base64 encoded message
 */

exports.encodeBase64Packet = function(packet, callback) {
  var message = 'b' + exports.packets[packet.type];
  if (Blob && packet.data instanceof Blob) {
    var fr = new FileReader();
    fr.onload = function() {
      var b64 = fr.result.split(',')[1];
      callback(message + b64);
    };
    return fr.readAsDataURL(packet.data);
  }

  var b64data;
  try {
    b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  } catch (e) {
    // iPhone Safari doesn't let you apply with typed arrays
    var typed = new Uint8Array(packet.data);
    var basic = new Array(typed.length);
    for (var i = 0; i < typed.length; i++) {
      basic[i] = typed[i];
    }
    b64data = String.fromCharCode.apply(null, basic);
  }
  message += global.btoa(b64data);
  return callback(message);
};

/**
 * Decodes a packet. Changes format to Blob if requested.
 *
 * @return {Object} with `type` and `data` (if any)
 * @api private
 */

exports.decodePacket = function (data, binaryType) {
  // String data
  if (typeof data == 'string' || data === undefined) {
    if (data.charAt(0) == 'b') {
      return exports.decodeBase64Packet(data.substr(1), binaryType);
    }

    data = utf8.decode(data);
    var type = data.charAt(0);

    if (Number(type) != type || !packetslist[type]) {
      return err;
    }

    if (data.length > 1) {
      return { type: packetslist[type], data: data.substring(1) };
    } else {
      return { type: packetslist[type] };
    }
  }

  var asArray = new Uint8Array(data);
  var type = asArray[0];
  var rest = sliceBuffer(data, 1);
  if (Blob && binaryType === 'blob') {
    rest = new Blob([rest]);
  }
  return { type: packetslist[type], data: rest };
};

/**
 * Decodes a packet encoded in a base64 string
 *
 * @param {String} base64 encoded message
 * @return {Object} with `type` and `data` (if any)
 */

exports.decodeBase64Packet = function(msg, binaryType) {
  var type = packetslist[msg.charAt(0)];
  if (!global.ArrayBuffer) {
    return { type: type, data: { base64: true, data: msg.substr(1) } };
  }

  var data = base64encoder.decode(msg.substr(1));

  if (binaryType === 'blob' && Blob) {
    data = new Blob([data]);
  }

  return { type: type, data: data };
};

/**
 * Encodes multiple messages (payload).
 *
 *     <length>:data
 *
 * Example:
 *
 *     11:hello world2:hi
 *
 * If any contents are binary, they will be encoded as base64 strings. Base64
 * encoded strings are marked with a b before the length specifier
 *
 * @param {Array} packets
 * @api private
 */

exports.encodePayload = function (packets, supportsBinary, callback) {
  if (typeof supportsBinary == 'function') {
    callback = supportsBinary;
    supportsBinary = null;
  }

  if (supportsBinary) {
    if (Blob && !isAndroid) {
      return exports.encodePayloadAsBlob(packets, callback);
    }

    return exports.encodePayloadAsArrayBuffer(packets, callback);
  }

  if (!packets.length) {
    return callback('0:');
  }

  function setLengthHeader(message) {
    return message.length + ':' + message;
  }

  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, supportsBinary, function(message) {
      doneCallback(null, setLengthHeader(message));
    });
  }

  map(packets, encodeOne, function(err, results) {
    return callback(results.join(''));
  });
};

/**
 * Async array map using after
 */

function map(ary, each, done) {
  var result = new Array(ary.length);
  var next = after(ary.length, done);

  var eachWithIndex = function(i, el, cb) {
    each(el, function(error, msg) {
      result[i] = msg;
      cb(error, result);
    });
  };

  for (var i = 0; i < ary.length; i++) {
    eachWithIndex(i, ary[i], next);
  }
}

/*
 * Decodes data when a payload is maybe expected. Possible binary contents are
 * decoded from their base64 representation
 *
 * @param {String} data, callback method
 * @api public
 */

exports.decodePayload = function (data, binaryType, callback) {
  if (typeof data != 'string') {
    return exports.decodePayloadAsBinary(data, binaryType, callback);
  }

  if (typeof binaryType === 'function') {
    callback = binaryType;
    binaryType = null;
  }

  var packet;
  if (data == '') {
    // parser error - ignoring payload
    return callback(err, 0, 1);
  }

  var length = ''
    , n, msg;

  for (var i = 0, l = data.length; i < l; i++) {
    var chr = data.charAt(i);

    if (':' != chr) {
      length += chr;
    } else {
      if ('' == length || (length != (n = Number(length)))) {
        // parser error - ignoring payload
        return callback(err, 0, 1);
      }

      msg = data.substr(i + 1, n);

      if (length != msg.length) {
        // parser error - ignoring payload
        return callback(err, 0, 1);
      }

      if (msg.length) {
        packet = exports.decodePacket(msg, binaryType);

        if (err.type == packet.type && err.data == packet.data) {
          // parser error in individual packet - ignoring payload
          return callback(err, 0, 1);
        }

        var ret = callback(packet, i + n, l);
        if (false === ret) return;
      }

      // advance cursor
      i += n;
      length = '';
    }
  }

  if (length != '') {
    // parser error - ignoring payload
    return callback(err, 0, 1);
  }

};

/**
 * Encodes multiple messages (payload) as binary.
 *
 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
 * 255><data>
 *
 * Example:
 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
 *
 * @param {Array} packets
 * @return {ArrayBuffer} encoded payload
 * @api private
 */

exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  if (!packets.length) {
    return callback(new ArrayBuffer(0));
  }

  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, true, function(data) {
      return doneCallback(null, data);
    });
  }

  map(packets, encodeOne, function(err, encodedPackets) {
    var totalLength = encodedPackets.reduce(function(acc, p) {
      var len;
      if (typeof p === 'string'){
        len = p.length;
      } else {
        len = p.byteLength;
      }
      return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
    }, 0);

    var resultArray = new Uint8Array(totalLength);

    var bufferIndex = 0;
    encodedPackets.forEach(function(p) {
      var isString = typeof p === 'string';
      var ab = p;
      if (isString) {
        var view = new Uint8Array(p.length);
        for (var i = 0; i < p.length; i++) {
          view[i] = p.charCodeAt(i);
        }
        ab = view.buffer;
      }

      if (isString) { // not true binary
        resultArray[bufferIndex++] = 0;
      } else { // true binary
        resultArray[bufferIndex++] = 1;
      }

      var lenStr = ab.byteLength.toString();
      for (var i = 0; i < lenStr.length; i++) {
        resultArray[bufferIndex++] = parseInt(lenStr[i]);
      }
      resultArray[bufferIndex++] = 255;

      var view = new Uint8Array(ab);
      for (var i = 0; i < view.length; i++) {
        resultArray[bufferIndex++] = view[i];
      }
    });

    return callback(resultArray.buffer);
  });
};

/**
 * Encode as Blob
 */

exports.encodePayloadAsBlob = function(packets, callback) {
  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, true, function(encoded) {
      var binaryIdentifier = new Uint8Array(1);
      binaryIdentifier[0] = 1;
      if (typeof encoded === 'string') {
        var view = new Uint8Array(encoded.length);
        for (var i = 0; i < encoded.length; i++) {
          view[i] = encoded.charCodeAt(i);
        }
        encoded = view.buffer;
        binaryIdentifier[0] = 0;
      }

      var len = (encoded instanceof ArrayBuffer)
        ? encoded.byteLength
        : encoded.size;

      var lenStr = len.toString();
      var lengthAry = new Uint8Array(lenStr.length + 1);
      for (var i = 0; i < lenStr.length; i++) {
        lengthAry[i] = parseInt(lenStr[i]);
      }
      lengthAry[lenStr.length] = 255;

      if (Blob) {
        var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
        doneCallback(null, blob);
      }
    });
  }

  map(packets, encodeOne, function(err, results) {
    return callback(new Blob(results));
  });
};

/*
 * Decodes data when a payload is maybe expected. Strings are decoded by
 * interpreting each byte as a key code for entries marked to start with 0. See
 * description of encodePayloadAsBinary
 *
 * @param {ArrayBuffer} data, callback method
 * @api public
 */

exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  if (typeof binaryType === 'function') {
    callback = binaryType;
    binaryType = null;
  }

  var bufferTail = data;
  var buffers = [];

  while (bufferTail.byteLength > 0) {
    var tailArray = new Uint8Array(bufferTail);
    var isString = tailArray[0] === 0;
    var msgLength = '';
    for (var i = 1; ; i++) {
      if (tailArray[i] == 255) break;
      msgLength += tailArray[i];
    }
    bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
    msgLength = parseInt(msgLength);

    var msg = sliceBuffer(bufferTail, 0, msgLength);
    if (isString) {
      try {
        msg = String.fromCharCode.apply(null, new Uint8Array(msg));
      } catch (e) {
        // iPhone Safari doesn't let you apply to typed arrays
        var typed = new Uint8Array(msg);
        var basic = new Array(typed.length);
        for (var i = 0; i < typed.length; i++) {
          basic[i] = typed[i];
        }
        msg = String.fromCharCode.apply(null, basic);
      }
    }
    buffers.push(msg);
    bufferTail = sliceBuffer(bufferTail, msgLength);
  }

  var total = buffers.length;
  buffers.forEach(function(buffer, i) {
    callback(exports.decodePacket(buffer, binaryType), i, total);
  });
};
<commit_msg>Don't pass too many arguments<commit_after>/**
 * Module dependencies.
 */

var keys = require('./keys');
var sliceBuffer = require('arraybuffer.slice');
var base64encoder = require('base64-arraybuffer');
var after = require('after');
var utf8 = require('utf8');

/**
 * Check if we are running an android browser. That requires us to use
 * ArrayBuffer with polling transports...
 *
 * http://ghinda.net/jpeg-blob-ajax-android/
 */

var isAndroid = navigator.userAgent.match(/Android/i);

/**
 * Current protocol version.
 */

exports.protocol = 2;

/**
 * Packet types.
 */

var packets = exports.packets = {
    open:     0    // non-ws
  , close:    1    // non-ws
  , ping:     2
  , pong:     3
  , message:  4
  , upgrade:  5
  , noop:     6
};

var packetslist = keys(packets);

/**
 * Premade error packet.
 */

var err = { type: 'error', data: 'parser error' };

/**
 * Create a blob api even for blob builder when vendor prefixes exist
 */

var Blob = require('blob');

/**
 * Encodes a packet.
 *
 *     <packet type id> [ <data> ]
 *
 * Example:
 *
 *     5hello world
 *     3
 *     4
 *
 * Binary is encoded in an identical principle
 *
 * @api private
 */

exports.encodePacket = function (packet, supportsBinary, callback) {
  if (typeof supportsBinary == 'function') {
    callback = supportsBinary;
    supportsBinary = false;
  }

  var data = (packet.data === undefined)
    ? undefined
    : packet.data.buffer || packet.data;

  if (global.ArrayBuffer && data instanceof ArrayBuffer) {
    return encodeArrayBuffer(packet, supportsBinary, callback);
  } else if (Blob && data instanceof global.Blob) {
    return encodeBlob(packet, supportsBinary, callback);
  }

  // Sending data as a utf-8 string
  var encoded = packets[packet.type];

  // data fragment is optional
  if (undefined !== packet.data) {
    encoded += utf8.encode(String(packet.data));
  }

  return callback('' + encoded);

};

/**
 * Encode packet helpers for binary types
 */

function encodeArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var data = packet.data;
  var contentArray = new Uint8Array(data);
  var resultBuffer = new Uint8Array(1 + data.byteLength);

  resultBuffer[0] = packets[packet.type];
  for (var i = 0; i < contentArray.length; i++) {
    resultBuffer[i+1] = contentArray[i];
  }

  return callback(resultBuffer.buffer);
}

function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var fr = new FileReader();
  fr.onload = function() {
    packet.data = fr.result;
    exports.encodePacket(packet, supportsBinary, callback);
  };
  return fr.readAsArrayBuffer(packet.data);
}

function encodeBlob(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  if (isAndroid) {
    return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  }

  var length = new Uint8Array(1);
  length[0] = packets[packet.type];
  var blob = new Blob([length.buffer, packet.data]);

  return callback(blob);
}

/**
 * Encodes a packet with binary data in a base64 string
 *
 * @param {Object} packet, has `type` and `data`
 * @return {String} base64 encoded message
 */

exports.encodeBase64Packet = function(packet, callback) {
  var message = 'b' + exports.packets[packet.type];
  if (Blob && packet.data instanceof Blob) {
    var fr = new FileReader();
    fr.onload = function() {
      var b64 = fr.result.split(',')[1];
      callback(message + b64);
    };
    return fr.readAsDataURL(packet.data);
  }

  var b64data;
  try {
    b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  } catch (e) {
    // iPhone Safari doesn't let you apply with typed arrays
    var typed = new Uint8Array(packet.data);
    var basic = new Array(typed.length);
    for (var i = 0; i < typed.length; i++) {
      basic[i] = typed[i];
    }
    b64data = String.fromCharCode.apply(null, basic);
  }
  message += global.btoa(b64data);
  return callback(message);
};

/**
 * Decodes a packet. Changes format to Blob if requested.
 *
 * @return {Object} with `type` and `data` (if any)
 * @api private
 */

exports.decodePacket = function (data, binaryType) {
  // String data
  if (typeof data == 'string' || data === undefined) {
    if (data.charAt(0) == 'b') {
      return exports.decodeBase64Packet(data.substr(1), binaryType);
    }

    data = utf8.decode(data);
    var type = data.charAt(0);

    if (Number(type) != type || !packetslist[type]) {
      return err;
    }

    if (data.length > 1) {
      return { type: packetslist[type], data: data.substring(1) };
    } else {
      return { type: packetslist[type] };
    }
  }

  var asArray = new Uint8Array(data);
  var type = asArray[0];
  var rest = sliceBuffer(data, 1);
  if (Blob && binaryType === 'blob') {
    rest = new Blob([rest]);
  }
  return { type: packetslist[type], data: rest };
};

/**
 * Decodes a packet encoded in a base64 string
 *
 * @param {String} base64 encoded message
 * @return {Object} with `type` and `data` (if any)
 */

exports.decodeBase64Packet = function(msg, binaryType) {
  var type = packetslist[msg.charAt(0)];
  if (!global.ArrayBuffer) {
    return { type: type, data: { base64: true, data: msg.substr(1) } };
  }

  var data = base64encoder.decode(msg.substr(1));

  if (binaryType === 'blob' && Blob) {
    data = new Blob([data]);
  }

  return { type: type, data: data };
};

/**
 * Encodes multiple messages (payload).
 *
 *     <length>:data
 *
 * Example:
 *
 *     11:hello world2:hi
 *
 * If any contents are binary, they will be encoded as base64 strings. Base64
 * encoded strings are marked with a b before the length specifier
 *
 * @param {Array} packets
 * @api private
 */

exports.encodePayload = function (packets, supportsBinary, callback) {
  if (typeof supportsBinary == 'function') {
    callback = supportsBinary;
    supportsBinary = null;
  }

  if (supportsBinary) {
    if (Blob && !isAndroid) {
      return exports.encodePayloadAsBlob(packets, callback);
    }

    return exports.encodePayloadAsArrayBuffer(packets, callback);
  }

  if (!packets.length) {
    return callback('0:');
  }

  function setLengthHeader(message) {
    return message.length + ':' + message;
  }

  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, supportsBinary, function(message) {
      doneCallback(null, setLengthHeader(message));
    });
  }

  map(packets, encodeOne, function(err, results) {
    return callback(results.join(''));
  });
};

/**
 * Async array map using after
 */

function map(ary, each, done) {
  var result = new Array(ary.length);
  var next = after(ary.length, done);

  var eachWithIndex = function(i, el, cb) {
    each(el, function(error, msg) {
      result[i] = msg;
      cb(error, result);
    });
  };

  for (var i = 0; i < ary.length; i++) {
    eachWithIndex(i, ary[i], next);
  }
}

/*
 * Decodes data when a payload is maybe expected. Possible binary contents are
 * decoded from their base64 representation
 *
 * @param {String} data, callback method
 * @api public
 */

exports.decodePayload = function (data, binaryType, callback) {
  if (typeof data != 'string') {
    return exports.decodePayloadAsBinary(data, binaryType, callback);
  }

  if (typeof binaryType === 'function') {
    callback = binaryType;
    binaryType = null;
  }

  var packet;
  if (data == '') {
    // parser error - ignoring payload
    return callback(err, 0, 1);
  }

  var length = ''
    , n, msg;

  for (var i = 0, l = data.length; i < l; i++) {
    var chr = data.charAt(i);

    if (':' != chr) {
      length += chr;
    } else {
      if ('' == length || (length != (n = Number(length)))) {
        // parser error - ignoring payload
        return callback(err, 0, 1);
      }

      msg = data.substr(i + 1, n);

      if (length != msg.length) {
        // parser error - ignoring payload
        return callback(err, 0, 1);
      }

      if (msg.length) {
        packet = exports.decodePacket(msg, binaryType);

        if (err.type == packet.type && err.data == packet.data) {
          // parser error in individual packet - ignoring payload
          return callback(err, 0, 1);
        }

        var ret = callback(packet, i + n, l);
        if (false === ret) return;
      }

      // advance cursor
      i += n;
      length = '';
    }
  }

  if (length != '') {
    // parser error - ignoring payload
    return callback(err, 0, 1);
  }

};

/**
 * Encodes multiple messages (payload) as binary.
 *
 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
 * 255><data>
 *
 * Example:
 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
 *
 * @param {Array} packets
 * @return {ArrayBuffer} encoded payload
 * @api private
 */

exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  if (!packets.length) {
    return callback(new ArrayBuffer(0));
  }

  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, true, function(data) {
      return doneCallback(null, data);
    });
  }

  map(packets, encodeOne, function(err, encodedPackets) {
    var totalLength = encodedPackets.reduce(function(acc, p) {
      var len;
      if (typeof p === 'string'){
        len = p.length;
      } else {
        len = p.byteLength;
      }
      return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
    }, 0);

    var resultArray = new Uint8Array(totalLength);

    var bufferIndex = 0;
    encodedPackets.forEach(function(p) {
      var isString = typeof p === 'string';
      var ab = p;
      if (isString) {
        var view = new Uint8Array(p.length);
        for (var i = 0; i < p.length; i++) {
          view[i] = p.charCodeAt(i);
        }
        ab = view.buffer;
      }

      if (isString) { // not true binary
        resultArray[bufferIndex++] = 0;
      } else { // true binary
        resultArray[bufferIndex++] = 1;
      }

      var lenStr = ab.byteLength.toString();
      for (var i = 0; i < lenStr.length; i++) {
        resultArray[bufferIndex++] = parseInt(lenStr[i]);
      }
      resultArray[bufferIndex++] = 255;

      var view = new Uint8Array(ab);
      for (var i = 0; i < view.length; i++) {
        resultArray[bufferIndex++] = view[i];
      }
    });

    return callback(resultArray.buffer);
  });
};

/**
 * Encode as Blob
 */

exports.encodePayloadAsBlob = function(packets, callback) {
  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, true, function(encoded) {
      var binaryIdentifier = new Uint8Array(1);
      binaryIdentifier[0] = 1;
      if (typeof encoded === 'string') {
        var view = new Uint8Array(encoded.length);
        for (var i = 0; i < encoded.length; i++) {
          view[i] = encoded.charCodeAt(i);
        }
        encoded = view.buffer;
        binaryIdentifier[0] = 0;
      }

      var len = (encoded instanceof ArrayBuffer)
        ? encoded.byteLength
        : encoded.size;

      var lenStr = len.toString();
      var lengthAry = new Uint8Array(lenStr.length + 1);
      for (var i = 0; i < lenStr.length; i++) {
        lengthAry[i] = parseInt(lenStr[i]);
      }
      lengthAry[lenStr.length] = 255;

      if (Blob) {
        var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
        doneCallback(null, blob);
      }
    });
  }

  map(packets, encodeOne, function(err, results) {
    return callback(new Blob(results));
  });
};

/*
 * Decodes data when a payload is maybe expected. Strings are decoded by
 * interpreting each byte as a key code for entries marked to start with 0. See
 * description of encodePayloadAsBinary
 *
 * @param {ArrayBuffer} data, callback method
 * @api public
 */

exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  if (typeof binaryType === 'function') {
    callback = binaryType;
    binaryType = null;
  }

  var bufferTail = data;
  var buffers = [];

  while (bufferTail.byteLength > 0) {
    var tailArray = new Uint8Array(bufferTail);
    var isString = tailArray[0] === 0;
    var msgLength = '';
    for (var i = 1; ; i++) {
      if (tailArray[i] == 255) break;
      msgLength += tailArray[i];
    }
    bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
    msgLength = parseInt(msgLength);

    var msg = sliceBuffer(bufferTail, 0, msgLength);
    if (isString) {
      try {
        msg = String.fromCharCode.apply(null, new Uint8Array(msg));
      } catch (e) {
        // iPhone Safari doesn't let you apply to typed arrays
        var typed = new Uint8Array(msg);
        msg = '';
        for (var i = 0; i < typed.length; i++) {
          msg += String.fromCharCode(typed[i]);
        }
      }
    }
    buffers.push(msg);
    bufferTail = sliceBuffer(bufferTail, msgLength);
  }

  var total = buffers.length;
  buffers.forEach(function(buffer, i) {
    callback(exports.decodePacket(buffer, binaryType), i, total);
  });
};
<|endoftext|>


<commit_before>var q = require("q");
var mammoth = require("./");

exports.Converter = mammoth.Converter;
exports.fileInput = fileInput;

function fileInput(inputElement, callback) {
    var converter = new mammoth.Converter(mammoth.standardOptions);
    function handleFileSelect(event) {
        var file = event.target.files[0];

        var reader = new FileReader();

        reader.onload = function(loadEvent) {
            var arrayBuffer = loadEvent.target.result;
            converter.convertToHtml({file: openFile(arrayBuffer)})
                .then(callback, function(error) {
                    callback({error: error});
                })
                .done();
        };

        reader.readAsArrayBuffer(file);
    }
    inputElement.addEventListener('change', handleFileSelect, false);
}

function openFile(arrayBuffer) {
    var zipFile = new JSZip(arrayBuffer);
    function exists(name) {
        return zipFile.file(name) !== null;
    }

    function read(name, encoding) {
        var array = zipFile.file(name).asUint8Array();
        var buffer = new Buffer(array);
        if (encoding) {
            return q.when(buffer.toString(encoding));
        } else {
            return q.when(buffer);
        }
    }
    return {
        exists: exists,
        read: read
    };
}
<commit_msg>Handle exceptions when attempting to open zip file<commit_after>var q = require("q");
var mammoth = require("./");

exports.Converter = mammoth.Converter;
exports.fileInput = fileInput;

function fileInput(inputElement, callback) {
    var converter = new mammoth.Converter(mammoth.standardOptions);
    function handleFileSelect(event) {
        var file = event.target.files[0];

        var reader = new FileReader();

        reader.onload = function(loadEvent) {
            var arrayBuffer = loadEvent.target.result;
            try {
                converter.convertToHtml({file: openFile(arrayBuffer)})
                    .then(callback, function(error) {
                        callback({error: error});
                    })
                    .done();
            } catch (error) {
                callback({error: error});
            }
        };

        reader.readAsArrayBuffer(file);
    }
    inputElement.addEventListener('change', handleFileSelect, false);
}

function openFile(arrayBuffer) {
    var zipFile = new JSZip(arrayBuffer);
    function exists(name) {
        return zipFile.file(name) !== null;
    }

    function read(name, encoding) {
        var array = zipFile.file(name).asUint8Array();
        var buffer = new Buffer(array);
        if (encoding) {
            return q.when(buffer.toString(encoding));
        } else {
            return q.when(buffer);
        }
    }
    return {
        exists: exists,
        read: read
    };
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

// French Translation

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define({
    "SORT_LINES"             : "Zeilen Sortieren",
    "REVERSE_LINES"          : "Zeilenreihenfolge umdrehen",
    "SORT_LINES_BY_LENGTH"   : "Zeilen nach Länge sortieren",
    "SHUFFLE_LINES"          : "Zeilen durcheinander",
    "REMOVE_DUPLICATE_LINES" : "Doppelte Zeilen entfernen"
});
<commit_msg>Update strings.js<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

// French Translation

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define({
    "SORT_LINES"             : "Zeilen Sortieren",
    "REVERSE_LINES"          : "Zeilenreihenfolge umdrehen",
	"REVERSE_LINES_SELECTION"          : "Reverse line selection",
    "SORT_LINES_BY_LENGTH"   : "Zeilen nach Länge sortieren",
    "SHUFFLE_LINES"          : "Zeilen durcheinander",
    "REMOVE_DUPLICATE_LINES" : "Doppelte Zeilen entfernen"
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var _         = require('underscore');
var co        = require('co');
var config    = require('./config.js');
var gpio      = require('rpi-gpio');
var ldap      = require('./ldap.js');
var log       = require('logule').init(module, 'cascade');
var model     = require('./model.js');
var thunkify  = require('thunkify');
var usb       = require('usb-detection');
var wait      = require('co-wait');

/**
 * Thunks
 * @see https://github.com/visionmedia/node-thunkify
 */

var write     = thunkify(gpio.write);

/**
 * Initialize Cascade
 *
 * @constructor
 */

function Cascade() {

  /**
   * usb detection handlers
   * @see https://github.com/KABA-CCEAC/node-usb-detection
   */

  usb.on('add', this._handleAddDevice);
  usb.on('remove', this._handleRemoveDevice);

  /**
   * setup rpi pins
   *
   * GPIO 22 = change slot
   * GPIO X = status light
   *
   * @see https://github.com/JamesBarwell/rpi-gpio.js
   */

  gpio.setup(16, gpio.DIR_OUT, function(err) {
    if (err) throw err;
    gpio.write(16, true, function(err) {
      if (err) throw err;
    });
  });

  // ..

  log.info('init!');
}

// ------------------------------------------------------------------------------------
// USB handlers
// ------------------------------------------------------------------------------------

/**
 * Handle usb-detection `add` device event
 *
 * @param err
 * @param devices
 * @private
 */

Cascade.prototype._handleAddDevice = function(device) {
  ldap.findUserForDevice(device.serialNumber, function(err, res) {
    if (err) throw err;
    if (res.usbSerial == device.serialNumber) {
      cycleSlot(250);
    }
  });
};

/**
 * Handle usb-detection `remove` device event
 *
 * @param err
 * @param devices
 * @private
 */

Cascade.prototype._handleRemoveDevice = function(device) {
 // ..
};

// ------------------------------------------------------------------------------------
// RPI helpers
// ------------------------------------------------------------------------------------

/**
 * Set pin high and after `delay` set pin low
 * @param delay in milliseconds
 */

function cycleSlot(delay) {
  co(function *() {
    var error;
    // ..
    if (error = yield write(16, false)) {
      throw error;
    } else {
      yield wait(delay);
      if (error = yield write(16, true)) {
        throw error;
      }
    }
  })();
}

/**
 * Expose `Cascade`
 * @type {Cascade}
 */

module.exports = Cascade;
<commit_msg>remove experimental harmony generators, add nfc handlers, add gpio initers, cleaning up<commit_after>
/**
 * Module dependencies
 */

var config    = require('./config.js');
var gpio      = require('rpi-gpio');
var ldap      = require('./ldap.js');
var log       = require('logule').init(module, 'cascade');
var model     = require('./model.js');
var nfc       = require('./nfc.js');
var usb       = require('usb-detection');

/**
 * Initialize Cascade
 *
 * @constructor
 */

function Cascade() {

  /**
   * usb detection handlers
   * @see https://github.com/KABA-CCEAC/node-usb-detection
   */

  usb.on('add', this._handleAddUsbDevice);
  usb.on('remove', this._handleRemoveDevice);

  /**
   * nfc detection handlers
   * @see https://github.com/camme/node-nfc
   */

  nfc.on('ats', this._handleNfcAts);
  nfc.on('uid', this._handleNfcUid);

  /**
   * setup rpi pins
   *
   * GPIO 21 = change slot relay
   * GPIO 12 = status light
   *
   * @see https://github.com/JamesBarwell/rpi-gpio.js
   */

  // change slot relay

  gpio.setup(config.rpi.relayPin, gpio.DIR_OUT, function(err) {
    if (err) throw err;
    gpio.write(config.rpi.relayPin, true, function(err) {
      if (err) throw err;
    });
  });

  // front status led

  gpio.setup(config.rpi.ledPin, gpio.DIR_OUT, function(err) {
    if (err) throw err;
    gpio.write(config.rpi.ledPin, true, function(err) {
      if (err) throw err;
    });
  });

  // ..

  log.info('init!');
}

// ------------------------------------------------------------------------------------
// NFC handlers
// ------------------------------------------------------------------------------------

/**
 *
 * @param ats
 * @private
 */

Cascade.prototype._handleNfcAts = function(ats) {
  //stub
};

/**
 *
 * @param _uid
 * @private
 */

Cascade.prototype._handleNfcUid = function(_uid) {
  var uid = _uid.toString('hex')
  ldap.findUserForNFCID(uid, function(err, res) {
    if (err) throw err;
    if (res.nfcID == uid) {
      cycleSlot(250);
    }
  });
}

// ------------------------------------------------------------------------------------
// USB handlers
// ------------------------------------------------------------------------------------

/**
 * Handle usb-detection `add` device event
 *
 * @param err
 * @param devices
 * @private
 */

Cascade.prototype._handleAddUsbDevice = function(device) {
  ldap.findUserForUSBSerial(device.serialNumber, function(err, res) {
    if (err) throw err;
    if (res.usbSerial == device.serialNumber) {
      cycleSlot(250);
    }
  });
};

/**
 * Handle usb-detection `remove` device event
 *
 * @param err
 * @param devices
 * @private
 */

Cascade.prototype._handleRemoveDevice = function(device) {
  // ..
};

// ------------------------------------------------------------------------------------
// RPI helpers
// ------------------------------------------------------------------------------------

/**
 * Set pin high and after `delay` set pin low
 * @param delay in milliseconds
 */

function cycleSlot(delay) {
  gpio.write(config.rpi.relayPin, false, function(err) {
    if (err) throw err;
    setTimeout(function() {
      gpio.write(config.rpi.relayPin, true, function(err) {
        if (err) throw err;
      });
    }, delay)
  });
}

/**
 * Expose `Cascade`
 * @type {Cascade}
 */

module.exports = Cascade;
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------
// Module: dwl/has/cordova
//-------------------------------------------------------------------------
//	Has rules defined by this class.
//--------------------------------------------------------------------
//	"cordova"					Returns true if running under Cordova, else false
//  "cordova-accelerometer"		Returns true if has accelerometer access, else false
//	"cordova-alert"				Returns true if has native alert dialog, else false
//	"cordova-android"			Returns Android OS version if running on Android, else false
//	"cordova-beep"				Returns true if can sound a device beep, else false
//	"cordova-blackberry"		Returns Blackberry OS version if running on Blackberry, else false
//  "cordova-camera"			Returns true if has camera / album access, else false
//	"cordova-capture-audio"		Returns true if has audio capture access, else false
//	"cordova-capture-image"		Returns true if has image capture access, else false
//	"cordova-capture-video"		Returns true if has video capture access, else false
//	"cordova-compass"			Returns true if has compass access, else false
//	"cordova-confirm"			Returns true if has native confirm dialog, else false
//	"cordova-connection"		Returns connection type ("ETHERNET"|"WIFI"|"CELL_2G"|"CELL_3G"|"CELL_4G"|"NONE"|"UNKNOWN"|"UNDEFINED"), else false
//	"cordova-contacts"			Returns true if has contact list access, else false
//	"cordova-device"			Returns device object if running on a device, else false
//	"cordova-file"				Returns true if has file system access, else false
//	"cordova-geolocation"		Returns true if has geolocation access, else false
//	"cordova-ios"				Returns IOS OS version if running on IOS device, else false
//	"cordova-ipad"				Returns iPad OS version if running on iPad, else false
//	"cordova-iphone"			Returns iPhone OS version if running on iPhone, else false
//	"cordova-media"				Returns true if has audio record/play access, else false
//	"cordova-platform"			Returns platform name (eg "Android") if running on a device, else false
//	"cordova-storage"			Returns true if has local database access, else false
//	"cordova-webos"				Returns WebOS OS version if running on WebOS, else false
//	"cordova-windows"			Returns Windows OS version if running on Windows, else false
//--------------------------------------------------------------------

define([
    /* TODO: Remove dependency on dojo/_base/lang (inline the lang.getObject() using private function) */
    "dojo/_base/lang",
    "dojo/has"
], function(lang, has) {

	//--------------------------------------------------------------------
	var MODULE = "dwl/has/cordova";
	//console.log("Cordova - Has setup");
	var c = {};

	c.hasTests = [
		"cordova",
		"cordova-accelerometer",
		"cordova-alert",
		"cordova-android",
		"cordova-beep",
		"cordova-blackberry",
		"cordova-camera",
		"cordova-capture-audio",
		"cordova-capture-image",
		"cordova-capture-video",
		"cordova-compass",
		"cordova-confirm",
		"cordova-connection",
		"cordova-contacts",
		"cordova-device",
		"cordova-file",
		"cordova-geolocation",
		"cordova-ios",
		"cordova-ipad",
		"cordova-iphone",
		"cordova-media",
		"cordova-platform",
		"cordova-storage",
		"cordova-webos",
		"cordova-windows"
    ],

    //--------------------------------------------------------------------
	has.add("cordova", function() {
		var v = lang.getObject("device.cordova");
		return v ? v : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-accelerometer", function() {
		return !!( has("cordova") && navigator.accelerometer);
	});

	//--------------------------------------------------------------------
	has.add("cordova-camera", function() {
		return !!( has("cordova") && navigator.camera);
	});

	//--------------------------------------------------------------------
	has.add("cordova-audio", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureAudio") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-capture-audio", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureAudio") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-capture-image", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureImage") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-capture-video", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureVideo") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-compass", function() {
		return !!( has("cordova") && navigator.compass);
	});

	//--------------------------------------------------------------------
	has.add("cordova-connection", function() {
		var type = lang.getObject("navigator.connection.type");
		if ( has("cordova") && type ) {
			switch (type ) {
			case Connection.ETHERNET  : type = "ETHERNET"  ; break;
			case Connection.WIFI      : type = "WIFI"      ; break;
			case Connection.CELL_2G   : type = "CELL_2G"   ; break;
			case Connection.CELL_3G   : type = "CELL_3G"   ; break;
			case Connection.CELL_4G   : type = "CELL_4G"   ; break;
			case Connection.NONE      : type = "NONE"      ; break;
			case Connection.UNKNOWN   : type = "UNKNOWN"   ; break;
			default                   : type = "UNDEFINED" ; break;
			}
			return type;
		}
		return false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-contacts", function() {
		return !!( has("cordova") && lang.getObject("navigator.contacts") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-device", function() {
		var dev = window.device;
		return ( has("cordova") && dev ) ? dev : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-platform", function() {
		var dev = has("cordova-device");
		if ( dev ) {
			//-- older cordova returns an array, newer a string.
			return dev.platform[0].length > 1 ? dev.platform[0] : dev.platform;
		}
		return null;
	});

	//--------------------------------------------------------------------
	has.add("cordova-android", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/android/i) )  ? dev.version : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-iphone", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/iphone/i) )  ? dev.version : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-ipad", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return(platform && platform.match(/ipad/i) )  ? dev.version : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-ios", function() {
		return has("cordova-iphone") || has("cordova-ipad");
	});

	//--------------------------------------------------------------------
	has.add("cordova-blackberry", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/blackberry/i) ) ? dev.version : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-windows", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/win/i) )  ? dev.version : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-webos", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/webos/i) )  ? dev.version : false;
	});

	//--------------------------------------------------------------------
	has.add("cordova-file", function() {
		return !!( has("cordova") && window.requestFileSystem );
	});

	//--------------------------------------------------------------------
	has.add("cordova-geolocation", function() {
//		return !!( has("cordova") && lang.getObject("navigator.geolocation.getCurrentPosition") );
		return !!lang.getObject("navigator.geolocation.getCurrentPosition");
	});

	//--------------------------------------------------------------------
	has.add("cordova-media", function() {
		return !!( has("cordova") && window.Media );
	});

	//--------------------------------------------------------------------
	has.add("cordova-alert", function() {
		return !!( has("cordova") && lang.getObject("navigator.notification.alert") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-confirm", function() {
		return !!( has("cordova") && lang.getObject("navigator.notification.confirm") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-beep", function() {
		return !!( has("cordova") && lang.getObject("navigator.notification.beep") );
	});

	//--------------------------------------------------------------------
	has.add("cordova-storage", function() {
		return !!( has("cordova") && window.openDatabase);
	});

	//--------------------------------------------------------------------
	c.dumpHasTests = function() {
		var F = MODULE+".dumpHasTests(): ";
		var tests = {};
		for( var i = 0; i < c.hasTests.length; i++ ) {
			var t = c.hasTests[i];
			tests[t] = has(t);
		}
		//console.log(F, tests );
		return tests;
	};

	return c;
});
<commit_msg>Remove wasted bytes from useless comments<commit_after>//	Has.js feature test rules defined for Cordova API's
//--------------------------------------------------------------------
//	"cordova"					Returns true if running under Cordova, else false
//  "cordova-accelerometer"		Returns true if has accelerometer access, else false
//	"cordova-alert"				Returns true if has native alert dialog, else false
//	"cordova-android"			Returns Android OS version if running on Android, else false
//	"cordova-beep"				Returns true if can sound a device beep, else false
//	"cordova-blackberry"		Returns Blackberry OS version if running on Blackberry, else false
//  "cordova-camera"			Returns true if has camera / album access, else false
//	"cordova-capture-audio"		Returns true if has audio capture access, else false
//	"cordova-capture-image"		Returns true if has image capture access, else false
//	"cordova-capture-video"		Returns true if has video capture access, else false
//	"cordova-compass"			Returns true if has compass access, else false
//	"cordova-confirm"			Returns true if has native confirm dialog, else false
//	"cordova-connection"		Returns connection type ("ETHERNET"|"WIFI"|"CELL_2G"|"CELL_3G"|"CELL_4G"|"NONE"|"UNKNOWN"|"UNDEFINED"), else false
//	"cordova-contacts"			Returns true if has contact list access, else false
//	"cordova-device"			Returns device object if running on a device, else false
//	"cordova-file"				Returns true if has file system access, else false
//	"cordova-geolocation"		Returns true if has geolocation access, else false
//	"cordova-ios"				Returns IOS OS version if running on IOS device, else false
//	"cordova-ipad"				Returns iPad OS version if running on iPad, else false
//	"cordova-iphone"			Returns iPhone OS version if running on iPhone, else false
//	"cordova-media"				Returns true if has audio record/play access, else false
//	"cordova-platform"			Returns platform name (eg "Android") if running on a device, else false
//	"cordova-storage"			Returns true if has local database access, else false
//	"cordova-webos"				Returns WebOS OS version if running on WebOS, else false
//	"cordova-windows"			Returns Windows OS version if running on Windows, else false
//--------------------------------------------------------------------

define([
    /* TODO: Remove dependency on dojo/_base/lang (inline the lang.getObject() using private function) */
    "dojo/_base/lang",
    "dojo/has"
], function(lang, has) {

	//--------------------------------------------------------------------
	var MODULE = "dwl/has/cordova";
	//console.log("Cordova - Has setup");
	var c = {};

	c.hasTests = [
		"cordova",
		"cordova-accelerometer",
		"cordova-alert",
		"cordova-android",
		"cordova-beep",
		"cordova-blackberry",
		"cordova-camera",
		"cordova-capture-audio",
		"cordova-capture-image",
		"cordova-capture-video",
		"cordova-compass",
		"cordova-confirm",
		"cordova-connection",
		"cordova-contacts",
		"cordova-device",
		"cordova-file",
		"cordova-geolocation",
		"cordova-ios",
		"cordova-ipad",
		"cordova-iphone",
		"cordova-media",
		"cordova-platform",
		"cordova-storage",
		"cordova-webos",
		"cordova-windows"
    ],

	has.add("cordova", function() {
		var v = lang.getObject("device.cordova");
		return v ? v : false;
	});

	has.add("cordova-accelerometer", function() {
		return !!( has("cordova") && navigator.accelerometer);
	});

	has.add("cordova-camera", function() {
		return !!( has("cordova") && navigator.camera);
	});

	has.add("cordova-audio", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureAudio") );
	});

	has.add("cordova-capture-audio", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureAudio") );
	});

	has.add("cordova-capture-image", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureImage") );
	});

	has.add("cordova-capture-video", function() {
		return !!( has("cordova") && lang.getObject("navigator.device.capture.captureVideo") );
	});

	has.add("cordova-compass", function() {
		return !!( has("cordova") && navigator.compass);
	});

	has.add("cordova-connection", function() {
		var type = lang.getObject("navigator.connection.type");
		if ( has("cordova") && type ) {
			switch (type ) {
			case Connection.ETHERNET  : type = "ETHERNET"  ; break;
			case Connection.WIFI      : type = "WIFI"      ; break;
			case Connection.CELL_2G   : type = "CELL_2G"   ; break;
			case Connection.CELL_3G   : type = "CELL_3G"   ; break;
			case Connection.CELL_4G   : type = "CELL_4G"   ; break;
			case Connection.NONE      : type = "NONE"      ; break;
			case Connection.UNKNOWN   : type = "UNKNOWN"   ; break;
			default                   : type = "UNDEFINED" ; break;
			}
			return type;
		}
		return false;
	});

	has.add("cordova-contacts", function() {
		return !!( has("cordova") && lang.getObject("navigator.contacts") );
	});

	has.add("cordova-device", function() {
		var dev = window.device;
		return ( has("cordova") && dev ) ? dev : false;
	});

	has.add("cordova-platform", function() {
		var dev = has("cordova-device");
		if ( dev ) {
			//-- older cordova returns an array, newer a string.
			return dev.platform[0].length > 1 ? dev.platform[0] : dev.platform;
		}
		return null;
	});

	has.add("cordova-android", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/android/i) )  ? dev.version : false;
	});

	has.add("cordova-iphone", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/iphone/i) )  ? dev.version : false;
	});

	has.add("cordova-ipad", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return(platform && platform.match(/ipad/i) )  ? dev.version : false;
	});

	has.add("cordova-ios", function() {
		return has("cordova-iphone") || has("cordova-ipad");
	});

	has.add("cordova-blackberry", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/blackberry/i) ) ? dev.version : false;
	});

	has.add("cordova-windows", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/win/i) )  ? dev.version : false;
	});

	has.add("cordova-webos", function() {
		var dev = has("cordova-device");
		var platform = has("cordova-platform");
		return (platform && platform.match(/webos/i) )  ? dev.version : false;
	});

	has.add("cordova-file", function() {
		return !!( has("cordova") && window.requestFileSystem );
	});

	has.add("cordova-geolocation", function() {
		return !!lang.getObject("navigator.geolocation.getCurrentPosition");
	});

	has.add("cordova-media", function() {
		return !!( has("cordova") && window.Media );
	});

	has.add("cordova-alert", function() {
		return !!( has("cordova") && lang.getObject("navigator.notification.alert") );
	});

	has.add("cordova-confirm", function() {
		return !!( has("cordova") && lang.getObject("navigator.notification.confirm") );
	});

	has.add("cordova-beep", function() {
		return !!( has("cordova") && lang.getObject("navigator.notification.beep") );
	});

	has.add("cordova-storage", function() {
		return !!( has("cordova") && window.openDatabase);
	});

	c.dumpHasTests = function() {
		var F = MODULE+".dumpHasTests(): ";
		var tests = {};
		for( var i = 0; i < c.hasTests.length; i++ ) {
			var t = c.hasTests[i];
			tests[t] = has(t);
		}
		//console.log(F, tests );
		return tests;
	};

	return c;
});
<|endoftext|>


<commit_before>// Copyright (c) 2016 Matthew Brennan Jones <matthew.brennan.jones@gmail.com>
// This software uses a MIT style license
// https://github.com/SoftwareAddictionShow/no-more-jquery
"use strict";

// Great website for reasons not to use jquery:
// http://youmightnotneedjquery.com

let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.hidden { display: none; }';
document.getElementsByTagName('head')[0].appendChild(style);

function $one(selector) {
	return document.querySelector(selector);
}

function $all(selector) {
	return document.querySelectorAll(selector);
}

function hide(selector) {
	let elements = document.querySelectorAll(selector);
	for (let i=0; i<elements.length; ++i) {
		elements[i].classList.add('hidden');
	}
}

function show(selector) {
	let elements = document.querySelectorAll(selector);
	for (let i=0; i<elements.length; ++i) {
		elements[i].classList.remove('hidden');
	}
}

function documentOnReady(cb) {
	if (document.readyState !== 'loading') {
		cb();
	} else {
		document.addEventListener('DOMContentLoaded', cb);
	}
}

function httpGet(url, cb, timeout) {
	httpRequest(url, 'GET', cb, timeout);
}

function httpPost(url, cb, timeout) {
	httpRequest(url, 'POST', cb, timeout);
}

function httpRequest(url, method, cb, timeout) {
	timeout = timeout || 3000;
	let xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (this.readyState === 4) {
			cb(this.response, this.status);
		} else if (this.readyState === 0) {
			cb(null);
		}
	};
	xhr.onerror = function() {
		cb(null);
	};
	xhr.open(method, url, true);
	xhr.timeout = timeout;
	xhr.send(null);
}

// FIXME: Use a unique random number, rather than this global
let g_anim_counter = 0;
function animateCSS(element, start_fields, end_fields, duration, iteration_count, direction) {
	iteration_count = iteration_count || 1;
	direction = direction || 'normal';
	let anim_name = 'anim_' + (++g_anim_counter);

	let style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = "\
	." + anim_name + " {\
		animation-duration: " + duration + ";\
		animation-name: " + anim_name + ";\
		animation-iteration-count: " + iteration_count + ";\
		animation-direction: " + direction + ";\
	}\
	@keyframes " + anim_name + " {\
		from {\
			" + start_fields + "\
		}\
	}\
	@keyframes " + anim_name + " {\
		to {\
			" + end_fields + "\
		}\
	}";
	document.getElementsByTagName('head')[0].appendChild(style);

	element.addEventListener('animationstart', function() {
		console.info('animationstart');
	}, false);
	element.addEventListener('animationend', function() {
		console.info('animationend');
		document.getElementsByTagName('head')[0].removeChild(style);
	}, false);
	element.addEventListener('animationiteration', function() {
		console.info('animationiteration');
	}, false);
	element.className = anim_name;
}

function animateValue(cb, old_value, new_value, target_time) {
	let is_bigger = old_value > new_value;
	let diff_value = is_bigger ? old_value - new_value : new_value - old_value;
	let start_time = null;

	let stepTime = function(timestamp) {
		if (start_time === null) {
			start_time = timestamp;
		}
		let elapsed_time = timestamp - start_time;
		let percent = elapsed_time / target_time;
		if (percent >= 1.0) {
			percent = 1.0;
		}

		let trans_value = 0;
		if (is_bigger) {
			trans_value = old_value - (diff_value * percent);
		} else {
			trans_value= old_value + (diff_value * percent);
		}
		cb(trans_value);
		if (percent !== 1.0) {
			window.requestAnimationFrame(stepTime);
		}
	};
	window.requestAnimationFrame(stepTime);
}
<commit_msg>Replaced string concatenation mess with template literals.<commit_after>// Copyright (c) 2016 Matthew Brennan Jones <matthew.brennan.jones@gmail.com>
// This software uses a MIT style license
// https://github.com/SoftwareAddictionShow/no-more-jquery
"use strict";

// Great website for reasons not to use jquery:
// http://youmightnotneedjquery.com

let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.hidden { display: none; }';
document.getElementsByTagName('head')[0].appendChild(style);

function $one(selector) {
	return document.querySelector(selector);
}

function $all(selector) {
	return document.querySelectorAll(selector);
}

function hide(selector) {
	let elements = document.querySelectorAll(selector);
	for (let i=0; i<elements.length; ++i) {
		elements[i].classList.add('hidden');
	}
}

function show(selector) {
	let elements = document.querySelectorAll(selector);
	for (let i=0; i<elements.length; ++i) {
		elements[i].classList.remove('hidden');
	}
}

function documentOnReady(cb) {
	if (document.readyState !== 'loading') {
		cb();
	} else {
		document.addEventListener('DOMContentLoaded', cb);
	}
}

function httpGet(url, cb, timeout) {
	httpRequest(url, 'GET', cb, timeout);
}

function httpPost(url, cb, timeout) {
	httpRequest(url, 'POST', cb, timeout);
}

function httpRequest(url, method, cb, timeout) {
	timeout = timeout || 3000;
	let xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (this.readyState === 4) {
			cb(this.response, this.status);
		} else if (this.readyState === 0) {
			cb(null);
		}
	};
	xhr.onerror = function() {
		cb(null);
	};
	xhr.open(method, url, true);
	xhr.timeout = timeout;
	xhr.send(null);
}

// FIXME: Use a unique random number, rather than this global
let g_anim_counter = 0;
function animateCSS(element, start_fields, end_fields, duration, iteration_count, direction) {
	iteration_count = iteration_count || 1;
	direction = direction || 'normal';
	let anim_name = 'anim_' + (++g_anim_counter);

	let style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = `
	.${anim_name} {
		animation-duration: ${duration};
		animation-name: ${anim_name};
		animation-iteration-count: ${iteration_count};
		animation-direction: ${direction};
	}
	@keyframes ${anim_name} {
		from {
			${start_fields}
		}
	}
	@keyframes ${anim_name} {
		to {
			${end_fields}
		}
	}`;
	document.getElementsByTagName('head')[0].appendChild(style);

	element.addEventListener('animationstart', function() {
		console.info('animationstart');
	}, false);
	element.addEventListener('animationend', function() {
		console.info('animationend');
		document.getElementsByTagName('head')[0].removeChild(style);
	}, false);
	element.addEventListener('animationiteration', function() {
		console.info('animationiteration');
	}, false);
	element.className = anim_name;
}

function animateValue(cb, old_value, new_value, target_time) {
	let is_bigger = old_value > new_value;
	let diff_value = is_bigger ? old_value - new_value : new_value - old_value;
	let start_time = null;

	let stepTime = function(timestamp) {
		if (start_time === null) {
			start_time = timestamp;
		}
		let elapsed_time = timestamp - start_time;
		let percent = elapsed_time / target_time;
		if (percent >= 1.0) {
			percent = 1.0;
		}

		let trans_value = 0;
		if (is_bigger) {
			trans_value = old_value - (diff_value * percent);
		} else {
			trans_value= old_value + (diff_value * percent);
		}
		cb(trans_value);
		if (percent !== 1.0) {
			window.requestAnimationFrame(stepTime);
		}
	};
	window.requestAnimationFrame(stepTime);
}
<|endoftext|>


<commit_before>define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) {

  'use strict';

  function open(item) {
    function onBlock(item, byteSource) {
      return byteSource.slice(0, 8).getBytes().then(function(headerBytes) {
        var length = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4).getUint32(0, false);
        var name = macRoman(headerBytes, 4, 4);
        var blockItem = itemOM.createItem(name);
        item.addItem(blockItem);
        if (length > 8) {
          blockItem.byteSource = byteSource.slice(8, length);
        }
        if (byteSource.byteLength >= (length + 8)) {
          return onBlock(item, byteSource.slice(length));
        }
      });
    }
    return onBlock(item, item.byteSource);
  }

  return open;

});
<commit_msg>Use block IDs<commit_after>define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) {

  'use strict';

  function open(item) {
    function onBlock(item, byteSource) {
      return byteSource.slice(0, 12).getBytes().then(function(headerBytes) {
        var dv = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4);
        var length = dv.getUint32(0, false);
        var name = macRoman(headerBytes, 4, 4);
        var id = dv.getInt32(8, false);
        var blockItem = itemOM.createItem(name + " " + id);
        item.addItem(blockItem);
        if (length > 8) {
          blockItem.byteSource = byteSource.slice(12, length);
        }
        if (byteSource.byteLength >= (length + 12)) {
          return onBlock(item, byteSource.slice(length));
        }
      });
    }
    return onBlock(item, item.byteSource);
  }

  return open;

});
<|endoftext|>


<commit_before>module.exports = {
	"env": {
		"browser": true,
		"es6": true
	},
	"extends": [
		"plugin:vue/essential",
		"standard"
	],
	"globals": {
		"Atomics": "readonly",
		"SharedArrayBuffer": "readonly"
	},
	"parserOptions": {
		"ecmaVersion": 2018,
		"sourceType": "module"
	},
	"plugins": [
		"vue"
	]
};
<commit_msg>Added eslint config for NuxtJS<commit_after>module.exports = {
	root: true,
	env: {
		browser: true,
		node: true
	},
	parserOptions: {
		parser: 'babel-eslint'
	},
	extends: [],
	plugins: [],
	// add your custom rules here
	rules: {
		indent: ['warn', 'tab'],
		'no-tabs': 0,
		'vue/html-closing-bracket-newline': ['error', {
			multiline: 'never'
		}],
		'vue/max-attributes-per-line': 'off',
		'vue/html-indent': ['error', type, {
			attribute: 20,
			baseIndent: 1,
			closeBracket: 1,
			alignAttributesVertically: false,
			ignores: []
		}],
		'vue/html-self-closing': ['error', {
			html: {
				void: 'never',
				normal: 'always',
				component: 'always'
			},
			svg: 'always',
			math: 'always'
		}]
	}
}
<|endoftext|>