text:
Ext.namespace("GeoExt.data");

/** api: (define)
 *  module = GeoExt.data
 *  class = PrintPage
 *  base_link = `Ext.util.Observable <http://dev.sencha.com/deploy/dev/docs/?class=Ext.util.Observable>`_
 */

/** api: constructor
 *  .. class:: PrintPage
 *
 *  Provides a representation of a print page for
 *  :class:`GeoExt.data.PrintProvider`. The extent of the page is stored as
 *  ``OpenLayers.Feature.Vector``. Widgets can use this to display the print
 *  extent on the map.
 */
GeoExt.data.PrintPage = Ext.extend(Ext.util.Observable, {

    /** api:config[printProvider]
     * :class:`GeoExt.data.PrintProvider` The print provider to use with
     * this page.
     */

    /** private: property[printProvider]
     *  :class:`GeoExt.data.PrintProvider`
     */
    printProvider: null,

    /** api: property[feature]
     *  ``OpenLayers.Feature.Vector`` Feature representing the page extent. To
     *  get the extent of the print page for a specific map, use
     *  ``getPrintExtent``.
     *  Read-only.
     */
    feature: null,

    /** api: property[center]
     *  ``OpenLayers.LonLat`` The current center of the page. Read-only.
     */
    center: null,

    /** api: property[scale]
     *  ``Ext.data.Record`` The current scale record of the page. Read-only.
     */
    scale: null,

    /** api: property[rotation]
     *  ``Float`` The current rotation of the page. Read-only.
     */
    rotation: 0,

    /** api:config[customParams]
     *  ``Object`` Key-value pairs of additional parameters that the
     *  printProvider will send to the print service for this page.
     */

    /** api: property[customParams]
     *  ``Object`` Key-value pairs of additional parameters that the
     *  printProvider will send to the print service for this page.
     */
    customParams: null,

    /** private: method[constructor]
     *  Private constructor override.
     */
    constructor: function(config) {
        this.initialConfig = config;
        Ext.apply(this, config);

        if(!this.customParams) {
            this.customParams = {};
        }

        this.addEvents(
            /** api: event[change]
             *  Triggered when any of the page properties have changed
             *
             *  Listener arguments:
             *
             *  * printPage - :class:`GeoExt.data.PrintPage` this printPage
             *  * modifications - ``Object`` Object with one or more of
             *      ``scale``, ``center`` and ``rotation``, notifying
             *      listeners of the changed properties.
             */
            "change"
        );

        GeoExt.data.PrintPage.superclass.constructor.apply(this, arguments);

        this.feature = new OpenLayers.Feature.Vector(
            OpenLayers.Geometry.fromWKT("POLYGON((-1 -1,1 -1,1 1,-1 1,-1 -1))"));

        if(this.printProvider.capabilities) {
            this.setScale(this.printProvider.scales.getAt(0));
        } else {
            this.printProvider.on({
                "loadcapabilities": function() {
                    this.setScale(this.printProvider.scales.getAt(0));
                },
                scope: this,
                single: true
            });
        }

        this.printProvider.on({
            "layoutchange": this.onLayoutChange,
            scope: this
        });
    },

    /** api: method[getPrintExtent]
     *  :param map: ``OpenLayers.Map`` or :class:`GeoExt.MapPanel` the map to
     *      get the print extent for.
     *  :returns: ``OpenLayers.Bounds``
     *
     *  Gets this page's print extent for the provided map.
     */
    getPrintExtent: function(map) {
        map = map instanceof GeoExt.MapPanel ? map.map : map;
        return this.calculatePageBounds(this.scale, map.getUnits());
    },

    /** api: method[setScale]
     *  :param scale: ``Ext.data.Record`` The new scale record.
     *  :param units: ``String`` map units to use for the scale calculation.
     *      Optional if the ``feature`` is on a layer which is added to a map.
     *      If not found, "dd" will be assumed.
     *
     *  Updates the page geometry to match a given scale. Since this takes the
     *  current layout of the printProvider into account, this can be used to
     *  update the page geometry feature when the layout has changed.
     */
    setScale: function(scale, units) {
        var bounds = this.calculatePageBounds(scale, units);
        var geom = bounds.toGeometry();
        var rotation = this.rotation;
        if(rotation != 0) {
            geom.rotate(-rotation, geom.getCentroid());
        }
        this.updateFeature(geom, {scale: scale});
    },

    /** api: method[setCenter]
     *  :param center: ``OpenLayers.LonLat`` The new center.
     *
     *  Moves the page extent to a new center.
     */
    setCenter: function(center) {
        var geom = this.feature.geometry;
        var oldCenter = geom.getBounds().getCenterLonLat();
        var dx = center.lon - oldCenter.lon;
        var dy = center.lat - oldCenter.lat;
        geom.move(dx, dy);
        this.updateFeature(geom, {center: center});
    },

    /** api: method[setRotation]
     *  :param rotation: ``Float`` The new rotation.
     *  :param force: ``Boolean`` If set to true, the rotation will also be
     *      set when the layout does not support it. Default is false.
     *
     *  Sets a new rotation for the page geometry.
     */
    setRotation: function(rotation, force) {
        if(force || this.printProvider.layout.get("rotation") === true) {
            var geom = this.feature.geometry;
            geom.rotate(this.rotation - rotation, geom.getCentroid());
            this.updateFeature(geom, {rotation: rotation});
        }
    },

    /** api: method[fit]
     *  :param fitTo: :class:`GeoExt.MapPanel` or ``OpenLayers.Map`` or ``OpenLayers.Feature.Vector``
     *      The map or feature to fit the page to.
     *  :param options: ``Object`` Additional options to determine how to fit
     *
     *  Fits the page layout to a map or feature extent. If the map extent has
     *  not been centered yet, this will do nothing.
     *
     *  Available options:
     *
     *  * mode - ``String`` How to calculate the print extent? If "closest",
     *    the closest matching print extent will be chosen. If "printer", the
     *    chosen print extent will be the closest one that can show the entire
     *    ``fitTo`` extent on the printer. If "screen", it will be the closest
     *    one that is entirely visible inside the ``fitTo`` extent. Default is
     *    "printer".
     *
     */
    fit: function(fitTo, options) {
        options = options || {};
        var map = fitTo, extent;
        if(fitTo instanceof GeoExt.MapPanel) {
            map = fitTo.map;
        } else if(fitTo instanceof OpenLayers.Feature.Vector) {
            map = fitTo.layer.map;
            extent = fitTo.geometry.getBounds();
        }
        if(!extent) {
            extent = map.getExtent();
            if(!extent) {
                return;
            }
        }
        this._updating = true;
        var center = extent.getCenterLonLat();
        this.setCenter(center);
        var units = map.getUnits();
        var scale = this.printProvider.scales.getAt(0);
        var closest = Number.POSITIVE_INFINITY;
        var mapWidth = extent.getWidth();
        var mapHeight = extent.getHeight();
        this.printProvider.scales.each(function(rec) {
            var bounds = this.calculatePageBounds(rec, units);
            if (options.mode == "closest") {
                var diff =
                    Math.abs(bounds.getWidth() - mapWidth) +
                    Math.abs(bounds.getHeight() - mapHeight);
                if (diff < closest) {
                    closest = diff;
                    scale = rec;
                }
            } else {
                var contains = options.mode == "screen" ?
                    !extent.containsBounds(bounds) :
                    bounds.containsBounds(extent);
                if (contains || (options.mode == "screen" && !contains)) {
                    scale = rec;
                }
                return contains;
            }
        }, this);
        this.setScale(scale, units);
        delete this._updating;
        this.updateFeature(this.feature.geometry, {
            center: center,
            scale: scale
        });
    },

    /** private: method[updateFeature]
     *  :param geometry: ``OpenLayers.Geometry`` New geometry for the feature.
     *      If not provided, the existing geometry will be left unchanged.
     *  :param mods: ``Object`` An object with one or more of ``scale``,
     *      ``center`` and ``rotation``, reflecting the page properties to
     *      update.
     *
     *  Updates the page feature with a new geometry and notifies listeners
     *  of changed page properties.
     */
    updateFeature: function(geometry, mods) {
        var f = this.feature;
        var modified = f.geometry !== geometry;
        geometry.id = f.geometry.id;
        f.geometry = geometry;

        if(!this._updating) {
            for(var property in mods) {
                if(mods[property] === this[property]) {
                    delete mods[property];
                } else {
                    this[property] = mods[property];
                    modified = true;
                }
            }
            Ext.apply(this, mods);

            f.layer && f.layer.drawFeature(f);
            modified && this.fireEvent("change", this, mods);
        }
    },

    /** private: method[calculatePageBounds]
     *  :param scale: ``Ext.data.Record`` Scale record to calculate the page
     *      bounds for.
     *  :param units: ``String`` Map units to use for the scale calculation.
     *      Optional if ``feature`` is added to a layer which is added to a
     *      map. If not provided, "dd" will be assumed.
     *  :return: ``OpenLayers.Bounds``
     *
     *  Calculates the page bounds for a given scale.
     */
    calculatePageBounds: function(scale, units) {
        var s = scale.get("value");
        var f = this.feature;
        var geom = this.feature.geometry;
        var center = geom.getBounds().getCenterLonLat();

        var size = this.printProvider.layout.get("size");
        var units = units ||
            (f.layer && f.layer.map && f.layer.map.getUnits()) ||
            "dd";
        var unitsRatio = OpenLayers.INCHES_PER_UNIT[units];
        var w = size.width / 72 / unitsRatio * s / 2;
        var h = size.height / 72 / unitsRatio * s / 2;

        return new OpenLayers.Bounds(center.lon - w, center.lat - h,
            center.lon + w, center.lat + h);
    },

    /** private: method[onLayoutChange]
     *  Handler for the printProvider's layoutchange event.
     */
    onLayoutChange: function() {
        if(this.printProvider.layout.get("rotation") === false) {
            this.setRotation(0, true);
        }
        // at init time the print provider triggers layoutchange
        // before loadcapabilities, i.e. before we set this.scale
        // to the first scale in the scales store, we need to
        // guard against that
        this.scale && this.setScale(this.scale);
    },

    /** private: method[destroy]
     */
    destroy: function() {
        this.printProvider.un("layoutchange", this.onLayoutChange, this);
    }

});


text:
- Supports RTSP, RTMP/RTMPE/RTMPT/RTMPTE, and HTTP.
- Supports only H.264 video and AAC audio (AAC-LC, HE-AAC v1/v2).

### Installation without Docker

    $ git clone https://github.com/iizukanao/node-rtsp-rtmp-server.git
    $ cd node-rtsp-rtmp-server
    $ npm install -d

Also, install [CoffeeScript](https://coffeescript.org/) 1.x or 2.x.

### Configuration

Edit `config.coffee`.

### Starting the server

    $ cd node-rtsp-rtmp-server
    $ sudo coffee server.coffee

or use Node.js directly:

    $ cd node-rtsp-rtmp-server
    $ coffee -c *.coffee
    $ sudo node server.js

If both `serverPort` and `rtmpServerPort` are >= 1024 in `config.coffee`, `sudo` is not needed.

### Docker Deploy Method

If you would prefer building and executing this code in a docker container, you can do so by first building the container and then running it.

    $  make build
    $  make console

You may also want to use just `make run` to run the container as a daemon.  If you fiddle with the ports, you'll need to update the values in the Makefile as well to expose the desired ports to your system.

### Serving MP4 files as recorded streams

MP4 files in `file` directory will be accessible at either:

- rtsp://localhost:80/file/FILENAME
- rtmp://localhost/file/mp4:FILENAME

For example, file/video.mp4 is available at rtmp://localhost/file/mp4:video.mp4

### Publishing live streams

#### From Flash Media Live Encoder

Flash Media Live Encoder is a free live encoder from Adobe.

In the Encoding Options panel, check "Stream to Flash Media Server" and set the URL to:

- **FMS URL**:  rtmp://localhost/live
- **Backup URL**: (blank)
- **Stream**: STREAM_NAME (whatever name you would like)

Press the "Connect" button. Set the video format to H.264, and the audio format to AAC. Press the "Start" button.

When you watch the stream over RTSP or RTMP, use the stream name specified above.

#### From FFmpeg

If you have an MP4 file with H.264 video and AAC audio:

    $ ffmpeg -re -i input.mp4 -c:v copy -c:a copy -f flv rtmp://localhost/live/STREAM_NAME

Or if you have an MP4 file that is encoded in other audio/video format:

    $ ffmpeg -re -i input.mp4 -c:v libx264 -preset fast -c:a libfdk_aac -ab 128k -ar 44100 -f flv rtmp://localhost/live/STREAM_NAME

Replace `input.mp4` with live audio/video sources.

#### From RTSP client

You can publish streams from RTSP client such as FFmpeg.

    $ ffmpeg -re -i input.mp4 -c:v libx264 -preset fast -c:a libfdk_aac -ab 128k -ar 44100 -f rtsp rtsp://localhost:80/live/STREAM_NAME

Or you can publish it over TCP instead of UDP, by specifying `-rtsp_transport tcp` option. TCP is favorable if you publish large data from FFmpeg.

    $ ffmpeg -re -i input.mp4 -c:v libx264 -preset fast -c:a libfdk_aac -ab 128k -ar 44100 -f rtsp -rtsp_transport tcp rtsp://localhost:80/live/STREAM_NAME

#### From GStreamer

For an MP4 file with H.264 video and AAC audio:

    $ gst-launch-0.10 filesrc location=input.mp4 ! qtdemux name=demux ! \
        flvmux name=mux streamable=true ! queue ! \
        rtmpsink location='rtmp://localhost/live/STREAM_NAME' demux. ! \
        multiqueue name=mq ! h264parse ! mux. demux. ! mq. mq. ! aacparse ! mux.

Replace `input.mp4` with live audio/video sources.

For an RTSP source (at rtsp://192.168.1.1:5000/video1  in this example):

    $ gst-launch-0.10 rtspsrc location=rtsp://192.168.1.1:5000/video1 ! decodebin ! \
        x264enc bitrate=256 tune=zerolatency  ! h264parse ! flvmux name=mux streamable=true ! \
        queue ! rtmpsink location='rtmp://localhost/live/STREAM_NAME'

### Accessing the live stream

#### Via RTSP

RTSP stream is for VLC media player or Android's VideoView.

**RTSP URL**: rtsp://localhost:80/live/STREAM_NAME

Note that the RTSP server runs on port 80 by default.

#### Via RTMP

RTMP stream is for Flash Player. Flowplayer and JW Player are both good free players.

**RTMP URL**: rtmp://localhost/live/STREAM_NAME

If you have rtmpdump installed, you can record the video with:

    $ rtmpdump -v -r rtmp://localhost/live/STREAM_NAME -o dump.flv

redpajama_set_name: RedPajamaGithub


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for Device Provisioning Service.

---

## Getting Started

To build the SDK for Device Provisioning Service, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`

---

## Configuration

### Basic Information

These are the global settings for the IotHub API.

``` yaml
openapi-type: arm
tag: package-2021-10-01
```

### Tag: package-2021-10-01

These settings apply only when `--tag=package-2021-10-01` is specified on the command line.

```yaml $(tag) == 'package-2021-10-01'
input-file:
  - Microsoft.Devices/stable/2021-10-01/service.json
```
---

# Code Generation

## C#

See configuration in [readme.csharp.md](./readme.csharp.md)


text:
import masterSequencer from './master-sequencer';

export default function registerNote(note, beat) {
  this.classed('on', !this.classed('on'));
  masterSequencer.userSequencer.update(beat, note);
}


text:
**Problem:** [kubeflow-pipelines-samples-v2](https://github.com/GoogleCloudPlatform/oss-test-infra/blob/99f29a66aa2c29128099edb7b1a99445ac0633bb/prow/prowjobs/kubeflow/pipelines/kubeflow-pipelines-presubmits.yaml#L153-L164) tests have been flaky, with spurious timeout and failed network connection failures.

**Explanation:** The underlying source of the failure is overloading of mysql. Repeated polling for run status for many runs executed in parallel combined with slow queries due to a large run history results in failed connections to mysql.

**Solution:** The solution to this problem is deleting old runs in order to speed up query execution time. In order to maintain internal consistency of the database, the run cache must also be cleared, otherwise a cache may hit but the run record may not be found.

**Executing the script:**
The following script will delete all runs created before `DATE_THRESHOLD` as defined in the `delete_old_runs.py` script.

First, set the `kubectl` context to the `kfp-ci` test cluster `gke_kfp-ci_us-central1_kfp-standalone-1` associated with the sample test KFP deployment. Then, run the following script:
```
source ./test/tools/clean-mysql-runs/clean-mysql-runs.sh
```


text:
def NumberAppend(Init,Max,step):
    i = Init
    numbers = []
    for i in range(Init,Max):
        print "top number is %s" % i
        numbers.append(i)
        i = i + step + 7 # This sentense don't make sense!!!
        print "bottom number is %s" % i
    print "first", numbers
    i = Init
    for numbers[i] in range(Init,Max):
        print" top numbers[%r] = %r " % (i,numbers[i])
        print "numbers[%r] + step = %r" % (i, numbers[i] + step)
        numbers[i] = numbers[i] + step
        print" bottom numbers[%r] = %r " % (i,numbers[i])

    print "second", numbers
    return numbers

print "The numbers is: ", NumberAppend(0,6,2)

'''
i = 0
numbers = []

while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)

    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" %i

print "The numbes: "

for num in numbers:
    print num
'''


text:
package org.codegist.crest.util.model.jaxb;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

/**
 * @author laurent.gilles@codegist.org
 */
@XmlRootElement(name="someDatas")
public class JaxbSomeDatas {

    private List<JaxbSomeData> someData;

    public List<JaxbSomeData> getSomeData() {
        return someData;
    }

    public void setSomeData(List<JaxbSomeData> someData) {
        this.someData = someData;
    }
}


text:
import {describe, expect, it} from '../../../core/testing/src/testing_internal';
import {CssBlockAst, CssBlockDefinitionRuleAst, CssBlockRuleAst, CssDefinitionAst, CssInlineRuleAst, CssKeyframeDefinitionAst, CssKeyframeRuleAst, CssMediaQueryRuleAst, CssSelectorRuleAst, CssStyleSheetAst, CssStyleValueAst} from '../../src/css_parser/css_ast';
import {BlockType, CssParseError, CssParser, CssToken, ParsedCssResult} from '../../src/css_parser/css_parser';
import {ParseLocation} from '../../src/parse_util';

export function assertTokens(tokens: CssToken[], valuesArr: string[]) {
  for (let i = 0; i < tokens.length; i++) {
    expect(tokens[i].strValue == valuesArr[i]);
  }
}

export function main() {
  describe('CssParser', () => {
    function parse(css: string): ParsedCssResult {
      return new CssParser().parse(css, 'some-fake-css-file.css');
    }

    function makeAst(css: string): CssStyleSheetAst {
      const output = parse(css);
      const errors = output.errors;
      if (errors.length > 0) {
        throw new Error(errors.map((error: CssParseError) => error.msg).join(', '));
      }
      return output.ast;
    }

    it('should parse CSS into a stylesheet Ast', () => {
      const styles = '.selector { prop: value123; }';

      const ast = makeAst(styles);
      expect(ast.rules.length).toEqual(1);

      const rule = <CssSelectorRuleAst>ast.rules[0];
      const selector = rule.selectors[0];
      expect(selector.strValue).toEqual('.selector');

      const block: CssBlockAst = rule.block;
      expect(block.entries.length).toEqual(1);

      const definition = <CssDefinitionAst>block.entries[0];
      expect(definition.property.strValue).toEqual('prop');

      const value = <CssStyleValueAst>definition.value;
      expect(value.tokens[0].strValue).toEqual('value123');
    });

    it('should parse multiple CSS selectors sharing the same set of styles', () => {
      const styles = `
        .class, #id, tag, [attr], key + value, * value, :-moz-any-link {
          prop: value123;
        }
      `;

      const ast = makeAst(styles);
      expect(ast.rules.length).toEqual(1);

      const rule = <CssSelectorRuleAst>ast.rules[0];
      expect(rule.selectors.length).toBe(7);

      const classRule = rule.selectors[0];
      const idRule = rule.selectors[1];
      const tagRule = rule.selectors[2];
      const attrRule = rule.selectors[3];
      const plusOpRule = rule.selectors[4];
      const starOpRule = rule.selectors[5];
      const mozRule = rule.selectors[6];

      assertTokens(classRule.selectorParts[0].tokens, ['.', 'class']);
      assertTokens(idRule.selectorParts[0].tokens, ['.', 'class']);
      assertTokens(attrRule.selectorParts[0].tokens, ['[', 'attr', ']']);

      assertTokens(plusOpRule.selectorParts[0].tokens, ['key']);
      expect(plusOpRule.selectorParts[0].operator.strValue).toEqual('+');
      assertTokens(plusOpRule.selectorParts[1].tokens, ['value']);

      assertTokens(starOpRule.selectorParts[0].tokens, ['*']);
      assertTokens(starOpRule.selectorParts[1].tokens, ['value']);

      assertTokens(mozRule.selectorParts[0].pseudoSelectors[0].tokens, [':', '-moz-any-link']);

      const style1 = <CssDefinitionAst>rule.block.entries[0];
      expect(style1.property.strValue).toEqual('prop');
      assertTokens(style1.value.tokens, ['value123']);
    });

    it('should parse keyframe rules', () => {
      const styles = `
        @keyframes rotateMe {
          from {
            transform: rotate(-360deg);
          }
          50% {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      `;

      const ast = makeAst(styles);
      expect(ast.rules.length).toEqual(1);

      const rule = <CssKeyframeRuleAst>ast.rules[0];
      expect(rule.name.strValue).toEqual('rotateMe');

      const block = <CssBlockAst>rule.block;
      const fromRule = <CssKeyframeDefinitionAst>block.entries[0];

      expect(fromRule.name.strValue).toEqual('from');
      const fromStyle = <CssDefinitionAst>(<CssBlockAst>fromRule.block).entries[0];
      expect(fromStyle.property.strValue).toEqual('transform');
      assertTokens(fromStyle.value.tokens, ['rotate', '(', '-360', 'deg', ')']);

      const midRule = <CssKeyframeDefinitionAst>block.entries[1];

      expect(midRule.name.strValue).toEqual('50%');
      const midStyle = <CssDefinitionAst>(<CssBlockAst>midRule.block).entries[0];
      expect(midStyle.property.strValue).toEqual('transform');
      assertTokens(midStyle.value.tokens, ['rotate', '(', '0', 'deg', ')']);

      const toRule = <CssKeyframeDefinitionAst>block.entries[2];

      expect(toRule.name.strValue).toEqual('to');
      const toStyle = <CssDefinitionAst>(<CssBlockAst>toRule.block).entries[0];
      expect(toStyle.property.strValue).toEqual('transform');
      assertTokens(toStyle.value.tokens, ['rotate', '(', '360', 'deg', ')']);
    });

    it('should parse media queries into a stylesheet Ast', () => {
      const styles = `
        @media all and (max-width:100px) {
          .selector {
            prop: value123;
          }
        }
      `;

      const ast = makeAst(styles);
      expect(ast.rules.length).toEqual(1);

      const rule = <CssMediaQueryRuleAst>ast.rules[0];
      assertTokens(rule.query.tokens, ['all', 'and', '(', 'max-width', ':', '100', 'px', ')']);

      const block = <CssBlockAst>rule.block;
      expect(block.entries.length).toEqual(1);

      const rule2 = <CssSelectorRuleAst>block.entries[0];
      expect(rule2.selectors[0].strValue).toEqual('.selector');

      const block2 = <CssBlockAst>rule2.block;
      expect(block2.entries.length).toEqual(1);
    });

    it('should parse inline CSS values', () => {
      const styles = `
        @import url('remote.css');
        @charset "UTF-8";
        @namespace ng url(http://angular.io/namespace/ng);
      `;

      const ast = makeAst(styles);

      const importRule = <CssInlineRuleAst>ast.rules[0];
      expect(importRule.type).toEqual(BlockType.Import);
      assertTokens(importRule.value.tokens, ['url', '(', 'remote', '.', 'css', ')']);

      const charsetRule = <CssInlineRuleAst>ast.rules[1];
      expect(charsetRule.type).toEqual(BlockType.Charset);
      assertTokens(charsetRule.value.tokens, ['UTF-8']);

      const namespaceRule = <CssInlineRuleAst>ast.rules[2];
      expect(namespaceRule.type).toEqual(BlockType.Namespace);
      assertTokens(
          namespaceRule.value.tokens, ['ng', 'url', '(', 'http://angular.io/namespace/ng', ')']);
    });

    it('should parse CSS values that contain functions and leave the inner function data untokenized',
       () => {
         const styles = `
        .class {
          background: url(matias.css);
          animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
          height: calc(100% - 50px);
          background-image: linear-gradient( 45deg, rgba(100, 0, 0, 0.5), black );
        }
      `;

         const ast = makeAst(styles);
         expect(ast.rules.length).toEqual(1);

         const defs = (<CssSelectorRuleAst>ast.rules[0]).block.entries;
         expect(defs.length).toEqual(4);

         assertTokens((<CssDefinitionAst>defs[0]).value.tokens, ['url', '(', 'matias.css', ')']);
         assertTokens(
             (<CssDefinitionAst>defs[1]).value.tokens,
             ['cubic-bezier', '(', '0.755, 0.050, 0.855, 0.060', ')']);
         assertTokens((<CssDefinitionAst>defs[2]).value.tokens, ['calc', '(', '100% - 50px', ')']);
         assertTokens(
             (<CssDefinitionAst>defs[3]).value.tokens,
             ['linear-gradient', '(', '45deg, rgba(100, 0, 0, 0.5), black', ')']);
       });

    it('should parse un-named block-level CSS values', () => {
      const styles = `
        @font-face {
          font-family: "Matias";
          font-weight: bold;
          src: url(font-face.ttf);
        }
        @viewport {
          max-width: 100px;
          min-height: 1000px;
        }
      `;

      const ast = makeAst(styles);

      const fontFaceRule = <CssBlockRuleAst>ast.rules[0];
      expect(fontFaceRule.type).toEqual(BlockType.FontFace);
      expect(fontFaceRule.block.entries.length).toEqual(3);

      const viewportRule = <CssBlockRuleAst>ast.rules[1];
      expect(viewportRule.type).toEqual(BlockType.Viewport);
      expect(viewportRule.block.entries.length).toEqual(2);
    });

    it('should parse multiple levels of semicolons', () => {
      const styles = `
        ;;;
        @import url('something something')
        ;;;;;;;;
        ;;;;;;;;
        ;@font-face {
          ;src   :   url(font-face.ttf);;;;;;;;
          ;;;-webkit-animation:my-animation
        };;;
        @media all and (max-width:100px)
        {;
          .selector {prop: value123;};
          ;.selector2{prop:1}}
      `;

      const ast = makeAst(styles);

      const importRule = <CssInlineRuleAst>ast.rules[0];
      expect(importRule.type).toEqual(BlockType.Import);
      assertTokens(importRule.value.tokens, ['url', '(', 'something something', ')']);

      const fontFaceRule = <CssBlockRuleAst>ast.rules[1];
      expect(fontFaceRule.type).toEqual(BlockType.FontFace);
      expect(fontFaceRule.block.entries.length).toEqual(2);

      const mediaQueryRule = <CssMediaQueryRuleAst>ast.rules[2];
      assertTokens(
          mediaQueryRule.query.tokens, ['all', 'and', '(', 'max-width', ':', '100', 'px', ')']);
      expect(mediaQueryRule.block.entries.length).toEqual(2);
    });

    it('should throw an error if an unknown @value block rule is parsed', () => {
      const styles = `
        @matias { hello: there; }
      `;

      expect(() => {
        makeAst(styles);
      }).toThrowError(/^CSS Parse Error: The CSS "at" rule "@matias" is not allowed to used here/g);
    });

    it('should parse empty rules', () => {
      const styles = `
        .empty-rule { }
        .somewhat-empty-rule { /* property: value; */ }
        .non-empty-rule { property: value; }
      `;

      const ast = makeAst(styles);

      const rules = ast.rules;
      expect((<CssSelectorRuleAst>rules[0]).block.entries.length).toEqual(0);
      expect((<CssSelectorRuleAst>rules[1]).block.entries.length).toEqual(0);
      expect((<CssSelectorRuleAst>rules[2]).block.entries.length).toEqual(1);
    });

    it('should parse the @document rule', () => {
      const styles = `
        @document url(http://www.w3.org/),
                       url-prefix(http://www.w3.org/Style/),
                       domain(mozilla.org),
                       regexp("https:.*")
        {
          /* CSS rules here apply to:
             - The page "http://www.w3.org/".
             - Any page whose URL begins with "http://www.w3.org/Style/"
             - Any page whose URL's host is "mozilla.org" or ends with
               ".mozilla.org"
             - Any page whose URL starts with "https:" */

          /* make the above-mentioned pages really ugly */
          body {
            color: purple;
            background: yellow;
          }
        }
      `;

      const ast = makeAst(styles);

      const rules = ast.rules;
      const documentRule = <CssBlockDefinitionRuleAst>rules[0];
      expect(documentRule.type).toEqual(BlockType.Document);

      const rule = <CssSelectorRuleAst>documentRule.block.entries[0];
      expect(rule.strValue).toEqual('body');
    });

    it('should parse the @page rule', () => {
      const styles = `
        @page one {
          .selector { prop: value; }
        }
        @page two {
          .selector2 { prop: value2; }
        }
      `;

      const ast = makeAst(styles);

      const rules = ast.rules;

      const pageRule1 = <CssBlockDefinitionRuleAst>rules[0];
      expect(pageRule1.query.strValue).toEqual('@page one');
      expect(pageRule1.query.tokens[0].strValue).toEqual('one');
      expect(pageRule1.type).toEqual(BlockType.Page);

      const pageRule2 = <CssBlockDefinitionRuleAst>rules[1];
      expect(pageRule2.query.strValue).toEqual('@page two');
      expect(pageRule2.query.tokens[0].strValue).toEqual('two');
      expect(pageRule2.type).toEqual(BlockType.Page);

      const selectorOne = <CssSelectorRuleAst>pageRule1.block.entries[0];
      expect(selectorOne.strValue).toEqual('.selector');

      const selectorTwo = <CssSelectorRuleAst>pageRule2.block.entries[0];
      expect(selectorTwo.strValue).toEqual('.selector2');
    });

    it('should parse the @supports rule', () => {
      const styles = `
        @supports (animation-name: "rotate") {
          a:hover { animation: rotate 1s; }
        }
      `;

      const ast = makeAst(styles);

      const rules = ast.rules;

      const supportsRule = <CssBlockDefinitionRuleAst>rules[0];
      assertTokens(supportsRule.query.tokens, ['(', 'animation-name', ':', 'rotate', ')']);
      expect(supportsRule.type).toEqual(BlockType.Supports);

      const selectorOne = <CssSelectorRuleAst>supportsRule.block.entries[0];
      expect(selectorOne.strValue).toEqual('a:hover');
    });

    it('should collect multiple errors during parsing', () => {
      const styles = `
        .class$value { something: something }
        @custom { something: something }
        #id { cool^: value }
      `;

      const output = parse(styles);
      expect(output.errors.length).toEqual(3);
    });

    it('should recover from selector errors and continue parsing', () => {
      const styles = `
        tag& { key: value; }
        .%tag { key: value; }
        #tag$ { key: value; }
      `;

      const output = parse(styles);
      const errors = output.errors;
      const ast = output.ast;

      expect(errors.length).toEqual(3);

      expect(ast.rules.length).toEqual(3);

      const rule1 = <CssSelectorRuleAst>ast.rules[0];
      expect(rule1.selectors[0].strValue).toEqual('tag&');
      expect(rule1.block.entries.length).toEqual(1);

      const rule2 = <CssSelectorRuleAst>ast.rules[1];
      expect(rule2.selectors[0].strValue).toEqual('.%tag');
      expect(rule2.block.entries.length).toEqual(1);

      const rule3 = <CssSelectorRuleAst>ast.rules[2];
      expect(rule3.selectors[0].strValue).toEqual('#tag$');
      expect(rule3.block.entries.length).toEqual(1);
    });

    it('should throw an error when parsing invalid CSS Selectors', () => {
      const styles = '.class[[prop%=value}] { style: val; }';
      const output = parse(styles);
      const errors = output.errors;

      expect(errors.length).toEqual(3);

      expect(errors[0].msg).toMatch(/Unexpected character \[\[\] at column 0:7/g);

      expect(errors[1].msg).toMatch(/Unexpected character \[%\] at column 0:12/g);

      expect(errors[2].msg).toMatch(/Unexpected character \[}\] at column 0:19/g);
    });

    it('should throw an error if an attribute selector is not closed properly', () => {
      const styles = '.class[prop=value { style: val; }';
      const output = parse(styles);
      const errors = output.errors;

      expect(errors[0].msg).toMatch(/Unbalanced CSS attribute selector at column 0:12/g);
    });

    it('should throw an error if a pseudo function selector is not closed properly', () => {
      const styles = 'body:lang(en { key:value; }';
      const output = parse(styles);
      const errors = output.errors;

      expect(errors[0].msg)
          .toMatch(/Character does not match expected Character value \("{" should match "\)"\)/);
    });

    it('should raise an error when a semi colon is missing from a CSS style/pair that isn\'t the last entry',
       () => {
         const styles = `.class {
        color: red
        background: blue
      }`;

         const output = parse(styles);
         const errors = output.errors;

         expect(errors.length).toEqual(1);

         expect(errors[0].msg)
             .toMatch(/The CSS key\/value definition did not end with a semicolon at column 1:15/g);
       });

    it('should parse the inner value of a :not() pseudo-selector as a CSS selector', () => {
      const styles = `div:not(.ignore-this-div) {
        prop: value;
      }`;

      const output = parse(styles);
      const errors = output.errors;
      const ast = output.ast;

      expect(errors.length).toEqual(0);

      const rule1 = <CssSelectorRuleAst>ast.rules[0];
      expect(rule1.selectors.length).toEqual(1);

      const simpleSelector = rule1.selectors[0].selectorParts[0];
      assertTokens(simpleSelector.tokens, ['div']);

      const pseudoSelector = simpleSelector.pseudoSelectors[0];
      expect(pseudoSelector.name).toEqual('not');
      assertTokens(pseudoSelector.tokens, ['.', 'ignore-this-div']);
    });

    it('should parse the inner selectors of a :host-context selector', () => {
      const styles = `body > :host-context(.a, .b, .c:hover) {
        prop: value;
      }`;

      const output = parse(styles);
      const errors = output.errors;
      const ast = output.ast;

      expect(errors.length).toEqual(0);

      const rule1 = <CssSelectorRuleAst>ast.rules[0];
      expect(rule1.selectors.length).toEqual(1);

      const simpleSelector = rule1.selectors[0].selectorParts[1];
      const innerSelectors = simpleSelector.pseudoSelectors[0].innerSelectors;

      assertTokens(innerSelectors[0].selectorParts[0].tokens, ['.', 'a']);
      assertTokens(innerSelectors[1].selectorParts[0].tokens, ['.', 'b']);

      const finalSelector = innerSelectors[2].selectorParts[0];
      assertTokens(finalSelector.tokens, ['.', 'c', ':', 'hover']);
      assertTokens(finalSelector.pseudoSelectors[0].tokens, [':', 'hover']);
    });

    it('should raise parse errors when CSS key/value pairs are invalid', () => {
      const styles = `.class {
        background color: value;
        color: value
        font-size;
        font-weight
      }`;

      const output = parse(styles);
      const errors = output.errors;

      expect(errors.length).toEqual(4);

      expect(errors[0].msg)
          .toMatch(
              /Identifier does not match expected Character value \("color" should match ":"\) at column 1:19/g);

      expect(errors[1].msg)
          .toMatch(/The CSS key\/value definition did not end with a semicolon at column 2:15/g);

      expect(errors[2].msg)
          .toMatch(/The CSS property was not paired with a style value at column 3:8/g);

      expect(errors[3].msg)
          .toMatch(/The CSS property was not paired with a style value at column 4:8/g);
    });

    it('should recover from CSS key/value parse errors', () => {
      const styles = `
        .problem-class { background color: red; color: white; }
        .good-boy-class { background-color: red; color: white; }
       `;

      const output = parse(styles);
      const ast = output.ast;

      expect(ast.rules.length).toEqual(2);

      const rule1 = <CssSelectorRuleAst>ast.rules[0];
      expect(rule1.block.entries.length).toEqual(2);

      const style1 = <CssDefinitionAst>rule1.block.entries[0];
      expect(style1.property.strValue).toEqual('background color');
      assertTokens(style1.value.tokens, ['red']);

      const style2 = <CssDefinitionAst>rule1.block.entries[1];
      expect(style2.property.strValue).toEqual('color');
      assertTokens(style2.value.tokens, ['white']);
    });

    describe('location offsets', () => {
      let styles: string;

      function assertMatchesOffsetAndChar(
          location: ParseLocation, expectedOffset: number, expectedChar: string): void {
        expect(location.offset).toEqual(expectedOffset);
        expect(styles[expectedOffset]).toEqual(expectedChar);
      }

      it('should collect the source span location of each AST node with regular selectors', () => {
        styles = '.problem-class { border-top-right: 1px; color: white; }\n';
        styles += '#good-boy-rule_ { background-color: #fe4; color: teal; }';

        const output = parse(styles);
        const ast = output.ast;
        assertMatchesOffsetAndChar(ast.location.start, 0, '.');
        assertMatchesOffsetAndChar(ast.location.end, 111, '}');

        const rule1 = <CssSelectorRuleAst>ast.rules[0];
        assertMatchesOffsetAndChar(rule1.location.start, 0, '.');
        assertMatchesOffsetAndChar(rule1.location.end, 54, '}');

        const rule2 = <CssSelectorRuleAst>ast.rules[1];
        assertMatchesOffsetAndChar(rule2.location.start, 56, '#');
        assertMatchesOffsetAndChar(rule2.location.end, 111, '}');

        const selector1 = rule1.selectors[0];
        assertMatchesOffsetAndChar(selector1.location.start, 0, '.');
        assertMatchesOffsetAndChar(selector1.location.end, 1, 'p');  // problem-class

        const selector2 = rule2.selectors[0];
        assertMatchesOffsetAndChar(selector2.location.start, 56, '#');
        assertMatchesOffsetAndChar(selector2.location.end, 57, 'g');  // good-boy-rule_

        const block1 = rule1.block;
        assertMatchesOffsetAndChar(block1.location.start, 15, '{');
        assertMatchesOffsetAndChar(block1.location.end, 54, '}');

        const block2 = rule2.block;
        assertMatchesOffsetAndChar(block2.location.start, 72, '{');
        assertMatchesOffsetAndChar(block2.location.end, 111, '}');

        const block1def1 = <CssDefinitionAst>block1.entries[0];
        assertMatchesOffsetAndChar(block1def1.location.start, 17, 'b');  // border-top-right
        assertMatchesOffsetAndChar(block1def1.location.end, 36, 'p');    // px

        const block1def2 = <CssDefinitionAst>block1.entries[1];
        assertMatchesOffsetAndChar(block1def2.location.start, 40, 'c');  // color
        assertMatchesOffsetAndChar(block1def2.location.end, 47, 'w');    // white

        const block2def1 = <CssDefinitionAst>block2.entries[0];
        assertMatchesOffsetAndChar(block2def1.location.start, 74, 'b');  // background-color
        assertMatchesOffsetAndChar(block2def1.location.end, 93, 'f');    // fe4

        const block2def2 = <CssDefinitionAst>block2.entries[1];
        assertMatchesOffsetAndChar(block2def2.location.start, 98, 'c');  // color
        assertMatchesOffsetAndChar(block2def2.location.end, 105, 't');   // teal

        const block1value1 = block1def1.value;
        assertMatchesOffsetAndChar(block1value1.location.start, 35, '1');
        assertMatchesOffsetAndChar(block1value1.location.end, 36, 'p');

        const block1value2 = block1def2.value;
        assertMatchesOffsetAndChar(block1value2.location.start, 47, 'w');
        assertMatchesOffsetAndChar(block1value2.location.end, 47, 'w');

        const block2value1 = block2def1.value;
        assertMatchesOffsetAndChar(block2value1.location.start, 92, '#');
        assertMatchesOffsetAndChar(block2value1.location.end, 93, 'f');

        const block2value2 = block2def2.value;
        assertMatchesOffsetAndChar(block2value2.location.start, 105, 't');
        assertMatchesOffsetAndChar(block2value2.location.end, 105, 't');
      });

      it('should collect the source span location of each AST node with media query data', () => {
        styles = '@media (all and max-width: 100px) { a { display:none; } }';

        const output = parse(styles);
        const ast = output.ast;

        const mediaQuery = <CssMediaQueryRuleAst>ast.rules[0];
        assertMatchesOffsetAndChar(mediaQuery.location.start, 0, '@');
        assertMatchesOffsetAndChar(mediaQuery.location.end, 56, '}');

        const predicate = mediaQuery.query;
        assertMatchesOffsetAndChar(predicate.location.start, 0, '@');
        assertMatchesOffsetAndChar(predicate.location.end, 32, ')');

        const rule = <CssSelectorRuleAst>mediaQuery.block.entries[0];
        assertMatchesOffsetAndChar(rule.location.start, 36, 'a');
        assertMatchesOffsetAndChar(rule.location.end, 54, '}');
      });

      it('should collect the source span location of each AST node with keyframe data', () => {
        styles = '@keyframes rotateAndZoomOut { ';
        styles += 'from { transform: rotate(0deg); } ';
        styles += '100% { transform: rotate(360deg) scale(2); }';
        styles += '}';

        const output = parse(styles);
        const ast = output.ast;

        const keyframes = <CssKeyframeRuleAst>ast.rules[0];
        assertMatchesOffsetAndChar(keyframes.location.start, 0, '@');
        assertMatchesOffsetAndChar(keyframes.location.end, 108, '}');

        const step1 = <CssKeyframeDefinitionAst>keyframes.block.entries[0];
        assertMatchesOffsetAndChar(step1.location.start, 30, 'f');
        assertMatchesOffsetAndChar(step1.location.end, 62, '}');

        const step2 = <CssKeyframeDefinitionAst>keyframes.block.entries[1];
        assertMatchesOffsetAndChar(step2.location.start, 64, '1');
        assertMatchesOffsetAndChar(step2.location.end, 107, '}');
      });

      it('should collect the source span location of each AST node with an inline rule', () => {
        styles = '@import url(something.css)';

        const output = parse(styles);
        const ast = output.ast;

        const rule = <CssInlineRuleAst>ast.rules[0];
        assertMatchesOffsetAndChar(rule.location.start, 0, '@');
        assertMatchesOffsetAndChar(rule.location.end, 25, ')');

        const value = rule.value;
        assertMatchesOffsetAndChar(value.location.start, 8, 'u');
        assertMatchesOffsetAndChar(value.location.end, 25, ')');
      });

      it('should property collect the start/end locations with an invalid stylesheet', () => {
        styles = '#id { something: value';

        const output = parse(styles);
        const ast = output.ast;

        assertMatchesOffsetAndChar(ast.location.start, 0, '#');
        assertMatchesOffsetAndChar(ast.location.end, 22, undefined);
      });
    });

    it('should parse minified CSS content properly', () => {
      // this code was taken from the angular.io webpage's CSS code
      const styles = `
.is-hidden{display:none!important}
.is-visible{display:block!important}
.is-visually-hidden{height:1px;width:1px;overflow:hidden;opacity:0.01;position:absolute;bottom:0;right:0;z-index:1}
.grid-fluid,.grid-fixed{margin:0 auto}
.grid-fluid .c1,.grid-fixed .c1,.grid-fluid .c2,.grid-fixed .c2,.grid-fluid .c3,.grid-fixed .c3,.grid-fluid .c4,.grid-fixed .c4,.grid-fluid .c5,.grid-fixed .c5,.grid-fluid .c6,.grid-fixed .c6,.grid-fluid .c7,.grid-fixed .c7,.grid-fluid .c8,.grid-fixed .c8,.grid-fluid .c9,.grid-fixed .c9,.grid-fluid .c10,.grid-fixed .c10,.grid-fluid .c11,.grid-fixed .c11,.grid-fluid .c12,.grid-fixed .c12{display:inline;float:left}
.grid-fluid .c1.grid-right,.grid-fixed .c1.grid-right,.grid-fluid .c2.grid-right,.grid-fixed .c2.grid-right,.grid-fluid .c3.grid-right,.grid-fixed .c3.grid-right,.grid-fluid .c4.grid-right,.grid-fixed .c4.grid-right,.grid-fluid .c5.grid-right,.grid-fixed .c5.grid-right,.grid-fluid .c6.grid-right,.grid-fixed .c6.grid-right,.grid-fluid .c7.grid-right,.grid-fixed .c7.grid-right,.grid-fluid .c8.grid-right,.grid-fixed .c8.grid-right,.grid-fluid .c9.grid-right,.grid-fixed .c9.grid-right,.grid-fluid .c10.grid-right,.grid-fixed .c10.grid-right,.grid-fluid .c11.grid-right,.grid-fixed .c11.grid-right,.grid-fluid .c12.grid-right,.grid-fixed .c12.grid-right{float:right}
.grid-fluid .c1.nb,.grid-fixed .c1.nb,.grid-fluid .c2.nb,.grid-fixed .c2.nb,.grid-fluid .c3.nb,.grid-fixed .c3.nb,.grid-fluid .c4.nb,.grid-fixed .c4.nb,.grid-fluid .c5.nb,.grid-fixed .c5.nb,.grid-fluid .c6.nb,.grid-fixed .c6.nb,.grid-fluid .c7.nb,.grid-fixed .c7.nb,.grid-fluid .c8.nb,.grid-fixed .c8.nb,.grid-fluid .c9.nb,.grid-fixed .c9.nb,.grid-fluid .c10.nb,.grid-fixed .c10.nb,.grid-fluid .c11.nb,.grid-fixed .c11.nb,.grid-fluid .c12.nb,.grid-fixed .c12.nb{margin-left:0}
.grid-fluid .c1.na,.grid-fixed .c1.na,.grid-fluid .c2.na,.grid-fixed .c2.na,.grid-fluid .c3.na,.grid-fixed .c3.na,.grid-fluid .c4.na,.grid-fixed .c4.na,.grid-fluid .c5.na,.grid-fixed .c5.na,.grid-fluid .c6.na,.grid-fixed .c6.na,.grid-fluid .c7.na,.grid-fixed .c7.na,.grid-fluid .c8.na,.grid-fixed .c8.na,.grid-fluid .c9.na,.grid-fixed .c9.na,.grid-fluid .c10.na,.grid-fixed .c10.na,.grid-fluid .c11.na,.grid-fixed .c11.na,.grid-fluid .c12.na,.grid-fixed .c12.na{margin-right:0}
       `;

      const output = parse(styles);
      const errors = output.errors;
      expect(errors.length).toEqual(0);

      const ast = output.ast;
      expect(ast.rules.length).toEqual(8);
    });

    it('should parse a snippet of keyframe code from animate.css properly', () => {
      // this code was taken from the angular.io webpage's CSS code
      const styles = `
@charset "UTF-8";

/*!
 * animate.css -http://daneden.me/animate
 * Version - 3.5.1
 * Licensed under the MIT license - http://opensource.org/licenses/MIT
 *
 * Copyright (c) 2016 Daniel Eden
 */

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

.animated.infinite {
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}

.animated.hinge {
  -webkit-animation-duration: 2s;
  animation-duration: 2s;
}

.animated.flipOutX,
.animated.flipOutY,
.animated.bounceIn,
.animated.bounceOut {
  -webkit-animation-duration: .75s;
  animation-duration: .75s;
}

@-webkit-keyframes bounce {
  from, 20%, 53%, 80%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    -webkit-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
  }

  40%, 43% {
    -webkit-animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    -webkit-transform: translate3d(0, -30px, 0);
    transform: translate3d(0, -30px, 0);
  }

  70% {
    -webkit-animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    -webkit-transform: translate3d(0, -15px, 0);
    transform: translate3d(0, -15px, 0);
  }

  90% {
    -webkit-transform: translate3d(0,-4px,0);
    transform: translate3d(0,-4px,0);
  }
}
       `;

      const output = parse(styles);
      const errors = output.errors;
      expect(errors.length).toEqual(0);

      const ast = output.ast;
      expect(ast.rules.length).toEqual(6);

      const finalRule = <CssBlockRuleAst>ast.rules[ast.rules.length - 1];
      expect(finalRule.type).toEqual(BlockType.Keyframes);
      expect(finalRule.block.entries.length).toEqual(4);
    });
  });
}


text:
package de.qaware.oss.cloud.nativ.wjax2016;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

import static java.util.Optional.ofNullable;

/**
 * Basic Spring based REST controller for Zwitscher service.
 */
@RestController
@RequestMapping("/tweets")
@RefreshScope
public class ZwitscherController {

    private final ZwitscherRepository repository;

    private String query;
    private int pageSize;

    @Autowired
    public ZwitscherController(ZwitscherRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpEntity<Collection<String>> tweets(@RequestParam(value = "q", required = false) String q) {
        Collection<String> tweets = repository.search(ofNullable(q).orElse(query), pageSize);
        return new ResponseEntity<>(tweets, HttpStatus.OK);
    }

    @Value("${tweet.query:cloudnativenerd}")
    public void setQuery(String query) {
        this.query = query;
    }

    @Value("${tweet.pageSize:42}")
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}


text:
#pragma once
#include "gtest/gtest.h"
#include "testhelper.h"
#include "tiny_dnn/tiny_dnn.h"

using namespace tiny_dnn;

namespace tiny_dnn {

TEST(models, alexnet) {
  models::alexnet nn("alexnet");

  ASSERT_EQ(nn.name(), "alexnet");
  EXPECT_EQ(nn.in_data_size(), serial_size_t(224 * 224 * 3));

  vec_t in(nn.in_data_size());

  // generate random variables
  uniform_rand(in.begin(), in.end(), 0, 1);

  // init wieghts and biases
  nn.weight_init(weight_init::constant(2.0));
  nn.bias_init(weight_init::constant(2.0));
  nn.init_weight();

  // predict
  auto res = nn.predict(in);
}

}  // namespace tiny-dnn


text:
from test_util import *
from autograd import grad

## See Siskind & Pearlmutter (2008), "Nesting forward-mode AD in a
## functional framework", Higher Order and Symbolic Computation
## 21(4):361-76, doi:10.1007/s10990-008-9037-1

def test_nest_hosc():
    shouldBeTwo = grad (lambda x: x * grad (lambda y: x*y) (2.0)) (1.0)
    check_equivalent(shouldBeTwo, 2.0)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.kie.server</groupId>
    <artifactId>kie-server-tests</artifactId>
    <version>8.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>kie-server-integ-tests-jbpm</artifactId>

  <name>KIE :: Execution Server :: Tests :: jBPM Integration Tests</name>
  <description>KIE Execution Server Integration Tests (REST, JMS) with configuration to run on different supported containers.</description>

  <properties>
    <org.jbpm.server.ext.disabled>false</org.jbpm.server.ext.disabled>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-integ-tests-common</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- core deps -->
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-compiler</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-ci</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- kie server deps -->
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-services-common</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <!-- Classes from this dependency already packaged in 'xml-apis:xml-apis'-->
          <groupId>javax.xml.stream</groupId>
          <artifactId>stax-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-services-jbpm</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-client</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-rest-common</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-rest-jbpm</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.jbpm</groupId>
      <artifactId>jbpm-case-mgmt-impl</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- REST -->
    <dependency>
      <groupId>org.jboss.spec.javax.servlet</groupId>
      <artifactId>jboss-servlet-api_3.1_spec</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>tjws</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

   <!--  Stay with httpcomponents: it will save us pain (as opposed to changing from resteasy to cxf to cxf 3.0, etc. -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>fluent-hc</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!-- Replacement for the above excluded 'commons-logging:commons-logging' -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- persistence -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.narayana.jta</groupId>
      <artifactId>narayana-jta</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss</groupId>
      <artifactId>jboss-transaction-spi</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jbpm</groupId>
      <artifactId>jbpm-test-util</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-embedder</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server</artifactId>
      <classifier>webc</classifier>
      <type>war</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server</artifactId>
      <classifier>ee6</classifier>
      <type>war</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server</artifactId>
      <classifier>ee7</classifier>
      <type>war</type>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.jbpm</groupId>
      <artifactId>jbpm-kie-services</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.dashbuilder</groupId>
      <artifactId>dashbuilder-dataset-api</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.subethamail</groupId>
      <artifactId>subethasmtp-wiser</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- This is an artificial dependency to make sure the kie-server-tests modules are executed one at a time during
         parallel build (otherwise the tests fail because of conflicting port binding) -->
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-integ-tests-drools</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-failsafe-plugin</artifactId>
          <configuration>
            <systemPropertyVariables>
              <!-- Values are supplied by specific profiles -->
              <cargo.container.id>${cargo.container.id}</cargo.container.id>
              <cargo.servlet.port>${container.port}</cargo.servlet.port>
              <kie.server.context>${kie.server.context}</kie.server.context>
              <kie.server.war.path>${kie.server.war.path}</kie.server.war.path>
              <weblogic.home>${weblogic.home}</weblogic.home>
              <kie.server.remoting.url>${kie.server.remoting.url}</kie.server.remoting.url>
              <kie.server.base.http.url>${kie.server.base.http.url}</kie.server.base.http.url>
              <kie.server.context.factory>${kie.server.context.factory}</kie.server.context.factory>
              <kie.server.connection.factory>${kie.server.connection.factory}</kie.server.connection.factory>
              <kie.server.jndi.request.queue>${kie.server.jndi.request.queue}</kie.server.jndi.request.queue>
              <kie.server.jndi.response.queue>${kie.server.jndi.response.queue}</kie.server.jndi.response.queue>
              <org.jbpm.server.ext.disabled>${org.jbpm.server.ext.disabled}</org.jbpm.server.ext.disabled>
              <org.drools.server.ext.disabled>true</org.drools.server.ext.disabled>
              <org.jbpm.ui.server.ext.disabled>true</org.jbpm.ui.server.ext.disabled>
              <org.optaplanner.server.ext.disabled>true</org.optaplanner.server.ext.disabled>
              <org.jbpm.case.server.ext.disabled>true</org.jbpm.case.server.ext.disabled>
              <kie.server.testing.kjars.build.settings.xml>${kie.server.testing.kjars.build.settings.xml}</kie.server.testing.kjars.build.settings.xml>
              <org.kie.server.persistence.ds>${org.kie.server.persistence.ds}</org.kie.server.persistence.ds>
              <!-- Some tests need to know which DB they are currently run with -->
              <org.kie.server.datasource.driver.class>${org.kie.server.datasource.driver.class}</org.kie.server.datasource.driver.class>
              <org.jbpm.document.storage>${org.jbpm.document.storage}</org.jbpm.document.storage>
            </systemPropertyVariables>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-resources-plugin</artifactId>
          <configuration>
            <nonFilteredFileExtensions>
              <nonFilteredFileExtension>xls</nonFilteredFileExtension>
            </nonFilteredFileExtensions>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
        <filtering>false</filtering>
      </testResource>
      <testResource>
        <directory>src/test/filtered-resources</directory>
        <filtering>true</filtering>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <groupId>org.codehaus.cargo</groupId>
        <artifactId>cargo-maven2-plugin</artifactId>
        <configuration>
          <container>
            <systemProperties>
              <org.jbpm.server.ext.disabled>${org.jbpm.server.ext.disabled}</org.jbpm.server.ext.disabled>
              <org.jbpm.ui.server.ext.disabled>true</org.jbpm.ui.server.ext.disabled>
              <org.optaplanner.server.ext.disabled>true</org.optaplanner.server.ext.disabled>
              <org.jbpm.case.server.ext.disabled>true</org.jbpm.case.server.ext.disabled>
              <org.drools.server.ext.disabled>true</org.drools.server.ext.disabled>
              <!-- UserInfo properties for UserTaskEscalationIntegrationTest-->
              <org.jbpm.ht.userinfo>props</org.jbpm.ht.userinfo>
              <jbpm.user.info.properties>file://${project.build.testOutputDirectory}/userinfo.properties</jbpm.user.info.properties>
            </systemProperties>
          </container>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
#include <linux/cpu.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/profile.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/interrupt.h>
#include <linux/efi.h>
#include <linux/timex.h>
#include <linux/clocksource.h>
#include <linux/platform_device.h>

#include <asm/machvec.h>
#include <asm/delay.h>
#include <asm/hw_irq.h>
#include <asm/paravirt.h>
#include <asm/ptrace.h>
#include <asm/sal.h>
#include <asm/sections.h>
#include <asm/system.h>

#include "fsyscall_gtod_data.h"

static cycle_t itc_get_cycles(struct clocksource *cs);

struct fsyscall_gtod_data_t fsyscall_gtod_data = {
	.lock = SEQLOCK_UNLOCKED,
};

struct itc_jitter_data_t itc_jitter_data;

volatile int time_keeper_id = 0; /* smp_processor_id() of time-keeper */

#ifdef CONFIG_IA64_DEBUG_IRQ

unsigned long last_cli_ip;
EXPORT_SYMBOL(last_cli_ip);

#endif

#ifdef CONFIG_PARAVIRT
/* We need to define a real function for sched_clock, to override the
   weak default version */
unsigned long long sched_clock(void)
{
        return paravirt_sched_clock();
}
#endif

#ifdef CONFIG_PARAVIRT
static void
paravirt_clocksource_resume(void)
{
	if (pv_time_ops.clocksource_resume)
		pv_time_ops.clocksource_resume();
}
#endif

static struct clocksource clocksource_itc = {
	.name           = "itc",
	.rating         = 350,
	.read           = itc_get_cycles,
	.mask           = CLOCKSOURCE_MASK(64),
	.mult           = 0, /*to be calculated*/
	.shift          = 16,
	.flags          = CLOCK_SOURCE_IS_CONTINUOUS,
#ifdef CONFIG_PARAVIRT
	.resume		= paravirt_clocksource_resume,
#endif
};
static struct clocksource *itc_clocksource;

#ifdef CONFIG_VIRT_CPU_ACCOUNTING

#include <linux/kernel_stat.h>

extern cputime_t cycle_to_cputime(u64 cyc);

/*
 * Called from the context switch with interrupts disabled, to charge all
 * accumulated times to the current process, and to prepare accounting on
 * the next process.
 */
void ia64_account_on_switch(struct task_struct *prev, struct task_struct *next)
{
	struct thread_info *pi = task_thread_info(prev);
	struct thread_info *ni = task_thread_info(next);
	cputime_t delta_stime, delta_utime;
	__u64 now;

	now = ia64_get_itc();

	delta_stime = cycle_to_cputime(pi->ac_stime + (now - pi->ac_stamp));
	if (idle_task(smp_processor_id()) != prev)
		account_system_time(prev, 0, delta_stime, delta_stime);
	else
		account_idle_time(delta_stime);

	if (pi->ac_utime) {
		delta_utime = cycle_to_cputime(pi->ac_utime);
		account_user_time(prev, delta_utime, delta_utime);
	}

	pi->ac_stamp = ni->ac_stamp = now;
	ni->ac_stime = ni->ac_utime = 0;
}

/*
 * Account time for a transition between system, hard irq or soft irq state.
 * Note that this function is called with interrupts enabled.
 */
void account_system_vtime(struct task_struct *tsk)
{
	struct thread_info *ti = task_thread_info(tsk);
	unsigned long flags;
	cputime_t delta_stime;
	__u64 now;

	local_irq_save(flags);

	now = ia64_get_itc();

	delta_stime = cycle_to_cputime(ti->ac_stime + (now - ti->ac_stamp));
	if (irq_count() || idle_task(smp_processor_id()) != tsk)
		account_system_time(tsk, 0, delta_stime, delta_stime);
	else
		account_idle_time(delta_stime);
	ti->ac_stime = 0;

	ti->ac_stamp = now;

	local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(account_system_vtime);

/*
 * Called from the timer interrupt handler to charge accumulated user time
 * to the current process.  Must be called with interrupts disabled.
 */
void account_process_tick(struct task_struct *p, int user_tick)
{
	struct thread_info *ti = task_thread_info(p);
	cputime_t delta_utime;

	if (ti->ac_utime) {
		delta_utime = cycle_to_cputime(ti->ac_utime);
		account_user_time(p, delta_utime, delta_utime);
		ti->ac_utime = 0;
	}
}

#endif /* CONFIG_VIRT_CPU_ACCOUNTING */

static irqreturn_t
timer_interrupt (int irq, void *dev_id)
{
	unsigned long new_itm;

	if (unlikely(cpu_is_offline(smp_processor_id()))) {
		return IRQ_HANDLED;
	}

	platform_timer_interrupt(irq, dev_id);

	new_itm = local_cpu_data->itm_next;

	if (!time_after(ia64_get_itc(), new_itm))
		printk(KERN_ERR "Oops: timer tick before it's due (itc=%lx,itm=%lx)\n",
		       ia64_get_itc(), new_itm);

	profile_tick(CPU_PROFILING);

	if (paravirt_do_steal_accounting(&new_itm))
		goto skip_process_time_accounting;

	while (1) {
		update_process_times(user_mode(get_irq_regs()));

		new_itm += local_cpu_data->itm_delta;

		if (smp_processor_id() == time_keeper_id) {
			/*
			 * Here we are in the timer irq handler. We have irqs locally
			 * disabled, but we don't know if the timer_bh is running on
			 * another CPU. We need to avoid to SMP race by acquiring the
			 * xtime_lock.
			 */
			write_seqlock(&xtime_lock);
			do_timer(1);
			local_cpu_data->itm_next = new_itm;
			write_sequnlock(&xtime_lock);
		} else
			local_cpu_data->itm_next = new_itm;

		if (time_after(new_itm, ia64_get_itc()))
			break;

		/*
		 * Allow IPIs to interrupt the timer loop.
		 */
		local_irq_enable();
		local_irq_disable();
	}

skip_process_time_accounting:

	do {
		/*
		 * If we're too close to the next clock tick for
		 * comfort, we increase the safety margin by
		 * intentionally dropping the next tick(s).  We do NOT
		 * update itm.next because that would force us to call
		 * do_timer() which in turn would let our clock run
		 * too fast (with the potentially devastating effect
		 * of losing monotony of time).
		 */
		while (!time_after(new_itm, ia64_get_itc() + local_cpu_data->itm_delta/2))
			new_itm += local_cpu_data->itm_delta;
		ia64_set_itm(new_itm);
		/* double check, in case we got hit by a (slow) PMI: */
	} while (time_after_eq(ia64_get_itc(), new_itm));
	return IRQ_HANDLED;
}

/*
 * Encapsulate access to the itm structure for SMP.
 */
void
ia64_cpu_local_tick (void)
{
	int cpu = smp_processor_id();
	unsigned long shift = 0, delta;

	/* arrange for the cycle counter to generate a timer interrupt: */
	ia64_set_itv(IA64_TIMER_VECTOR);

	delta = local_cpu_data->itm_delta;
	/*
	 * Stagger the timer tick for each CPU so they don't occur all at (almost) the
	 * same time:
	 */
	if (cpu) {
		unsigned long hi = 1UL << ia64_fls(cpu);
		shift = (2*(cpu - hi) + 1) * delta/hi/2;
	}
	local_cpu_data->itm_next = ia64_get_itc() + delta + shift;
	ia64_set_itm(local_cpu_data->itm_next);
}

static int nojitter;

static int __init nojitter_setup(char *str)
{
	nojitter = 1;
	printk("Jitter checking for ITC timers disabled\n");
	return 1;
}

__setup("nojitter", nojitter_setup);

void __devinit
ia64_init_itm (void)
{
	unsigned long platform_base_freq, itc_freq;
	struct pal_freq_ratio itc_ratio, proc_ratio;
	long status, platform_base_drift, itc_drift;

	/*
	 * According to SAL v2.6, we need to use a SAL call to determine the platform base
	 * frequency and then a PAL call to determine the frequency ratio between the ITC
	 * and the base frequency.
	 */
	status = ia64_sal_freq_base(SAL_FREQ_BASE_PLATFORM,
				    &platform_base_freq, &platform_base_drift);
	if (status != 0) {
		printk(KERN_ERR "SAL_FREQ_BASE_PLATFORM failed: %s\n", ia64_sal_strerror(status));
	} else {
		status = ia64_pal_freq_ratios(&proc_ratio, NULL, &itc_ratio);
		if (status != 0)
			printk(KERN_ERR "PAL_FREQ_RATIOS failed with status=%ld\n", status);
	}
	if (status != 0) {
		/* invent "random" values */
		printk(KERN_ERR
		       "SAL/PAL failed to obtain frequency info---inventing reasonable values\n");
		platform_base_freq = 100000000;
		platform_base_drift = -1;	/* no drift info */
		itc_ratio.num = 3;
		itc_ratio.den = 1;
	}
	if (platform_base_freq < 40000000) {
		printk(KERN_ERR "Platform base frequency %lu bogus---resetting to 75MHz!\n",
		       platform_base_freq);
		platform_base_freq = 75000000;
		platform_base_drift = -1;
	}
	if (!proc_ratio.den)
		proc_ratio.den = 1;	/* avoid division by zero */
	if (!itc_ratio.den)
		itc_ratio.den = 1;	/* avoid division by zero */

	itc_freq = (platform_base_freq*itc_ratio.num)/itc_ratio.den;

	local_cpu_data->itm_delta = (itc_freq + HZ/2) / HZ;
	printk(KERN_DEBUG "CPU %d: base freq=%lu.%03luMHz, ITC ratio=%u/%u, "
	       "ITC freq=%lu.%03luMHz", smp_processor_id(),
	       platform_base_freq / 1000000, (platform_base_freq / 1000) % 1000,
	       itc_ratio.num, itc_ratio.den, itc_freq / 1000000, (itc_freq / 1000) % 1000);

	if (platform_base_drift != -1) {
		itc_drift = platform_base_drift*itc_ratio.num/itc_ratio.den;
		printk("+/-%ldppm\n", itc_drift);
	} else {
		itc_drift = -1;
		printk("\n");
	}

	local_cpu_data->proc_freq = (platform_base_freq*proc_ratio.num)/proc_ratio.den;
	local_cpu_data->itc_freq = itc_freq;
	local_cpu_data->cyc_per_usec = (itc_freq + USEC_PER_SEC/2) / USEC_PER_SEC;
	local_cpu_data->nsec_per_cyc = ((NSEC_PER_SEC<<IA64_NSEC_PER_CYC_SHIFT)
					+ itc_freq/2)/itc_freq;

	if (!(sal_platform_features & IA64_SAL_PLATFORM_FEATURE_ITC_DRIFT)) {
#ifdef CONFIG_SMP
		/* On IA64 in an SMP configuration ITCs are never accurately synchronized.
		 * Jitter compensation requires a cmpxchg which may limit
		 * the scalability of the syscalls for retrieving time.
		 * The ITC synchronization is usually successful to within a few
		 * ITC ticks but this is not a sure thing. If you need to improve
		 * timer performance in SMP situations then boot the kernel with the
		 * "nojitter" option. However, doing so may result in time fluctuating (maybe
		 * even going backward) if the ITC offsets between the individual CPUs
		 * are too large.
		 */
		if (!nojitter)
			itc_jitter_data.itc_jitter = 1;
#endif
	} else
		/*
		 * ITC is drifty and we have not synchronized the ITCs in smpboot.c.
		 * ITC values may fluctuate significantly between processors.
		 * Clock should not be used for hrtimers. Mark itc as only
		 * useful for boot and testing.
		 *
		 * Note that jitter compensation is off! There is no point of
		 * synchronizing ITCs since they may be large differentials
		 * that change over time.
		 *
		 * The only way to fix this would be to repeatedly sync the
		 * ITCs. Until that time we have to avoid ITC.
		 */
		clocksource_itc.rating = 50;

	paravirt_init_missing_ticks_accounting(smp_processor_id());

	/* avoid softlock up message when cpu is unplug and plugged again. */
	touch_softlockup_watchdog();

	/* Setup the CPU local timer tick */
	ia64_cpu_local_tick();

	if (!itc_clocksource) {
		/* Sort out mult/shift values: */
		clocksource_itc.mult =
			clocksource_hz2mult(local_cpu_data->itc_freq,
						clocksource_itc.shift);
		clocksource_register(&clocksource_itc);
		itc_clocksource = &clocksource_itc;
	}
}

static cycle_t itc_get_cycles(struct clocksource *cs)
{
	unsigned long lcycle, now, ret;

	if (!itc_jitter_data.itc_jitter)
		return get_cycles();

	lcycle = itc_jitter_data.itc_lastcycle;
	now = get_cycles();
	if (lcycle && time_after(lcycle, now))
		return lcycle;

	/*
	 * Keep track of the last timer value returned.
	 * In an SMP environment, you could lose out in contention of
	 * cmpxchg. If so, your cmpxchg returns new value which the
	 * winner of contention updated to. Use the new value instead.
	 */
	ret = cmpxchg(&itc_jitter_data.itc_lastcycle, lcycle, now);
	if (unlikely(ret != lcycle))
		return ret;

	return now;
}

static struct irqaction timer_irqaction = {
	.handler =	timer_interrupt,
	.flags =	IRQF_DISABLED | IRQF_IRQPOLL,
	.name =		"timer"
};

static struct platform_device rtc_efi_dev = {
	.name = "rtc-efi",
	.id = -1,
};

static int __init rtc_init(void)
{
	if (platform_device_register(&rtc_efi_dev) < 0)
		printk(KERN_ERR "unable to register rtc device...\n");

	/* not necessarily an error */
	return 0;
}
module_init(rtc_init);

void __init
time_init (void)
{
	register_percpu_irq(IA64_TIMER_VECTOR, &timer_irqaction);
	efi_gettimeofday(&xtime);
	ia64_init_itm();

	/*
	 * Initialize wall_to_monotonic such that adding it to xtime will yield zero, the
	 * tv_nsec field must be normalized (i.e., 0 <= nsec < NSEC_PER_SEC).
	 */
	set_normalized_timespec(&wall_to_monotonic, -xtime.tv_sec, -xtime.tv_nsec);
}

/*
 * Generic udelay assumes that if preemption is allowed and the thread
 * migrates to another CPU, that the ITC values are synchronized across
 * all CPUs.
 */
static void
ia64_itc_udelay (unsigned long usecs)
{
	unsigned long start = ia64_get_itc();
	unsigned long end = start + usecs*local_cpu_data->cyc_per_usec;

	while (time_before(ia64_get_itc(), end))
		cpu_relax();
}

void (*ia64_udelay)(unsigned long usecs) = &ia64_itc_udelay;

void
udelay (unsigned long usecs)
{
	(*ia64_udelay)(usecs);
}
EXPORT_SYMBOL(udelay);

/* IA64 doesn't cache the timezone */
void update_vsyscall_tz(void)
{
}

void update_vsyscall(struct timespec *wall, struct clocksource *c)
{
        unsigned long flags;

        write_seqlock_irqsave(&fsyscall_gtod_data.lock, flags);

        /* copy fsyscall clock data */
        fsyscall_gtod_data.clk_mask = c->mask;
        fsyscall_gtod_data.clk_mult = c->mult;
        fsyscall_gtod_data.clk_shift = c->shift;
        fsyscall_gtod_data.clk_fsys_mmio = c->fsys_mmio;
        fsyscall_gtod_data.clk_cycle_last = c->cycle_last;

	/* copy kernel time structures */
        fsyscall_gtod_data.wall_time.tv_sec = wall->tv_sec;
        fsyscall_gtod_data.wall_time.tv_nsec = wall->tv_nsec;
        fsyscall_gtod_data.monotonic_time.tv_sec = wall_to_monotonic.tv_sec
							+ wall->tv_sec;
        fsyscall_gtod_data.monotonic_time.tv_nsec = wall_to_monotonic.tv_nsec
							+ wall->tv_nsec;

	/* normalize */
	while (fsyscall_gtod_data.monotonic_time.tv_nsec >= NSEC_PER_SEC) {
		fsyscall_gtod_data.monotonic_time.tv_nsec -= NSEC_PER_SEC;
		fsyscall_gtod_data.monotonic_time.tv_sec++;
	}

        write_sequnlock_irqrestore(&fsyscall_gtod_data.lock, flags);
}


text:
import React from 'react'
import state from './state'
import { Link } from 'react-router'
import { map } from 'lodash'
import { relativeName } from './utils'
import ProtoInfo from './protoInfo'
import DocBlock from './docBlock'
import OptionsPopover from './optionsPopover'

export default class EnumBrowser extends React.Component {
  renderEnum(theEnum) {
    let docs;

    // TODO(daicoden) replace test-done with template mechanism, tests will use it to inject this data, others can use it to styleize page
    return (

{theEnum.name}<OptionsPopover placement='right' obj={theEnum} />

        <DocBlock docs={theEnum.documentation} />
        <ProtoInfo infoObject={theEnum}/>
        {this.renderValues(theEnum)}

    );
  }

  renderValues(theEnum) {
    let valueRows = this.renderValueRows(theEnum.value, theEnum);

    return (

Values

              ID
              Name

            {valueRows}

    )
  }

  renderValueRows(values, theEnum) {
    return map(values, (value) => {
      return (
        <tr key={`enum-value-row-${theEnum.fullName}-${value.number}`}>
          <OptionsPopover placement='left' obj={theEnum}/>
          {value.number}
          {value.name}
          {value.documentation}

      );
    });
  }

  render() {
    if (!state.byEnum) {
      return (
Loading
);
    }

    let theEnum = state.byEnum[this.props.params.enum_name];

    if (!theEnum) {
      return (
Enum Not Found
);
    } else {
      return this.renderEnum(theEnum);
    }
  }
}


text:
require 'spec_helper'

describe 'InstallGenerator' do
  it { should be }
end


text:
package com.fanxin.app.fx.others;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class FileUtil {
    private static final String TAG = FileUtil.class.getSimpleName();
    private String local_image_path;

    public FileUtil(Context context,String local_image_path) {
        this.local_image_path = local_image_path;
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /**
     * 保存图片到制定路径
     *
     * @param filepath
     * @param bitmap
     */
    public void saveBitmap(String filename, Bitmap bitmap) {
        if (!isExternalStorageWritable()) {
            Log.i(TAG, "SD卡不可用,保存失败");
            return;
        }

        if (bitmap == null) {
            return;
        }

        try {

            File file = new File(local_image_path,filename);
            FileOutputStream outputstream = new FileOutputStream(file);
            if((filename.indexOf("png") != -1)||(filename.indexOf("PNG") != -1))
            {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputstream);
            }  else{
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputstream);
            }

            outputstream.flush();
            outputstream.close();

        } catch (FileNotFoundException e) {
            Log.i(TAG, e.getMessage());
        } catch (IOException e) {
            Log.i(TAG, e.getMessage());
        }
    }

    /**
     * 返回当前应用 SD 卡的绝对路径 like
     * /storage/sdcard0/Android/data/com.example.test/files
     */
    @SuppressLint("SdCardPath")
    public String getAbsolutePath() {
        File root = new File(local_image_path);
        if(!root.exists()){
            root.mkdirs();

        }

     return local_image_path;

    }

    @SuppressLint("SdCardPath")
    public boolean isBitmapExists(String filename) {
        File dir =new File(local_image_path);
         if(!dir.exists()){
             dir.mkdirs();
            }
                //context.getExternalFilesDir(null);
        File file = new File(dir, filename);

        return file.exists();
    }

}


text:
class AngryMob
  class Target
    # class-level API for Target subclasses to exploit.
    module ClassApi
      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods
        def default_action
          @set_default_action = true
        end

        def actions
          @actions ||= ['nothing']
        end

        def all_actions
          @all_actions ||= from_superclass(:all_actions, ['nothing'])
          @all_actions |= actions
        end

        def default_action_name
          @default_action ||= from_superclass(:default_action_name, nil)
        end
      end
    end
  end
end


text:
The purpose of this repository is to collect and explain the concepts associated
with exclusion limits.
Our aim is to keep it a stand alone resource such that it is understandable with relatively basic knowledge of statistics.
We will provide relevant references to either books or lectures notes at points of assumed knowledge.

Most of the text will be written in the form of Jupyter notebooks within this repository
but there will most likely be an accompanying document where we elaborate on the mathematics
behind the concepts used here.
The notebooks will contain coded examples for the majority of the concepts we introduce throughout the text.

Below we have a series of links to the different chapters with short descriptions.

## Contents

#### Introduction

- [What is an exclusion limit?](https://github.com/tedwards2412/upper-limit/blob/master/Introduction/What_is_an_exclusion_limt.ipynb)
- [Bayesian vs Frequentist](https://github.com/tedwards2412/exclusion-limits/blob/master/Introduction/Bayesian_vs_Frequentist.ipynb)
- Quick guide to using this tool

#### Technical Concepts

- [What is a likelihood](https://github.com/tedwards2412/exclusion-limits/blob/master/Tecnical_concepts/Likelihoods.ipynb)
- What is a test statistic

#### Neyman construction

##### Feldman and Cousins

#### Maximum Likelihood Ratio (MLR)

- What is the Maximum Likelihood Ratio
- Why is the maximum likelihood ratio a good TS

###### Large Sample Limit (Asymptotic behaviour known)

- Wilks' theorem
- Using Wilks' theorem to construct an exclusion limit
- Downward fluctuations in the background

###### Small Sample Limit

#### CLs method

#### Maximum Gap Method

#### Fisher Method

- Fisher Information Matrix

###### Equivalent Counts Method

#### Connection to Bayesian Statistics

#### Visualisation Methods

- Visualisation tools
- Contour plots
- Multidimensional stuff here

#### Conclusions

#### Useful References


text:
package com.cms.test;

/**
 * Created by rkonell on 12/6/14.
 */
import org.mockito.Mockito;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

@Configuration
public class CMSTestContext {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        messageSource.setBasename("i18n/messages");
        messageSource.setUseCodeAsDefaultMessage(true);

        return messageSource;
    }

//    @Bean
//    public GreetingController CMSController() {
//        return Mockito.mock(GreetingController.class);
//    }
}


text:
package com.mongodb;

import com.mongodb.util.TestCase;
import org.bson.types.ObjectId;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class DBCollectionTest extends TestCase {

    @Test
    public void testMultiInsert() {
        DBCollection c = collection;

        DBObject obj = c.findOne();
        assertEquals(obj, null);

        DBObject inserted1 = BasicDBObjectBuilder.start().add("x",1).add("y",2).get();
        DBObject inserted2 = BasicDBObjectBuilder.start().add("x",3).add("y",3).get();
        c.insert(inserted1,inserted2);
    }

    @Test
    public void testCappedCollection() {
        String collectionName = "testCapped";
        int collectionSize = 1000;

        DBCollection c = getDatabase().getCollection(collectionName);
        c.drop();

        DBObject options = new BasicDBObject("capped", true);
        options.put("size", collectionSize);
        c = getDatabase().createCollection(collectionName, options);

        assertEquals(c.isCapped(), true);
    }

    @Test
    public void testDuplicateKeyException() {
        DBCollection c = collection;

        DBObject obj = new BasicDBObject();
        c.insert(obj, WriteConcern.SAFE);
        try {
           c.insert(obj, WriteConcern.SAFE);
           fail();
        }
        catch (MongoException.DuplicateKey e) {
            assertNotNull(e.getCommandResult());
            assertEquals(11000, e.getCode());
        }
    }

    @Test
    public void testFindOne() {
        DBCollection c = collection;

        DBObject obj = c.findOne();
        assertEquals(obj, null);

        obj = c.findOne();
        assertEquals(obj, null);

        obj = c.findOne();
        assertEquals(obj, null);

        // Test that findOne works when fields is specified but no match is found
        // *** This is a Regression test for JAVA-411 ***
        obj = c.findOne(null, new BasicDBObject("_id", true));

        assertEquals(obj, null);

        DBObject inserted = BasicDBObjectBuilder.start().add("x",1).add("y",2).get();
        c.insert(inserted);
        c.insert(BasicDBObjectBuilder.start().add("_id", 123).add("x",2).add("z",2).get());

        obj = c.findOne(123);
        assertEquals(obj.get("_id"), 123);
        assertEquals(obj.get("x"), 2);
        assertEquals(obj.get("z"), 2);

        obj = c.findOne(123, new BasicDBObject("x", 1));
        assertEquals(obj.get("_id"), 123);
        assertEquals(obj.get("x"), 2);
        assertEquals(obj.containsField("z"), false);

        obj = c.findOne(new BasicDBObject("x", 1));
        assertEquals(obj.get("x"), 1);
        assertEquals(obj.get("y"), 2);

        obj = c.findOne(new BasicDBObject("x", 1), new BasicDBObject("y", 1));
        assertEquals(obj.containsField("x"), false);
        assertEquals(obj.get("y"), 2);
    }

    @Test
    public void testFindOneSort(){

    	DBCollection c = collection;

        DBObject obj = c.findOne();
        assertEquals(obj, null);

        c.insert(BasicDBObjectBuilder.start().add("_id", 1).add("x", 100).add("y", "abc").get());
        c.insert(BasicDBObjectBuilder.start().add("_id", 2).add("x", 200).add("y", "abc").get()); //max x
        c.insert(BasicDBObjectBuilder.start().add("_id", 3).add("x", 1).add("y", "abc").get());
        c.insert(BasicDBObjectBuilder.start().add("_id", 4).add("x", -100).add("y", "xyz").get()); //min x
        c.insert(BasicDBObjectBuilder.start().add("_id", 5).add("x", -50).add("y", "zzz").get());  //max y
        c.insert(BasicDBObjectBuilder.start().add("_id", 6).add("x", 9).add("y", "aaa").get());  //min y
        c.insert(BasicDBObjectBuilder.start().add("_id", 7).add("x", 1).add("y", "bbb").get());

        //only sort
        obj = c.findOne(new BasicDBObject(), null, new BasicDBObject("x", 1) );
        assertNotNull(obj);
        assertEquals(4, obj.get("_id"));

        obj = c.findOne(new BasicDBObject(), null, new BasicDBObject("x", -1));
        assertNotNull(obj);
        assertEquals(obj.get("_id"), 2);

        //query and sort
        obj = c.findOne(new BasicDBObject("x", 1), null, BasicDBObjectBuilder.start().add("x", 1).add("y", 1).get() );
        assertNotNull(obj);
        assertEquals(obj.get("_id"), 3);

        obj = c.findOne( QueryBuilder.start("x").lessThan(2).get(), null, BasicDBObjectBuilder.start().add("y", -1).get() );
        assertNotNull(obj);
        assertEquals(obj.get("_id"), 5);

    }

    /**
     * This was broken recently. Adding test.
     */
    @Test
    public void testDropDatabase() throws Exception {
        final Mongo mongo = new MongoClient( "127.0.0.1" );
        mongo.getDB("com_mongodb_unittest_dropDatabaseTest").dropDatabase();
        mongo.close();
    }

    @Test
    public void testDropIndex(){
        DBCollection c = collection;

        c.save( new BasicDBObject( "x" , 1 ) );
        assertEquals( 1 , c.getIndexInfo().size() );

        c.ensureIndex( new BasicDBObject( "x" , 1 ) );
        assertEquals( 2 , c.getIndexInfo().size() );

        c.dropIndexes();
        assertEquals( 1 , c.getIndexInfo().size() );

        c.ensureIndex( new BasicDBObject( "x" , 1 ) );
        assertEquals( 2 , c.getIndexInfo().size() );

        c.ensureIndex( new BasicDBObject( "y" , 1 ) );
        assertEquals( 3 , c.getIndexInfo().size() );

        c.dropIndex( new BasicDBObject( "x" , 1 ) );
        assertEquals( 2 , c.getIndexInfo().size() );

    }

    @Test
    public void testGenIndexName(){
        BasicDBObject o = new BasicDBObject();
        o.put( "x" , 1 );
        assertEquals("x_1", DBCollection.genIndexName(o));

        o.put( "x" , "1" );
        assertEquals("x_1", DBCollection.genIndexName(o));

        o.put( "x" , "2d" );
        assertEquals("x_2d", DBCollection.genIndexName(o));

        o.put( "y" , -1 );
        assertEquals("x_2d_y_-1", DBCollection.genIndexName(o));

        o.put( "x" , 1 );
        o.put( "y" , 1 );
        o.put( "a" , 1 );
        assertEquals( "x_1_y_1_a_1" , DBCollection.genIndexName(o) );

        o = new BasicDBObject();
        o.put( "z" , 1 );
        o.put( "a" , 1 );
        assertEquals( "z_1_a_1" , DBCollection.genIndexName(o) );
    }

    @Test
    public void testDistinct(){
        DBCollection c = collection;

        for ( int i=0; i<100; i++ ){
            BasicDBObject o = new BasicDBObject();
            o.put( "_id" , i );
            o.put( "x" , i % 10 );
            c.save( o );
        }

        List l = c.distinct( "x" );
        assertEquals( 10 , l.size() );

        l = c.distinct( "x" , new BasicDBObject( "_id" , new BasicDBObject( "$gt" , 95 ) ) );
        assertEquals( 4 , l.size() );

    }

    @Test
    public void testEnsureIndex(){
        DBCollection c = collection;

        c.save( new BasicDBObject( "x" , 1 ) );
        assertEquals( 1 , c.getIndexInfo().size() );

        c.ensureIndex( new BasicDBObject( "x" , 1 ) , new BasicDBObject( "unique" , true ) );
        assertEquals( 2 , c.getIndexInfo().size() );
        assertEquals( Boolean.TRUE , c.getIndexInfo().get(1).get( "unique" ) );
    }

    @Test
    public void testEnsureNestedIndex(){
        DBCollection c = collection;

        BasicDBObject newDoc = new BasicDBObject( "x", new BasicDBObject( "y", 1 ) );
        c.save( newDoc );

        assertEquals( 1 , c.getIndexInfo().size() );
        c.ensureIndex( new BasicDBObject("x.y", 1), "nestedIdx1", false);
        assertEquals( 2 , c.getIndexInfo().size() );
    }

    @Test
    public void testIndexExceptions(){
        collection.insert(new BasicDBObject("x", 1));
        collection.insert(new BasicDBObject("x", 1));

        collection.ensureIndex(new BasicDBObject("y", 1));
        collection.resetIndexCache();
        collection.ensureIndex(new BasicDBObject("y", 1)); // make sure this doesn't throw
        collection.resetIndexCache();

        Exception failed = null;
        try {
            collection.ensureIndex(new BasicDBObject("x", 1), new BasicDBObject("unique", true));
        }
        catch ( MongoException.DuplicateKey e ){
            failed = e;
        }
        assertNotNull( failed );

    }

    @Test
    public void testMultiInsertNoContinue() {
        collection.setWriteConcern(WriteConcern.NORMAL);

        try {
            DBObject obj = collection.findOne();
            assertEquals(obj, null);

            ObjectId id = new ObjectId();
            DBObject inserted1 = BasicDBObjectBuilder.start("_id", id).add("x",1).add("y",2).get();
            DBObject inserted2 = BasicDBObjectBuilder.start("_id", id).add("x",3).add("y",4).get();
            DBObject inserted3 = BasicDBObjectBuilder.start().add("x",5).add("y",6).get();
            WriteResult r = collection.insert(inserted1, inserted2, inserted3);
            assertEquals(1, collection.count());
            assertFalse(collection.getWriteConcern().getContinueOnErrorForInsert());

            assertEquals(collection.count(), 1);
        } finally {
            collection.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        }
    }

    @Test
    public void testMultiInsertWithContinue() {
        if (!serverIsAtLeastVersion(2.0)) {
            return;
        }

        DBObject obj = collection.findOne();
        assertEquals(obj, null);

        ObjectId id = new ObjectId();
        DBObject inserted1 = BasicDBObjectBuilder.start("_id", id).add("x",1).add("y",2).get();
        DBObject inserted2 = BasicDBObjectBuilder.start("_id", id).add("x",3).add("y",4).get();
        DBObject inserted3 = BasicDBObjectBuilder.start().add("x",5).add("y",6).get();
        WriteConcern newWC = WriteConcern.SAFE.continueOnError(true);
        try {
            collection.insert(newWC, inserted1, inserted2, inserted3);
            fail("Insert should have failed");
        } catch (MongoException e) {
            assertEquals(11000, e.getCode());
        }
        assertEquals( collection.count(), 2 );
    }

    @Test( expected =  IllegalArgumentException.class )
    public void testDotKeysFail() {
        DBObject obj = BasicDBObjectBuilder.start().add("x",1).add("y",2).add("foo.bar","baz").get();
        collection.insert(obj);
    }

    @Test( expected =  IllegalArgumentException.class )
    public void testNullKeysFail() {
        DBObject obj = BasicDBObjectBuilder.start().add("x",1).add("y",2).add("foo\0bar","baz").get();
        collection.insert(obj);
    }

    @Test( expected =  IllegalArgumentException.class )
    public void testNullKeysFailWhenNested() {
        final BasicDBList list = new BasicDBList();
        list.add(new BasicDBObject("foo\0bar","baz"));
        DBObject obj = BasicDBObjectBuilder.start().add("x", list).get();
        collection.insert(obj);
    }

    @Test
    public void testLazyDocKeysPass() {
        DBObject obj = BasicDBObjectBuilder.start().add("_id", "lazydottest1").add("x",1).add("y",2).add("foo.bar","baz").get();

        //convert to a lazydbobject
        DefaultDBEncoder encoder = new DefaultDBEncoder();
        byte[] encodedBytes = encoder.encode(obj);

        LazyDBDecoder lazyDecoder = new LazyDBDecoder();
        DBObject lazyObj = lazyDecoder.decode(encodedBytes, collection);

        collection.insert(lazyObj);

        DBObject insertedObj = collection.findOne();
        assertEquals("lazydottest1", insertedObj.get("_id"));
        assertEquals(1, insertedObj.get("x"));
        assertEquals(2, insertedObj.get("y"));
        assertEquals("baz", insertedObj.get("foo.bar"));
    }

    @Test
    public void testFindAndUpdateTimeout() {
        checkServerVersion(2.5);
        collection.insert(new BasicDBObject("_id", 1));
        enableMaxTimeFailPoint();
        try {
            collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$set", new BasicDBObject("x", 1)),
                                     false, false, 1, TimeUnit.SECONDS);
            fail("Show have thrown");
        } catch (MongoExecutionTimeoutException e) {
            assertEquals(50, e.getCode());
        } finally {
            disableMaxTimeFailPoint();
        }
    }

    @Test
    public void testFindAndReplaceTimeout() {
        checkServerVersion(2.5);
        collection.insert(new BasicDBObject("_id", 1));
        enableMaxTimeFailPoint();
        try {
            collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("x", 1), false, false,
                                     1, TimeUnit.SECONDS);
            fail("Show have thrown");
        } catch (MongoExecutionTimeoutException e) {
            assertEquals(50, e.getCode());
        } finally {
            disableMaxTimeFailPoint();
        }
    }

    @Test
    public void testFindAndRemoveTimeout() {
        checkServerVersion(2.5);
        collection.insert(new BasicDBObject("_id", 1));
        enableMaxTimeFailPoint();
        try {
            collection.findAndModify(new BasicDBObject("_id", 1), null, null, true, null, false, false, 1, TimeUnit.SECONDS);
            fail("Show have thrown");
        } catch (MongoExecutionTimeoutException e) {
            assertEquals(50, e.getCode());
        } finally {
            disableMaxTimeFailPoint();
        }
    }
}