text:
You are here to help on **vue-formly-buefy**? Awesome, feel welcome and read the following sections to know what and how to work on something.

It's an open source project and we love to receive contributions from our community — you! There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests or writing code which can be incorporated into **vue-formly-buefy** itself.

## Code of Conduct
All members of our community are expected to follow our [Code of Conduct](https://github.com/yarbshk/vue-formly-buefy/blob/master/CODE_OF_CONDUCT.md). Please make sure you are welcoming and friendly in all of our spaces.

## Issues
Before you submit an issue, please **search the issue tracker**, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.

We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we ask you to **provide a minimal reproduction scenario** that include:
- Version of the plugin used.
- Environment information (3rd-party libraries, technology stack etc.).
- A use-case that fails.

If you get stuck at any point you can create a [ticket on GitHub](https://github.com/yarbshk/vue-formly-buefy/issues).

## Pull requests
**Working on your first Pull Request?** You can learn how from this free series, [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github).

If you would make PR for something that is bigger than a one or two line fix:
1. Create your own fork of the code.
2. **Before start development** be sure you are following:
    - Our [Code of Conduct](https://github.com/yarbshk/vue-formly-buefy/blob/master/CODE_OF_CONDUCT.md).
    - [The documented overview](https://github.com/yarbshk/vue-formly-buefy/wiki#overview) to have a particular roadmap.
    - The code style for the project (use our `.eslintrc`).
    - Commit message convention (sentence case, present time).
3. Do the changes in your fork.
4. **Write one or more specs** (unit-tests) for all features or bug fixes.
5. Provide documentation for all public API methods.
6. Only **if you like the change** and think **the project could use it**:
    - Send a pull request.

## Getting started
To **run the project for development** use the following micro guide:
1. Get local copy of the project.
2. Be sure that [Docker](https://www.docker.com/), [Docker Compose](https://docs.docker.com/compose/) and Google Chrome (needs for test) installed.
3. Kill a process which occupy the `9876` port (needs for test).
4. Set the `yarn && yarn test` command for the `node` service in the `docker-compose.yml`.
5. Open root directory of the project in the terminal and run the `docker-compose up` command.

When work has done properly all npm packages will be install and Karma test server run on the `9876` port.


text:
package org.qi4j.library.rest.common;

import org.qi4j.api.common.UseDefaults;
import org.qi4j.api.property.Property;
import org.qi4j.api.value.ValueComposite;

import java.util.Map;

/**
 * Value that represents a form. This can be used to mimic a HTML form.
 */
public interface Form
      extends ValueComposite
{
   @UseDefaults
   Property<Map<String,String>> form();
}

redpajama_set_name: RedPajamaGithub


text:
ARG ocaml_version=4.12
FROM ocaml/opam:ubuntu-20.04-ocaml-$ocaml_version AS fstardep

# FIXME: the `opam depext` command should be unnecessary with opam 2.1
RUN opam depext conf-gmp z3.4.8.5 conf-m4

ADD --chown=opam:opam ./ FStar/

# Install opam dependencies only
RUN opam install --deps-only FStar/fstar.opam

ARG opamthreads=24

FROM fstardep AS fstarbuild

# Build the package,
RUN eval $(opam env) && env Z3_LICENSE="$(opam config expand '%{prefix}%')/.opam-switch/sources/z3.4.8.5/LICENSE.txt" OTHERFLAGS='--admit_smt_queries true' make -C FStar -j $opamthreads package_unknown_platform

# Create a separate image to test the package
FROM fstardep AS fstarbin

# Remove F* sources (keep deps)
RUN mv FStar FStar.todelete && rm -rf FStar.todelete

# Copy the F* binary package
COPY --from=fstarbuild /home/opam/FStar/src/ocaml-output/fstar.tar.gz /home/opam/fstar.tar.gz
RUN tar xzf fstar.tar.gz
ENV FSTAR_HOME /home/opam/fstar
ENV PATH="${FSTAR_HOME}/bin:${PATH}"

# Copy examples and docs
ADD --chown=opam:opam examples/ fstar_examples/
ADD --chown=opam:opam doc/ fstar_doc/

# Test the F* binary package

# Case 1: test the fresh package
FROM fstarbin
RUN eval $(opam env) && make -C fstar_examples -j $opamthreads
RUN eval $(opam env) && make -C fstar_doc/tutorial -j $opamthreads regressions

# Case 2: rebuild ulib and test again
FROM fstarbin
RUN eval $(opam env) && make -C $FSTAR_HOME/ulib rebuild -j $opamthreads
RUN eval $(opam env) && make -C fstar_examples/hello -j $opamthreads
RUN eval $(opam env) && make -C $FSTAR_HOME/ulib clean_checked && make -C $FSTAR_HOME/ulib -j $opamthreads
RUN eval $(opam env) && make -C fstar_examples -j $opamthreads
RUN eval $(opam env) && make -C fstar_doc/tutorial -j $opamthreads regressions

# Test the fresh package without OCaml
FROM ubuntu:20.04 AS fstarnoocaml
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update
RUN apt-get --yes install --no-install-recommends make sudo libgomp1

# Create a new user and give them sudo rights
RUN useradd -d /home/test test
RUN echo 'test ALL=NOPASSWD: ALL' >> /etc/sudoers
RUN mkdir /home/test
RUN chown test:test /home/test
USER test
ENV HOME /home/test
WORKDIR $HOME
SHELL ["/bin/bash", "--login", "-c"]

# Copy the package
COPY --from=fstarbuild /home/opam/FStar/src/ocaml-output/fstar.tar.gz /home/test/fstar.tar.gz
RUN tar xzf fstar.tar.gz
ENV FSTAR_HOME /home/test/fstar
ENV PATH="${FSTAR_HOME}/bin:${PATH}"

# Copy tests, examples and docs
ADD --chown=test:test examples/ fstar_examples/
ADD --chown=test:test doc/ fstar_doc/

# Case 3: test F* package without OCaml
FROM fstarnoocaml
RUN make -C fstar_examples -j $opamthreads
RUN make -C fstar_doc/tutorial -j $opamthreads regressions

# Case 4: test F* package without OCaml, but recheck ulib
FROM fstarnoocaml
RUN make -C $FSTAR_HOME/ulib clean_checked && make -C $FSTAR_HOME/ulib -j $opamthreads
RUN make -C fstar_examples -j $opamthreads
RUN make -C fstar_doc/tutorial -j $opamthreads regressions

# This is the last image. So we can also copy the file that contains
# the desired filename for the package, to be extracted via
# `docker cp`
COPY --from=fstarbuild /home/opam/FStar/src/ocaml-output/version_platform.txt /home/test/version_platform.txt


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /**
                                                                                * react-native-swiper
                                                                                * @author leecade<leecade@163.com>
                                                                                */

// Using bare setTimeout, setInterval, setImmediate
// and requestAnimationFrame calls is very dangerous
// because if you forget to cancel the request before
// the component is unmounted, you risk the callback
// throwing an exception.

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactNative = require('react-native');

var _reactNative2 = _interopRequireDefault(_reactNative);

var _reactTimerMixin = require('react-timer-mixin');

var _reactTimerMixin2 = _interopRequireDefault(_reactTimerMixin);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _Dimensions$get = _reactNative.Dimensions.get('window');

var width = _Dimensions$get.width;
var height = _Dimensions$get.height;

/**
 * Default styles
 * @type {StyleSheetPropType}
 */

var styles = _reactNative.StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    position: 'relative'
  },

  wrapper: {
    backgroundColor: 'transparent'
  },

  slide: {
    backgroundColor: 'transparent'
  },

  pagination_x: {
    position: 'absolute',
    bottom: 25,
    left: 0,
    right: 0,
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent'
  },

  pagination_y: {
    position: 'absolute',
    right: 15,
    top: 0,
    bottom: 0,
    flexDirection: 'column',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent'
  },

  title: {
    height: 30,
    justifyContent: 'center',
    position: 'absolute',
    paddingLeft: 10,
    bottom: -30,
    left: 0,
    flexWrap: 'nowrap',
    width: 250,
    backgroundColor: 'transparent'
  },

  buttonWrapper: {
    backgroundColor: 'transparent',
    flexDirection: 'row',
    position: 'absolute',
    top: 0,
    left: 0,
    flex: 1,
    paddingHorizontal: 10,
    paddingVertical: 10,
    justifyContent: 'space-between',
    alignItems: 'center'
  },

  buttonText: {
    fontSize: 50,
    color: '#007aff',
    fontFamily: 'Arial'
  }
});

// missing `module.exports = exports['default'];` with babel6
// export default React.createClass({
module.exports = _react2.default.createClass({
  displayName: 'exports',

  /**
   * Props Validation
   * @type {Object}
   */
  propTypes: {
    horizontal: _react2.default.PropTypes.bool,
    children: _react2.default.PropTypes.node.isRequired,
    style: _reactNative.View.propTypes.style,
    pagingEnabled: _react2.default.PropTypes.bool,
    showsHorizontalScrollIndicator: _react2.default.PropTypes.bool,
    showsVerticalScrollIndicator: _react2.default.PropTypes.bool,
    bounces: _react2.default.PropTypes.bool,
    scrollsToTop: _react2.default.PropTypes.bool,
    removeClippedSubviews: _react2.default.PropTypes.bool,
    automaticallyAdjustContentInsets: _react2.default.PropTypes.bool,
    showsPagination: _react2.default.PropTypes.bool,
    showsButtons: _react2.default.PropTypes.bool,
    loadMinimal: _react2.default.PropTypes.bool,
    loadMinimalSize: _react2.default.PropTypes.number,
    loop: _react2.default.PropTypes.bool,
    autoplay: _react2.default.PropTypes.bool,
    autoplayTimeout: _react2.default.PropTypes.number,
    autoplayDirection: _react2.default.PropTypes.bool,
    index: _react2.default.PropTypes.number,
    renderPagination: _react2.default.PropTypes.func
  },

  mixins: [_reactTimerMixin2.default],

  /**
   * Default props
   * @return {object} props
   * @see http://facebook.github.io/react-native/docs/scrollview.html
   */
  getDefaultProps: function getDefaultProps() {
    return {
      horizontal: true,
      pagingEnabled: true,
      showsHorizontalScrollIndicator: false,
      showsVerticalScrollIndicator: false,
      bounces: false,
      scrollsToTop: false,
      removeClippedSubviews: true,
      automaticallyAdjustContentInsets: false,
      showsPagination: true,
      showsButtons: false,
      loop: true,
      loadMinimal: false,
      loadMinimalSize: 1,
      autoplay: false,
      autoplayTimeout: 2.5,
      autoplayDirection: true,
      index: 0
    };
  },

  /**
   * Init states
   * @return {object} states
   */
  getInitialState: function getInitialState() {
    return this.initState(this.props);
  },

  /**
   * autoplay timer
   * @type {null}
   */
  autoplayTimer: null,

  componentWillReceiveProps: function componentWillReceiveProps(props) {
    this.setState(this.initState(props));
  },
  componentDidMount: function componentDidMount() {
    this.autoplay();
  },
  initState: function initState(props) {
    // set the current state
    var state = this.state || {};

    var initState = {
      isScrolling: false,
      autoplayEnd: false,
      loopJump: false
    };

    initState.total = props.children ? props.children.length || 1 : 0;

    if (state.total === initState.total) {
      // retain the index
      initState.index = state.index;
    } else {
      // reset the index
      initState.index = initState.total > 1 ? Math.min(props.index, initState.total - 1) : 0;
    }

    // Default: horizontal
    initState.dir = props.horizontal === false ? 'y' : 'x';
    initState.width = props.width || width;
    initState.height = props.height || height;
    initState.offset = {};

    if (initState.total > 1) {
      var setup = initState.index;
      if (props.loop) {
        setup++;
      }
      initState.offset[initState.dir] = initState.dir === 'y' ? initState.height * setup : initState.width * setup;
    }
    return initState;
  },

  loopJump: function loopJump() {
    var _this = this;

    if (this.state.loopJump) {
      var i = this.state.index + (this.props.loop ? 1 : 0);
      setTimeout(function () {
        return _this.refs.scrollView.setPageWithoutAnimation && _this.refs.scrollView.setPageWithoutAnimation(i);
      }, 50);
    }
  },

  /**
   * Automatic rolling
   */
  autoplay: function autoplay() {
    var _this2 = this;

    if (!Array.isArray(this.props.children) || !this.props.autoplay || this.state.isScrolling || this.state.autoplayEnd) {
      return;
    }

    clearTimeout(this.autoplayTimer);

    this.autoplayTimer = this.setTimeout(function () {
      if (!_this2.props.loop && (_this2.props.autoplayDirection ? _this2.state.index === _this2.state.total - 1 : _this2.state.index === 0)) {
        return _this2.setState({ autoplayEnd: true });
      }

      _this2.scrollBy(_this2.props.autoplayDirection ? 1 : -1);
    }, this.props.autoplayTimeout * 1000);
  },

  /**
   * Scroll begin handle
   * @param  {object} e native event
   */
  onScrollBegin: function onScrollBegin(e) {
    var _this3 = this;

    // update scroll state
    this.setState({ isScrolling: true });

    this.setTimeout(function () {
      _this3.props.onScrollBeginDrag && _this3.props.onScrollBeginDrag(e, _this3.state, _this3);
    });
  },

  /**
   * Scroll end handle
   * @param  {object} e native event
   */
  onScrollEnd: function onScrollEnd(e) {
    var _this4 = this;

    // update scroll state
    this.setState({
      isScrolling: false
    });

    // making our events coming from android compatible to updateIndex logic
    if (!e.nativeEvent.contentOffset) {
      if (this.state.dir === 'x') {
        e.nativeEvent.contentOffset = { x: e.nativeEvent.position * this.state.width };
      } else {
        e.nativeEvent.contentOffset = { y: e.nativeEvent.position * this.state.height };
      }
    }

    this.updateIndex(e.nativeEvent.contentOffset, this.state.dir);

    // Note: `this.setState` is async, so I call the `onMomentumScrollEnd`
    // in setTimeout to ensure synchronous update `index`
    this.setTimeout(function () {
      _this4.autoplay();
      _this4.loopJump();

      // if `onMomentumScrollEnd` registered will be called here
      _this4.props.onMomentumScrollEnd && _this4.props.onMomentumScrollEnd(e, _this4.state, _this4);
    });
  },

  /*
   * Drag end handle
   * @param {object} e native event
   */
  onScrollEndDrag: function onScrollEndDrag(e) {
    var contentOffset = e.nativeEvent.contentOffset;
    var _props = this.props;
    var horizontal = _props.horizontal;
    var children = _props.children;
    var _state = this.state;
    var offset = _state.offset;
    var index = _state.index;

    var previousOffset = horizontal ? offset.x : offset.y;
    var newOffset = horizontal ? contentOffset.x : contentOffset.y;

    if (previousOffset === newOffset && (index === 0 || index === children.length - 1)) {
      this.setState({
        isScrolling: false
      });
    }
  },

  /**
   * Update index after scroll
   * @param  {object} offset content offset
   * @param  {string} dir    'x' || 'y'
   */
  updateIndex: function updateIndex(offset, dir) {

    var state = this.state;
    var index = state.index;
    var diff = offset[dir] - state.offset[dir];
    var step = dir === 'x' ? state.width : state.height;
    var loopJump = false;

    // Do nothing if offset no change.
    if (!diff) return;

    // Note: if touch very very quickly and continuous,
    // the variation of `index` more than 1.
    // parseInt() ensures it's always an integer
    index = parseInt(index + Math.round(diff / step));

    if (this.props.loop) {
      if (index <= -1) {
        index = state.total - 1;
        offset[dir] = step * state.total;
        loopJump = true;
      } else if (index >= state.total) {
        index = 0;
        offset[dir] = step;
        loopJump = true;
      }
    }

    this.setState({
      index: index,
      offset: offset,
      loopJump: loopJump
    });
  },

  /**
   * Scroll by index
   * @param  {number} index offset index
   */
  scrollBy: function scrollBy(index) {
    var _this5 = this;

    if (this.state.isScrolling || this.state.total < 2) return;
    var state = this.state;
    var diff = (this.props.loop ? 1 : 0) + index + this.state.index;
    var x = 0;
    var y = 0;
    if (state.dir === 'x') x = diff * state.width;
    if (state.dir === 'y') y = diff * state.height;

    if (_reactNative.Platform.OS === 'android') {
      this.refs.scrollView && this.refs.scrollView.setPage(diff);
    } else {
      this.refs.scrollView && this.refs.scrollView.scrollTo({ x: x, y: y });
    }

    // update scroll state
    this.setState({
      isScrolling: true,
      autoplayEnd: false
    });

    // trigger onScrollEnd manually in android
    if (_reactNative.Platform.OS === 'android') {
      this.setTimeout(function () {
        _this5.onScrollEnd({
          nativeEvent: {
            position: diff
          }
        });
      }, 0);
    }
  },
  scrollViewPropOverrides: function scrollViewPropOverrides() {
    var _this6 = this;

    var props = this.props;
    var overrides = {};

    /*
    const scrollResponders = [
      'onMomentumScrollBegin',
      'onTouchStartCapture',
      'onTouchStart',
      'onTouchEnd',
      'onResponderRelease',
    ]
    */

    for (var prop in props) {
      // if(~scrollResponders.indexOf(prop)
      if (typeof props[prop] === 'function' && prop !== 'onMomentumScrollEnd' && prop !== 'renderPagination' && prop !== 'onScrollBeginDrag') {
        (function () {
          var originResponder = props[prop];
          overrides[prop] = function (e) {
            return originResponder(e, _this6.state, _this6);
          };
        })();
      }
    }

    return overrides;
  },

  /**
   * Render pagination
   * @return {object} react-dom
   */
  renderPagination: function renderPagination() {

    // By default, dots only show when `total` > 2
    if (this.state.total <= 1) return null;

    var dots = [];
    var ActiveDot = this.props.activeDot || _react2.default.createElement(_reactNative.View, { style: {
        backgroundColor: '#007aff',
        width: 8,
        height: 8,
        borderRadius: 4,
        marginLeft: 3,
        marginRight: 3,
        marginTop: 3,
        marginBottom: 3
      } });
    var Dot = this.props.dot || _react2.default.createElement(_reactNative.View, { style: {
        backgroundColor: 'rgba(0,0,0,.2)',
        width: 8,
        height: 8,
        borderRadius: 4,
        marginLeft: 3,
        marginRight: 3,
        marginTop: 3,
        marginBottom: 3
      } });
    for (var i = 0; i < this.state.total; i++) {
      dots.push(i === this.state.index ? _react2.default.cloneElement(ActiveDot, { key: i }) : _react2.default.cloneElement(Dot, { key: i }));
    }

    return _react2.default.createElement(
      _reactNative.View,
      { pointerEvents: 'none', style: [styles['pagination_' + this.state.dir], this.props.paginationStyle] },
      dots
    );
  },
  renderTitle: function renderTitle() {
    var child = this.props.children[this.state.index];
    var title = child && child.props && child.props.title;
    return title ? _react2.default.createElement(
      _reactNative.View,
      { style: styles.title },
      this.props.children[this.state.index].props.title
    ) : null;
  },
  renderNextButton: function renderNextButton() {
    var _this7 = this;

    var button = void 0;

    if (this.props.loop || this.state.index != this.state.total - 1) {
      button = this.props.nextButton || _react2.default.createElement(
        _reactNative.Text,
        { style: styles.buttonText },
        '›'
      );
    }

    return _react2.default.createElement(
      _reactNative.TouchableOpacity,
      { onPress: function onPress() {
          return button !== null && _this7.scrollBy.call(_this7, 1);
        } },
      _react2.default.createElement(
        _reactNative.View,
        null,
        button
      )
    );
  },
  renderPrevButton: function renderPrevButton() {
    var _this8 = this;

    var button = null;

    if (this.props.loop || this.state.index != 0) {
      button = this.props.prevButton || _react2.default.createElement(
        _reactNative.Text,
        { style: styles.buttonText },
        '‹'
      );
    }

    return _react2.default.createElement(
      _reactNative.TouchableOpacity,
      { onPress: function onPress() {
          return button !== null && _this8.scrollBy.call(_this8, -1);
        } },
      _react2.default.createElement(
        _reactNative.View,
        null,
        button
      )
    );
  },
  renderButtons: function renderButtons() {
    return _react2.default.createElement(
      _reactNative.View,
      { pointerEvents: 'box-none', style: [styles.buttonWrapper, { width: this.state.width, height: this.state.height }, this.props.buttonWrapperStyle] },
      this.renderPrevButton(),
      this.renderNextButton()
    );
  },
  renderScrollView: function renderScrollView(pages) {
    if (_reactNative.Platform.OS === 'ios') return _react2.default.createElement(
      _reactNative.ScrollView,
      _extends({ ref: 'scrollView'
      }, this.props, this.scrollViewPropOverrides(), {
        contentContainerStyle: [styles.wrapper, this.props.style],
        contentOffset: this.state.offset,
        onScrollBeginDrag: this.onScrollBegin,
        onMomentumScrollEnd: this.onScrollEnd,
        onScrollEndDrag: this.onScrollEndDrag }),
      pages
    );
    return _react2.default.createElement(
      _reactNative.ViewPagerAndroid,
      _extends({ ref: 'scrollView'
      }, this.props, {
        initialPage: this.props.loop ? this.state.index + 1 : this.state.index,
        onPageSelected: this.onScrollEnd,
        style: { flex: 1 } }),
      pages
    );
  },

  /**
   * Default render
   * @return {object} react-dom
   */
  render: function render() {
    var state = this.state;
    var props = this.props;
    var children = props.children;
    var index = state.index;
    var total = state.total;
    var loop = props.loop;
    var dir = state.dir;
    var key = 0;
    var loopVal = loop ? 1 : 0;

    var pages = [];

    var pageStyle = [{ width: state.width, height: state.height }, styles.slide];
    var pageStyleLoading = {
      width: this.state.width,
      height: this.state.height,
      justifyContent: 'center',
      alignItems: 'center'
    };

    // For make infinite at least total > 1
    if (total > 1) {

      // Re-design a loop model for avoid img flickering
      pages = Object.keys(children);
      if (loop) {
        pages.unshift(total - 1 + '');
        pages.push('0');
      }

      pages = pages.map(function (page, i) {
        if (props.loadMinimal) {
          if (i >= index + loopVal - props.loadMinimalSize && i <= index + loopVal + props.loadMinimalSize) {
            return _react2.default.createElement(
              _reactNative.View,
              { style: pageStyle, key: i },
              children[page]
            );
          } else {
            return _react2.default.createElement(
              _reactNative.View,
              { style: pageStyleLoading, key: 'loading-' + i },
              _react2.default.createElement(_reactNative.ActivityIndicator, null)
            );
          }
        } else {
          return _react2.default.createElement(
            _reactNative.View,
            { style: pageStyle, key: i },
            children[page]
          );
        }
      });
    } else pages = _react2.default.createElement(
      _reactNative.View,
      { style: pageStyle },
      children
    );

    return _react2.default.createElement(
      _reactNative.View,
      { style: [styles.container, {
          width: state.width,
          height: state.height
        }] },
      this.renderScrollView(pages),
      props.showsPagination && (props.renderPagination ? this.props.renderPagination(state.index, state.total, this) : this.renderPagination()),
      this.renderTitle(),
      this.props.showsButtons && this.renderButtons()
    );
  }
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bulletin of the Forestry and Forest Products Research Institute, Ibaraki, Japan 351: 165 (1988)

#### Original name
Pestalotia heucherae Tehon & E.Y. Daniels

### Remarks
null


text:
<?php
namespace MarketMeSuite\Phranken\Database\Object;

use MarketMeSuite\Phranken\Crypt\UniqueIDGenerator;
use MarketMeSuite\Phranken\Database\Exception\DbObjectException;
use MarketMeSuite\Phranken\Database\Interfaces\IDbObject;

/**
 * Provides a way to load database objects into a well defined class structure
 */
abstract class DbObject implements IDbObject
{
    /**
     * The default "id" field for records
     * In mongo this is usually '_id' and in mysql it is 'id'
     * Because DbObject is database agnostic this is able to be overridden
     * by subclasses that may be for other database engines.
     * @var string
     */
    public static $ID_FIELD = '_id';

    /**
     * The property version of ID_FIELD
     *
     * @var string
     */
    public static $ID_PROP = 'id';

    /**
     * @var array An array of key => value pairs
     */
    public $map;

    /**
     * When true, if fromArray is called with an array that does
     * not have all the keys present in $map an DbObjectException
     * is thrown with details of the missing keys.
     * When false, missing keys are ignored.
     *
     * @var bool
     */
    protected $strictMap = false;

    /**
     * To be recognised by the toArray method, this bool should
     * control whether null values in properties are allowed.
     *
     * @var bool When true, null propert values are permitted
     *           otherwise properties with null values are
     *           ommitted from the final array
     */
    protected $toArrayAllowNull = false;

    /**
     * loads a mongo document array into this object structure
     *
     * @param  array $data A document array from a mongo query
     *
     * @throws DbObjectException If a required mapped property does not exist in $data
     */
    public function fromArray(array $data)
    {
        $map = $this->getMap();

        // if strict map is true then
        // assert that the map has all
        // keys needed
        if ($this->getStrictMap() === true) {
            $this->assertArrayHasAllMapKeys($data);
        }

        foreach ($map as $dbKey => $variableName) {

            if (!property_exists($this, $variableName)) {
                throw new DbObjectException('property "' . $variableName . '" was not found in this object');
            }

            // if the key exists then set the property
            if (isset($data[$dbKey])) {
                $this->{$variableName} = $data[$dbKey];
            }
        }
    }

    /**
     * Asserts that all keys in the configured map exist
     * within provided $arr
     *
     * @param array $arr An associative array
     *
     * @throws DbObjectException If any keys from map do not exist
     *                           within $arr
     */
    public function assertArrayHasAllMapKeys(array $arr)
    {
        $map = $this->getMap();

        $providedkeys = array_keys($arr);
        $mappedKeys   = array_keys($map);

        $missingKeys = array_diff($mappedKeys, $providedkeys);

        if (!empty($missingKeys)) {
            throw new DbObjectException(
                'provided $arr does not have all required keys. Missing: ' .
                implode(',', $missingKeys)
            );
        }
    }

    /**
     * When true, if fromArray is called with an array that does
     * not have all the keys present in $map an DbObjectException
     * is thrown with details of the missing keys.
     * When false, missing keys are ignored.
     *
     * @param boolean $strictMap
     */
    public function setStrictMap($strictMap)
    {
        $this->strictMap = $strictMap;
    }

    /**
     * @return bool
     */
    public function getStrictMap()
    {
        return $this->strictMap;
    }

    /**
     * Converts this object into a database-compatable associative array
     * @return array An associative array representing this object
     */
    public function toArray()
    {
        $map = $this->getMap();
        $out = array();

        foreach ($map as $dbKey => $variableName) {

            $value = $this->getProp($variableName);

            // If the property is an instance of
            // IDbObject then execute it's toArray
            // and use the result as the value
            if ($value instanceof IDbObject) {
                $value = $value->toArray();
            }

            // if a value is encountered that is null then
            // and the class is set to ignore null values
            // then do not add this key => value to the array
            if ($this->getToArrayAllowNull() === false && $value === null) {
                continue;
            }

            $out[$dbKey] = $value;
        }

        return $out;
    }

    /**
     * Converts this object into particular mongo queries
     *
     * @param  string $type The type of query to export
     *
     * @return array        The result of toArray() with particular fields ommitted/added
     *                      depending on the type
     * @throws DbObjectException If $type is not a recognised type
     */
    public function toQuery($type)
    {
        $arr = $this->toArray();
        switch ($type) {
            case 'set':
                // the _id field can not exist for set queries
                unset($arr[$this->getIdFieldName()]);
                return $arr;
                break;
            case 'insert':
                // generate a UUID for the insert query if no id is already set
                $ident = $this->getProp($this->getIdPropName());
                if (empty($ident)) {

                    $arr[$this->getIdFieldName()] = UniqueIDGenerator::GenerateUUID();
                    $this->setProp($this->getIdPropName(), $arr[$this->getIdFieldName()]);
                }
                return $arr;
                break;
            default:
                throw new DbObjectException('query type "' . $type . '" has no actions');
                break;
        }
    }

    /**
     * sets an object property
     *
     * @param string $key   The name of the property
     * @param mixed  $value The value to set $key to
     *
     * @throws DbObjectException If $key does not exist in the configured map
     */
    public function setProp($key, $value)
    {
        $map = $this->getMap();

        // does the key exist in the map?
        if (!in_array($key, $map)) {
            throw new DbObjectException('"' . $key . '" does not exist in map');
        }

        $this->{$key} = $value;
    }

    /**
     * Gets a property
     *
     * @param  string $key The name of the property
     *
     * @return mixed       The value of $key
     *
     * @throws DbObjectException When $key does not exist in map
     */
    public function getProp($key)
    {
        $map = $this->getMap();

        if (!in_array($key, $map)) {
            throw new DbObjectException('"' . $key . '" does not exist in map');
        }

        return $this->{$key};
    }

    /**
     * Runs multiple fromArray() for every item in $arr
     *
     * @param array|\Traversable $iterator An array of mongo documents, Can also be a mongo cursor
     * @param string             $class    A valid class name that implements IDbObject
     *
     * @return array An array of objects
     * @throws DbObjectException When $class does not implement IDbObject
     */
    public static function multiFromArray($iterator, $class = 'DbObject')
    {
        if ((is_array($iterator) || $iterator instanceof \Traversable) === false) {
            throw new DbObjectException('$iterator was not and array and did not implement Traversable');
        }

        if (new $class instanceof IDbObject) {
            // nothing
        } else {
            throw new DbObjectException('$class must implement IDbObject');
        }

        $objects = array();

        foreach ($iterator as $dbArr) {

            /** @var IDbObject $newObject */
            $newObject = new $class;
            $newObject->fromArray($dbArr);
            $objects[] = $newObject;
        }

        return $objects;
    }

    /**
     * Runs multiple toArray() for every IDbObject in $arr
     *
     * @param array $arr An array of IDbObject instances
     *
     * @param string[] $allowedFields An array of the field names to show in conversion
     *
     * @throws \MarketMeSuite\Phranken\Database\Exception\DbObjectException
     * @return array An array of arrays where each sub array is the result of calling
     * toArray on each objecting in $arr
     */
    public static function multiToArray(array $arr, array $allowedFields = array())
    {
        $arrs = array();

        foreach ($arr as $dbobject) {

            if ($dbobject instanceof IDbObject) {
                // nothing
            } else {
                throw new DbObjectException('$dbobject must implement IDbObject');
            }

            $arr = $dbobject->toArray();

            if (!empty($allowedFields)) {

                foreach ($arr as $key => $value) {
                    if (!in_array($key, $allowedFields)) {
                        unset($arr[$key]);
                    }
                }
            }

            $arrs[] = $arr;
        }

        return $arrs;
    }

    /**
     * @see IDbObject::getMap
     */
    public function getMap()
    {
        return $this->map;
    }

    /**
     * @see IDbObject::setMap
     */
    public function setMap(array $map)
    {
        $this->map = $map;
    }

    /**
     * @see IDbObject::setIdFieldName
     */
    public function setIdFieldName($name)
    {
        static::$ID_FIELD = $name;
    }

    /**
     * @see IDbObject::getIdFieldName
     */
    public function getIdFieldName()
    {
        return static::$ID_FIELD;
    }

    /**
     * The local id field is the local name of the property
     *
     * @param string $name The name of the id field
     */
    public function setIdPropName($name)
    {
        static::$ID_PROP = $name;
    }

    /**
     * Gets the set id that was set with setIdPropName()
     * @see setIdPropName
     */
    public function getIdPropName()
    {
        return static::$ID_PROP;
    }

    /**
     * @param boolean $allowNull
     */
    public function setToArrayAllowNull($allowNull)
    {
        $this->toArrayAllowNull = $allowNull;
    }

    /**
     * @return boolean
     */
    public function getToArrayAllowNull()
    {
        return $this->toArrayAllowNull;
    }
}


text:
local base_total = 0;

function handle_record(record)
    base_total = base_total + record:get("BASEBAL");
end

function complete(result)
    result:set("BASE_TOTAL", base_total);
end


text:
#ifndef _SIRIKATA_NETWORK_IODEFS_HPP_
#define _SIRIKATA_NETWORK_IODEFS_HPP_

#include <sirikata/core/util/Platform.hpp>

// First we forward declare a bunch of Boost.Asio specific classes
// so we can use them without including everything that Boost.Asio
// includes indirectly
namespace boost {

namespace system {
class error_code;
class system_error;
class error_condition;
class error_category;
}

namespace asio {
class io_service;

namespace detail {
template <typename Dispatcher, typename Handler>
class wrapped_handler;
} // namespace detail

} // namespace asio
} // namespace boost

namespace Sirikata {
namespace Network {

// Exposes internal implementation service, allowing implementations to hook,
// directly in, but assumes that we could load alternative plugins with a
// different implementation
typedef boost::asio::io_service InternalIOService;

// Useful typedefs used throughout the Network IO API
typedef std::tr1::function<void()> IOCallback;

// The real classes we provide which attempt to abstract the event queue / IO
// services.
class IOService;
class IOServiceFactory;
class IOTimer;
class IOStrand;
class IOWork;

// Subclasses of internal classes, exposed to allow for safe cross-library
// allocation and use.
class InternalIOWork;
class InternalIOStrand;
class TCPSocket;
class TCPListener;
class TCPResolver;
class UDPSocket;
class UDPResolver;
class DeadlineTimer;

// Subclasses of internal classes which are wrapped by a strand, guaranteeing
// serializability of their event handlers
class StrandTCPSocket;

} // namespace Network
} // namespace Sirikata

#endif //_SIRIKATA_NETWORK_IODEFS_HPP_


text:
'use strict';

const chai = require('chai');
const chaiHTTP = require('chai-http');
chai.use(chaiHTTP);
const request = chai.request;
const expect = chai.expect;
const mongoose = require('mongoose');

const TEST_DB_SERVER = 'mongodb://localhost/test_db';
process.env.DB_SERVER = TEST_DB_SERVER;

let app = require('./test_server');

let server, userToken, drugId;

describe('testing different routes for our server ', () => {
  before((done) =>{
    server = app.listen(4001, ()=>{
      console.log('Server on 4001');
      done();
    });
  });
  after((done) =>{
    mongoose.connection.db.dropDatabase(()=>{
      mongoose.disconnect(() => {
        server.close();
        done();
      });
    });
  });
  it('should POST a new user', (done) => {
    request('localhost:4001')
      .post('/api/user/signup')
      .send({phoneNumber:'1234456', carrier:'sprint', username:'me1', password:'yep'})
      .end((err, res)=>{
        expect(err).to.eql(null);
        expect(res).to.have.status(200);
        expect(res.body).to.have.property('token');
        done();
      });
  });

  it('should not POST a new user', (done) => {
    request('localhost:4001')
      .post('/api/user/signup')
      .send({phoneNumber:'123456078'})
      .end((err, res)=>{
        expect(res).to.have.status(400);
        expect(res.text).to.have.string('Nope');
        done();
      });
  });

  it('should GET a new user', (done) => {
    request('localhost:4001')
      .get('/api/user/signin')
      .auth('me1', 'yep')
      .end((err, res)=>{
        userToken = res.body.token;
        expect(err).to.eql(null);
        expect(res).to.have.status(200);
        expect(res.body).to.have.property('token');
        done();
      });
  });

  it('should not GET a new user due to bad credentials', (done) => {
    request('localhost:4001')
      .get('/api/user/signin')
      .auth('notAUser', 'nope')
      .end((err, res)=>{
        expect(res).to.have.status(404);
        expect(res.body).to.have.string('could not authorize');
        done();
      });
  });

  it('should POST a new drug', (done) =>{
    request('localhost:4001')
      .post('/api/drug/newDrug')
      .set('Authorization', 'Bearer ' + userToken)
      .send({drug: 'zocor'})
      .end((err, res)=>{
        drugId = res.body._id;
        expect(err).to.eql(null);
        expect(res).to.have.status(200);
        expect(res.body.drug).to.eql('zocor');
        done();
      });
  });

  it('should GET a drug', (done) =>{
    request('localhost:4001')
      .get('/api/drug/' + drugId)
      .end((err, res)=>{
        expect(err).to.eql(null);
        expect(res).to.have.status(200);
        expect(res.body.drug).to.eql('zocor');
        done();
      });
  });

  it('should not POST a new drug due to no drug being sent', (done) =>{
    request('localhost:4001')
      .post('/api/drug/newDrug')
      .set('Authorization', 'Bearer ' + userToken)
      .end((err, res)=>{
        expect(res).to.have.status(400);
        done();
      });
  });

  it('should not POST a new drug due to no auth token', (done) =>{
    request('localhost:4001')
      .post('/api/drug/newDrug')
      .set('Authorization', 'Bearer ')
      .end((err, res)=>{
        expect(res).to.have.status(401);
        done();
      });
  });

  it('should GET data form the homepage', (done) =>{
    request('localhost:4001')
      .get('/')
      .end((err, res) =>{
        expect(res.text).to.have.string('Welcome to Rx SMS');
        expect(res).to.have.status(200);
        done();
      });
  });

  it('should POST data and get back no interactions', (done) =>{
    request('localhost:4001')
      .post('/inbound')
      .send({HtmlBody:'warfarin', From:'1234456@pm.sprint.com'})
      .end((err, res) =>{
        expect(res).to.have.status(200);
        expect(res.body).to.eql('no interactions found');
        done();
      });
  });

  it('should POST data and get back interactions', (done) =>{
    request('localhost:4001')
      .post('/inbound')
      .send({HtmlBody:'verapamil', From:'1234456@pm.sprint.com'})
      .end((err, res) =>{
        expect(res).to.have.status(200);
        expect(res.body).to.eql('Interaction between zocor and Verapamil: The serum concentration of Simvastatin can be increased when it is combined with Verapamil.');
        done();
      });
  });

  it('should GET a drug by id', (done) =>{
    request('localhost:4001')
      .get('/api/drug/' + drugId)
      .end((err, res) =>{
        expect(res).to.have.status(200);
        expect(res.body).to.have.property('interactions');
        done();
      });
  });

});


text:
package com.google.cloud.datalabeling.v1beta1.samples;

// [START datalabeling_v1beta1_generated_datalabelingserviceclient_listinstructions_sync]
import com.google.cloud.datalabeling.v1beta1.DataLabelingServiceClient;
import com.google.cloud.datalabeling.v1beta1.Instruction;
import com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest;
import com.google.cloud.datalabeling.v1beta1.ProjectName;

public class SyncListInstructions {

  public static void main(String[] args) throws Exception {
    syncListInstructions();
  }

  public static void syncListInstructions() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataLabelingServiceClient dataLabelingServiceClient = DataLabelingServiceClient.create()) {
      ListInstructionsRequest request =
          ListInstructionsRequest.newBuilder()
              .setParent(ProjectName.of("[PROJECT]").toString())
              .setFilter("filter-1274492040")
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      for (Instruction element : dataLabelingServiceClient.listInstructions(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END datalabeling_v1beta1_generated_datalabelingserviceclient_listinstructions_sync]


text:
// Copyright 2011-2014 Johann Duscher (a.k.a. Jonny Dee). All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
//    1. Redistributions of source code must retain the above copyright notice, this list of
//       conditions and the following disclaimer.
//
//    2. Redistributions in binary form must reproduce the above copyright notice, this list
//       of conditions and the following disclaimer in the documentation and/or other materials
//       provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY JOHANN DUSCHER ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Johann Duscher.

#ifndef NZMQT_H
#define NZMQT_H

#include "global.hpp"

#include <zmq.hpp>

#include <QByteArray>
#include <QFlag>
#include <QList>
#include <QMetaType>
#include <QMutex>
#include <QObject>
#include <QRunnable>
#include <QVector>
#include <QTimer>

// Define default context implementation to be used.
#ifndef NZMQT_DEFAULT_ZMQCONTEXT_IMPLEMENTATION
    #define NZMQT_DEFAULT_ZMQCONTEXT_IMPLEMENTATION PollingZMQContext
    //#define NZMQT_DEFAULT_ZMQCONTEXT_IMPLEMENTATION SocketNotifierZMQContext
#endif

// Define default number of IO threads to be used by ZMQ.
#ifndef NZMQT_DEFAULT_IOTHREADS
    #define NZMQT_DEFAULT_IOTHREADS 4
#endif

// Define default poll interval for polling-based implementation.
#ifndef NZMQT_POLLINGZMQCONTEXT_DEFAULT_POLLINTERVAL
    #define NZMQT_POLLINGZMQCONTEXT_DEFAULT_POLLINTERVAL 50 /* msec */
#endif

// Declare metatypes for using them in Qt signals.
Q_DECLARE_METATYPE(QList< QList<QByteArray> >)
Q_DECLARE_METATYPE(QList<QByteArray>)

class QSocketNotifier;

namespace nzmqt
{
    typedef zmq::free_fn free_fn;
    typedef zmq::pollitem_t pollitem_t;

    typedef zmq::error_t ZMQException;

    using zmq::poll;
    using zmq::version;

    // This class wraps ZMQ's message structure.
    class NZMQT_API ZMQMessage : private zmq::message_t
    {
        friend class ZMQSocket;

        typedef zmq::message_t super;

    public:
        ZMQMessage();

        ZMQMessage(size_t size_);

        ZMQMessage(void* data_, size_t size_, free_fn *ffn_, void* hint_ = 0);

        ZMQMessage(const QByteArray& b);

        using super::rebuild;

        void move(ZMQMessage* msg_);

        void copy(ZMQMessage* msg_);

        using super::more;

        void clone(ZMQMessage* msg_);

        using super::data;

        using super::size;

        QByteArray toByteArray();
    };

    class ZMQContext;

    // This class cannot be instantiated. Its purpose is to serve as an
    // intermediate base class that provides Qt-based convenience methods
    // to subclasses.
    class NZMQT_API ZMQSocket : public QObject, private zmq::socket_t
    {
        Q_OBJECT
        Q_ENUMS(Type Event SendFlag ReceiveFlag Option)
        Q_FLAGS(Event Events)
        Q_FLAGS(SendFlag SendFlags)
        Q_FLAGS(ReceiveFlag ReceiveFlags)

        typedef QObject qsuper;
        typedef zmq::socket_t zmqsuper;

    public:
        enum Type
        {
            TYP_PUB = ZMQ_PUB,
            TYP_SUB = ZMQ_SUB,
            TYP_PUSH = ZMQ_PUSH,
            TYP_PULL = ZMQ_PULL,
            TYP_REQ = ZMQ_REQ,
            TYP_REP = ZMQ_REP,
            TYP_DEALER = ZMQ_DEALER,
            TYP_ROUTER = ZMQ_ROUTER,
            TYP_PAIR = ZMQ_PAIR,
            TYP_XPUB = ZMQ_XPUB,
            TYP_XSUB = ZMQ_XSUB
        };

        enum Event
        {
            EVT_POLLIN = ZMQ_POLLIN,
            EVT_POLLOUT = ZMQ_POLLOUT,
            EVT_POLLERR = ZMQ_POLLERR
        };
        Q_DECLARE_FLAGS(Events, Event)

        enum SendFlag
        {
            SND_MORE = ZMQ_SNDMORE,
            SND_NOBLOCK = ZMQ_DONTWAIT
        };
        Q_DECLARE_FLAGS(SendFlags, SendFlag)

        enum ReceiveFlag
        {
            RCV_NOBLOCK = ZMQ_DONTWAIT
        };
        Q_DECLARE_FLAGS(ReceiveFlags, ReceiveFlag)

        enum Option
        {
            // Get only.
            OPT_TYPE = ZMQ_TYPE,
            OPT_RCVMORE = ZMQ_RCVMORE,
            OPT_FD = ZMQ_FD,
            OPT_EVENTS = ZMQ_EVENTS,

            // Set only.
            OPT_SUBSCRIBE = ZMQ_SUBSCRIBE,
            OPT_UNSUBSCRIBE = ZMQ_UNSUBSCRIBE,

            // Get and set.
            OPT_AFFINITY = ZMQ_AFFINITY,
            OPT_IDENTITY = ZMQ_IDENTITY,
            OPT_RATE = ZMQ_RATE,
            OPT_RECOVERY_IVL = ZMQ_RECOVERY_IVL,
            OPT_SNDBUF = ZMQ_SNDBUF,
            OPT_RCVBUF = ZMQ_RCVBUF,
            OPT_LINGER = ZMQ_LINGER,
            OPT_RECONNECT_IVL = ZMQ_RECONNECT_IVL,
            OPT_RECONNECT_IVL_MAX = ZMQ_RECONNECT_IVL_MAX,
            OPT_BACKLOG = ZMQ_BACKLOG
        };

        ~ZMQSocket();

        using zmqsuper::operator void *;

        void setOption(Option optName_, const void *optionVal_, size_t optionValLen_);

        void setOption(Option optName_, const char* str_);

        void setOption(Option optName_, const QByteArray& bytes_);

        void setOption(Option optName_, qint32 value_);

        void setOption(Option optName_, quint32 value_);

        void setOption(Option optName_, qint64 value_);

        void setOption(Option optName_, quint64 value_);

        void getOption(Option option_, void *optval_, size_t *optvallen_) const;

        void bindTo(const QString& addr_);

        void bindTo(const char *addr_);

        void connectTo(const QString& addr_);

        void connectTo(const char* addr_);

        bool sendMessage(ZMQMessage& msg_, SendFlags flags_ = SND_NOBLOCK);

        bool sendMessage(const QByteArray& bytes_, SendFlags flags_ = SND_NOBLOCK);

        // Interprets the provided list of byte arrays as a multi-part message
        // and sends them accordingly.
        // If an empty list is provided this method doesn't do anything and returns trua.
        bool sendMessage(const QList<QByteArray>& msg_, SendFlags flags_ = SND_NOBLOCK);

        // Receives a message or a message part.
        bool receiveMessage(ZMQMessage* msg_, ReceiveFlags flags_ = RCV_NOBLOCK);

        // Receives a message.
        // The message is represented as a list of byte arrays representing
        // a message's parts. If the message is not a multi-part message the
        // list will only contain one array.
        QList<QByteArray> receiveMessage();

        // Receives all messages currently available.
        // Each message is represented as a list of byte arrays representing the messages
        // and their parts in case of multi-part messages. If a message isn't a multi-part
        // message the corresponding byte array list will only contain one element.
        // Note that this method won't work with REQ-REP protocol.
        QList< QList<QByteArray> > receiveMessages();

        qint32 fileDescriptor() const;

        Events events() const;

        // Returns true if there are more parts of a multi-part message
        // to be received.
        bool hasMoreMessageParts() const;

        void setIdentity(const char* nameStr_);

        void setIdentity(const QString& name_);

        void setIdentity(const QByteArray& name_);

        QByteArray identity() const;

        void setLinger(int msec_);

        qint32 linger() const;

        void subscribeTo(const char* filterStr_);

        void subscribeTo(const QString& filter_);

        void subscribeTo(const QByteArray& filter_);

        void unsubscribeFrom(const char* filterStr_);

        void unsubscribeFrom(const QString& filter_);

        void unsubscribeFrom(const QByteArray& filter_);

    signals:
//        void messageReceived(const QList<QByteArray>&);
        void readyRead();

    public slots:
        void close();

    protected:
        ZMQSocket(ZMQContext* context_, Type type_);
    private:
        friend class ZMQContext;
//        friend class PollingZMQContext;

        ZMQContext* m_context;
    };
    Q_DECLARE_OPERATORS_FOR_FLAGS(ZMQSocket::Events)
    Q_DECLARE_OPERATORS_FOR_FLAGS(ZMQSocket::SendFlags)
    Q_DECLARE_OPERATORS_FOR_FLAGS(ZMQSocket::ReceiveFlags)

    // This class is an abstract base class for concrete implementations.
    class NZMQT_API ZMQContext : public QObject, private zmq::context_t
    {
        Q_OBJECT

        typedef QObject qsuper;
        typedef zmq::context_t zmqsuper;

        friend class ZMQSocket;

    public:
        ZMQContext(QObject* parent_ = 0, int io_threads_ = NZMQT_DEFAULT_IOTHREADS);

        // Deleting children is necessary, because otherwise the children are deleted after the context
        // which results in a blocking state. So we delete the children before the zmq::context_t
        // destructor implementation is called.
        ~ZMQContext();

        using zmqsuper::operator void*;

        // Creates a socket instance of the specified type and parent.
        // The created instance will have the specified parent
        // (as usual you can also call 'ZMQSocket::setParent()' method to change
        // ownership later on). Make sure, however, that the socket's parent
        // belongs to the same thread as the socket instance itself (as it is required
        // by Qt). Otherwise, you will encounter strange errors.
        ZMQSocket* createSocket(ZMQSocket::Type type_, QObject* parent_ = 0);

        virtual void setInterval(int interval_) = 0;

        virtual void setPollTimeOut(long timeout) = 0;

        virtual int getInterval() const = 0;

        virtual long getPollTimeOut() const = 0;
        // Start watching for incoming messages.
        virtual void start() = 0;

        // Stop watching for incoming messages.
        virtual void stop() = 0;

        // Indicates if watching for incoming messages is enabled.
        virtual bool isStopped() const = 0;

    protected:
        typedef QVector<ZMQSocket*> Sockets;

        // Creates a socket instance of the specified type.
        virtual ZMQSocket* createSocketInternal(ZMQSocket::Type type_) = 0;

        virtual void registerSocket(ZMQSocket* socket_);

        // Remove the given socket object from the list of registered sockets.
        virtual void unregisterSocket(ZMQSocket* socket_);

        virtual const Sockets& registeredSockets() const;

    private:
        Sockets m_sockets;
    };

/*
    class ZMQDevice : public QObject, public QRunnable
    {
        Q_OBJECT
        Q_ENUMS(Type)

    public:
        enum Type
        {
            TYP_QUEUE = ZMQ_QUEUE,
            TYP_FORWARDED = ZMQ_FORWARDER,
            TYP_STREAMER = ZMQ_STREAMER
        };

        ZMQDevice(Type type, ZMQSocket* frontend, ZMQSocket* backend);

        void run();

    private:
        Type type_;
        ZMQSocket* frontend_;
        ZMQSocket* backend_;
    };
*/

    class PollingZMQContext;

    // An instance of this class cannot directly be created. Use one
    // of the 'PollingZMQContext::createSocket()' factory methods instead.
    class NZMQT_API PollingZMQSocket : public ZMQSocket
    {
        Q_OBJECT

        typedef ZMQSocket super;

        friend class PollingZMQContext;

    protected:
        PollingZMQSocket(PollingZMQContext* context_, Type type_);

//        // This method is called by the socket's context object in order
//        // to signal a new received message.
//        void onMessageReceived(const QList<QByteArray>& message);
    };

    class NZMQT_API PollingZMQContext : public ZMQContext, public QRunnable
    {
        Q_OBJECT

        typedef ZMQContext super;

    public:
        PollingZMQContext(QObject* parent_ = 0, int io_threads_ = NZMQT_DEFAULT_IOTHREADS);

        // Sets the polling interval.
        // Note that the interval does not denote the time the zmq::poll() function will
        // block in order to wait for incoming messages. Instead, it denotes the time in-between
        // consecutive zmq::poll() calls.
        void setInterval(int interval_);

        void setPollTimeOut(long timeout);

        int getInterval() const;

        long getPollTimeOut() const;

        // Starts the polling process by scheduling a call to the 'run()' method into Qt's event loop.
        void start();

        // Stops the polling process in the sense that no further 'run()' calls will be scheduled into
        // Qt's event loop.
        void stop();

        bool isStopped() const;

    public slots:
        // If the polling process is not stopped (by a previous call to the 'stop()' method) this
        // method will call the 'poll()' method once and re-schedule a subsequent call to this method
        // using the current polling interval.
        void run();

        // This method will poll on all currently available poll-items (known ZMQ sockets)
        // using the given timeout to wait for incoming messages. Note that this timeout has
        // nothing to do with the polling interval. Instead, the poll method will block the current
        // thread by waiting at most the specified amount of time for incoming messages.
        // This method is public because it can be called directly if you need to.
        void poll();

    signals:
        // This signal will be emitted by run() method if a call to poll(...) method
        // results in an exception.
        void pollError(int errorNum, const QString& errorMsg);

    protected:
        PollingZMQSocket* createSocketInternal(ZMQSocket::Type type_);

        // Add the given socket to list list of poll-items.
        void registerSocket(ZMQSocket* socket_);

        // Remove the given socket object from the list of poll-items.
        void unregisterSocket(ZMQSocket* socket_);

    private:
        typedef QVector<pollitem_t> PollItems;

        QTimer tmer;
        long timeout;
        PollItems m_pollItems;
        QMutex m_pollItemsMutex;
        int m_interval;
        volatile bool m_stopped;
    };

    // An instance of this class cannot directly be created. Use one
    // of the 'SocketNotifierZMQContext::createSocket()' factory methods instead.
    class NZMQT_API SocketNotifierZMQSocket : public ZMQSocket
    {
        Q_OBJECT

        friend class SocketNotifierZMQContext;

        typedef ZMQSocket super;

//    public:
//        using super::sendMessage;

//        bool sendMessage(const QByteArray& bytes_, SendFlags flags_ = SND_NOBLOCK);

    protected:
        SocketNotifierZMQSocket(ZMQContext* context_, Type type_);

    protected slots:
        void socketReadActivity();

//        void socketWriteActivity();

    private:
        QSocketNotifier *socketNotifyRead_;
//        QSocketNotifier *socketNotifyWrite_;
    };

    class NZMQT_API SocketNotifierZMQContext : public ZMQContext
    {
        Q_OBJECT

        typedef ZMQContext super;

    public:
        SocketNotifierZMQContext(QObject* parent_ = 0, int io_threads_ = NZMQT_DEFAULT_IOTHREADS);

        void start();

        void stop();

        bool isStopped() const;

    protected:
        SocketNotifierZMQSocket* createSocketInternal(ZMQSocket::Type type_);
    };

    NZMQT_API inline ZMQContext* createDefaultContext(QObject* parent_ = 0, int io_threads_ = NZMQT_DEFAULT_IOTHREADS)
    {
        return new NZMQT_DEFAULT_ZMQCONTEXT_IMPLEMENTATION(parent_, io_threads_);
    }
}

#if !defined(NZMQT_LIB)
 #include "impl.hpp"
#endif

#endif // NZMQT_H


text:
namespace MinVR {

using namespace G3D;

DisplayTile::DisplayTile(
    Vector3 topLeftCorner,
    Vector3 topRightCorner,
    Vector3 botLeftCorner,
    Vector3 botRightCorner,
    TileRenderType tileRenderType,
    double  nearClipPlane,
    double  farClipPlane,
    int viewportXpos,
    int viewportYpos,
    int viewportWidth,
    int viewportHeight)
{
  topLeft = topLeftCorner;
  topRight = topRightCorner;
  botLeft = botLeftCorner;
  botRight = botRightCorner;
  renderType = tileRenderType;
  nearClip = nearClipPlane;
  farClip = farClipPlane;
  viewportX = viewportXpos;
  viewportY = viewportYpos;
  viewportW = viewportWidth;
  viewportH = viewportHeight;

  calculateRoomToTile();
}

DisplayTile::~DisplayTile()
{
}

void
DisplayTile::calculateRoomToTile()
{
  Vector3 center = (topLeft + topRight + botLeft + botRight) / 4.0;
  Vector3 x = (topRight - topLeft).unit();
  Vector3 y = (topLeft - botLeft).unit();
  Vector3 z = x.cross(y).unit();
  Matrix3 rot(x[0],y[0],z[0],x[1],y[1],z[1],x[2],y[2],z[2]);
  CoordinateFrame tile2room(rot, center);
  room2tile = tile2room.inverse();
}

const DisplayTile&
DisplayTile::defaultDesktopTile()
{
  static DisplayTile d(Vector3(-0.65, 0.5, 0.0),
                       Vector3( 0.65, 0.5, 0.0),
                       Vector3(-0.65,-0.5, 0.0),
                       Vector3( 0.65,-0.5, 0.0),
                       TILE_MONO, 0.01, 100);
  return d;
}

} // end namespace