text:
title: "Develop, Test, Build"
category: "working-with-lineman"
slug: "develop-test-build"
ordinal: 5
---

#### Web Server (Express JS)

Once you've generated a directory structure with the default project template, or cloned a framework project template then it's time to get developing with Lineman.

In your command-line interface:

1. Navigate to your project directory:

   ```bash
   $ cd your-project
   ```
2. Start Lineman's development environment:

   ```bash
   $ lineman run
   ```
3. Point your web-browser at _http://localhost:8000_

#### Test Runner (Testem)

Lineman integrates a full-featured test runner called Testem. Whether you are using the default project template, or have cloned a framework project template you will have a set of default tests within the `spec` directory. Lineman works by compiling all your files whenever it detects a change on disk during `lineman run`.

In another command-line interface session:

```bash
$ lineman spec
```

By default, Lineman configures Testem to re-run tests on every file change and automatically launches Chrome to execute tests using a generated Jasmine specrunner html file:

```bash
TEST'EM 'SCRIPTS!
Open the URL below in a browser to connect.
http://localhost:7357/
━━━━━━━━━━━━━━┓
  Chrome 31.0 ┃
    1/1 ✔     ┃
              ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✔ 1 tests complete.

[Press ENTER to run tests; q to quit]
```

#### Continuous Integration (Testem)

Lineman comes pre-configured to execute your tests using Testems "CI"
mode which will run tests against PhantomJS and yield output in TAP13
format which is easy for CI environments (such as Jenkins) to consume:

[Be sure to install [PhantomJS](http://phantomjs.org/download.html)
first!]

```bash
$ lineman spec-ci
```

The `spec-ci` command will compile your app, and then run tests within PhantomJS 1.9:

```bash
Running "spec-ci" task
ok 1 PhantomJS 1.9 - .helloText then expect(this.result).toEqual("Hello, World!").

1..1
# tests 1
# pass  1
# fail  0

Done, without errors.
```

If you'd like to output your CI report to a file, you can configure this in your
`config/application.js` like so:

``` javascript
'spec-ci': {
  options: {
    reporter: {
      type: 'xunit',
      dest: 'path/to/my/report.xml'
    }
  }
}
```

Other supported reporter types include "dot" and "tap".

#### Build Tool (Grunt)

When you are ready to bundle up your modern-client app and add the compiled JavaScript, HTML, CSS, Images, and Webfonts to your static web server you can use Lineman's build command:

```bash
$ lineman build
```

This will execute all of Lineman's `common` and `dist` phase tasks:

```bash
Running "common" task

Running "coffee:compile" (coffee) task
File generated/js/app.coffee.js created.
File generated/js/spec.coffee.js created.
>> Destination (generated/js/spec-helpers.coffee.js) not written because compiled files were empty.

Running "less:compile" (less) task
>> Destination not written because no source files were found.
File generated/css/app.less.css created.

Running "jshint:files" (jshint) task

Running "handlebars:compile" (handlebars) task
>> Destination not written because compiled files were empty.

Running "jst:compile" (jst) task
File "generated/template/underscore.js" created.

Running "concat:js" (concat) task
File "generated/js/app.js" created.

Running "concat:spec" (concat) task
File "generated/js/spec.js" created.

Running "concat:css" (concat) task
File "generated/css/app.css" created.

Running "images:dev" (images) task
Copying images to 'generated/img'

Running "webfonts:dev" (webfonts) task
Copying webfonts to 'generated/webfonts'

Running "pages:dev" (pages) task
generated/index.html generated from app/pages/index.us

Running "dist" task

Running "uglify:js" (uglify) task
File "dist/js/app.js" created.

Running "cssmin:compress" (cssmin) task
File dist/css/app.css created.

Running "images:dist" (images) task
Copying images to 'dist/img'

Running "webfonts:dist" (webfonts) task
Copying webfonts to 'dist/webfonts'

Running "pages:dist" (pages) task
dist/index.html generated from app/pages/index.us

Done, without errors.
```

Lineman will use Grunt to execute a number of tasks and generate your production bundle in the `dist` folder at the root of your project directory, here's what the output looks like:

``` bash
$ tree dist

dist
├── css
│   └── app.css
├── favicon.ico
├── index.html
└── js
    └── app.js

```

redpajama_set_name: RedPajamaGithub


text:
describe("complete attributes", function() {

    var attributes = [{
            naturalName: "title"
        }, {
            naturalName: "year"
        }, {
            naturalName: "artist",
            possibleValues: [
                "daft punk",
                "moriarty",
                "the rolling stones",
                "abba",
                "electro deluxe"]
        }] ;

    var completer = new Completer( attributes ) ;

    it("complete simple attribute", function() {
        possibleCompletedQueries = completer.getPossibleCompletedQueries( "ar" ) ;
        expect( possibleCompletedQueries.length ).toEqual( 2 ) ;
        expect( possibleCompletedQueries.indexOf("year") >= 0 ).toBe(true) ;
        expect( possibleCompletedQueries.indexOf("artist") >= 0 ).toBe(true) ;
    });

    it("complete simple value", function() {
        possibleCompletedQueries = completer.getPossibleCompletedQueries( "artist:ro" ) ;
        expect( possibleCompletedQueries.length ).toEqual( 2 ) ;
        expect( possibleCompletedQueries.indexOf("the rolling stones") >= 0 ).toBe(true) ;
        expect( possibleCompletedQueries.indexOf("electro deluxe") >= 0 ).toBe(true) ;
    });
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>OpenNI 2.0: openni::VideoMode Class Reference</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

OpenNI 2.0

Main Page

Namespaces

Classes

Files

Class List

Class Index

Class Members

openni

VideoMode

Public Member Functions |
Friends

openni::VideoMode Class Reference

#include <OpenNI.h>

List of all members.

Public Member Functions

 	VideoMode ()

 	VideoMode (const VideoMode &other)

int 	getFps () const

PixelFormat 	getPixelFormat () const

int 	getResolutionX () const

int 	getResolutionY () const

VideoMode & 	operator= (const VideoMode &other)

void 	setFps (int fps)

void 	setPixelFormat (PixelFormat format)

void 	setResolution (int resolutionX, int resolutionY)

Friends

class 	SensorInfo

class 	VideoFrameRef

class 	VideoStream

Detailed Description

Encapsulates a group of settings for a VideoStream. Settings stored include frame rate, resolution, and pixel format.

This class is used as an input for changing the settings of a VideoStream, as well as an output for reporting the current settings of that class. It is also used by SensorInfo to report available video modes of a stream.

Recommended practice is to use SensorInfo::getSupportedVideoModes() to obtain a list of valid video modes, and then to use items from that list to pass new settings to VideoStream. This is much less likely to produce an invalid video mode than instantiating and manually changing objects of this class.

Constructor & Destructor Documentation

          openni::VideoMode::VideoMode
          (
          	)
           [inline]

Default constructor, creates an empty VideoMode object. Application programs should, in most cases, use the copy constructor to copy an existing valid video mode. This is much less error prone that creating and attempting to configure a new VideoMode from scratch.

          openni::VideoMode::VideoMode
          (
          const VideoMode &
          other	)
           [inline]

Copy constructor, creates a new VideoMode identical to an existing VideoMode.

Parameters:

[in]	other	Existing VideoMode to copy.

Member Function Documentation

          int openni::VideoMode::getFps
          (
          	)
           const [inline]

Getter function for the frame rate of this VideoMode.

Returns:

Current frame rate, measured in frames per second.

          PixelFormat openni::VideoMode::getPixelFormat
          (
          	)
           const [inline]

Getter function for the pixel format of this VideoMode.

Returns:

Current pixel format setting of this VideoMode.

          int openni::VideoMode::getResolutionX
          (
          	)
           const [inline]

Getter function for the X resolution of this VideoMode.

Returns:

Current horizontal resolution of this VideoMode, in pixels.

          int openni::VideoMode::getResolutionY
          (
          	)
           const [inline]

Getter function for the Y resolution of this VideoMode.

Returns:

Current vertical resolution of this VideoMode, in pixels.

          VideoMode& openni::VideoMode::operator=
          (
          const VideoMode &
          other	)
           [inline]

Assignment operator. Sets the pixel format, frame rate, and resolution of this VideoMode to equal that of a different VideoMode.

Parameters:

[in]	other	Existing VideoMode to copy settings from.

          void openni::VideoMode::setFps
          (
          int
          fps	)
           [inline]

Setter function for the frame rate. Application use of this function is not recommended. Instead, use SensorInfo::getSupportedVideoModes() to obtain a list of valid video modes.

Parameters:

[in]	fps	Desired new frame rate, measured in frames per second.

          void openni::VideoMode::setPixelFormat
          (
          PixelFormat
          format	)
           [inline]

Setter function for the pixel format of this VideoMode. Application use of this function is not recommended. Instead, use SensorInfo::getSupportedVideoModes() to obtain a list of valid video modes.

Parameters:

[in]	format	Desired new pixel format for this VideoMode.

          void openni::VideoMode::setResolution
          (
          int
          resolutionX,

          int
          resolutionY

          )
          	 [inline]

Setter function for the resolution of this VideoMode. Application use of this function is not recommended. Instead, use SensorInfo::getSupportedVideoModes() to obtain a list of valid video modes.

Parameters:

[in]	resolutionX	Desired new horizontal resolution in pixels.

[in]	resolutionY	Desired new vertical resolution in pixels.

Friends And Related Function Documentation

          friend class SensorInfo [friend]

          friend class VideoFrameRef [friend]

          friend class VideoStream [friend]

The documentation for this class was generated from the following file:

OpenNI.h

<address class="footer">
Generated on Tue Jan 15 2013 19:17:03 for OpenNI 2.0 by

 1.7.6.1
</address>


text:
var toBuffer = require('data-uri-to-buffer')

function parseDataUri (dataUri) {

  return {
    mimeType: normalizeMimeType(parseMimeType(dataUri)),
    data: toBuffer(dataUri)
  }
}

function parseMimeType(uri) {
  return uri.substring(5, uri.indexOf(';'))
}

var prefix = /^(\w+\/)+/
function normalizeMimeType(mime) {
  mime = mime.toLowerCase()
  var once = mime.match(prefix)
  if (!once || !(once = once[1])) {
    return mime
  }
  return mime.replace(prefix, once)

}

module.exports = parseDataUri


text:
import { FC } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { post } from '@waldur/core/api';
import { translate } from '@waldur/i18n';
import { waitForConfirmation } from '@waldur/modal/actions';
import { showErrorResponse, showSuccess } from '@waldur/store/notify';
import { getUser } from '@waldur/workspace/selectors';

import { formatResourceType } from '../utils';

import { ActionItem } from './ActionItem';

const getConfirmationText = (resource) => {
  const context = {
    name: resource.name.toUpperCase(),
    resourceType: formatResourceType(resource) || 'resource',
  };
  return translate(
    'Are you sure you want to unlink {name} {resourceType}? ',
    context,
  );
};

export const UnlinkActionItem: FC<{ resource }> = ({ resource }) => {
  const dispatch = useDispatch();
  const user = useSelector(getUser);
  if (!user.is_staff) {
    return null;
  }
  const callback = async () => {
    try {
      await waitForConfirmation(
        dispatch,
        translate('Unlink resource'),
        getConfirmationText(resource),
      );
    } catch {
      return;
    }

    try {
      await post(`${resource.url}unlink/`);
      dispatch(showSuccess(translate('Resource has been unlinked.')));
    } catch (e) {
      dispatch(showErrorResponse(e, translate('Unable to unlink resource.')));
    }
  };
  return (
    <ActionItem
      title={translate('Unlink')}
      action={callback}
      className="text-danger"
    />
  );
};


text:
> A node service to check weather info periodically and speak out loud

## Getting Started

Install this crontab to execute every hour
```
0 * * * * /usr/local/bin/node /Users/admin/Projects/nau/info-to-speech.git/app.js
```

## Documentation

_(Coming soon)_

## Examples

_(Coming soon)_

## Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com).

## License

Copyright (c) 2014 Thanh Tran
Licensed under the MIT license.


text:
HOME

DESIGN/ORDER

ORDER w QUOTE

MY ACCOUNT

VIEW CART

CONTACT US


text:
package org.apiviewer.standalone.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apiviewer.core.transform.ApiDiscoveryDefinitionConverter;
import org.apiviewer.standalone.dao.StandAloneAPIDao;
import org.apiviewer.standalone.dao.StandAloneAPIEntity;
import org.apiviewer.standalone.dao.StandAloneAPIEntityCollection;
import org.apiviewer.standalone.domain.model.ApiDefinitionModel;
import org.apiviewer.standalone.domain.model.ApiUIDefinitionModel;
import org.apiviewer.standalone.service.ApiViewerQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ApiViewerQueryServiceImpl implements ApiViewerQueryService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApiViewerQueryServiceImpl.class);

	@Autowired
	private StandAloneAPIDao standAloneAPIDaoService;

	private ApiDiscoveryDefinitionConverter converter = new ApiDiscoveryDefinitionConverter();

	@Override
	public List<ApiUIDefinitionModel> getApis() {

		StandAloneAPIEntityCollection collection = standAloneAPIDaoService.getStandAloneAPIs();

		List<ApiUIDefinitionModel> models = new ArrayList<ApiUIDefinitionModel>();

		for (StandAloneAPIEntity standAloneApiEntity : collection.getEntities()) {
			ApiUIDefinitionModel model = new ApiUIDefinitionModel();
			model.setDeployedServiceSpecUrl(standAloneApiEntity.getApiDocLocation());
			String basePath = standAloneApiEntity.getApiDocLocation().substring(0,
					standAloneApiEntity.getApiDocLocation().lastIndexOf("/"));
			model.setDeployedServiceUrl(basePath);
			model.setId(standAloneApiEntity.getId());
			model.setGitRepoName(standAloneApiEntity.getGitRepoName());
			ApiDefinitionModel swaggerModel = null;
			try {
				swaggerModel = converter.getParametersFromJson(standAloneApiEntity.getApiDocLocation());
			} catch (IOException e) {
				LOGGER.info("Exception occured {}", e.getMessage());
			}

			model.setApiDefinition(swaggerModel);

			models.add(model);
		}

		return models;
	}

}


text:
describe('TrackAnnot.view.window.Cesium', function() {
    'use strict';

    var instance = null, chart = null, toggles = null, esj = ExtSpec.Jasmine;

    beforeEach(function() {
        this.addMatchers(esj.Matchers);
        instance = ExtSpec.create("TrackAnnot.view.window.Cesium", function() {
            this.callParent = jasmine.createSpy('callParent').andReturn({});
            this.addEvents = jasmine.createSpy('addEvents');
            this.addStateEvents = jasmine.createSpy('addStateEvents');
            this.on = jasmine.createSpy('on');
            this.fireEvent = jasmine.createSpy('fireEvent');
            ExtSpec.Jasmine.createConfigSpies(this);
        });
        function toggler(name) {
            var state = true;
            return function(v) {
                if (v === undefined) {
                    return state;
                }
                return state = v;
            };
        }
        chart = {
          color: '#1188ff',
          lighting: false
        };
        toggles = ['toggleCurrent', 'togglePoints', 'toggleLine', 'toggleWall', 'toggleAnnotateLine', 'toggleAnnotatePoints'];
        toggles.forEach(function(name) {
            chart[name] = toggler(name);
        });
        chart.centerOnTrack = jasmine.createSpy('centerOnTrack');
        chart.getTrackColor = function() {
          return chart.color;
        };
        chart.setTrackColor = function(val) {
          chart.color = val;
        };
        chart.getTrackColorAsHex = function() {
          return this.getTrackColor().substr(1);
        };
        chart.setTrackColorAsHex = function(hex) {
          this.setTrackColor('#' + hex);
        };
        chart.on = jasmine.createSpy('on');
        chart.setEnableLighting = function(val) {
          chart.lighting = val;
        };
        chart.getEnableLighting = function() {
          return chart.lighting;
        };

        instance.chart = chart;
    });

    describe('centerOnTrack', function() {
       it('should call centerOnTrack of chart', function() {
           instance.centerOnTrack();

           expect(chart.centerOnTrack).toHaveBeenCalled();
       });
    });

    describe('onPointClick', function() {
        it('should forward event', function() {
           var dt = new Date('2014-09-19T15:00Z');
           instance.onPointClick(dt, chart);

           expect(instance.fireEvent).toHaveBeenCalledWith('pointclick', dt, chart);
        });
    });

    describe('getChart', function() {
       it('should return chart', function() {
           expect(instance.getChart()).toEqual(chart);
       });
    });

    describe('initComponent', function() {
        beforeEach(function() {
            var menu = {
                showAt:function() {},
            };
            var colorPicker = jasmine.createSpyObj('textfield', ['setValue']);

            Ext.create = function(name, config) {
                if (name === 'TrackAnnot.view.Metric.Cesium') {
                    return chart;
                } else if (name === 'Ext.menu.Menu') {
                    menu.config = config;
                    return menu;
                } else if (name === 'Ext.form.field.Text') {
                  colorPicker.config = config;
                  return colorPicker;
                }
            };
            instance.initComponent();
        });

        it('should create chart item', function() {
            expect(instance.items).toEqual([chart]);
        });

        it('should forward chart.pointclick event', function() {
            expect(chart.on).toHaveBeenCalledWith('pointclick', instance.onPointClick, instance);
            expect(instance.addEvents).toHaveBeenCalledWith('pointclick');
        });

        it('should register togglechange and colorchange as state change event', function() {
            expect(instance.addEvents).toHaveBeenCalledWith('togglechange', 'colorchange', 'togglelighting');
            expect(instance.addStateEvents).toHaveBeenCalledWith('togglechange', 'colorchange', 'togglelighting');
        });

        it('should add gear tool', function() {
            var tool = instance.tools[0];
            expect(tool.type).toEqual('gear');
        });

        it('should create a actions menu with 11 items', function() {
            expect(instance.actionsMenu.config.items.length).toEqual(11);
        });
    });

    describe('toggleItem', function() {
        var item = null;
        beforeEach(function() {
            item = {itemId: 'toggleCurrent'};
            instance.toggleItem(item, false);
        });

        it('should forward toggle to chart and fire togglechange event', function() {
            expect(chart.toggleCurrent()).toBeFalsy();
            expect(instance.fireEvent).toHaveBeenCalledWith('togglechange', item, false);
        });
    });

    describe('getState', function() {
        it('should add chart toggle states to parent state', function() {
            var state = instance.getState();

            expect(instance.callParent).toHaveBeenCalled();
            var expected = {
                'toggleCurrent': true,
                'togglePoints': true,
                'toggleLine': true,
                'toggleWall': true,
                'toggleAnnotateLine': true,
                'toggleAnnotatePoints': true,
                'color': '1188ff',
                'lighting': false
            };
            expect(state).toEqual(expected);
        });
    });

    describe('applyState', function() {
        it('should check menu items and forward toggle to chart', function() {
            var checkitem = jasmine.createSpyObj('Ext.menu.CheckItem', ['setChecked']);
            var menu = jasmine.createSpyObj('Ext.menu.menu', ['getComponent']);
            menu.getComponent.andReturn(checkitem);
            instance.colorPicker = jasmine.createSpyObj('textfield', ['setValue']);
            instance.actionsMenu = menu;
            var state = {
                'toggleCurrent': false,
                'togglePoints': false,
                'toggleLine': false,
                'toggleWall': false,
                'toggleAnnotateLine': false,
                'toggleAnnotatePoints': false,
                'color': '1188ff',
                'lighting': false
            };

            instance.applyState(state);

            expect(checkitem.setChecked).toHaveBeenCalledWith(false);
            expect(checkitem.setChecked.calls.length).toEqual(7);
            expect(chart.toggleCurrent()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('toggleCurrent');
            expect(chart.togglePoints()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('togglePoints');
            expect(chart.toggleLine()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('toggleLine');
            expect(chart.toggleWall()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('toggleWall');
            expect(chart.toggleAnnotateLine()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('toggleAnnotateLine');
            expect(chart.toggleAnnotatePoints()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('toggleAnnotatePoints');
            expect(instance.colorPicker.setValue).toHaveBeenCalledWith('1188ff');
            expect(chart.getEnableLighting()).toBeFalsy();
            expect(menu.getComponent).toHaveBeenCalledWith('lighting');
        });

        it('should not change menuitem and chart when state is missing for toggle', function() {
            var checkitem = jasmine.createSpyObj('Ext.menu.CheckItem', ['setChecked']);
            var menu = jasmine.createSpyObj('Ext.menu.menu', ['getComponent']);
            menu.getComponent.andReturn(checkitem);
            instance.actionsMenu = menu;
            var state = {};

            instance.applyState(state);

            expect(chart.toggleCurrent()).toBeTruthy();
            expect(chart.togglePoints()).toBeTruthy();
            expect(chart.toggleLine()).toBeTruthy();
            expect(chart.toggleWall()).toBeTruthy();
            expect(chart.toggleAnnotateLine()).toBeTruthy();
            expect(chart.toggleAnnotatePoints()).toBeTruthy();
            expect(menu.getComponent).not.toHaveBeenCalled();
        });
    });

    describe('onColorChange() ', function() {
      var textfield;

      beforeEach(function() {
        textfield = jasmine.createSpyObj('textfield', ['isValid', 'setFieldStyle']);
      });

      describe('with valid value', function() {
        beforeEach(function() {
          textfield.isValid.andReturn(true);

          instance.onColorChange(textfield, '996611');
        });

        it('should set color in chart', function() {
          expect(chart.color).toEqual('#996611');
        });

        it('should change background color of textfield', function() {
          expect(textfield.setFieldStyle).toHaveBeenCalledWith('background: #996611');
        });

        it('should fire colorchange event', function() {
          expect(instance.fireEvent).toHaveBeenCalledWith('colorchange', textfield, '996611');
        });
      });

      describe('with invalid value', function() {
        beforeEach(function() {
          textfield.isValid.andReturn(false);

          instance.onColorChange(textfield, 'red');
        });

        it('should not set color in chart', function() {
          expect(chart.color).toEqual('#1188ff');
        });

        it('should not change background color of textfield', function() {
          expect(textfield.setFieldStyle).not.toHaveBeenCalled();
        });

        it('should not fire colorchange event', function() {
          expect(instance.fireEvent).not.toHaveBeenCalled();
        });

      });
    });
});


text:
tomcat Cookbook CHANGELOG
=========================
This file is used to list changes made in each version of the tomcat cookbook.

v0.15.2
-------
### New Feature
- [COOK-3622] - Add support for Amazon platform to the tomcat cookbook.

### Bug
- [COOK-3379] - Only regenerate keystore and restart tomcat when source files change
- [COOK-1599] - Add retry and delay to tomcat service definition

v0.15.0
-------
### Improvement
- **[COOK-3565](https://tickets.opscode.com/browse/COOK-3565)** - Make server.xml connectors maxThreads params configurable via attributes

### New Feature
- **[COOK-3333](https://tickets.opscode.com/browse/COOK-3333)** - Add SmartOS support

v0.14.4
-------
### Bug
- **[COOK-3378](https://tickets.opscode.com/browse/COOK-3378)** - Use keystore in the port 8443 connector
- **[COOK-3204](https://tickets.opscode.com/browse/COOK-3204)** - Fix hard-coded path to `tomcat-users.xml`
- **[COOK-3203](https://tickets.opscode.com/browse/COOK-3203)** - Support "reload" on Ubuntu 12.04

### Improvement
- **[COOK-3195](https://tickets.opscode.com/browse/COOK-3195)** - Fix error for creating endorsed dir
- **[COOK-3083](https://tickets.opscode.com/browse/COOK-3083)** - Add an attribute to lib directory

v0.14.2
-------
### Bug
- [COOK-3165]: Typo in tomcat attributes/default.rb file for `webapp_dir` attribute on Debian/Ubuntu

v0.14.0
-------
### Sub-task
- [COOK-1808]: Add Support for Tomcat 7 (ubuntu 12.04+, debian 7+)

v0.13.0
-------
### Improvement
- [COOK-2999]: Attributes are "set" and not "default"

### Bug
- [COOK-2421]: Correct name of cookbook in attributes/default.rb
- [COOK-2838]: Fix foodcritic warnings in tomcat cookbook

### New Feature
- [COOK-2422]: Support disabling Tomcat auth
- [COOK-2425]: Add  SSL connector support
- [COOK-2533]: Ability to set loglevel
- [COOK-2736]: Add CATALINA_OPTS for Tomcat start/run options

v0.12.0
-------
- [COOK-1736] - Add AUTHBIND attribute

v0.11.0
-------
- [COOK-1499] - manage tomcat users

v0.10.4
-------
- [COOK-1110] - remove deprecated (by upstream) jpackage recipe


text:
package ar.com.daidalos.afiledialog;

import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import ar.com.daidalos.afiledialog.view.FileItem;

/**
 * This class implements the common features of a file chooser.
 */
class FileChooserCore {

	// ----- Attributes ----- //

	/**
	 * The file chooser in which all the operations are performed.
	 */
	private FileChooser chooser;

	/**
	 * The listeners for the event of select a file.
	 */
	private List<OnFileSelectedListener> listeners;

	/**
	 * A regular expression for filter the files.
	 */
	private String filter;

	/**
	 * A boolean indicating if only the files that can be selected (they pass the filter) must be show.
	 */
	private boolean showOnlySelectable;

	/**
	 * A boolean indicating if the user can create files.
	 */
	private boolean canCreateFiles;

	/**
	 * A boolean indicating if the chooser is going to be used to select folders.
	 */
	private boolean folderMode;

	/**
	 * A file that indicates the folder that is currently being displayed.
	 */
	private File currentFolder;

	/**
	 * This attribut allows to override the default value of the labels.
	 */
	private FileChooserLabels labels;

	/**
	 * A boolean that indicates if a confirmation dialog must be displaying when selecting a file.
	 */
	private boolean showConfirmationOnSelect;

	/**
	 * A boolean that indicates if a confirmation dialog must be displaying when creating a file.
	 */
	private boolean showConfirmationOnCreate;

	/**
	 * A boolean indicating if the folder's full path must be show in the title.
	 */
	private boolean showFullPathInTitle;

	// ---- Static attributes ----- //

	/**
	 * Static attribute for save the folder displayed by default.
	 */
	private static File defaultFolder;

	/**
	 * Static constructor.
	 */
	static {
		defaultFolder = null;
	}

	// ----- Constructor ----- //

	/**
	 * Creates an instance of this class.
	 *
	 * @param fileChooser The graphical file chooser.
	 */
	public FileChooserCore(FileChooser fileChooser) {
		// Initialize attributes.
		this.chooser = fileChooser;
		this.listeners = new LinkedList<OnFileSelectedListener>();
		this.filter = null;
		this.showOnlySelectable = false;
		this.setCanCreateFiles(false);
		this.setFolderMode(false);
		this.currentFolder = null;
		this.labels = null;
		this.showConfirmationOnCreate = false;
		this.showConfirmationOnSelect = false;
		this.showFullPathInTitle = false;

		// Add listener for the  buttons.
		LinearLayout root = this.chooser.getRootLayout();
		Button addButton = (Button) root.findViewById(R.id.buttonAdd);
		addButton.setOnClickListener(addButtonClickListener);
		Button okButton = (Button) root.findViewById(R.id.buttonOk);
		okButton.setOnClickListener(okButtonClickListener);
	}

	// ----- Events methods ----- //

	/**
	 * Implementation of the click listener for when the add button is clicked.
	 */
	private View.OnClickListener addButtonClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			// Get the current context.
			Context context = v.getContext();

			// Create an alert dialog.
			AlertDialog.Builder alert = new AlertDialog.Builder(context);

			// Define the dialog's labels.
			String title = context.getString(FileChooserCore.this.folderMode? R.string.daidalos_create_folder : R.string.daidalos_create_file);
			if(FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogTitle != null) title = FileChooserCore.this.labels.createFileDialogTitle;
			String message = context.getString(FileChooserCore.this.folderMode? R.string.daidalos_enter_folder_name : R.string.daidalos_enter_file_name);
			if(FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogMessage != null) message = FileChooserCore.this.labels.createFileDialogMessage;
			String posButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogAcceptButton != null)? FileChooserCore.this.labels.createFileDialogAcceptButton : context.getString(R.string.daidalos_accept);
			String negButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogCancelButton != null)? FileChooserCore.this.labels.createFileDialogCancelButton : context.getString(R.string.daidalos_cancel);

			// Set the title and the message.
			alert.setTitle( title );
			alert.setMessage( message );

			// Set an EditText view to get the file's name.
			final EditText input = new EditText(context);
			alert.setView(input);

			// Set the 'ok' and 'cancel' buttons.
			alert.setPositiveButton(posButton, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					String fileName = input.getText().toString();
					// Verify if a value has been entered.
					if(fileName != null && fileName.length() > 0) {
						// Notify the listeners.
						FileChooserCore.this.notifyListeners(FileChooserCore.this.currentFolder, fileName);
					}
				}
			});
			alert.setNegativeButton(negButton, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// Do nothing, automatically the dialog is going to be closed.
				}
			});

			// Show the dialog.
			alert.show();
		}
	};

	/**
	 * Implementation of the click listener for when the ok button is clicked.
	 */
	private View.OnClickListener okButtonClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			// Notify the listeners.
			FileChooserCore.this.notifyListeners(FileChooserCore.this.currentFolder, null);
		}
	};

	/**
	 * Implementation of the click listener for when a file item is clicked.
	 */
	private FileItem.OnFileClickListener fileItemClickListener = new FileItem.OnFileClickListener() {
		public void onClick(FileItem source) {
			// Verify if the item is a folder.
			File file = source.getFile();
			if(file.isDirectory()) {
				// Open the folder.
				FileChooserCore.this.loadFolder(file);
			} else {
				// Notify the listeners.
				FileChooserCore.this.notifyListeners(file, null);
			}
		}
	};

	/**
	 * Add a listener for the event of a file selected.
	 *
	 * @param listener The listener to add.
	 */
	public void addListener(OnFileSelectedListener listener) {
		this.listeners.add(listener);
	}

	/**
	 * Removes a listener for the event of a file selected.
	 *
	 * @param listener The listener to remove.
	 */
	public void removeListener(OnFileSelectedListener listener) {
		this.listeners.remove(listener);
	}

	/**
	 * Removes all the listeners for the event of a file selected.
	 */
	public void removeAllListeners() {
		this.listeners.clear();
	}

	/**
	 * Interface definition for a callback to be invoked when a file is selected.
	 */
	public interface OnFileSelectedListener {
		/**
		 * Called when a file has been selected.
		 *
		 * @param file The file selected.
		 */
		void onFileSelected(File file);

		/**
		 * Called when an user wants to be create a file.
		 *
		 * @param folder The file's parent folder.
		 * @param name The file's name.
		 */
		void onFileSelected(File folder, String name);
	}

	/**
	 * Notify to all listeners that a file has been selected or created.
	 *
	 * @param file The file or folder selected or the folder in which the file must be created.
	 * @param name The name of the file that must be created or 'null' if a file was selected (instead of being created).
	 */
	private void notifyListeners(final File file, final String name) {
		// Determine if a file has been selected or created.
		final boolean creation = name != null && name.length() > 0;

		// Verify if a confirmation dialog must be show.
		if((creation && this.showConfirmationOnCreate || !creation && this.showConfirmationOnSelect)) {
			// Create an alert dialog.
			Context context = this.chooser.getContext();
			AlertDialog.Builder alert = new AlertDialog.Builder(context);

			// Define the dialog's labels.
			String message = null;
			if(FileChooserCore.this.labels != null && ((creation && FileChooserCore.this.labels.messageConfirmCreation != null) || (!creation && FileChooserCore.this.labels.messageConfirmSelection != null)))  {
				message = creation? FileChooserCore.this.labels.messageConfirmCreation : FileChooserCore.this.labels.messageConfirmSelection;
			} else {
				if(FileChooserCore.this.folderMode) {
					message = context.getString(creation? R.string.daidalos_confirm_create_folder : R.string.daidalos_confirm_select_folder);
				} else {
					message = context.getString(creation? R.string.daidalos_confirm_create_file : R.string.daidalos_confirm_select_file);
				}
			}
			if(message != null) message = message.replace("$file_name", name!=null? name : file.getName());
			String posButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.labelConfirmYesButton != null)? FileChooserCore.this.labels.labelConfirmYesButton : context.getString(R.string.daidalos_yes);
			String negButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.labelConfirmNoButton != null)? FileChooserCore.this.labels.labelConfirmNoButton : context.getString(R.string.daidalos_no);

			// Set the message and the 'yes' and 'no' buttons.
			alert.setMessage( message );
			alert.setPositiveButton(posButton, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// Notify to listeners.
					for(int i=0; i<FileChooserCore.this.listeners.size(); i++) {
						if(creation) {
							FileChooserCore.this.listeners.get(i).onFileSelected(file, name);
						} else {
							FileChooserCore.this.listeners.get(i).onFileSelected(file);
						}
					}
				}
			});
			alert.setNegativeButton(negButton, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// Do nothing, automatically the dialog is going to be closed.
				}
			});

			// Show the dialog.
			alert.show();
		} else {
			// Notify to listeners.
			for(int i=0; i<FileChooserCore.this.listeners.size(); i++) {
				if(creation) {
					FileChooserCore.this.listeners.get(i).onFileSelected(file, name);
				} else {
					FileChooserCore.this.listeners.get(i).onFileSelected(file);
				}
			}
		}
	}

	// ----- Get and set methods ----- //

	/**
	 * Allows to define if a confirmation dialog must be show when selecting a file.
	 *
	 * @param show 'true' for show the confirmation dialog, 'false' for not show the dialog.
	 */
	public void setShowConfirmationOnSelect(boolean show) {
		this.showConfirmationOnSelect = show;
	}

	/**
	 * Allows to define if a confirmation dialog must be show when creating a file.
	 *
	 * @param show 'true' for show the confirmation dialog, 'false' for not show the dialog.
	 */
	public void setShowConfirmationOnCreate(boolean show) {
		this.showConfirmationOnCreate = show;
	}

	/**
	 * Allows to define if, in the title, must be show only the current folder's name or the full file's path..
	 *
	 * @param show 'true' for show the full path, 'false' for show only the name.
	 */
	public void setShowFullPathInTitle(boolean show) {
		this.showFullPathInTitle = show;
	}

	/**
	 * Defines the value of the labels.
	 *
	 * @param label The labels.
	 */
	public void setLabels(FileChooserLabels labels) {
		this.labels = labels;

		// Verify if the buttons for add a file or select a folder has been modified.
		if(labels != null) {
			LinearLayout root = this.chooser.getRootLayout();

			if(labels.labelAddButton != null) {
				Button addButton = (Button) root.findViewById(R.id.buttonAdd);
				addButton.setText(labels.labelAddButton);
			}

			if(labels.labelSelectButton != null) {
				Button okButton = (Button) root.findViewById(R.id.buttonOk);
				okButton.setText(labels.labelSelectButton);
			}
		}
	}

	/**
	 * Set a regular expression to filter the files that can be selected.
	 *
	 * @param filter A regular expression.
	 */
	public void setFilter(String filter) {
		if(filter == null || filter.length() == 0 ) {
			this.filter = null;
		} else {
			this.filter = filter;
		}

		// Reload the list of files.
		this.loadFolder(this.currentFolder);
	}

	/**
	 * Defines if the chooser is going to be used to select folders, instead of files.
	 *
	 * @param folderMode 'true' for select folders or 'false' for select files.
	 */
	public void setFolderMode(boolean folderMode) {
		this.folderMode = folderMode;

		// Show or hide the 'Ok' button.
		updateButtonsLayout();

		// Reload the list of files.
		this.loadFolder(this.currentFolder);
	}

	/**
	 * Defines if the user can create files, instead of only select files.
	 *
	 * @param canCreate 'true' if the user can create files or 'false' if it can only select them.
	 */
	public void setCanCreateFiles(boolean canCreate) {
		this.canCreateFiles = canCreate;

		// Show or hide the 'Add' button.
		updateButtonsLayout();
	}

	/**
	 * Defines if only the files that can be selected (they pass the filter) must be show.
	 *
	 * @param show 'true' if only the files that can be selected must be show or 'false' if all the files must be show.
	 */
	public void setShowOnlySelectable(boolean show) {
		this.showOnlySelectable = show;

		// Reload the list of files.
		this.loadFolder(this.currentFolder);
	}

	/**
	 * Returns the current folder.
	 *
	 * @return The current folder.
	 */
	public File getCurrentFolder() {
		return this.currentFolder;
	}

	// ----- Miscellaneous methods ----- //

	/**
	 * Changes the height of the layout for the buttons, according if the buttons are visible or not.
	 */
	private void updateButtonsLayout() {
		// Get the buttons layout.
		LinearLayout root = this.chooser.getRootLayout();
		LinearLayout buttonsLayout = (LinearLayout) root.findViewById(R.id.linearLayoutButtons);

		// Verify if the 'Add' button is visible or not.
		View addButton = root.findViewById(R.id.buttonAdd);
		addButton.setVisibility(this.canCreateFiles? View.VISIBLE : View.INVISIBLE);
		addButton.getLayoutParams().width = this.canCreateFiles? ViewGroup.LayoutParams.MATCH_PARENT : 0;

		// Verify if the 'Ok' button is visible or not.
		View okButton = root.findViewById(R.id.buttonOk);
		okButton.setVisibility(this.folderMode? View.VISIBLE : View.INVISIBLE);
		okButton.getLayoutParams().width = this.folderMode? ViewGroup.LayoutParams.MATCH_PARENT : 0;

		// If both buttons are invisible, hide the layout.
		ViewGroup.LayoutParams params = buttonsLayout.getLayoutParams();
		if(this.canCreateFiles || this.folderMode) {
			// Show the layout.
			params.height = ViewGroup.LayoutParams.WRAP_CONTENT;

			// If only the 'Ok' button is visible, put him first. Otherwise, put 'Add' first.
			buttonsLayout.removeAllViews();
			if(this.folderMode && !this.canCreateFiles) {
				buttonsLayout.addView(okButton);
				buttonsLayout.addView(addButton);
			} else {
				buttonsLayout.addView(addButton);
				buttonsLayout.addView(okButton);
			}
		} else {
			// Hide the layout.
			params.height = 0;
		}
	}

	/**
	 * Loads all the files of the SD card root.
	 */
	public void loadFolder() {
		this.loadFolder(defaultFolder);
	}

	/**
	 * Loads all the files of a folder in the file chooser.
	 *
	 * If no path is specified ('folderPath' is null) the root folder of the SD card is going to be used.
	 *
	 * @param folderPath The folder's path.
	 */
	public void loadFolder(String folderPath) {
		// Get the file path.
		File path = null;
		if(folderPath != null && folderPath.length() > 0) {
			path = new File(folderPath);
		}

		this.loadFolder(path);
	}

	/**
	 * Loads all the files of a folder in the file chooser.
	 *
	 * If no path is specified ('folder' is null) the root folder of the SD card is going to be used.
	 *
	 * @param folder The folder.
	 */
	public void loadFolder(File folder) {
		// Remove previous files.
		LinearLayout root = this.chooser.getRootLayout();
		LinearLayout layout = (LinearLayout) root.findViewById(R.id.linearLayoutFiles);
		layout.removeAllViews();

		// Get the file path.
		if(folder == null || !folder.exists()) {
			if(defaultFolder != null) {
				this.currentFolder = defaultFolder;
			} else {
				this.currentFolder = Environment.getExternalStorageDirectory();
			}
		} else {
			this.currentFolder = folder;
		}

		// Verify if the path exists.
		if(this.currentFolder.exists() && layout != null) {
			List<FileItem> fileItems = new LinkedList<FileItem>();

			// Add the parent folder.
			if(this.currentFolder.getParent() != null) {
				File parent = new File(this.currentFolder.getParent());
				if(parent.exists()) {
					fileItems.add(new FileItem(this.chooser.getContext(), parent, ".."));
				}
			}

			// Verify if the file is a directory.
			if(this.currentFolder.isDirectory()) {
				// Get the folder's files.
				File[] fileList = this.currentFolder.listFiles();
				if(fileList != null) {
					// Order the files alphabetically and separating folders from files.
					Arrays.sort(fileList, new Comparator<File>() {
						public int compare(File file1, File file2) {
							if(file1 != null && file2 != null) {
								if(file1.isDirectory() && (!file2.isDirectory())) return -1;
								if(file2.isDirectory() && (!file1.isDirectory())) return 1;
								return file1.getName().compareTo(file2.getName());
							}
							return 0;
						}
					});

					// Iterate all the files in the folder.
					for(int i=0; i<fileList.length; i++) {
						// Verify if file can be selected (is a directory or folder mode is not activated and the file pass the filter, if defined).
						boolean selectable = true;
						if(!fileList[i].isDirectory()) {
							selectable = !this.folderMode && (this.filter == null || fileList[i].getName().matches(this.filter));
						}

						// Verify if the file must be show.
						if(selectable || !this.showOnlySelectable) {
							// Create the file item and add it to the list.
							FileItem fileItem = new FileItem(this.chooser.getContext(), fileList[i]);
							fileItem.setSelectable(selectable);
							fileItems.add(fileItem);
						}
					}
				}

				// Set the name of the current folder.
				String currentFolderName = this.showFullPathInTitle? this.currentFolder.getPath() : this.currentFolder.getName();
				this.chooser.setCurrentFolderName(currentFolderName);
			} else {
				// The file is not a folder, add only this file.
				fileItems.add(new FileItem(this.chooser.getContext(), this.currentFolder));
			}

			// Add click listener and add the FileItem objects to the layout.
			for(int i=0; i<fileItems.size(); i++) {
				fileItems.get(i).addListener(this.fileItemClickListener);
				layout.addView(fileItems.get(i));
			}

			// Refresh default folder.
			defaultFolder = this.currentFolder;
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 是否居中显示 -->
    <bool name="default_circle_indicator_centered">true</bool>

    <!-- 选中时的颜色 -->
    <color name="default_circle_indicator_fill_color">#EB9718</color>
    <!-- 未选中时的颜色 -->
    <color name="default_circle_indicator_page_color">#FFFFFF</color>
    <!-- E93333 -->

    <integer name="default_circle_indicator_orientation">0</integer>
    <!-- 圆点的半径大小 -->
    <dimen name="default_circle_indicator_radius">4dip</dimen>
    <!-- 选择false时会有滑动动画 -->
    <bool name="default_circle_indicator_snap">false</bool>
    <!-- 未选中时周围圈的颜色 -->
    <color name="default_circle_indicator_stroke_color">#FFFFFF</color>
    <!-- FF0000 -->
    <!-- 未选中时周围圈的宽度 -->
    <dimen name="default_circle_indicator_stroke_width">0dip</dimen>

</resources>


text:
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <string>
#include <list>
#include <FreeImage.h>

char* get_cmd_option(char** begin, char** end, const std::string & option) {
    char** it = std::find(begin, end, option);
    if (it != end && ++it != end)
        return *it;
    return 0;
}

bool cmd_option_exists(char** begin, char** end, const std::string& option) {
    return std::find(begin, end, option) != end;
}

struct pixel {
  BYTE r, g, b;
};

struct image {
  unsigned int w, h;
  pixel *data;
};

image image_;

//read image
pixel *read_img(char const *name, unsigned int *width, unsigned int *height, float scale) {
    FIBITMAP *image;
    int i,j,pnum;
    RGBQUAD aPixel;
    pixel *data;

    FREE_IMAGE_FORMAT image_format = FreeImage_GetFileType(name,0);

    if((image = FreeImage_Load(image_format, name, 0)) == NULL) {
        return NULL;
    }

    image = FreeImage_Rescale(image, FreeImage_GetWidth(image)*scale, FreeImage_GetHeight(image)*scale);

    *width = FreeImage_GetWidth(image);
    *height = FreeImage_GetHeight(image);
    data = (pixel *)malloc((*height)*(*width)*sizeof(pixel *));
    pnum=0;

    for(i = 0 ; i < (*height) ; i++) {
        for(j = 0 ; j < (*width) ; j++) {
            FreeImage_GetPixelColor(image, j, (*height) - i, &aPixel);
            data[pnum].r = (aPixel.rgbRed);
            data[pnum].g = (aPixel.rgbGreen);
            data[pnum++].b = (aPixel.rgbBlue);
        }
    }
    FreeImage_Unload(image);
    return data;
}

int main(int argc, char *argv[]) {

  if (argc == 1 ||
    !cmd_option_exists(argv, argv+argc, "-f") ||
    !cmd_option_exists(argv, argv+argc, "-s")) {
    std::cout << "Usage: " << argv[0] << " -f <input_image> -s <scale>" << std::endl <<
     "INFO: argv[0] " << std::endl ;
    return 0;
  }

  std::string input_file = get_cmd_option(argv, argv+argc, "-f");
  float scale = atof(get_cmd_option(argv, argv+argc, "-s"));

  std::cout << "loading image..." << std::endl;
  std::cout << "Path: " << input_file << std::endl;

  unsigned int width, height;
  auto data = read_img(input_file.c_str(), &width, &height, scale);

  std::cout << "width: "  << width << ", "
            << "height: " << height << std::endl;

  std::string output_file = input_file.substr(0, input_file.size()-4) + "_w" + std::to_string(width) + "_h" + std::to_string(height) + ".data";
  std::cout << output_file << std::endl;

  std::cout << "writing raw..." << std::endl;

  std::ofstream raw_file;
  raw_file.open(output_file.c_str(), std::ios::trunc | std::ios::binary);

  raw_file.write((char*)data, width*height*sizeof(char)*3);

  raw_file.close();

  std::cout << "done" << std::endl;

  return 0;

}


text:
using System;
using System.Collections.Generic;
using GameEngine.Data.Common;
using GameEngine.Data.Entities;
using GameEngine.Data.Tiles;
using General.Common;
using General.Encoding;
using Microsoft.Xna.Framework;

namespace GameEngine.Data.GameLoader {
	public class MapData : IEncodable {
		public string Name, Author;
		public int Width;
		public int Height;

		public MockupTile[][][] Tiles;
		public List<Tuple<int, Vector2>> Entities;
		public List<MockupTileset> Tilesets;
		public MapData[] Connections; //0 = up, 1 = right, 2 = down, 3 = right;

		public MapData() {
			Connections = new MapData[4];
			Entities = new List<Tuple<Int32, Vector2>>();
		}

		public Map CreateMap(World world) {
			Map result = new Map(world.EntityFactory, Name, Author, Width, Height);
			result.Tilesets = this.Tilesets;
			foreach (MockupTileset tileset in result.Tilesets) {
				tileset.world = world;
			}
			result.Tiles = Tiles;

			for (int i = 0; i < result.Width; i++)
				for (int j = 0; j < result.Height; j++)
					for (int k = 0; k < Map.LayerCount; k++)
						Tiles[i][j][k].map = result;

			foreach (Tuple<Int32, Vector2> token in Entities) {
				MapEntity e = world.EntityContainer.Get(token.Item1).CreateEntity(world.EntityFactory);
				e.Position = token.Item2;
				result.Entities.Add(e);
			}
			return result;
		}

		public void Encode(BinaryOutput stream, Map map) {
			stream.Write(map.Name);
			stream.Write(map.Author);

			stream.Write(map.Width);
			stream.Write(map.Height);

			stream.Write(map.Tilesets);

			for (int i = 0; i < map.Width; i++) {
				for (int j = 0; j < map.Height; j++) {
					for (int k = 0; k < Map.LayerCount; k++) {
						map.Tiles[i][j][k].Encode(stream);
					}
				}
			}

			stream.Write(map.Entities.Count);
			foreach (MapEntity e in map.Entities) {
				stream.Write(e.TemplateID);
				stream.Write(e.Position);
			}
		}

		public void Encode(BinaryOutput stream) {
			//nothing, we need map!
		}

		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.Author = stream.ReadString();

			this.Width = stream.ReadInt32();
			this.Height = stream.ReadInt32();

			this.Tiles = new MockupTile[Width][][];
			for (int i = 0; i < Width; i++) {
				Tiles[i] = new MockupTile[Height][];
				for (int j = 0; j < Height; j++) {
					Tiles[i][j] = new MockupTile[Map.LayerCount];
				}
			}

			int w = Width;
			int h = Height;

			this.Tilesets = stream.ReadList<MockupTileset>();

			for (int i = 0; i < w; i++) {
				for (int j = 0; j < h; j++) {
					for (int k = 0; k < Map.LayerCount; k++) {
						Tiles[i][j][k] = stream.ReadObject<MockupTile>();
					}
				}
			}

			int c = stream.ReadInt32();
			for (int i = 0; i < c; i++) {
				Tuple<Int32, Vector2> t = new Tuple<Int32, Vector2>(stream.ReadInt32(), stream.ReadVector2());
				Entities.Add(t);
			}
			return this;
		}
	}
}


text:
# 1. Introduction

This document is intended as a reference guide to the full syntax and semantics of
the SQL++ Query Language, a SQL-inspired language for working with semistructured data.
SQL++ has much in common with SQL, but some differences do exist due to the different
data models that the two languages were designed to serve.
SQL was designed in the 1970's for interacting with the flat, schema-ified world of
relational databases, while SQL++ is much newer and targets the nested, schema-optional
(or even schema-less) world of modern NoSQL systems.

In the context of Apache AsterixDB, SQL++ is intended for working with the Asterix Data Model
([ADM](../datamodel.html)),a data model based on a superset of JSON with an enriched and flexible type system.
New AsterixDB users are encouraged to read and work through the (much friendlier) guide
"[AsterixDB 101: An ADM and SQL++ Primer](primer-sqlpp.html)" before attempting to make use of this document.
In addition, readers are advised to read through the [Asterix Data Model (ADM) reference guide](../datamodel.html)
first as well, as an understanding of the data model is a prerequisite to understanding SQL++.

In what follows, we detail the features of the SQL++ language in a grammar-guided manner.
We list and briefly explain each of the productions in the SQL++ grammar, offering examples
(and results) for clarity.


text:
import { createElement, useRef, useEffect, useState, useCallback, forwardRef } from 'react'
import {
    withContainer,
    useDimensions,
    useTheme,
    getRelativeCursor,
    isCursorInRect,
} from '@nivo/core'
import { renderAxesToCanvas, renderGridLinesToCanvas } from '@nivo/axes'
import { renderLegendToCanvas } from '@nivo/legends'
import { useTooltip } from '@nivo/tooltip'
import { useVoronoiMesh, renderVoronoiToCanvas, renderVoronoiCellToCanvas } from '@nivo/voronoi'
import { LineCanvasPropTypes, LineCanvasDefaultProps } from './props'
import { useLine } from './hooks'

const LineCanvas = ({
    width,
    height,
    margin: partialMargin,
    pixelRatio,

    data,
    xScale: xScaleSpec,
    xFormat,
    yScale: yScaleSpec,
    yFormat,
    curve,

    layers,

    colors,
    lineWidth,

    enableArea,
    areaBaselineValue,
    areaOpacity,

    enablePoints,
    pointSize,
    pointColor,
    pointBorderWidth,
    pointBorderColor,

    enableGridX,
    gridXValues,
    enableGridY,
    gridYValues,
    axisTop,
    axisRight,
    axisBottom,
    axisLeft,

    legends,

    isInteractive,
    debugMesh,
    //onMouseEnter,
    //onMouseMove,
    onMouseLeave,
    onClick,
    tooltip,

    canvasRef,
}) => {
    const canvasEl = useRef(null)
    const { margin, innerWidth, innerHeight, outerWidth, outerHeight } = useDimensions(
        width,
        height,
        partialMargin
    )
    const theme = useTheme()
    const [currentPoint, setCurrentPoint] = useState(null)

    const { lineGenerator, areaGenerator, series, xScale, yScale, points } = useLine({
        data,
        xScale: xScaleSpec,
        xFormat,
        yScale: yScaleSpec,
        yFormat,
        width: innerWidth,
        height: innerHeight,
        colors,
        curve,
        areaBaselineValue,
        pointColor,
        pointBorderColor,
    })

    const { delaunay, voronoi } = useVoronoiMesh({
        points,
        width: innerWidth,
        height: innerHeight,
        debug: debugMesh,
    })

    useEffect(() => {
        if (canvasRef) {
            canvasRef.current = canvasEl.current
        }

        canvasEl.current.width = outerWidth * pixelRatio
        canvasEl.current.height = outerHeight * pixelRatio

        const ctx = canvasEl.current.getContext('2d')

        ctx.scale(pixelRatio, pixelRatio)

        ctx.fillStyle = theme.background
        ctx.fillRect(0, 0, outerWidth, outerHeight)
        ctx.translate(margin.left, margin.top)

        layers.forEach(layer => {
            if (typeof layer === 'function') {
                layer({
                    ctx,
                    innerWidth,
                    innerHeight,
                    series,
                    points,
                    xScale,
                    yScale,
                    lineWidth,
                    lineGenerator,
                    areaGenerator,
                    currentPoint,
                    setCurrentPoint,
                })
            }

            if (layer === 'grid' && theme.grid.line.strokeWidth > 0) {
                ctx.lineWidth = theme.grid.line.strokeWidth
                ctx.strokeStyle = theme.grid.line.stroke

                enableGridX &&
                    renderGridLinesToCanvas(ctx, {
                        width: innerWidth,
                        height: innerHeight,
                        scale: xScale,
                        axis: 'x',
                        values: gridXValues,
                    })

                enableGridY &&
                    renderGridLinesToCanvas(ctx, {
                        width: innerWidth,
                        height: innerHeight,
                        scale: yScale,
                        axis: 'y',
                        values: gridYValues,
                    })
            }

            if (layer === 'axes') {
                renderAxesToCanvas(ctx, {
                    xScale,
                    yScale,
                    width: innerWidth,
                    height: innerHeight,
                    top: axisTop,
                    right: axisRight,
                    bottom: axisBottom,
                    left: axisLeft,
                    theme,
                })
            }

            if (layer === 'areas' && enableArea === true) {
                ctx.save()
                ctx.globalAlpha = areaOpacity

                areaGenerator.context(ctx)
                series.forEach(serie => {
                    ctx.fillStyle = serie.color
                    ctx.beginPath()
                    areaGenerator(serie.data.map(d => d.position))
                    ctx.fill()
                })

                ctx.restore()
            }

            if (layer === 'lines') {
                lineGenerator.context(ctx)
                series.forEach(serie => {
                    ctx.strokeStyle = serie.color
                    ctx.lineWidth = lineWidth
                    ctx.beginPath()
                    lineGenerator(serie.data.map(d => d.position))
                    ctx.stroke()
                })
            }

            if (layer === 'points' && enablePoints === true && pointSize > 0) {
                points.forEach(point => {
                    ctx.fillStyle = point.color
                    ctx.beginPath()
                    ctx.arc(point.x, point.y, pointSize / 2, 0, 2 * Math.PI)
                    ctx.fill()

                    if (pointBorderWidth > 0) {
                        ctx.strokeStyle = point.borderColor
                        ctx.lineWidth = pointBorderWidth
                        ctx.stroke()
                    }
                })
            }

            if (layer === 'mesh' && debugMesh === true) {
                renderVoronoiToCanvas(ctx, voronoi)
                if (currentPoint) {
                    renderVoronoiCellToCanvas(ctx, voronoi, currentPoint.index)
                }
            }

            if (layer === 'legends') {
                const legendData = series
                    .map(serie => ({
                        id: serie.id,
                        label: serie.id,
                        color: serie.color,
                    }))
                    .reverse()

                legends.forEach(legend => {
                    renderLegendToCanvas(ctx, {
                        ...legend,
                        data: legend.data || legendData,
                        containerWidth: innerWidth,
                        containerHeight: innerHeight,
                        theme,
                    })
                })
            }
        })
    }, [
        canvasEl,
        outerWidth,
        outerHeight,
        layers,
        theme,
        lineGenerator,
        series,
        xScale,
        yScale,
        enableGridX,
        gridXValues,
        enableGridY,
        gridYValues,
        axisTop,
        axisRight,
        axisBottom,
        axisLeft,
        legends,
        points,
        enablePoints,
        pointSize,
        currentPoint,
    ])

    const getPointFromMouseEvent = useCallback(
        event => {
            const [x, y] = getRelativeCursor(canvasEl.current, event)
            if (!isCursorInRect(margin.left, margin.top, innerWidth, innerHeight, x, y)) return null

            const pointIndex = delaunay.find(x - margin.left, y - margin.top)
            return points[pointIndex]
        },
        [canvasEl, margin, innerWidth, innerHeight, delaunay]
    )

    const { showTooltipFromEvent, hideTooltip } = useTooltip()

    const handleMouseHover = useCallback(
        event => {
            const point = getPointFromMouseEvent(event)
            setCurrentPoint(point)

            if (point) {
                showTooltipFromEvent(createElement(tooltip, { point }), event)
            } else {
                hideTooltip()
            }
        },
        [getPointFromMouseEvent, setCurrentPoint, showTooltipFromEvent, hideTooltip, tooltip]
    )

    const handleMouseLeave = useCallback(
        event => {
            hideTooltip()
            setCurrentPoint(null)
            currentPoint && onMouseLeave && onMouseLeave(currentPoint, event)
        },
        [hideTooltip, setCurrentPoint, onMouseLeave]
    )

    const handleClick = useCallback(
        event => {
            if (onClick) {
                const point = getPointFromMouseEvent(event)
                point && onClick(point, event)
            }
        },
        [getPointFromMouseEvent, onClick]
    )

    return (
        <canvas
            ref={canvasEl}
            width={outerWidth * pixelRatio}
            height={outerHeight * pixelRatio}
            style={{
                width: outerWidth,
                height: outerHeight,
                cursor: isInteractive ? 'auto' : 'normal',
            }}
            onMouseEnter={isInteractive ? handleMouseHover : undefined}
            onMouseMove={isInteractive ? handleMouseHover : undefined}
            onMouseLeave={isInteractive ? handleMouseLeave : undefined}
            onClick={isInteractive ? handleClick : undefined}
        />
    )
}

LineCanvas.propTypes = LineCanvasPropTypes
LineCanvas.defaultProps = LineCanvasDefaultProps

const LineCanvasWithContainer = withContainer(LineCanvas)

export default forwardRef((props, ref) => <LineCanvasWithContainer {...props} canvasRef={ref} />)


text:
Alter the functionality of your code. Unpredictably.

#### Usage
This version of the pysenbug module operates through a decorator.

```
In [1]: from pysenbug import pysenbug

In [2]: @pysenbug
   ...: def open_box():
   ...:     print("meow")
   ...:

In [3]: open_box()

In [4]: open_box()
meow

In [5]: open_box()

In [6]: open_box()

In [7]: open_box()

In [8]: open_box()
meow

In [9]: open_box()

In [10]: open_box()
meow

In [11]: open_box()
meow
```

#### Altering the behavior of pysenbug
The pysenbug decorator supports, but does not require, certain optional parameters that change its behavior.

One such parameter is *chance*, a float or int between 0 and 1. Lower values reduce the chance that the function will return its normal value in favor of the bugged value.
```
In [12]: @pysenbug(chance=0)
   ...: def polonium_box():
   ...:         print('miao')
   ...:

In [13]: polonium_box()

In [14]: polonium_box()

In [15]: polonium_box()

In [16]: polonium_box()

In [17]: polonium_box()

In [18]: polonium_box()

In [19]: polonium_box()

In [20]: polonium_box()

In [21]: polonium_box()
```

The *return_value* parameter allows pysenbug to return custom values.
```
In [22]: @pysenbug(return_value='bark')
   ...: def uranium_box():
   ...:         return 'miow'
   ...:

In [23]: uranium_box()
Out[23]: 'bark'

In [24]: uranium_box()
Out[24]: 'bark'

In [25]: uranium_box()
Out[25]: 'miow'

In [26]: uranium_box()
Out[26]: 'miow'

In [27]: uranium_box()
Out[27]: 'miow'

In [28]: uranium_box()
Out[28]: 'miow'

In [29]: uranium_box()
Out[29]: 'bark'

In [30]: uranium_box()
Out[30]: 'bark'

In [31]: uranium_box()
Out[31]: 'bark'
```

Supplying a *probability_function* allows customization of failure frequency profiles.
```
In [32]: def hidden_variable():
   ...:         while True:
   ...:                 yield False
   ...:                 yield True
   ...:

In [33]: bohm_interpretation = hidden_variable()

In [34]: @pysenbug(probability_function=bohm_interpretation.next)
   ...: def bismuth_box():
   ...:         print('miau')
   ...:

In [35]: bismuth_box()
miau

In [36]: bismuth_box()

In [37]: bismuth_box()
miau

In [38]: bismuth_box()

In [39]: bismuth_box()
miau

In [40]: bismuth_box()

In [41]: bismuth_box()
miau
```

#### Future development
Future versions of pysenbug will feature metaclasses that infect their descendants' methods, and hopefully, faked tracebacks for maximum fun.


text:
package.path = package.path .. ";../?.lua;../?/init.lua"

local hui = require "hui"

local wm = hui.WindowManager()
local win = hui.Window(10, 10, 100, 100)

wm:addWindow(win)
win.backgroundColor = of.Color(200)

------------
-- Main Loop
------------

function setup()
end

function update()
end

function draw()
	wm:draw()
end

---------
-- Events
---------

function keyPressed(key)
	wm:keyPressed(key)
end

function keyReleased(key)
	wm:keyReleased(key)
end

function mouseMoved(x, y)
	wm:mouseMoved(x, y)
end

function mouseDragged(x, y)
	wm:mouseDragged(x, y)
end

function mousePressed(x, y, button)
	wm:mousePressed(x, y, button)
end

function mouseReleased(x, y, button)
	wm:mouseReleased(x, y, button)
end

function windowResized(w, h)
	wm:windowResized(w, h)
end


text:
package com.founder.fix.fixflow.core.impl.threadpool;

import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import com.founder.fix.fixflow.core.impl.log.LogFactory;

public class FixThreadPoolExecutor extends ThreadPoolExecutor {

	private String threadPoolKey;

	private String threadPoolName;

	private static com.founder.fix.fixflow.core.impl.log.DebugLog debugLog = LogFactory.getDebugLog(FixThreadPoolExecutor.class);

	private boolean isPaused;
	private ReentrantLock pauseLock = new ReentrantLock();
	private Condition unpaused = pauseLock.newCondition();

	public FixThreadPoolExecutor(String threadPoolKey,String threadPoolName,int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
		this.threadPoolKey=threadPoolKey;
		this.threadPoolName=threadPoolName;

	}

	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		super.beforeExecute(t, r);
		pauseLock.lock();
		try {
			while (isPaused)
				unpaused.await();
		} catch (InterruptedException ie) {
			t.interrupt();
		} finally {
			pauseLock.unlock();
		}
		debugLog.debug("线程 ["+threadPoolName +"] 开始执行.");
		debugLog.debug("开始时间 ["+new Date()+"]");
	}

	@Override
	protected void afterExecute(Runnable r, Throwable t) {
		super.afterExecute(r, t);
		debugLog.debug("线程 ["+threadPoolName +"] 执行结束.");
		debugLog.debug("结束时间 ["+new Date()+"]");
	}

	/**
	 * 暂停线程池
	 */
	public void pause() {
		pauseLock.lock();
		debugLog.debug("线程 ["+threadPoolName +"] 暂停.");
		debugLog.debug("暂停时间 ["+new Date()+"]");
		try {
			isPaused = true;
		} finally {
			pauseLock.unlock();
		}
	}

	/**
	 * 恢复线程池
	 */
	public void resume() {
		pauseLock.lock();
		debugLog.debug("线程 ["+threadPoolName +"] 恢复.");
		debugLog.debug("恢复时间 ["+new Date()+"]");
		try {
			isPaused = false;
			unpaused.signalAll();
		} finally {
			pauseLock.unlock();
		}
	}

	public String getThreadPoolKey() {
		return threadPoolKey;
	}
	public String getThreadPoolName() {
		return threadPoolName;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <View
        android:id="@+id/background"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@android:color/background_dark"
        app:layout_constraintHeight_percent="0.6"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <android.support.constraint.Guideline
        android:id="@+id/top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <android.support.constraint.Guideline
        android:id="@+id/bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.9"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Validate payment"
        android:textSize="24dp"
        app:layout_constraintTop_toTopOf="@id/top"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <com.mercadopago.android.px.base.TintableImageView
        android:id="@+id/fingerprint"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:srcCompat="@drawable/ic_fingerprint"
        app:layout_constraintHeight_percent="0.2"
        app:layout_constraintWidth_percent="0.2"
        app:layout_constraintBottom_toBottomOf="@id/bottom"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</android.support.constraint.ConstraintLayout>


text:
import os
from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-almostSignificant',
    version='0.054',
    packages=['almostSignificant'],
    install_requires=['django','illuminate'],
    include_package_data=True,
    license='MIT',  # example license
    description='A django app for streamlining DNA sequencing QC and information storage.',
    long_description=README,
    url='http://www.example.com/',
    author='Joseph Ward',
    author_email='j.x.ward@dundee.ac.uk',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License', # example license
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        # Replace these appropriately if you are stuck on Python 2.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


text:
package it.test.client;

import com.google.auto.value.AutoValue;
import com.google.common.annotations.GwtCompatible;

@AutoValue
@GwtCompatible(serializable = true)
public abstract class Processed2 {
  public static Processed2 create(String property) {
    return new AutoValue_Processed2(property);
  }

  public abstract String getProperty();
}


text:
#ifndef QJSON_P_H
#define QJSON_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <qjsonobject.h>
#include <qjsonvalue.h>
#include <qjsondocument.h>
#include <qjsonarray.h>
#include <qatomic.h>
#include <qstring.h>
#include <qendian.h>
#include <qnumeric.h>

#include "private/qsimd_p.h"

#include <limits.h>
#include <limits>

QT_BEGIN_NAMESPACE

/*
  This defines a binary data structure for Json data. The data structure is optimised for fast reading
  and minimum allocations. The whole data structure can be mmap'ed and used directly.

  In most cases the binary structure is not as space efficient as a utf8 encoded text representation, but
  much faster to access.

  The size requirements are:

  String:
    Latin1 data: 2 bytes header + string.length()
    Full Unicode: 4 bytes header + 2*(string.length())

  Values: 4 bytes + size of data (size can be 0 for some data)
    bool: 0 bytes
    double: 8 bytes (0 if integer with less than 27bits)
    string: see above
    array: size of array
    object: size of object
  Array: 12 bytes + 4*length + size of Value data
  Object: 12 bytes + 8*length + size of Key Strings + size of Value data

  For an example such as

    {                                           // object: 12 + 5*8                   = 52
         "firstName": "John",                   // key 12, value 8                    = 20
         "lastName" : "Smith",                  // key 12, value 8                    = 20
         "age"      : 25,                       // key 8, value 0                     = 8
         "address"  :                           // key 12, object below               = 140
         {                                      // object: 12 + 4*8
             "streetAddress": "21 2nd Street",  // key 16, value 16
             "city"         : "New York",       // key 8, value 12
             "state"        : "NY",             // key 8, value 4
             "postalCode"   : "10021"           // key 12, value 8
         },                                     // object total: 128
         "phoneNumber":                         // key: 16, value array below         = 172
         [                                      // array: 12 + 2*4 + values below: 156
             {                                  // object 12 + 2*8
               "type"  : "home",                // key 8, value 8
               "number": "212 555-1234"         // key 8, value 16
             },                                 // object total: 68
             {                                  // object 12 + 2*8
               "type"  : "fax",                 // key 8, value 8
               "number": "646 555-4567"         // key 8, value 16
             }                                  // object total: 68
         ]                                      // array total: 156
    }                                           // great total:                         412 bytes

    The uncompressed text file used roughly 500 bytes, so in this case we end up using about
    the same space as the text representation.

    Other measurements have shown a slightly bigger binary size than a compact text
    representation where all possible whitespace was stripped out.
*/
#define Q_DECLARE_JSONPRIVATE_TYPEINFO(Class, Flags) } Q_DECLARE_TYPEINFO(QJsonPrivate::Class, Flags); namespace QJsonPrivate {
namespace QJsonPrivate {

class Array;
class Object;
class Value;
class Entry;

template<typename T>
class q_littleendian
{
public:
    T val;

    q_littleendian &operator =(T i) { val = qToLittleEndian(i); return *this; }
    operator T() const { return qFromLittleEndian(val); }

    bool operator ==(T i) { return qFromLittleEndian(val) == i; }
    bool operator !=(T i) { return qFromLittleEndian(val) != i; }
    bool operator ==(q_littleendian<T> i) { return val == i.val; }
    bool operator !=(q_littleendian<T> i) { return val != i.val; }
    bool operator <(T i) { return qFromLittleEndian(val) < i; }
    bool operator >(T i) { return qFromLittleEndian(val) > i; }
    bool operator <=(T i) { return qFromLittleEndian(val) <= i; }
    bool operator >=(T i) { return qFromLittleEndian(val) >= i; }
    q_littleendian &operator +=(T i) {
        val = qToLittleEndian(qFromLittleEndian(val) + i);
        return *this;
    }
    q_littleendian &operator |=(T i) {
        val = qToLittleEndian(qFromLittleEndian(val) | i);
        return *this;
    }
    q_littleendian &operator &=(T i) {
        val = qToLittleEndian(qFromLittleEndian(val) & i);
        return *this;
    }
};
} // namespace QJsonPrivate

template <typename T>
class QTypeInfo<QJsonPrivate::q_littleendian<T> >
    : public QTypeInfoMerger<QJsonPrivate::q_littleendian<T>, T> {};

namespace QJsonPrivate {

typedef q_littleendian<short> qle_short;
typedef q_littleendian<unsigned short> qle_ushort;
typedef q_littleendian<int> qle_int;
typedef q_littleendian<unsigned int> qle_uint;

template<int pos, int width>
class qle_bitfield
{
public:
    uint val;

    enum {
        mask = ((1u << width) - 1) << pos
    };

    void operator =(uint t) {
        uint i = qFromLittleEndian(val);
        i &= ~mask;
        i |= t << pos;
        val = qToLittleEndian(i);
    }
    operator uint() const {
        uint t = qFromLittleEndian(val);
        t &= mask;
        t >>= pos;
        return t;
    }
    bool operator !() const {
        return !operator uint();
    }

    bool operator ==(uint t) { return uint(*this) == t; }
    bool operator !=(uint t) { return uint(*this) != t; }
    bool operator <(uint t) { return uint(*this) < t; }
    bool operator >(uint t) { return uint(*this) > t; }
    bool operator <=(uint t) { return uint(*this) <= t; }
    bool operator >=(uint t) { return uint(*this) >= t; }
    qle_bitfield &operator +=(uint i) {
        *this = (uint(*this) + i);
        return *this;
    }
    qle_bitfield &operator -=(uint i) {
        *this = (uint(*this) - i);
        return *this;
    }
    qle_bitfield &operator |=(uint i) {
        *this = (uint(*this) | i);
        return *this;
    }
    qle_bitfield &operator &=(uint i) {
        *this = (uint(*this) & i);
        return *this;
    }
};

template<int pos, int width>
class qle_signedbitfield
{
public:
    uint val;

    enum {
        mask = ((1u << width) - 1) << pos
    };

    void operator =(int t) {
        uint i = qFromLittleEndian(val);
        i &= ~mask;
        i |= t << pos;
        val = qToLittleEndian(i);
    }
    operator int() const {
        uint i = qFromLittleEndian(val);
        i <<= 32 - width - pos;
        int t = (int) i;
        t >>= 32 - width;
        return t;
    }
    bool operator !() const {
        return !operator int();
    }

    bool operator ==(int t) { return int(*this) == t; }
    bool operator !=(int t) { return int(*this) != t; }
    bool operator <(int t) { return int(*this) < t; }
    bool operator >(int t) { return int(*this) > t; }
    bool operator <=(int t) { return int(*this) <= t; }
    bool operator >=(int t) { return int(*this) >= t; }
    qle_signedbitfield &operator +=(int i) {
        *this = (int(*this) + i);
        return *this;
    }
    qle_signedbitfield &operator -=(int i) {
        *this = (int(*this) - i);
        return *this;
    }
};

typedef qle_uint offset;

// round the size up to the next 4 byte boundary
inline int alignedSize(int size) { return (size + 3) & ~3; }

static inline bool useCompressed(const QString &s)
{
    if (s.length() >= 0x8000)
        return false;
    const ushort *uc = (const ushort *)s.constData();
    const ushort *e = uc + s.length();
    while (uc < e) {
        if (*uc > 0xff)
            return false;
        ++uc;
    }
    return true;
}

static inline int qStringSize(const QString &string, bool compress)
{
    int l = 2 + string.length();
    if (!compress)
        l *= 2;
    return alignedSize(l);
}

// returns INT_MAX if it can't compress it into 28 bits
static inline int compressedNumber(double d)
{
    // this relies on details of how ieee floats are represented
    const int exponent_off = 52;
    const quint64 fraction_mask = 0x000fffffffffffffull;
    const quint64 exponent_mask = 0x7ff0000000000000ull;

    quint64 val;
    memcpy (&val, &d, sizeof(double));
    int exp = (int)((val & exponent_mask) >> exponent_off) - 1023;
    if (exp < 0 || exp > 25)
        return INT_MAX;

    quint64 non_int = val & (fraction_mask >> exp);
    if (non_int)
        return INT_MAX;

    bool neg = (val >> 63) != 0;
    val &= fraction_mask;
    val |= ((quint64)1 << 52);
    int res = (int)(val >> (52 - exp));
    return neg ? -res : res;
}

class Latin1String;

class String
{
public:
    explicit String(const char *data) { d = (Data *)data; }

    struct Data {
        qle_uint length;
        qle_ushort utf16[1];
    };

    Data *d;

    int byteSize() const { return sizeof(uint) + sizeof(ushort) * d->length; }
    bool isValid(int maxSize) const {
        // Check byteSize() <= maxSize, avoiding integer overflow
        maxSize -= sizeof(uint);
        return maxSize >= 0 && uint(d->length) <= maxSize / sizeof(ushort);
    }

    inline String &operator=(const QString &str)
    {
        d->length = str.length();
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
        const ushort *uc = (const ushort *)str.unicode();
        for (int i = 0; i < str.length(); ++i)
            d->utf16[i] = uc[i];
#else
        memcpy(d->utf16, str.unicode(), str.length()*sizeof(ushort));
#endif
        if (str.length() & 1)
            d->utf16[str.length()] = 0;
        return *this;
    }

    inline bool operator ==(const QString &str) const {
        int slen = str.length();
        int l = d->length;
        if (slen != l)
            return false;
        const ushort *s = (const ushort *)str.constData();
        const qle_ushort *a = d->utf16;
        const ushort *b = s;
        while (l-- && *a == *b)
            a++,b++;
        return (l == -1);
    }
    inline bool operator !=(const QString &str) const {
        return !operator ==(str);
    }
    inline bool operator >=(const QString &str) const {
        // ###
        return toString() >= str;
    }

    inline bool operator<(const Latin1String &str) const;
    inline bool operator>=(const Latin1String &str) const { return !operator <(str); }
    inline bool operator ==(const Latin1String &str) const;

    inline bool operator ==(const String &str) const {
        if (d->length != str.d->length)
            return false;
        return !memcmp(d->utf16, str.d->utf16, d->length*sizeof(ushort));
    }
    inline bool operator<(const String &other) const;
    inline bool operator >=(const String &other) const { return !(*this < other); }

    inline QString toString() const {
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
        return QString((QChar *)d->utf16, d->length);
#else
        int l = d->length;
        QString str(l, Qt::Uninitialized);
        QChar *ch = str.data();
        for (int i = 0; i < l; ++i)
            ch[i] = QChar(d->utf16[i]);
        return str;
#endif
    }

};

class Latin1String
{
public:
    explicit Latin1String(const char *data) { d = (Data *)data; }

    struct Data {
        qle_ushort length;
        char latin1[1];
    };
    Data *d;

    int byteSize() const { return sizeof(ushort) + sizeof(char)*(d->length); }
    bool isValid(int maxSize) const {
        return byteSize() <= maxSize;
    }

    inline Latin1String &operator=(const QString &str)
    {
        int len = d->length = str.length();
        uchar *l = (uchar *)d->latin1;
        const ushort *uc = (const ushort *)str.unicode();
        int i = 0;
#ifdef __SSE2__
        for ( ; i + 16 <= len; i += 16) {
            __m128i chunk1 = _mm_loadu_si128((__m128i*)&uc[i]); // load
            __m128i chunk2 = _mm_loadu_si128((__m128i*)&uc[i + 8]); // load
            // pack the two vector to 16 x 8bits elements
            const __m128i result = _mm_packus_epi16(chunk1, chunk2);
            _mm_storeu_si128((__m128i*)&l[i], result); // store
        }
#  ifdef Q_PROCESSOR_X86_64
        // we can do one more round, of 8 characters
        if (i + 8 <= len) {
            __m128i chunk = _mm_loadu_si128((__m128i*)&uc[i]); // load
            // pack with itself, we'll discard the high part anyway
            chunk = _mm_packus_epi16(chunk, chunk);
            // unaligned 64-bit store
            qToUnaligned(_mm_cvtsi128_si64(chunk), l + i);
            i += 8;
        }
#  endif
#endif
        for ( ; i < len; ++i)
            l[i] = uc[i];
        for ( ; (quintptr)(l+i) & 0x3; ++i)
            l[i] = 0;
        return *this;
    }

    QLatin1String toQLatin1String() const Q_DECL_NOTHROW {
        return QLatin1String(d->latin1, d->length);
    }

    inline bool operator<(const String &str) const
    {
        const qle_ushort *uc = (qle_ushort *) str.d->utf16;
        if (!uc || *uc == 0)
            return false;

        const uchar *c = (uchar *)d->latin1;
        const uchar *e = c + qMin((int)d->length, (int)str.d->length);

        while (c < e) {
            if (*c != *uc)
                break;
            ++c;
            ++uc;
        }
        return (c == e ? (int)d->length < (int)str.d->length : *c < *uc);

    }
    inline bool operator ==(const String &str) const {
        return (str == *this);
    }
    inline bool operator >=(const String &str) const {
        return !(*this < str);
    }

    inline QString toString() const {
        return QString::fromLatin1(d->latin1, d->length);
    }
};

#define DEF_OP(op) \
    inline bool operator op(Latin1String lhs, Latin1String rhs) Q_DECL_NOTHROW \
    { \
        return lhs.toQLatin1String() op rhs.toQLatin1String(); \
    } \
    inline bool operator op(QLatin1String lhs, Latin1String rhs) Q_DECL_NOTHROW \
    { \
        return lhs op rhs.toQLatin1String(); \
    } \
    inline bool operator op(Latin1String lhs, QLatin1String rhs) Q_DECL_NOTHROW \
    { \
        return lhs.toQLatin1String() op rhs; \
    } \
    inline bool operator op(const QString &lhs, Latin1String rhs) Q_DECL_NOTHROW \
    { \
        return lhs op rhs.toQLatin1String(); \
    } \
    inline bool operator op(Latin1String lhs, const QString &rhs) Q_DECL_NOTHROW \
    { \
        return lhs.toQLatin1String() op rhs; \
    } \
    /*end*/
DEF_OP(==)
DEF_OP(!=)
DEF_OP(< )
DEF_OP(> )
DEF_OP(<=)
DEF_OP(>=)
#undef DEF_OP

inline bool String::operator ==(const Latin1String &str) const
{
    if ((int)d->length != (int)str.d->length)
        return false;
    const qle_ushort *uc = d->utf16;
    const qle_ushort *e = uc + d->length;
    const uchar *c = (uchar *)str.d->latin1;

    while (uc < e) {
        if (*uc != *c)
            return false;
        ++uc;
        ++c;
    }
    return true;
}

inline bool String::operator <(const String &other) const
{
    int alen = d->length;
    int blen = other.d->length;
    int l = qMin(alen, blen);
    qle_ushort *a = d->utf16;
    qle_ushort *b = other.d->utf16;

    while (l-- && *a == *b)
        a++,b++;
    if (l==-1)
        return (alen < blen);
    return (ushort)*a < (ushort)*b;
}

inline bool String::operator<(const Latin1String &str) const
{
    const uchar *c = (uchar *) str.d->latin1;
    if (!c || *c == 0)
        return false;

    const qle_ushort *uc = d->utf16;
    const qle_ushort *e = uc + qMin((int)d->length, (int)str.d->length);

    while (uc < e) {
        if (*uc != *c)
            break;
        ++uc;
        ++c;
    }
    return (uc == e ? (int)d->length < (int)str.d->length : (ushort)*uc < *c);

}

static inline void copyString(char *dest, const QString &str, bool compress)
{
    if (compress) {
        Latin1String string(dest);
        string = str;
    } else {
        String string(dest);
        string = str;
    }
}

/*
 Base is the base class for both Object and Array. Both classe work more or less the same way.
 The class starts with a header (defined by the struct below), then followed by data (the data for
 values in the Array case and Entry's (see below) for objects.

 After the data a table follows (tableOffset points to it) containing Value objects for Arrays, and
 offsets from the beginning of the object to Entry's in the case of Object.

 Entry's in the Object's table are lexicographically sorted by key in the table(). This allows the usage
 of a binary search over the keys in an Object.
 */
class Base
{
public:
    qle_uint size;
    union {
        uint _dummy;
        qle_bitfield<0, 1> is_object;
        qle_bitfield<1, 31> length;
    };
    offset tableOffset;
    // content follows here

    inline bool isObject() const { return !!is_object; }
    inline bool isArray() const { return !isObject(); }

    inline offset *table() const { return (offset *) (((char *) this) + tableOffset); }

    int reserveSpace(uint dataSize, int posInTable, uint numItems, bool replace);
    void removeItems(int pos, int numItems);
};

class Object : public Base
{
public:
    Entry *entryAt(int i) const {
        return reinterpret_cast<Entry *>(((char *)this) + table()[i]);
    }
    int indexOf(const QString &key, bool *exists) const;
    int indexOf(QLatin1String key, bool *exists) const;

    bool isValid(int maxSize) const;
};

class Array : public Base
{
public:
    inline Value at(int i) const;
    inline Value &operator [](int i);

    bool isValid(int maxSize) const;
};

class Value
{
public:
    enum {
        MaxSize = (1<<27) - 1
    };
    union {
        uint _dummy;
        qle_bitfield<0, 3> type;
        qle_bitfield<3, 1> latinOrIntValue;
        qle_bitfield<4, 1> latinKey;
        qle_bitfield<5, 27> value;
        qle_signedbitfield<5, 27> int_value;
    };

    inline char *data(const Base *b) const { return ((char *)b) + value; }
    int usedStorage(const Base *b) const;

    bool toBoolean() const;
    double toDouble(const Base *b) const;
    QString toString(const Base *b) const;
    String asString(const Base *b) const;
    Latin1String asLatin1String(const Base *b) const;
    Base *base(const Base *b) const;

    bool isValid(const Base *b) const;

    static int requiredStorage(QJsonValue &v, bool *compressed);
    static uint valueToStore(const QJsonValue &v, uint offset);
    static void copyData(const QJsonValue &v, char *dest, bool compressed);
};
Q_DECLARE_JSONPRIVATE_TYPEINFO(Value, Q_PRIMITIVE_TYPE)

inline Value Array::at(int i) const
{
    return *(Value *) (table() + i);
}

inline Value &Array::operator [](int i)
{
    return *(Value *) (table() + i);
}

class Entry {
public:
    Value value;
    // key
    // value data follows key

    uint size() const {
        int s = sizeof(Entry);
        if (value.latinKey)
            s += shallowLatin1Key().byteSize();
        else
            s += shallowKey().byteSize();
        return alignedSize(s);
    }

    int usedStorage(Base *b) const {
        return size() + value.usedStorage(b);
    }

    String shallowKey() const
    {
        Q_ASSERT(!value.latinKey);
        return String((const char *)this + sizeof(Entry));
    }
    Latin1String shallowLatin1Key() const
    {
        Q_ASSERT(value.latinKey);
        return Latin1String((const char *)this + sizeof(Entry));
    }
    QString key() const
    {
        if (value.latinKey) {
            return shallowLatin1Key().toString();
        }
        return shallowKey().toString();
    }

    bool isValid(int maxSize) const {
        if (maxSize < (int)sizeof(Entry))
            return false;
        maxSize -= sizeof(Entry);
        if (value.latinKey)
            return shallowLatin1Key().isValid(maxSize);
        return shallowKey().isValid(maxSize);
    }

    bool operator ==(const QString &key) const;
    inline bool operator !=(const QString &key) const { return !operator ==(key); }
    inline bool operator >=(const QString &key) const;

    bool operator==(QLatin1String key) const;
    inline bool operator!=(QLatin1String key) const { return !operator ==(key); }
    inline bool operator>=(QLatin1String key) const;

    bool operator ==(const Entry &other) const;
    bool operator >=(const Entry &other) const;
};

inline bool Entry::operator >=(const QString &key) const
{
    if (value.latinKey)
        return (shallowLatin1Key() >= key);
    else
        return (shallowKey() >= key);
}

inline bool Entry::operator >=(QLatin1String key) const
{
    if (value.latinKey)
        return shallowLatin1Key() >= key;
    else
        return shallowKey() >= key;
}

inline bool operator <(const QString &key, const Entry &e)
{ return e >= key; }

inline bool operator<(QLatin1String key, const Entry &e)
{ return e >= key; }

class Header {
public:
    qle_uint tag; // 'qbjs'
    qle_uint version; // 1
    Base *root() { return (Base *)(this + 1); }
};

inline bool Value::toBoolean() const
{
    Q_ASSERT(type == QJsonValue::Bool);
    return value != 0;
}

inline double Value::toDouble(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::Double);
    if (latinOrIntValue)
        return int_value;

    quint64 i = qFromLittleEndian<quint64>((const uchar *)b + value);
    double d;
    memcpy(&d, &i, sizeof(double));
    return d;
}

inline String Value::asString(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::String && !latinOrIntValue);
    return String(data(b));
}

inline Latin1String Value::asLatin1String(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::String && latinOrIntValue);
    return Latin1String(data(b));
}

inline QString Value::toString(const Base *b) const
{
    if (latinOrIntValue)
        return asLatin1String(b).toString();
    else
        return asString(b).toString();
}

inline Base *Value::base(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::Array || type == QJsonValue::Object);
    return reinterpret_cast<Base *>(data(b));
}

class Data {
public:
    enum Validation {
        Unchecked,
        Validated,
        Invalid
    };

    QAtomicInt ref;
    int alloc;
    union {
        char *rawData;
        Header *header;
    };
    uint compactionCounter : 31;
    uint ownsData : 1;

    inline Data(char *raw, int a)
        : alloc(a), rawData(raw), compactionCounter(0), ownsData(true)
    {
    }
    inline Data(int reserved, QJsonValue::Type valueType)
        : rawData(0), compactionCounter(0), ownsData(true)
    {
        Q_ASSERT(valueType == QJsonValue::Array || valueType == QJsonValue::Object);

        alloc = sizeof(Header) + sizeof(Base) + reserved + sizeof(offset);
        header = (Header *)malloc(alloc);
        Q_CHECK_PTR(header);
        header->tag = QJsonDocument::BinaryFormatTag;
        header->version = 1;
        Base *b = header->root();
        b->size = sizeof(Base);
        b->is_object = (valueType == QJsonValue::Object);
        b->tableOffset = sizeof(Base);
        b->length = 0;
    }
    inline ~Data()
    { if (ownsData) free(rawData); }

    uint offsetOf(const void *ptr) const { return (uint)(((char *)ptr - rawData)); }

    QJsonObject toObject(Object *o) const
    {
        return QJsonObject(const_cast<Data *>(this), o);
    }

    QJsonArray toArray(Array *a) const
    {
        return QJsonArray(const_cast<Data *>(this), a);
    }

    Data *clone(Base *b, int reserve = 0)
    {
        int size = sizeof(Header) + b->size;
        if (b == header->root() && ref.load() == 1 && alloc >= size + reserve)
            return this;

        if (reserve) {
            if (reserve < 128)
                reserve = 128;
            size = qMax(size + reserve, qMin(size *2, (int)Value::MaxSize));
            if (size > Value::MaxSize) {
                qWarning("QJson: Document too large to store in data structure");
                return 0;
            }
        }
        char *raw = (char *)malloc(size);
        Q_CHECK_PTR(raw);
        memcpy(raw + sizeof(Header), b, b->size);
        Header *h = (Header *)raw;
        h->tag = QJsonDocument::BinaryFormatTag;
        h->version = 1;
        Data *d = new Data(raw, size);
        d->compactionCounter = (b == header->root()) ? compactionCounter : 0;
        return d;
    }

    void compact();
    bool valid() const;

private:
    Q_DISABLE_COPY(Data)
};

}

QT_END_NAMESPACE

#endif // QJSON_P_H