text:
## Table of contents

- Setup: [Getting started](#getting-started) · [Requirements](#requirements) · [Config](#config) · [Compilation](#compilation) · [Webpack](#webpack) · [Snowpack](snowpack.md)
- Usage: [Fixtures](#fixtures) · [Decorators](#decorators) · [Mocks](#declarative-mocks) · [Control panel](#control-panel) · [UI plugins](#ui-plugins) · [Static export](#static-export) · [React Native](#react-native) · [Server-side APIs](#server-side-apis)
- FAQ: [Create React App](#create-react-app) · [Next.js](#nextjs) · [Troubleshooting](#troubleshooting) · [Where's my old Cosmos?](#wheres-my-old-cosmos) · [Roadmap](../TODO.md)

The [example package](../example) is a useful complement to this guide.

## Getting started

1\. **Install React Cosmos**

```bash
# Using npm
npm i --D react-cosmos
# or Yarn
yarn add --dev react-cosmos
```

> Please see [Compilation](#compilation) to make sure you installed all necessary dependencies.

2\. **Add package.json scripts**

```diff
"scripts": {
+  "cosmos": "cosmos",
+  "cosmos:export": "cosmos-export"
}
```

3\. **Start React Cosmos**

```bash
# Using npm
npm run cosmos
# or Yarn
yarn cosmos
```

🚀 **[localhost:5000](http://localhost:5000)**

> You may also run `npx react-cosmos` in your project without installing any deps.

4\. **Create your first fixture**

Choose a simple component to get started.

<!-- prettier-ignore -->
```jsx
// Hello.jsx
import React from 'react';

export function Hello({ greeting, name }) {
  return <h1>{greeting}, {name}!</h1>;
}
```

Create a `.fixture` file. You can [customize this convention](#how-to-create-fixture-files) later.

> Fixture files contain a default export, which can be a React Component or any React Node.

```jsx
// Hello.fixture.jsx
import React from 'react';
import { Hello } from '../Hello';

export default <Hello greeting="Aloha" name="Alexa" />;
```

The `hello` fixture will show up in your React Cosmos UI and will render when you select it.

5\. **Build amazing user interfaces**

You've taken the first step towards designing reusable components. You can now prototype, test and interate on components in isolation. Use this to your advantage!

_Something wrong?_ Don't hesitate to [create a GitHub issue](https://github.com/react-cosmos/react-cosmos/issues/new/choose) (be helpful and include details) and to [join us on Slack](https://react-cosmos.slack.com/join/shared_invite/zt-g9rsalqq-clCoV7DWttVvzO5FAAmVAw).

## Requirements

The only hard requirements are React 16.8 and Node 10 (or newer).

React Cosmos works best with webpack 4. It takes extra effort to make it work with other bundlers, but it's not as scary as it might seem. Don't be afraid to ask for support.

> [Browserify](https://github.com/react-cosmos/react-cosmos-classic/tree/14e1a258f746df401a41ab65429df0d296b910e4/examples/browserify) and [Parcel](https://github.com/react-cosmos/parcel-ts-example) examples are available for Cosmos Classic. Props to whoever adapts them to React Cosmos 5!

## Config

No config is required to start. If you have custom needs or would like to convert a Cosmos Classic config, here's what you need to know.

The React Cosmos config is a **JSON** file, so it can only host serializable values. This design decision is meant to discourage complex configuration, make it easy to embed config options into the UI, and enable visual config management in the future.

By default, Cosmos reads `cosmos.config.json` from your root directory. You can pass a `--config` CLI arg for a custom config path.

> Most Cosmos Classic config options are still supported in the new JSON format. [Let me know](https://react-cosmos.slack.com/join/shared_invite/zt-g9rsalqq-clCoV7DWttVvzO5FAAmVAw) if you need old config options that no longer work.

### Available options

The best way to learn about the available options in the Cosmos config is to use [config.schema.json](../packages/react-cosmos/config.schema.json).

The schema is human readable, but you can also enhance your config with autocomplete in code editors like VS Code.

```jsonc
{
  "$schema": "http://json.schemastore.org/cosmos-config"
  // your options...
}
```

And if you use VS Code you can map the Cosmos config schema globally by [extending your user settings](https://code.visualstudio.com/docs/languages/json#_mapping-in-the-user-settings).

```json
"json.schemas": [
  {
    "fileMatch": ["cosmos.config.json"],
    "url": "http://json.schemastore.org/cosmos-config"
  }
]
```

Alternatively, you can reference the local Cosmos config schema in your workspace configuration.

```json
"json.schemas": [
  {
    "fileMatch": ["cosmos.config.json"],
    "url": "./node_modules/react-cosmos/config.schema.json"
  }
]
```

## Compilation

How you compile your code is 100% your business. React Cosmos jumps through hoops to compile your code using your existing build pipeline, but it doesn't install any additional dependencies that your setup requires to compile your code.

**React Cosmos compiles your code using the build dependencies already installed in your project.**

Unless you use a framework like Create React App or Next.js, you need to install build dependencies yourself. This includes stuff like Babel, TypeScript, webpack loaders, html-webpack-plugin, etc.

Here is a common list of packages required to build React with webpack and Babel:

> @babel/core @babel/preset-env @babel/preset-react babel-loader style-loader css-loader html-webpack-plugin@4

And unless you use a framework that does it under the hood, create a `.babelrc` (or similar) config in your project root.

```
{
  "presets": ["@babel/env", "@babel/react"]
}
```

## Webpack

Configuring webpack is the least romantic aspect of the Cosmos setup. Luckily, you only do it once. Depending on your setup, one of the following options will work for you.

### Default webpack config

In many cases Cosmos manages to get webpack working without human intervention. Try running Cosmos as is first.

### Custom webpack config

Probably the most common scenario. Most of us end up with a hairy webpack config sooner or later. Use the `webpack.configPath` setting to point to an existing webpack config.

```json
{
  "webpack": {
    "configPath": "./webpack.config.js"
  }
}
```

> You can also point to a module inside a dependency, like in the [Create React App](#create-react-app) example.

### Webpack config override

Overriding the webpack config gives you complete control. Use the `webpack.overridePath` setting to point to a module that customizes the webpack config used by Cosmos.

```json
{
  "webpack": {
    "overridePath": "./webpack.override.js"
  }
}
```

The override function receives a base webpack config — the default one generated by Cosmos or a custom one loaded from `webpack.configPath`. Extend the input config and return the result.

```js
// webpack.override.js
module.exports = (webpackConfig, env) => {
  return { ...webpackConfig /* do your thing */ };
};
```

### Output filename

Cosmos overwrites `output.filename` in the webpack config to `[name].js` by default. Due to caching, this isn't ideal when generating static exports via `cosmos-export` command. Use the `webpack.includeHashInOutputFilename` setting to change the filename template to `[name].[contenthash].js`.

```json
{
  "webpack": {
    "includeHashInOutputFilename": true
  }
}
```

## Fixtures

Fixture files contain a default export, which can be a React Component or any React Node.

> `React` must be imported in every fixture file.

The file paths of your fixture files (relative to your project root) are used to create a tree view explorer in the React Cosmos UI.

### Node fixtures

> Think of Node fixtures as the return value of a function component, or the first argument to `React.render`.

```jsx
// Button.fixture.jsx
export default <Button disabled>Click me</Button>;
```

### Component fixtures

Component fixtures are just function components with no props. They enable using Hooks inside fixtures, which is powerful for simulating state with stateless components.

```jsx
// CounterButton.fixture.jsx
export default () => {
  const [count, setCount] = React.useState(0);
  return <CounterButton count={count} increment={() => setCount(count + 1)} />;
};
```

### Multi fixture files

A fixture file can also export multiple fixtures if the default export is an object.

```jsx
// Button.fixture.jsx
export default {
  primary: <PrimaryButton>Click me</PrimaryButton>,
  primaryDisabled: <PrimaryButton disabled>Click me</PrimaryButton>,
  secondary: <SecondaryButton>Click me</SecondaryButton>,
  secondaryDisabled: <SecondaryButton disabled>Click me</SecondaryButton>,
};
```

The object property names will show up as fixture names in the Cosmos UI.

> [See this comment](https://github.com/react-cosmos/react-cosmos/issues/924#issuecomment-462082405) for the reasoning behind this solution (vs named exports).

### How to create fixture files

Two options:

1. End fixture file names with `.fixture.{js,jsx,ts,tsx}`
2. Put fixture files inside `__fixtures__`

Examples:

1. `blankState.fixture.jsx`
2. `__fixtures__/blankState.jsx`

> File name conventions can be configured using the `fixturesDir` and `fixtureFileSuffix` options.

**IMPORTANT:** Fixture files must be placed in the `src` directory when using Create React App, in order for Cosmos to bundle in the exact same environment as Create React App's.

## Decorators

Wrapping components inside fixtures is easy, but can become repetitive. _Decorators_ can be used to apply one or more component wrappers to a group of fixtures automatically.

A `cosmos.decorator` file looks like this:

```jsx
// cosmos.decorator.js
export default ({ children }) => <Provider store={store}>{children}</Provider>;
```

> A decorator only applies to fixture files contained in the decorator's directory. Decorators can be composed, in the order of their position in the file system hierarchy (from outer to inner).

### Migrating _proxies_

Migrating Cosmos Classic proxies to React Cosmos 5 is not intuitive. _Sorry for that!_ Check out the [nested decorators example](../example/src/NestedDecorators) and join the `#proxies-upgrade` [Slack](https://react-cosmos.slack.com/join/shared_invite/zt-g9rsalqq-clCoV7DWttVvzO5FAAmVAw) channel to learn more about this and to get help with your migration.

### Redux state mock

Check out [react-cosmos-redux](https://github.com/skidding/react-cosmos-redux) to see what an advanced React Cosmos decorator looks like.

## Declarative mocks

Coming up with dummy prop values is all that's required to create fixtures for many components. In other cases, however, components have _special needs_.

Some components need to be wrapped in certain _contexts_, like a Router provider. Other components fire `fetch` requests willy-nilly. All these implicit dependencies are component inputs and understanding them goes a long way.

The [react-mock](https://github.com/skidding/react-mock) project provides ways for mocking implicit component dependencies and helps you create fixtures for _stubborn_ components.

## Control panel

The [props panel](https://twitter.com/ReactCosmos/status/1139838627976843264) allows you to manipulate component props visually by default. But you can also get a custom control panel by manually defining the UI controls in your fixtures.

### `useValue`

```jsx
// CounterButton.fixture.jsx
import { useValue } from 'react-cosmos/fixture';

export default () => {
  const [count, setCount] = useValue('count', { defaultValue: 0 });
  return <CounterButton count={count} increment={() => setCount(count + 1)} />;
};
```

### `useSelect`

```jsx
// Button.fixture.jsx
import { useSelect } from 'react-cosmos/fixture';

export default () => {
  // useSelect also returns a setter as the second value in the return tuple,
  // like the useState hook, in case you want to change the value programatically.
  const [buttonType] = useSelect('buttonType', {
    options: ['primary', 'secondary', 'danger'],
  });
  return <Button type={buttonType}>Press me</Button>;
};
```

> Heads up: `useValue` and `useSelect` (and Cosmos in general) work great with TypeScript.

## UI plugins

A main feature of the React Cosmos redesign is the brand-new UI plugin architecture. While the new UI is created 100% from plugins, the plugin API is not yet documented nor made accessible. It will take a few big steps to get there, but this is the future.

### Custom [responsive viewports](https://twitter.com/ReactCosmos/status/1158701342208208897)

`responsivePreview` is a plugin included by default, and you can customize it through the Cosmos config.

```json
{
  "ui": {
    "responsivePreview": {
      "devices": [
        { "label": "iPhone 5", "width": 320, "height": 568 },
        { "label": "iPhone 6", "width": 375, "height": 667 },
        { "label": "iPhone 6 Plus", "width": 414, "height": 736 },
        { "label": "Medium", "width": 1024, "height": 768 },
        { "label": "Large", "width": 1440, "height": 900 },
        { "label": "1080p", "width": 1920, "height": 1080 }
      ]
    }
  }
}
```

## Static export

Run `cosmos-export` and get a nice component library that you can deploy to any static hosting service. The exported version won't have all the Cosmos features available in development (like opening the selected fixture in your code editor), but allows anybody with access to the static export URL to browse fixtures and play with component inputs.

> Use [http-server](https://github.com/indexzero/http-server) or any static file server to load the export locally.

## React Native

```
npm run cosmos-native
```

React Cosmos works great with React Native. Put the following inside `App.js` to get started.

```jsx
import React, { Component } from 'react';
import { NativeFixtureLoader } from 'react-cosmos/native';
// You generate cosmos.userdeps.js when you start the Cosmos server
import { rendererConfig, fixtures, decorators } from './cosmos.userdeps.js';

export default class App extends Component {
  render() {
    return (
      <NativeFixtureLoader
        rendererConfig={rendererConfig}
        fixtures={fixtures}
        decorators={decorators}
      />
    );
  }
}
```

Once your fixtures are loading properly, you'll probably want to split your App entry point to load Cosmos in development and your root component in production. Something like this:

```js
module.exports = global.__DEV__
  ? require('./App.cosmos')
  : require('./App.main');
```

**IMPORTANT:** React Native blacklists `__fixtures__` dirs by default. Unless you configure Cosmos to use a different directory pattern, you need to [override `getBlacklistRE` in the React Native CLI config](https://github.com/skidding/jobs-done/blob/585b1c472a123c9221dfec9018c9fa1e976d715e/rn-cli.config.js).

### React Native for Web

Run `cosmos --external-userdeps` instead of `cosmos-native` and Cosmos will [mirror your fixtures on both DOM and Native renderers](https://twitter.com/ReactCosmos/status/1156147491026472964).

## Server-side APIs

> Do **NOT** use these APIs in your fixture files, or any of your client code, as they require access to the file system and may bundle unwanted Node code in your client build.

### Config

Fetching a Cosmos config can be done in a number of ways, depending on whether or not you have a config file and, in case you do, if you prefer to specify the path manually or to rely on automatic detection.

#### Detect existing config based on cwd

`detectCosmosConfig` uses the same config detection strategy as the `cosmos` command.

```js
import { detectCosmosConfig } from 'react-cosmos';

const cosmosConfig = detectCosmosConfig();
```

#### Read existing config at exact path

`getCosmosConfigAtPath` is best when you don't want to care where you run a script from.

```js
import { getCosmosConfigAtPath } from 'react-cosmos';

const cosmosConfig = getCosmosConfigAtPath(require.resolve('./cosmos.config'));
```

#### Create default config

The minimum requirement to create a config is a root directory.

```js
import { createCosmosConfig } from 'react-cosmos';

const cosmosConfig = createCosmosConfig(__dirname);
```

#### Create custom config

You can also customize your config programatically, without the need for an external config file.

```js
import { createCosmosConfig } from 'react-cosmos';

const cosmosConfig = createCosmosConfig(__dirname, {
  // Options... (TypeScript is your friend)
});
```

### Fixtures

Get all your fixtures programatically. A ton of information is provided for each fixture, enabling you to hack away on top of React Cosmos. To generate visual snapshots from your fixtures, you load `rendererUrl` in a headless browser like [Puppeteer](https://github.com/puppeteer/puppeteer) and take a screenshot on page load. You can compare visual snapshots between deploys to catch sneaky UI regressions.

```js
import { getFixtures2 } from 'react-cosmos';

const fixtures = getFixtures2(cosmosConfig);

console.log(fixtures);
// [
//   {
//     "absoluteFilePath": "/path/to/components/pages/Error/__fixtures__/not-found.js",
//     "fileName": "not-found",
//     "name": null,
//     "parents": ["pages", "Error"]
//     "playgroundUrl": "http://localhost:5000/?fixtureId=%7B%22path%22%3A%22components%2Fpages%2FError%2F__fixtures__%2Fnot-found.js%22%2C%22name%22%3Anull%7D",
//     "relativeFilePath": "components/pages/Error/__fixtures__/not-found.js",
//     "rendererUrl": "http://localhost:5000/static/_renderer.html?_fixtureId=%7B%22path%22%3A%22components%2Fpages%2FError%2F__fixtures__%2Fnot-found.js%22%2C%22name%22%3Anull%7D",
//     "treePath": ["pages", "Error", "not-found"]
//   },
//   ...
```

> See a more complete output example [here](https://github.com/react-cosmos/react-cosmos/blob/d8b94c4f088cc7b0fdbab3e080858ed4dbb04bcb/example/fixtures2.test.ts).

Aside from the fixture information showcased above, each fixture object returned also contains a `getElement` function property, which takes no arguments. `getElement` allows you to render fixtures in your own time, in environments like jsdom. Just as in the React Cosmos UI, the fixture element will include any decorators you've defined for your fixtures. `getElement` can be used for Jest snapshot testing.

> The function is called `getFixtures2` because it supersedes a previous function that's no longer documented, but wasn't removed for backwards compatibility.

## Create React App

- Set `webpack.configPath` to `react-scripts/config/webpack.config`. Unless you use react-app-rewired (see below).
- Make sure to place fixture and decorator files in the `src` directory.
- Set `staticPath` to `public` to load static assets inside React Cosmos.
- Restrict `watchDirs` to `src` to ignore file changes outside the source directory.

This is a `cosmos.config.json` example for Create React App:

```json
{
  "staticPath": "public",
  "watchDirs": ["src"],
  "webpack": {
    "configPath": "react-scripts/config/webpack.config"
  }
}
```

### Using react-app-rewired

In a standard Create React App setup you config React Cosmos to use CRA's internal webpack config (see above). With react-app-rewired, however, create the following webpack config in your project root instead.

```js
// webpack.config.js
const { paths } = require('react-app-rewired');
const overrides = require('react-app-rewired/config-overrides');
const config = require(paths.scriptVersion + '/config/webpack.config.dev');

module.exports = overrides.webpack(config, process.env.NODE_ENV);
```

> React Cosmos picks up `webpack.config.js` automatically. Use `webpack.configPath` if you prefer to customize the webpack config path.

### Using CRACO with Tailwind CSS

[CRACO](https://github.com/gsoft-inc/craco) is an alternative to react-app-rewired for overriding CRA's internal webpack config. [Tailwind CSS](https://github.com/tailwindlabs/tailwindcss) recommends using CRACO to override CRA's PostCSS settings, which is why this guide targets CRACO and Tailwind CSS together.

- Create `webpack.config.js` in your root folder (if you haven't already) with the following contents:

```js
/* webpack.config.js */
const { createWebpackDevConfig } = require('@craco/craco');
const cracoConfig = require('./craco.config.js');
const webpackConfig = createWebpackDevConfig(cracoConfig);

module.exports = webpackConfig;
```

- If you're using Tailwind CSS or another similar CSS library, add your global CSS to `globalImports` in the Cosmos config. Create `cosmos.config.json` in your root folder (if you haven't already) with the following contents:

```json
{
  "globalImports": ["src/index.css"],
  "staticPath": "public"
}
```

> Cosmos picks up `webpack.config.js` automatically. Since you're relying on the exported wepack config generated by CRACO, don't forgot to remove `"webpack.configPath": "react-scripts/config/webpack.config"` from your `cosmos.config.json` if you previously set it. Use `webpack.configPath` if you prefer to customize the webpack config path.

> `globalImports` accepts an array of paths and you can add additional global CSS files like this: `"globalImports": ["src/index.css", "src/app.css"]`.

## Next.js

> **Currently Cosmos doesn't work with Next.js v10.0.6 or above. Downgrade to `next@10.0.5` until the issue is resolved. Read [#1289](https://github.com/react-cosmos/react-cosmos/issues/1289) for more context.**

> The following steps are required for running Cosmos in **Next.js v10**. [This repo](https://github.com/react-cosmos/react-cosmos-nextjs) is a working example. [Ask for help](https://react-cosmos.slack.com/join/shared_invite/zt-g9rsalqq-clCoV7DWttVvzO5FAAmVAw) if you're having issues integrating Cosmos with an older version of Next.js.

- Install `html-webpack-plugin@4` as a dev dependency.
- Configure Babel to use the `next/babel` preset.
- Optional: Set `staticPath` to `public` to load static assets inside Cosmos.
- Optional: Add `styles/globals.css` to `globalImports` to automatically load global CSS in Cosmos fixtures.

This is a `cosmos.config.json` example for Next.js:

```json
{
  "globalImports": ["styles/globals.css"],
  "staticPath": "public"
}
```

This is a `.babelrc` example for Next.js:

```json
{
  "presets": ["next/babel"],
  "plugins": []
}
```

## Troubleshooting

> **Warning**: Most React Cosmos issues are related to missing build dependencies. Please see [Compilation](#compilation).

#### localhost:5000/\_renderer.html 404s?

- Check for build errors in your terminal.
- Make sure you have html-webpack-plugin@4 installed, as well as [any other build dependency](#compilation).

#### Renderer not responding?

- Try renaming `filename` in HtmlWebpackPlugin options to `index.html`, or alternatively remove HtmlWebpackPlugin from your webpack config since Cosmos will create one for you if none is found. For more details see [this issue](https://github.com/react-cosmos/react-cosmos/issues/1220).

#### "Failed to execute postMessage..."?

- [You may have a URL instance in your state](https://github.com/react-cosmos/react-cosmos/issues/1002).

#### "localhost:3001/\_\_get-internal-source..." 404s?

- [Try changing your webpack `devtool` to something like `cheap-module-source-map`](https://github.com/react-cosmos/react-cosmos/issues/1045#issuecomment-535150617).

#### main.js file is cached?

- [Set `includeHashInOutputFilename` to `true`](https://github.com/react-cosmos/react-cosmos/tree/main/docs#output-filename).

#### Serving a static export from a nested path?

- [Set `publicUrl` to a relative path, like `"./"`](https://github.com/react-cosmos/react-cosmos/issues/1149).

#### Fixtures not detected?

- Run `cosmos` with the `--external-userdeps` flag. This should generate `cosmos.userdeps.js`. Check that file to see if your fixtures are being picked up by Cosmos.
- Check your directory structure. If you are using a Cosmos config file, Cosmos will use the directory of the config file as the root of your project. If your Cosmos config file is nested in a directory that isn't an ancestor of your fixture files, Cosmos will not find your fixtures. To solve this add a [`rootDir`](https://github.com/react-cosmos/react-cosmos/blob/d800a31b39d82c810f37a2ad0d25eed5308b830a/packages/react-cosmos/config.schema.json#L10-L14) entry to your Cosmos config pointing to your root directory.

## Where's my old Cosmos?

Cosmos Classic packages have been moved to [a dedicated repo](https://github.com/react-cosmos/react-cosmos-classic), which means we can continue to maintain Cosmos Classic or even run it alongside React Cosmos 5 in the same project (during the migration period).

That said, it's ideal for all Cosmos users to use the latest version. Please [let me know](https://react-cosmos.slack.com/join/shared_invite/zt-g9rsalqq-clCoV7DWttVvzO5FAAmVAw) if you need help upgrading.

---

[Join us on Slack](https://react-cosmos.slack.com/join/shared_invite/zt-g9rsalqq-clCoV7DWttVvzO5FAAmVAw) for feedback and questions.


text:
namespace dotless.Core.Parser
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class Zone
    {
        public Zone(NodeLocation location)
            : this(location, null, null)
        {
        }

        public Zone(NodeLocation location, string error, Zone callZone)
        {
            var input = location.Source;
            var index = location.Index;

            if (index > input.Length)
            {
                index = input.Length;
            }

            int lineNumber, position;
            GetLineNumber(location, out lineNumber, out position);

            var lines = input.Split('\n');

            FileName = location.FileName;
            Message = error;
            CallZone = callZone;
            LineNumber = lineNumber + 1;
            Position = position;
            Extract = new Extract(lines, lineNumber);
        }

        public static int GetLineNumber(NodeLocation location)
        {
            int lineNumber, position;
            GetLineNumber(location, out lineNumber, out position);
            return lineNumber + 1;
        }

        private static void GetLineNumber(NodeLocation location, out int lineNumber, out int position)
        {
            var input = location.Source;
            var index = location.Index;

            if (location.Index > input.Length)
            {
                index = input.Length;
            }

            var first = input.Substring(0, index);

            var start = first.LastIndexOf('\n') + 1;
            lineNumber = first.Count(c => c == '\n');
            position = index - start;
        }

        public int LineNumber { get; set; }
        public int Position { get; set; }
        public Extract Extract { get; set; }
        public string Message { get; set; }
        public string FileName { get; set; }
        public Zone CallZone { get; set; }
    }

    public class Extract
    {
        public Extract(string[] lines, int line)
        {
            Before = line > 0 ? lines[line - 1] : "/beginning of file";
            Line = lines[line];
            After = line + 1 < lines.Length ? lines[line + 1] : "/end of file";
        }

        public string After { get; set; }
        public string Before { get; set; }
        public string Line { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class Action_Do_Nothing : MonoBehaviour {
	public string ObjectToActivate;

	public void PerformAction()
	{
		GameObject objToActivate=GameObject.Find (ObjectToActivate);
		Debug.Log (this.name + " Action Do Nothing");
		objToActivate.SendMessage("Activate");
	}
}


text:
package mse

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// ZnodeModel is a nested struct in mse response
type ZnodeModel struct {
	Data string `json:"Data" xml:"Data"`
	Path string `json:"Path" xml:"Path"`
	Dir  bool   `json:"Dir" xml:"Dir"`
	Name string `json:"Name" xml:"Name"`
}


text:
<?php
namespace Hx\Authorize\Repo;

class DbRepository implements \Hx\Authorize\RepositoryInterface {

	private $selectNameSql, $selectListSql;
	private $userDbMapper, $accessDbMapper, $criteriaDbMapper;

	public function __construct(
		\Hx\Database\SqlServiceInterface $sqlService,
		\Hx\Authenticate\Repo\DbMapperInterface $userDbMapper,
		\Hx\Authorize\Repo\AccessDbMapperInterface $accessDbMapper,
		\Hx\Authorize\Repo\CriteriaDbMapperInterface $criteriaDbMapper)
	{
		$this->selectListSql = $sqlService->createSelectSql();

		$this->selectNameSql = $sqlService->createSelectSql();

		$this->userDbMapper = $userDbMapper;

		$this->accessDbMapper = $accessDbMapper;

		$this->criteriaDbMapper = $criteriaDbMapper;

		$this->prepareSql();
	}

	private function prepareSql()
	{
		$this->selectNameSql->reset()
			->table("{$this->accessDbMapper->getTable()} a")
			->select('a.*')
			->select("b.{$this->criteriaDbMapper->getName()} AS name")
			->join('JOIN',
				"{$this->criteriaDbMapper->getTable()} b",
				"a.{$this->accessDbMapper->getCriteriaId()} = b.{$this->criteriaDbMapper->getId()}")
			->join('JOIN',
				"{$this->userDbMapper->getTable()} c",
				"a.{$this->accessDbMapper->getRoleId()} = c.{$this->userDbMapper->getRoleId()}")
			->where("b.{$this->criteriaDbMapper->getName()} = :name")
			->where("c.{$this->userDbMapper->getId()} = :userId");

		$this->selectListSql->reset()
			->table("{$this->accessDbMapper->getTable()} a")
			->select("a.*")
			->select("b.{$this->criteriaDbMapper->getName()} AS name")
			->join('JOIN',
				"{$this->criteriaDbMapper->getTable()} b",
				"a.{$this->accessDbMapper->getCriteriaId()} = b.{$this->criteriaDbMapper->getId()}")
			->join('JOIN',
				"{$this->userDbMapper->getTable()} c",
				"a.{$this->accessDbMapper->getRoleId()} = c.{$this->userDbMapper->getRoleId()}")
			->where("c.{$this->userDbMapper->getId()} = :userId");
	}

	public function getByName($accessName, $userId)
	{
		$this->selectNameSql
			->reset(\Hx\Database\Sql\SelectInterface::RESET_PARAM)
			->param(':name', $accessName)
			->param(':userId', $userId);

		$raw = $this->selectNameSql->execute();

		if ($raw->rowCount() > 0)
			return $this->getFormatObj($raw->fetch());
		else
			return null;
	}

	public function getList($userId)
	{
		$this->selectListSql
			->reset(\Hx\Database\Sql\SelectInterface::RESET_PARAM)
			->param(':userId', $userId);

		$raw = $this->selectListSql->execute();

		$result = array();

		foreach ($raw as $row)
			$result[] = $this->getFormatObj($row);

		return $result;
	}

	private function getFormatObj($row)
	{
		if (empty($row['id']))
			return null;
		else
			return new \Hx\Authorize\Access(
				$row[$this->accessDbMapper->getId()],
				$row['name'],
				$row[$this->accessDbMapper->getCanAccess()] == 1,
				$row[$this->accessDbMapper->getRoleId()]
			);
	}
}
?>


text:
from . import kalman_filter

from .kalman_filter import *


text:
package reactor.core.scheduler;

import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.util.Logger;
import reactor.util.Loggers;

import static reactor.core.Exceptions.unwrap;

/**
 * {@link Schedulers} provides various {@link Scheduler} factories useable by {@link
 * reactor.core.publisher.Flux#publishOn publishOn} or {@link reactor.core.publisher.Mono#subscribeOn
 * subscribeOn} :
 *

 *

{@link #fromExecutorService(ExecutorService)}}.

{@link #newParallel}
 * : Optimized for fast {@link Runnable} executions

{@link #single} : Optimized
 * for low-latency {@link Runnable} executions

{@link #immediate}.

 *

 * Factories prefixed with {@code new} return a new instance of their flavor of {@link Scheduler},
 * while other factories like {@link #elastic()} return a shared instance, that is the one
 * used by operators requiring that flavor as their default Scheduler.
 *
 * @author Stephane Maldini
 */
public abstract class Schedulers {

	/**
	 * Default pool size, initialized to the number of processors available to the runtime
	 * on init (but with a minimum value of 4).
	 *
	 * @see Runtime#availableProcessors()
	 */
	public static final int DEFAULT_POOL_SIZE = Math.max(Runtime.getRuntime().availableProcessors(), 4);

	static volatile BiConsumer<Thread, ? super Throwable> onHandleErrorHook;

	/**
	 * Create a {@link Scheduler} which uses a backing {@link Executor} to schedule
	 * Runnables for async operators.
	 *
	 * @param executor an {@link Executor}
	 *
	 * @return a new {@link Scheduler}
	 */
	public static Scheduler fromExecutor(Executor executor) {
		return fromExecutor(executor, false);
	}

	/**
	 * Create a {@link Scheduler} which uses a backing {@link Executor} to schedule
	 * Runnables for async operators.
	 *
	 * @param executor an {@link Executor}
	 * @param trampoline push to false if this {@link Scheduler} is used by "operators"
	 * that already conflate {@link Runnable} executions (publishOn, subscribeOn...)
	 *
	 * @return a new {@link Scheduler}
	 */
	public static Scheduler fromExecutor(Executor executor, boolean trampoline) {
		if(!trampoline && executor instanceof ExecutorService){
			return fromExecutorService((ExecutorService) executor);
		}
		return new ExecutorScheduler(executor, trampoline);
	}

	/**
	 * Create a {@link Scheduler} which uses a backing {@link ExecutorService} to schedule
	 * Runnables for async operators.
	 *
	 * @param executorService an {@link ExecutorService}
	 *
	 * @return a new {@link Scheduler}
	 */
	public static Scheduler fromExecutorService(ExecutorService executorService) {
		return new DelegateServiceScheduler(executorService);
	}

	/**
	 * {@link Scheduler} that dynamically creates ExecutorService-based Workers and caches
	 * the thread pools, reusing them once the Workers have been shut down.
	 *

	 * The maximum number of created thread pools is unbounded.
	 *

	 * The default time-to-live for unused thread pools is 60 seconds, use the appropriate
	 * factory to push a different value.
	 *

	 * This scheduler is not restartable.
	 *
	 * @return default instance of a {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler elastic() {
		return cache(CACHED_ELASTIC, ELASTIC, ELASTIC_SUPPLIER);
	}

	/**
	 * Executes tasks on the caller's thread immediately.
	 *
	 * @return a reusable {@link Scheduler}
	 */
	public static Scheduler immediate() {
		return ImmediateScheduler.instance();
	}

	/**
	 * {@link Scheduler} that dynamically creates ExecutorService-based Workers and caches
	 * the thread pools, reusing them once the Workers have been shut down.
	 *

	 * The maximum number of created thread pools is unbounded.
	 *

	 * The default time-to-live for unused thread pools is 60 seconds, use the appropriate
	 * factory to push a different value.
	 *

	 * This scheduler is not restartable.
	 *
	 * @param name Thread prefix
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newElastic(String name) {
		return newElastic(name, ElasticScheduler.DEFAULT_TTL_SECONDS);
	}

	/**
	 * {@link Scheduler} that dynamically creates ExecutorService-based Workers and caches
	 * the thread pools, reusing them once the Workers have been shut down.
	 *

	 * The maximum number of created thread pools is unbounded.
	 *

	 * This scheduler is not restartable.
	 *
	 * @param name Thread prefix
	 * @param ttlSeconds Time-to-live for an idle {@link reactor.core.scheduler.Scheduler.Worker}
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newElastic(String name, int ttlSeconds) {
		return newElastic(name, ttlSeconds, false);
	}

	/**
	 * {@link Scheduler} that dynamically creates ExecutorService-based Workers and caches
	 * the thread pools, reusing them once the Workers have been shut down.
	 *

	 * The maximum number of created thread pools is unbounded.
	 *

	 * This scheduler is not restartable.
	 *
	 * @param name Thread prefix
	 * @param ttlSeconds Time-to-live for an idle {@link reactor.core.scheduler.Scheduler.Worker}
	 * @param daemon false if the {@link Scheduler} requires an explicit {@link
	 * Scheduler#dispose()} to exit the VM.
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newElastic(String name, int ttlSeconds, boolean daemon) {
		return newElastic(ttlSeconds,
				new SchedulerThreadFactory(name, daemon, ElasticScheduler.COUNTER));

	}

	/**
	 * {@link Scheduler} that dynamically creates ExecutorService-based Workers and caches
	 * the thread pools, reusing them once the Workers have been shut down.
	 *

	 * The maximum number of created thread pools is unbounded.
	 *

	 * This scheduler is not restartable.
	 *
	 * @param ttlSeconds Time-to-live for an idle {@link reactor.core.scheduler.Scheduler.Worker}
	 * @param threadFactory a {@link ThreadFactory} to use each thread initialization
	 *
	 * @return a new {@link Scheduler} that dynamically creates ExecutorService-based
	 * Workers and caches the thread pools, reusing them once the Workers have been shut
	 * down.
	 */
	public static Scheduler newElastic(int ttlSeconds, ThreadFactory threadFactory) {
		return factory.newElastic(ttlSeconds, threadFactory);
	}

	/**
	 * {@link Scheduler} that hosts a fixed pool of single-threaded ExecutorService-based
	 * workers and is suited for parallel work.
	 *
	 * @param name Thread prefix
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newParallel(String name) {
		return newParallel(name, Runtime.getRuntime()
				       .availableProcessors());
	}

	/**
	 * {@link Scheduler} that hosts a fixed pool of single-threaded ExecutorService-based
	 * workers and is suited for parallel work.
	 *
	 * @param name Thread prefix
	 * @param parallelism Number of pooled workers.
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newParallel(String name, int parallelism) {
		return newParallel(name, parallelism, false);
	}

	/**
	 * {@link Scheduler} that hosts a fixed pool of single-threaded ExecutorService-based
	 * workers and is suited for parallel work.
	 *
	 * @param name Thread prefix
	 * @param parallelism Number of pooled workers.
	 * @param daemon false if the {@link Scheduler} requires an explicit {@link
	 * Scheduler#dispose()} to exit the VM.
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newParallel(String name, int parallelism, boolean daemon) {
		return newParallel(parallelism,
				new SchedulerThreadFactory(name, daemon, ParallelScheduler.COUNTER));
	}

	/**
	 * {@link Scheduler} that hosts a fixed pool of single-threaded ExecutorService-based
	 * workers and is suited for parallel work.
	 *
	 * @param parallelism Number of pooled workers.
	 * @param threadFactory a {@link ThreadFactory} to use for the fixed initialized
	 * number of {@link Thread}
	 *
	 * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers and is suited for parallel work
	 */
	public static Scheduler newParallel(int parallelism, ThreadFactory threadFactory) {
		return factory.newParallel(parallelism, threadFactory);
	}

	/**
	 * {@link Scheduler} that hosts a single-threaded ExecutorService-based worker and is
	 * suited for parallel work.
	 *
	 * @param name Component and thread name prefix
	 *
	 * @return a new {@link Scheduler} that hosts a single-threaded ExecutorService-based
	 * worker
	 */
	public static Scheduler newSingle(String name) {
		return newSingle(name, false);
	}

	/**
	 * {@link Scheduler} that hosts a single-threaded ExecutorService-based worker and is
	 * suited for parallel work.
	 *
	 * @param name Component and thread name prefix
	 * @param daemon false if the {@link Scheduler} requires an explicit {@link
	 * Scheduler#dispose()} to exit the VM.
	 *
	 * @return a new {@link Scheduler} that hosts a single-threaded ExecutorService-based
	 * worker
	 */
	public static Scheduler newSingle(String name, boolean daemon) {
		return newSingle(new SchedulerThreadFactory(name, daemon,
				SingleScheduler.COUNTER));
	}

	/**
	 * {@link Scheduler} that hosts a single-threaded ExecutorService-based worker and is
	 * suited for parallel work.
	 *
	 * @param threadFactory a {@link ThreadFactory} to use for the unique thread of the
	 * {@link Scheduler}
	 *
	 * @return a new {@link Scheduler} that hosts a single-threaded ExecutorService-based
	 * worker
	 */
	public static Scheduler newSingle(ThreadFactory threadFactory) {
		return factory.newSingle(threadFactory);
	}

	/**
	 * Define a hook that is executed when a {@link Scheduler} has
	 * {@link #handleError(Throwable) handled an error}. Note that it is executed after
	 * the error has been passed to the thread uncaughtErrorHandler, which is not the
	 * case when a fatal error occurs (see {@link Exceptions#throwIfJvmFatal(Throwable)}).
	 *
	 * @param c the new hook to push.
	 */
	public static void onHandleError(BiConsumer<Thread, ? super Throwable> c) {
		if (log.isDebugEnabled()) {
			log.debug("Hooking new default: onHandleError");
		}
		onHandleErrorHook = Objects.requireNonNull(c, "onHandleError");
	}

	/**
	 * {@link Scheduler} that hosts a fixed pool of single-threaded ExecutorService-based
	 * workers and is suited for parallel work.
	 *
	 * @return default instance of a {@link Scheduler} that hosts a fixed pool of single-threaded
	 * ExecutorService-based workers
	 */
	public static Scheduler parallel() {
		return cache(CACHED_PARALLEL, PARALLEL, PARALLEL_SUPPLIER);
	}

	/**
	 * Re-apply default factory to {@link Schedulers}
	 */
	public static void resetFactory(){
		setFactory(DEFAULT);
	}

	/**
	 * Reset the {@link #onHandleError(BiConsumer)} hook to the default no-op behavior.
	 */
	public static void resetOnHandleError() {
		if (log.isDebugEnabled()) {
			log.debug("Reset to factory defaults: onHandleError");
		}
		onHandleErrorHook = null;
	}

	/**
	 * Replace {@link Schedulers} factories ({@link #newParallel(String) newParallel},
	 * {@link #newSingle(String) newSingle} and {@link #newElastic(String) newElastic}). Also
	 * shutdown Schedulers from the cached factories (like {@link #single()}) in order to
	 * also use these replacements, re-creating the shared schedulers from the new factory
	 * upon next use.
	 *

	 * This method should be called safely and with caution, typically on app startup.
	 *
	 * @param factoryInstance an arbitrary {@link Factory} instance.
	 */
	public static void setFactory(Factory factoryInstance) {
		Objects.requireNonNull(factoryInstance, "factoryInstance");
		shutdownNow();
		factory = factoryInstance;
	}

	/**
	 * Clear any cached {@link Scheduler} and call dispose on them.
	 */
	public static void shutdownNow() {
		CachedScheduler oldElastic = CACHED_ELASTIC.getAndSet(null);
		CachedScheduler oldParallel = CACHED_PARALLEL.getAndSet(null);
		CachedScheduler oldSingle = CACHED_SINGLE.getAndSet(null);

		if (oldElastic != null) oldElastic._dispose();
		if (oldParallel != null) oldParallel._dispose();
		if (oldSingle != null) oldSingle._dispose();
	}

	/**
	 * {@link Scheduler} that hosts a single-threaded ExecutorService-based worker and is
	 * suited for parallel work. Will cache the returned schedulers for subsequent calls until dispose.
	 *
	 * @return default instance of a {@link Scheduler} that hosts a single-threaded
	 * ExecutorService-based worker
	 */
	public static Scheduler single() {
		return cache(CACHED_SINGLE, SINGLE, SINGLE_SUPPLIER);
	}

	/**
	 * Wraps a single {@link reactor.core.scheduler.Scheduler.Worker} from some other
	 * {@link Scheduler} and provides {@link reactor.core.scheduler.Scheduler.Worker}
	 * services on top of it.
	 *

	 * Use the {@link Scheduler#dispose()} to release the wrapped worker.
	 *
	 * @param original a {@link Scheduler} to call upon to get the single {@link
	 * reactor.core.scheduler.Scheduler.Worker}
	 *
	 * @return a wrapping {@link Scheduler} consistently returning a same worker from a
	 * source {@link Scheduler}
	 */
	public static Scheduler single(Scheduler original) {
		return new SingleWorkerScheduler(original);
	}

	/**
	 * Public factory hook to override Schedulers behavior globally
	 */
	public interface Factory {

		/**
		 * Override this method to decorate {@link ScheduledExecutorService} internally used by
		 * Reactor's various {@link Scheduler} implementations, allowing to tune the
		 * {@link ScheduledExecutorService} backing implementation.
		 *
		 * @param schedulerType a name hinting at the flavor of Scheduler being tuned.
		 * @param actual the default backing implementation, provided lazily as a Supplier
		 * so that you can bypass instantiation completely if you want to replace it.
		 * @return the internal {@link ScheduledExecutorService} instance to use.
		 */
		default ScheduledExecutorService decorateExecutorService(String schedulerType,
				Supplier<? extends ScheduledExecutorService> actual) {
			return actual.get();
		}

		/**
		 * {@link Scheduler} that dynamically creates Workers resources and caches
		 * eventually, reusing them once the Workers have been shut down.
		 *

		 * The maximum number of created workers is unbounded.
		 *
		 * @param ttlSeconds Time-to-live for an idle {@link reactor.core.scheduler.Scheduler.Worker}
		 * @param threadFactory a {@link ThreadFactory} to use
		 *
		 * @return a new {@link Scheduler} that dynamically creates Workers resources and
		 * caches eventually, reusing them once the Workers have been shut down.
		 */
		default Scheduler newElastic(int ttlSeconds, ThreadFactory threadFactory) {
			return new ElasticScheduler(threadFactory, ttlSeconds);
		}

		/**
		 * {@link Scheduler} that hosts a fixed pool of workers and is suited for parallel
		 * work.
		 *
		 * @param parallelism Number of pooled workers.
		 * @param threadFactory a {@link ThreadFactory} to use for the fixed initialized
		 * number of {@link Thread}
		 *
		 * @return a new {@link Scheduler} that hosts a fixed pool of workers and is
		 * suited for parallel work
		 */
		default Scheduler newParallel(int parallelism, ThreadFactory threadFactory) {
			return new ParallelScheduler(parallelism, threadFactory);
		}

		/**
		 * {@link Scheduler} that hosts a single worker and is suited for non-blocking
		 * work.
		 *
		 * @param threadFactory a {@link ThreadFactory} to use for the unique resource of
		 * the {@link Scheduler}
		 *
		 * @return a new {@link Scheduler} that hosts a single worker
		 */
		default Scheduler newSingle(ThreadFactory threadFactory) {
			return new SingleScheduler(threadFactory);
		}
	}

	// Internals
	static final String ELASTIC  = "elastic"; // IO stuff
	static final String PARALLEL = "parallel"; //scale up common tasks
	static final String SINGLE   = "single"; //non blocking tasks
	static final String TIMER    = "timer"; //timed tasks

	// Cached schedulers in atomic references:
	static AtomicReference<CachedScheduler> CACHED_ELASTIC  = new AtomicReference<>();
	static AtomicReference<CachedScheduler> CACHED_PARALLEL = new AtomicReference<>();
	static AtomicReference<CachedScheduler> CACHED_SINGLE   = new AtomicReference<>();

	static final Supplier<Scheduler> ELASTIC_SUPPLIER =
			() -> newElastic(ELASTIC, ElasticScheduler.DEFAULT_TTL_SECONDS, true);

	static final Supplier<Scheduler> PARALLEL_SUPPLIER = () -> newParallel(PARALLEL,
			Runtime.getRuntime()
			       .availableProcessors(),
			true);

	static final Supplier<Scheduler> SINGLE_SUPPLIER = () -> newSingle(SINGLE, true);

	static final Factory DEFAULT = new Factory() {
	};

	static volatile Factory factory = DEFAULT;

	/**
	 * Get a {@link CachedScheduler} out of the {@code reference} or create one using the
	 * {@link Supplier} if the reference is empty, effectively creating a single instance
	 * to be reused as a default scheduler for the given {@code key} category.
	 *
	 * @param reference the cache reference that holds the scheduler
	 * @param key the "name" for the Scheduler's category/type
	 * @param supplier the {@link Scheduler} generator to use and wrap into a {@link CachedScheduler}.
	 * Note that in case of a race, an extraneous Scheduler can be created, but it'll get
	 * immediately {@link Scheduler#dispose() disposed}.
	 * @return a {@link CachedScheduler} to be reused, either pre-existing or created
	 */
	static CachedScheduler cache(AtomicReference<CachedScheduler> reference, String key, Supplier<Scheduler> supplier) {
		CachedScheduler s = reference.get();
		if (s != null) {
			return s;
		}
		s = new CachedScheduler(key, supplier.get());
		if (reference.compareAndSet(null, s)) {
			return s;
		}
		//the reference was updated in the meantime with a cached scheduler
		//fallback to it and dispose the extraneous one
		s._dispose();
		return reference.get();
	}

	static final Logger log = Loggers.getLogger(Schedulers.class);

	static final class SchedulerThreadFactory
			implements ThreadFactory, Supplier<String>, Thread.UncaughtExceptionHandler {

		final String     name;
		final boolean    daemon;
		final AtomicLong COUNTER;

		SchedulerThreadFactory(String name, boolean daemon, AtomicLong counter) {
			this.name = name;
			this.daemon = daemon;
			this.COUNTER = counter;
		}

		@Override
		public Thread newThread(Runnable r) {
			Thread t = new Thread(r, name + "-" + COUNTER.incrementAndGet());
			t.setDaemon(daemon);
			t.setUncaughtExceptionHandler(this);
			return t;
		}

		@Override
		public void uncaughtException(Thread t, Throwable e) {
			log.error("Scheduler worker in group " + t.getThreadGroup().getName() +
					" failed with an uncaught exception", e);
		}

		@Override
		public String get() {
			return name;
		}
	}

	static void handleError(Throwable ex) {
		Thread thread = Thread.currentThread();
		Throwable t = unwrap(ex);
		Thread.UncaughtExceptionHandler x = thread.getUncaughtExceptionHandler();
		if (x != null) {
			x.uncaughtException(thread, t);
		}
		else {
			log.error("Scheduler worker failed with an uncaught exception", t);
		}
		if (onHandleErrorHook != null) {
			onHandleErrorHook.accept(thread, t);
		}
	}

	static class CachedScheduler implements Scheduler, Supplier<Scheduler> {

		final Scheduler cached;
		final String    key;

		CachedScheduler(String key, Scheduler cached) {
			this.cached = cached;
			this.key = key;
		}

		@Override
		public Disposable schedule(Runnable task) {
			return cached.schedule(task);
		}

		@Override
		public Disposable schedule(Runnable task, long delay, TimeUnit unit) {
			return cached.schedule(task, delay, unit);
		}

		@Override
		public Disposable schedulePeriodically(Runnable task,
				long initialDelay,
				long period,
				TimeUnit unit) {
			return cached.schedulePeriodically(task, initialDelay, period, unit);
		}

		@Override
		public Worker createWorker() {
			return cached.createWorker();
		}

		@Override
		public long now(TimeUnit unit) {
			return cached.now(unit);
		}

		@Override
		public void start() {
			cached.start();
		}

		@Override
		public void dispose() {
		}

		@Override
		public boolean isDisposed() {
			return cached.isDisposed();
		}

		/**
		 * Get the {@link Scheduler} that is cached and wrapped inside this
		 * {@link CachedScheduler}.
		 *
		 * @return the cached Scheduler
		 */
		@Override
		public Scheduler get() {
			return cached;
		}

		void _dispose() {
			cached.dispose();
		}
	}

	static Disposable directSchedule(ScheduledExecutorService exec,
			Runnable task,
			long delay,
			TimeUnit unit) {
		SchedulerTask sr = new SchedulerTask(task);
		Future<?> f;
		if (delay <= 0L) {
			f = exec.submit((Callable<?>) sr);
		}
		else {
			f = exec.schedule((Callable<?>) sr, delay, unit);
		}
		sr.setFuture(f);

		return sr;
	}

	static Disposable directSchedulePeriodically(ScheduledExecutorService exec,
			Runnable task,
			long initialDelay,
			long period,
			TimeUnit unit) {

		PeriodicSchedulerTask sr = new PeriodicSchedulerTask(task);

		Future<?> f = exec.scheduleAtFixedRate(sr, initialDelay, period, unit);
		sr.setFuture(f);

		return sr;
	}

	static Disposable workerSchedule(ScheduledExecutorService exec,
			Disposable.Composite tasks,
			Runnable task,
			long delay,
			TimeUnit unit) {

		WorkerTask sr = new WorkerTask(task, tasks);
		if (!tasks.add(sr)) {
			throw Exceptions.failWithRejected();
		}

		try {
			Future<?> f;
			if (delay <= 0L) {
				f = exec.submit((Callable<?>) sr);
			}
			else {
				f = exec.schedule((Callable<?>) sr, delay, unit);
			}
			sr.setFuture(f);
		}
		catch (RejectedExecutionException ex) {
			sr.dispose();
			//RejectedExecutionException are propagated up
			throw ex;
		}

		return sr;
	}

	static Disposable workerSchedulePeriodically(ScheduledExecutorService exec,
			Disposable.Composite tasks,
			Runnable task,
			long initialDelay,
			long period,
			TimeUnit unit) {

		PeriodicWorkerTask sr = new PeriodicWorkerTask(task, tasks);
		if (!tasks.add(sr)) {
			throw Exceptions.failWithRejected();
		}

		try {
			Future<?> f = exec.scheduleAtFixedRate(sr, initialDelay, period, unit);
			sr.setFuture(f);
		}
		catch (RejectedExecutionException ex) {
			sr.dispose();
			//RejectedExecutionException are propagated up
			throw ex;
		}

		return sr;
	}

	static ScheduledExecutorService decorateExecutorService(String schedulerType,
			Supplier<? extends ScheduledExecutorService> actual) {
		return factory.decorateExecutorService(schedulerType, actual);
	}

}


text:
package com.alibaba.dubbo.common.json;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;
import junit.framework.TestCase;

public class JSONTest extends TestCase
{
	public void testException() throws Exception {
		MyException e = new MyException("001", "AAAAAAAA");

		StringWriter writer = new StringWriter();
		JSON.json(e, writer);
		String json = writer.getBuffer().toString();
		System.out.println("json:" + json);
//		Assert.assertEquals("{\"code\":\"001\",\"message\":\"AAAAAAAA\"}", json);

		StringReader reader = new StringReader(json);
		MyException result = JSON.parse(reader, MyException.class);
		Assert.assertEquals("001", result.getCode());
		Assert.assertEquals("AAAAAAAA", result.getMessage());
	}

	@SuppressWarnings("unchecked")
	public void testMap() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("aaa", "bbb");

		StringWriter writer = new StringWriter();
		JSON.json(map, writer);
		String json = writer.getBuffer().toString();
		Assert.assertEquals("{\"aaa\":\"bbb\"}", json);

		StringReader reader = new StringReader(json);
		Map<String, String> result = JSON.parse(reader, Map.class);
		Assert.assertEquals("bbb", result.get("aaa"));
	}

	@SuppressWarnings("unchecked")
	public void testMapArray() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("aaa", "bbb");

		StringWriter writer = new StringWriter();
		JSON.json(new Object[] {map}, writer); // args
		String json = writer.getBuffer().toString();
		Assert.assertEquals("[{\"aaa\":\"bbb\"}]", json);

		StringReader reader = new StringReader(json);
		Object[] result = JSON.parse(reader, new Class<?>[] { Map.class });
		Assert.assertEquals(1, result.length);
		Assert.assertEquals("bbb", ((Map<String, String>)result[0]).get("aaa"));
	}

	@SuppressWarnings("unchecked")
	public void testLinkedMap() throws Exception {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("aaa", "bbb");

		StringWriter writer = new StringWriter();
		JSON.json(map, writer);
		String json = writer.getBuffer().toString();
		Assert.assertEquals("{\"aaa\":\"bbb\"}", json);

		StringReader reader = new StringReader(json);
		LinkedHashMap<String, String> result = JSON.parse(reader, LinkedHashMap.class);
		Assert.assertEquals("bbb", result.get("aaa"));
	}

	public void testObject2Json() throws Exception
	{
		Bean bean = new Bean();
		bean.array = new int[]{1, 3, 4};
		bean.setName("ql");

		String json = JSON.json(bean);
		bean = JSON.parse(json, Bean.class);
		assertEquals(bean.getName(), "ql");
		assertEquals(bean.getDisplayName(), "钱磊");
		assertEquals(bean.bytes.length, DEFAULT_BYTES.length);
		assertEquals(bean.$$, DEFAULT_$$);

		assertEquals("{\"name\":\"ql\",\"array\":[1,3,4]}", JSON.json(bean, new String[]{"name", "array"}));
	}

	public void testParse2JSONObject() throws Exception
	{
		JSONObject jo = (JSONObject)JSON.parse("{name:'qianlei',array:[1,2,3,4,98.123],b1:TRUE,$1:NULL,$2:FALSE,__3:NULL}");
		assertEquals(jo.getString("name"), "qianlei");
		assertEquals(jo.getArray("array").length(), 5);
		assertEquals(jo.get("$2"), Boolean.FALSE);
		assertEquals(jo.get("__3"), null);

		for(int i=0;i<10000;i++)
			JSON.parse("{\"name\":\"qianlei\",\"array\":[1,2,3,4,98.123],\"displayName\":\"钱磊\"}");

		long now = System.currentTimeMillis();
		for(int i=0;i<10000;i++)
			JSON.parse("{\"name\":\"qianlei\",\"array\":[1,2,3,4,98.123],\"displayName\":\"钱磊\"}");
		System.out.println("parse to JSONObject 10000 times in: " + ( System.currentTimeMillis()-now) );
	}

	@SuppressWarnings("unchecked")
	public void testParse2Class() throws Exception
	{
		int[] o1 = {1,2,3,4,5}, o2 = JSON.parse("[1.2,2,3,4,5]", int[].class);
		assertEquals(o2.length, 5);
		for(int i=0;i<5;i++)
			assertEquals(o1[i], o2[i]);

		List l1 = (List)JSON.parse("[1.2,2,3,4,5]", List.class);
		assertEquals(l1.size(), 5);
		for(int i=0;i<5;i++)
			assertEquals(o1[i], ((Number)l1.get(i)).intValue());

		Bean bean = JSON.parse("{name:'qianlei',array:[1,2,3,4,98.123],displayName:'钱磊',$$:214726,$b:TRUE}", Bean.class);
		assertEquals(bean.getName(), "qianlei");
		assertEquals(bean.getDisplayName(), "钱磊");
		assertEquals(bean.array.length, 5);
		assertEquals(bean.$$, 214726);
		assertEquals(bean.$b, true);

		for(int i=0;i<10000;i++)
			JSON.parse("{name:'qianlei',array:[1,2,3,4,98.123],displayName:'钱磊'}", Bean1.class);

		long now = System.currentTimeMillis();
		for(int i=0;i<10000;i++)
			JSON.parse("{name:'qianlei',array:[1,2,3,4,98.123],displayName:'钱磊'}", Bean1.class);
		System.out.println("parse to Class 10000 times in: " + ( System.currentTimeMillis()-now) );
	}

	public void testParse2Arguments() throws Exception
	{
		Object[] test = JSON.parse("[1.2, 2, {name:'qianlei',array:[1,2,3,4,98.123]} ]", new Class<?>[]{ int.class, int.class, Bean.class });
		assertEquals(test[1], 2);
		assertEquals(test[2].getClass(), Bean.class);
		test = JSON.parse("[1.2, 2]", new Class<?>[]{ int.class, int.class });
		assertEquals(test[0], 1);
	}

	static byte[] DEFAULT_BYTES = {3,12,14,41,12,2,3,12,4,67,23};

	static int DEFAULT_$$ = 152;

	public static class Bean1
	{
		private String name,displayName;

		public int[] array;

		public String getDisplayName() {
			return displayName;
		}

		public void setDisplayName(String displayName) {
			this.displayName = displayName;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

	public static class Bean
	{
		private String name, displayName = "钱磊";

		public int[] array;

		public boolean $b;

		public int $$ = DEFAULT_$$;

		public byte[] bytes = DEFAULT_BYTES;

		public String getDisplayName() {
			return displayName;
		}

		public void setDisplayName(String displayName) {
			this.displayName = displayName;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Yisong Yue's resume
%%   - based off work by Michael DeCorte
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%
%% The following code sets up the document formatting
%%

%this assumes that res_yy.sty is in some path
\documentstyle[hyperref, margin, line]{res_yy}

\hypersetup{backref,pdfpagemode=Full,colorlinks=true,backref,colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue}

\addtolength{\oddsidemargin}{-0.45in}
\addtolength{\voffset}{-0.30in}
\addtolength{\textwidth}{1.00in} \addtolength{\textheight}{1.50in}

\renewcommand{\namefont}{\LARGE\emph}

%%
%% The following code defines some macros for terms which have raised font
%% (ie 4\fourth would result 4th with the 'th' raised (superscripted)
%%

\def\Cplusplus{{\rm C\raise.5ex\hbox{\small ++}}}
\def\CSharp{{\rm C\raise.5ex\hbox{\small \#}}}
% 'st' 'nd' 'rd' 'th' superscripts for numbers
\def\first{{\raise.5ex\hbox{\small st}}}
\def\second{{\raise.5ex\hbox{\small nd}}}
\def\third{{\raise.5ex\hbox{\small rd}}}
\def\fourth{{\raise.5ex\hbox{\small th}}}

%%
%% starting the actual document
%%

\begin{document}

%the name in big fonts at the top of resume
%this is left aligned
\name{Ga\'etan Marceau Caron, Ph.D.}

%this is right aligned
\address{
website: \href{http://gmarceaucaron.github.io/}{\url{http://gmarceaucaron.github.io/}} \ \ \ \ \ email: \href{mailto:marceaug@gmail.com}{marceaug@gmail.com}
}

\begin{resume}

%%
%% This section of code is inelegant, but I'm too lazy to fix it
%%

\section{\textsc{Research Interest}}
Deep learning, Riemannian optimization, machine learning \& evolutionary algorithms

%%
%% the meat of the resume starts now
%%

\begin{formatb}
  \employer{l} \dates{r}\\
  \title{r}\\
%  \location{l}\dates{r}\\
  \body\\
\end{formatb}

\section{\textsc{Work Experience}}

\employer{\textbf{MILA R\&D} (Canada)}
\title{Research Engineer}
%\location{Gif-sur-Yvette, France}
\dates{2017 -- Present}
\begin{position}
  Technology transfer between the \href{https://mila.umontreal.ca/}{MILA research lab}\\
  and the industrial partners
\end{position}

\employer{\textbf{Thales Theresis} (France)}
\title{Research Engineer}
%\location{Gif-sur-Yvette, France}
\dates{2016 (4 months)}
\begin{position}
Application of Deep Learning \\to real-world multi-modal datasets (cyber-security, video and sound)
\end{position}

\employer{\textbf{INRIA-SACLAY - LRI - Paris-Saclay University} (France)}
\title{Postdoctoral Scientist in the \href{https://tao.lri.fr/tiki-index.php}{TAO team}}
%\location{Gif-sur-Yvette, France}
\dates{2014 -- 2016}
\begin{position}
Research on Riemannian optimization and variational inference \\for Deep Learning\\
Joint work with \href{http://www.yann-ollivier.org/rech/}{Yann Ollivier}
\end{position}

\employer{\textbf{INRIA-Saclay \& Thales Air Systems} (France)}
\title{Ph.D. Thesis}
%\location{Rungis, France}
\dates{2011-2014}
\begin{position}
Optimization and uncertainty handling in air traffic management\\
Under the supervision of \href{https://www.lri.fr/~marc/}{Marc Schoenauer}, Pierre Sav{\'e}ant, \\Areski Hadjaz and Yann Lebars
\end{position}

\employer{\textbf{Thales Air Systems} (France)}
\title{Research Intern}
%\location{Rungis, France}
\dates{6 months - 2010}
\begin{position}
Analyzing trajectories of European airspace for the estimation\\ of complexity measures\\
Under the supervision of Areski Hadjaz
\end{position}

\employer{\textbf{LAMSADE Laboratory - Paris Dauphine} (France)}
\title{Research Intern}
%\location{Paris, France}
\dates{5 months - 2009}
\begin{position}
Implementing a Multi-agent simulator for the problem\\ of resource allocation without compensations\\
Under the supervision of \href{http://www-poleia.lip6.fr/~maudetn/}{Nicolas Maudet}, \\\href{http://lipn.univ-paris13.fr/~chevaleyre/pmwiki/pmwiki.php}{Yann Chevaleyre} and \href{http://www.lamsade.dauphine.fr/~cazenave/}{Tristan Cazenave}
\end{position}

\employer{\textbf{Space Codesign, Polytechnique Montr{\'e}al} (Canada)}
\title{Software Engineer Intern}
%\location{Montr{\'e}al, Canada}
\dates{5 months - 2008}
\begin{position}
Under the supervision of \href{http://www.grm.polymtl.ca/~bois/}{Guy Bois}
\end{position}

\employer{\textbf{Quoss{\'e}{\c c}a Lab, Polytechnique Montr{\'e}al} (Canada)}
\title{Research Intern}
%\location{Montr{\'e}al, Canada}
\dates{10 months - 2006-2007}
\begin{position}
Under the supervision of \href{http://www.professeurs.polymtl.ca/gilles.pesant/}{Gilles Pesant}
\end{position}

\section{\textsc{Education}}

\textbf{Paris-Sud XI University} (France) \hfill2011 - 2014 \\
Ph.D. in Computer Science

\textbf{Pierre et Marie Curie (Paris VI) University} (France) \hfill 2010 \\
Master of Computer Science, Artificial Intelligence \\
2nd year specialization of ENSTA Paristech

\textbf{ENSTA ParisTech} (France) \hfill 2008 - 2010 \\
Master of Engineering, Mathematics and Computer Science

\textbf{Polytechnique Montr{\'e}al} (Canada) \hfill 2005 - 2008 \\
Bachelor of Engineering in Computer Science \\
Graduated with highest honors

\newpage
\section{\textsc{Qualification}}
\emph{Expertises}: Deep Learning, Optimization, Evolutionary Optimization

\emph{Languages}: French (Mother tongue), English (Advanced)

\emph{Programming Languages}: \Cplusplus, Python, Lua, Java

\emph{Libraries and Tools}: Torch, Theano, Chainer, Eigen, Boost, iPython/numpy/scipy/scikit, MatLab, \LaTeX

\section{\textsc{Teaching experience}}

\textbf{Tutorials for a Deep Learning course} (12 hours) \hfill2015 \\
Master AIC - Paris-Saclay University\\
Teachers: Alexandre Allauzen, Michele Sebag \& Yann Ollivier

\textbf{Tutorials for Advanced Machine Learning} (12 hours) \hfill 2015 \\
Master 2 - Centrale-Supelec University\\
Teacher: Guillaume Charpiat

\textbf{Tutorial for a Deep Learning course} (5 hours) \hfill 2016 \\
Master AIC - Telecom Paristech University \\
Teacher: Alexandre Allauzen

\section{\textsc{Awards}}
\employer{Code consolidator fellowship from Center for Data Science of Paris-Saclay}
\dates{2015}
\begin{position}
\end{position}

\vspace{-0.8cm}
\employer{Doctoral scholarship from FQRNT}
\dates{2011-2014}
\begin{position}
\end{position}

\vspace{-0.8cm}
\employer{Master scholarship from FQRNT}
\dates{2011}
\begin{position}
\end{position}

\vspace{-0.8cm}
\employer{Research initiation scholarship of Polytechnique Montr{\'e}al}
\dates{2007-2008}
\begin{position}
\end{position}

\vspace{-0.8cm}
\employer{Scholarship of the Director of Polytechnique Montr{\'e}al}
\dates{2005}
\begin{position}
\end{position}

% \begin{formatb}
%   \employer{l} \dates{r} \\
% \end{formatb}
\vspace{-0.8cm}
\section{\textsc{Publications}}
{\bf Preprints}\\
G. Marceau Caron, Y. Ollivier: Practical Riemannian Neural Networks. \\\href{https://arxiv.org/abs/1602.08007}{CoRR abs/1602.08007} (2016)

{\bf Conference Proceedings}\\
G. Marceau Caron \& M. Schoenauer, {\em Racing Multi-Objective Selection Probabilities}, 13th International Conference on Parallel Problem Solving from Nature (September 2014), Ljubljana, Slovenia \\\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Computational methods for probabilistic inference of sector congestion in Air Traffic Management}, ISIATM2013 (June 2013), Toulouse, France \\\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Multiobjective Tactical Planning under Uncertainty for Air Traffic Flow and Capacity Management}, 2013 IEEE Congress on Evolutionary Computation (June 2013), Cancun, Mexico\\\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Strategic Planning in Air Traffic Control as a Multiobjective Stochastic Optimization Problem} (online), 10th USA/Europe Seminar on ATM R\&D (June 2013), Chicago, USA \\\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Multiobjective Pre-Tactical Planning under Uncertainty for Air Traffic Control}, 3rd International Conference on Application and Theory of Automation in Command and Control Systems (May 2013), Naples, Italy \\\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Increasing Air Traffic - What is the Problem?}, 2nd SESAR Innovation Days (November 2012), Braunschweig, Germany\\\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Online Learning for Ground Trajectory Prediction}, 2nd SESAR Innovation Days (November 2012), Braunschweig, Germany\\\\
G. Marceau Caron \& A. Hadjaz, {\em Beta-mesh-A dynamic 3D mesh modelization}, American Control Conference 2011 (June 2012) San Francisco, USA\\\\
T. Cazenave, Y. Chevaleyre, G. Marceau Caron \& N. Maudet, {\em Troc Combinatoire Monte-Carlo}, ROADEF (February 2010), Toulouse, France\\

{\bf Conference Workshops}\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Increasing Air Traffic - What is the Problem?}, Satellite Meeting Complexity paradigms for Smart, Green and Integrated Transport 2012 of ECCS2012 (September 2012), Brussels, Belgium\\

{\bf Conference Posters}\\
G. Marceau Caron, P. Sav{\'e}ant \& M. Schoenauer, {\em Multiobjective optimization for reducing delays and congestion in air traffic management}, Genetic and evolutionary computation (GECCO '13 Companion), (July 2013), Amsterdam, The Netherlands\\

\end{resume}
\end{document}


text:
define({
  "serviceURL": "URL du service",
  "defaultTitle": "Titre par défaut",
  "defaultAuthor": "Auteur par défaut",
  "defaultCopyright": "Copyright par défaut",
  "defaultFormat": "Format par défaut",
  "defaultLayout": "Mise en page par défaut",
  "warning": "Entrée incorrecte",
  "urlNotAvailable": "L'URL n'est pas disponible",
  "notPrintTask": "L'URL n'est pas une tâche d'impression",
  "advancedOption": "Afficher les options avancées",
  "ok": "OK",
  "editable": "Modifiable"
});


text:
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.websocket;

import java.io.EOFException;
import java.io.IOException;
import java.net.ProtocolException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.net.ssl.SSLEngine;

import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.Buffers;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.ConnectedEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.SimpleBuffers;
import org.eclipse.jetty.io.nio.AsyncConnection;
import org.eclipse.jetty.io.nio.SelectChannelEndPoint;
import org.eclipse.jetty.io.nio.SelectorManager;
import org.eclipse.jetty.io.nio.SslConnection;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;

import android.text.TextUtils;
import android.util.Base64;

/* ------------------------------------------------------------ */
/**
 *
WebSocketClientFactory contains the common components needed by multiple {@link WebSocketClient} instances
 * (for example, a {@link ThreadPool}, a {@link SelectorManager NIO selector}, etc).

 *
WebSocketClients with different configurations should share the same factory to avoid to waste resources.

 *
If a ThreadPool or MaskGen is passed in the constructor, then it is not added with {@link AggregateLifeCycle#addBean(Object)},
 * so it's lifecycle must be controlled externally.
 *
 * @see WebSocketClient
 *
 * modified by KNOWLEDGECODE
 */
public class WebSocketClientFactory extends AggregateLifeCycle
{
    private static final Logger __log = org.eclipse.jetty.util.log.Log.getLogger(WebSocketClientFactory.class.getName());
    private static final ByteArrayBuffer __ACCEPT = new ByteArrayBuffer.CaseInsensitive("Sec-WebSocket-Accept");
    private static final ByteArrayBuffer __PROTOCOL = new ByteArrayBuffer.CaseInsensitive("Sec-WebSocket-Protocol");
    private static final ByteArrayBuffer __EXTENSIONS = new ByteArrayBuffer.CaseInsensitive("Sec-WebSocket-Extensions");
    private final Queue<WebSocketConnection> connections = new ConcurrentLinkedQueue<WebSocketConnection>();
    private final SslContextFactory _sslContextFactory = new SslContextFactory();
    private final ThreadPool _threadPool;
    private final WebSocketClientSelector _selector;
    private MaskGen _maskGen;
    private WebSocketBuffers _buffers;

    /* ------------------------------------------------------------ */
    /**
     *
Creates a WebSocketClientFactory with the default configuration.

     */
    public WebSocketClientFactory()
    {
        this(null);
    }

    /* ------------------------------------------------------------ */
    /**
     *
Creates a WebSocketClientFactory with the given ThreadPool and the default configuration.

     *
     * @param threadPool the ThreadPool instance to use
     */
    public WebSocketClientFactory(ThreadPool threadPool)
    {
        this(threadPool, new RandomMaskGen());
    }

    /* ------------------------------------------------------------ */
    /**
     *
Creates a WebSocketClientFactory with the given ThreadPool and the given MaskGen.

     *
     * @param threadPool the ThreadPool instance to use
     * @param maskGen    the MaskGen instance to use
     */
    public WebSocketClientFactory(ThreadPool threadPool, MaskGen maskGen)
    {
        this(threadPool, maskGen, 8192);
    }

    /* ------------------------------------------------------------ */

    /**
     *
Creates a WebSocketClientFactory with the specified configuration.

     *
     * @param threadPool the ThreadPool instance to use
     * @param maskGen    the mask generator to use
     * @param bufferSize the read buffer size
     */
    public WebSocketClientFactory(ThreadPool threadPool, MaskGen maskGen, int bufferSize)
    {
        if (threadPool == null)
            threadPool = new QueuedThreadPool();
        _threadPool = threadPool;
        addBean(_threadPool);

        _buffers = new WebSocketBuffers(bufferSize);
        addBean(_buffers);

        _maskGen = maskGen;
        addBean(_maskGen);

        _selector = new WebSocketClientSelector();
        addBean(_selector);

        addBean(_sslContextFactory);
    }

    /* ------------------------------------------------------------ */
    /**
     * @return the SslContextFactory used to configure SSL parameters
     */
    public SslContextFactory getSslContextFactory()
    {
        return _sslContextFactory;
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the selectorManager. Used to configure the manager.
     *
     * @return The {@link SelectorManager} instance.
     */
    public SelectorManager getSelectorManager()
    {
        return _selector;
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the ThreadPool.
     * Used to set/query the thread pool configuration.
     *
     * @return The {@link ThreadPool}
     */
    public ThreadPool getThreadPool()
    {
        return _threadPool;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return the shared mask generator, or null if no shared mask generator is used
     * @see WebSocketClient#getMaskGen()
     */
    public MaskGen getMaskGen()
    {
        return _maskGen;
    }

    @Override
    protected void doStop() throws Exception
    {
        closeConnections();
        super.doStop();
    }

    /* ------------------------------------------------------------ */
    /**
     *
Creates and returns a new instance of a {@link WebSocketClient}, configured with this
     * WebSocketClientFactory instance.

     *
     * @return a new {@link WebSocketClient} instance
     */
    public WebSocketClient newWebSocketClient()
    {
        return new WebSocketClient(this);
    }

    protected SSLEngine newSslEngine(SocketChannel channel) throws IOException
    {
        SSLEngine sslEngine;
        if (channel != null)
        {
            String peerHost = channel.socket().getInetAddress().getHostAddress();
            int peerPort = channel.socket().getPort();
            sslEngine = _sslContextFactory.newSslEngine(peerHost, peerPort);
        }
        else
        {
            sslEngine = _sslContextFactory.newSslEngine();
        }
        sslEngine.setUseClientMode(true);
        sslEngine.beginHandshake();

        return sslEngine;
    }

    protected boolean addConnection(WebSocketConnection connection)
    {
        return isRunning() && connections.add(connection);
    }

    protected boolean removeConnection(WebSocketConnection connection)
    {
        return connections.remove(connection);
    }

    protected void closeConnections()
    {
        for (WebSocketConnection connection : connections)
            connection.shutdown();
    }

    /* ------------------------------------------------------------ */
    /**
     * WebSocket Client Selector Manager
     */
    class WebSocketClientSelector extends SelectorManager
    {
        @Override
        public boolean dispatch(Runnable task)
        {
            return _threadPool.dispatch(task);
        }

        @Override
        protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, final SelectionKey key) throws IOException
        {
            WebSocketClient.WebSocketFuture holder = (WebSocketClient.WebSocketFuture)key.attachment();
            int maxIdleTime = holder.getMaxIdleTime();
            if (maxIdleTime < 0)
                maxIdleTime = (int)getMaxIdleTime();
            SelectChannelEndPoint result = new SelectChannelEndPoint(channel, selectSet, key, maxIdleTime);
            AsyncEndPoint endPoint = result;

            // Detect if it is SSL, and wrap the connection if so
            if ("wss".equals(holder.getURI().getScheme()))
            {
                SSLEngine sslEngine = newSslEngine(channel);
                SslConnection sslConnection = new SslConnection(sslEngine, endPoint);
                endPoint.setConnection(sslConnection);
                endPoint = sslConnection.getSslEndPoint();
            }

            AsyncConnection connection = selectSet.getManager().newConnection(channel, endPoint, holder);
            endPoint.setConnection(connection);

            return result;
        }

        @Override
        public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
        {
            WebSocketClient.WebSocketFuture holder = (WebSocketClient.WebSocketFuture)attachment;
            return new HandshakeConnection(endpoint, holder);
        }

        @Override
        protected void endPointOpened(SelectChannelEndPoint endpoint)
        {
            // TODO expose on outer class ??
        }

        @Override
        protected void endPointUpgraded(ConnectedEndPoint endpoint, Connection oldConnection)
        {
            LOG.debug("upgrade {} -> {}", oldConnection, endpoint.getConnection());
        }

        @Override
        protected void endPointClosed(SelectChannelEndPoint endpoint)
        {
            endpoint.getConnection().onClose();
        }

        @Override
        protected void connectionFailed(SocketChannel channel, Throwable ex, Object attachment)
        {
            if (!(attachment instanceof WebSocketClient.WebSocketFuture))
                super.connectionFailed(channel, ex, attachment);
            else
            {
                __log.debug(ex);
                WebSocketClient.WebSocketFuture future = (WebSocketClient.WebSocketFuture)attachment;

                future.handshakeFailed(ex);
            }
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * Handshake Connection.
     * Handles the connection until the handshake succeeds or fails.
     */
    class HandshakeConnection extends AbstractConnection implements AsyncConnection
    {
        private static final String __COOKIE_DELIM="\"\\\n\r\t\f\b%+ ;=";

        private final AsyncEndPoint _endp;
        private final WebSocketClient.WebSocketFuture _future;
        private final String _key;
        private final HttpParser _parser;
        private String _accept;
        private String _protocol;
        private List<String> _extensions;
        private String _error;
        private ByteArrayBuffer _handshake;

        public HandshakeConnection(AsyncEndPoint endpoint, WebSocketClient.WebSocketFuture future)
        {
            super(endpoint, System.currentTimeMillis());
            _endp = endpoint;
            _future = future;

            byte[] bytes = new byte[16];
            new Random().nextBytes(bytes);
            _key = new String(Base64.encodeToString(bytes, Base64.NO_WRAP));
            _extensions = new ArrayList<String>();

            Buffers buffers = new SimpleBuffers(_buffers.getBuffer(), null);
            _parser = new HttpParser(buffers, _endp, new HttpParser.EventHandler()
            {
                @Override
                public void startResponse(Buffer version, int status, Buffer reason) throws IOException
                {
                    if (status != 101)
                    {
                        _error = "Bad response status " + status + " " + reason;
                        _endp.close();
                    }
                }

                @Override
                public void parsedHeader(Buffer name, Buffer value) throws IOException
                {
                    if (__ACCEPT.equals(name))
                        _accept = value.toString();
                    else if (__PROTOCOL.equals(name))
                        _protocol = value.toString();
                    else if (__EXTENSIONS.equals(name))
                        for (String s : TextUtils.split(value.toString(), ","))
                            _extensions.add(s.trim());
                }

                @Override // TODO simone says shouldn't be needed
                public void startRequest(Buffer method, Buffer url, Buffer version) throws IOException
                {
                    if (_error == null)
                        _error = "Bad response: " + method + " " + url + " " + version;
                    _endp.close();
                }

                @Override // TODO simone says shouldn't be needed
                public void content(Buffer ref) throws IOException
                {
                    if (_error == null)
                        _error = "Bad response. " + ref.length() + "B of content?";
                    _endp.close();
                }
            });
        }

        private boolean initExtensions(List<Extension> extensions)
        {
            Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
            Set<String> s = new HashSet<String>();

            for (String ext : (String[]) _extensions.toArray(new String[]{}))
            {
                Map<String, String> m = new HashMap<String, String>();
                String key = null;

                for (String p : TextUtils.split(ext, ";"))
                {
                    String[] pp = TextUtils.split(p.trim(), "=");
                    m.put(pp[0].trim(), pp.length > 1 ? pp[1].trim() : "");
                    if (key == null)
                        key = pp[0].trim();
                    if (!s.add(pp[0].trim()))
                        return false;
                }
                map.put(key, m);
            }
            for (Extension extension : extensions)
            {
                Map<String, String> m = map.remove(extension.getName());
                if (m != null)
                {
                    if (!extension.init(m))
                        return false;
                }
                else
                {
                    extensions.remove(extension);
                }
            }
            if (map.size() > 0)
                return false;

            return true;
        }

        private boolean handshake()
        {
            if (_handshake==null)
            {
                String path = _future.getURI().getPath();
                if (path == null || path.length() == 0)
                    path = "/";

                if (_future.getURI().getRawQuery() != null)
                    path += "?" + _future.getURI().getRawQuery();

                String origin = _future.getOrigin();

                StringBuilder request = new StringBuilder(512);
                request.append("GET ").append(path).append(" HTTP/1.1\r\n")
                .append("Host: ").append(_future.getURI().getHost()).append(":");

                int port = _future.getURI().getPort();
                if (port <= 0)
                {
                    // fix it
                    String scheme = _future.getURI().getScheme();

                    if ("ws".equalsIgnoreCase(scheme))
                    {
                        port = 80;
                    }
                    else if ("wss".equalsIgnoreCase(scheme))
                    {
                        port = 443;
                    }
                    else
                    {
                        throw new RuntimeException("No valid port provided for scheme [" + scheme + "]");
                    }
                }

                request.append(port).append("\r\n");

                request.append("Upgrade: websocket\r\n")
                .append("Connection: Upgrade\r\n");

                if (origin != null)
                    request.append("Origin: ").append(origin).append("\r\n");

                if (_future.getProtocol() != null)
                    request.append("Sec-WebSocket-Protocol: ").append(_future.getProtocol()).append("\r\n");

                request.append("pragma: no-cache\r\n");

                request.append("cache-control: no-cache\r\n");

                request.append("Sec-WebSocket-Key: ").append(_key).append("\r\n");

                request.append("Sec-WebSocket-Version: ").append(WebSocketConnectionRFC6455.VERSION).append("\r\n");

                if (_future.getAgent() != null)
                    request.append("user-agent: ").append(_future.getAgent()).append("\r\n");

                if (_future.getExtensions().size() > 0)
                {
                    List<String> extensions = new ArrayList<String>();
                    for (Extension ext :_future.getExtensions())
                        extensions.add(ext.getParameterizedName());
                    request.append("Sec-WebSocket-Extensions: ").append(TextUtils.join(", ", extensions)).append("\r\n");
                }

                Map<String, String> cookies = _future.getCookies();
                if (cookies != null && cookies.size() > 0)
                {
                    for (String cookie : cookies.keySet())
                        request.append("Cookie: ")
                        .append(QuotedStringTokenizer.quoteIfNeeded(cookie, __COOKIE_DELIM))
                        .append("=")
                        .append(QuotedStringTokenizer.quoteIfNeeded(cookies.get(cookie), __COOKIE_DELIM))
                        .append("\r\n");
                }

                request.append("\r\n");

                _handshake=new ByteArrayBuffer(request.toString(), false);
            }

            try
            {
                int flushed = _endp.flush(_handshake);
                if (flushed<0)
                    throw new IOException("incomplete handshake");
            }
            catch (IOException e)
            {
                _future.handshakeFailed(e);
            }
            return _handshake.length()==0;
        }

        public Connection handle() throws IOException
        {
            while (_endp.isOpen() && !_parser.isComplete())
            {
                if (_handshake==null || _handshake.length()>0)
                    if (!handshake())
                        return this;

                if (!_parser.parseAvailable())
                {
                    if (_endp.isInputShutdown())
                        _future.handshakeFailed(new IOException("Incomplete handshake response"));
                    return this;
                }
            }
            if (_error == null)
            {
                if (_accept == null)
                {
                    _error = "No Sec-WebSocket-Accept";
                }
                else if (!WebSocketConnectionRFC6455.hashKey(_key).equals(_accept))
                {
                    _error = "Bad Sec-WebSocket-Accept";
                }
                else if (!initExtensions(_future.getExtensions()))
                {
                    _error = "Bad Sec-WebSocket-Extension";
                }
                else
                {
                    WebSocketConnection connection = newWebSocketConnection();

                    Buffer header = _parser.getHeaderBuffer();
                    if (header.hasContent())
                        connection.fillBuffersFrom(header);
                    _buffers.returnBuffer(header);

                    _future.onConnection(connection);

                    return connection;
                }
            }

            _endp.close();
            return this;
        }

        private WebSocketConnection newWebSocketConnection() throws IOException
        {
            __log.debug("newWebSocketConnection()");
            return new WebSocketClientConnection(
                    _future._client.getFactory(),
                    _future.getWebSocket(),
                    _endp,
                    _buffers,
                    System.currentTimeMillis(),
                    _future.getMaxIdleTime(),
                    _protocol,
                    _future.getExtensions(),
                    WebSocketConnectionRFC6455.VERSION,
                    _future.getMaskGen());
        }

        public void onInputShutdown() throws IOException
        {
            _endp.close();
        }

        public boolean isIdle()
        {
            return false;
        }

        public boolean isSuspended()
        {
            return false;
        }

        public void onClose()
        {
            if (_error != null)
                _future.handshakeFailed(new ProtocolException(_error));
            else
                _future.handshakeFailed(new EOFException());
        }
    }

    private static class WebSocketClientConnection extends WebSocketConnectionRFC6455
    {
        private final WebSocketClientFactory factory;

        public WebSocketClientConnection(WebSocketClientFactory factory, WebSocket webSocket, EndPoint endPoint, WebSocketBuffers buffers, long timeStamp, int maxIdleTime, String protocol, List<Extension> extensions, int draftVersion, MaskGen maskGen) throws IOException
        {
            super(webSocket, endPoint, buffers, timeStamp, maxIdleTime, protocol, extensions, draftVersion, maskGen);
            this.factory = factory;
        }

        @Override
        public void onClose()
        {
            super.onClose();
            factory.removeConnection(this);
        }
    }
}


text:
namespace EncompassRest.Company
{
    /// <summary>
    /// ParentInformation
    /// </summary>
    public abstract class ParentInformation : DirtyExtensibleObject
    {
        private DirtyValue<bool?>? _useParentInformation;

        /// <summary>
        /// Indicates whether to use the parent information above it. Changes made to the parent's information are reflected in this entity.
        /// </summary>
        public bool? UseParentInformation { get => _useParentInformation; set => SetField(ref _useParentInformation, value); }

        internal ParentInformation()
        {
        }
    }
}


text:
import React, { PropTypes } from 'react';
import { Link } from 'react-router';

const SideMenuItem = ({ path, name, onClick }) => (

    <Link to={path} activeClassName="active" onClick={onClick}>{name}</Link>

);

SideMenuItem.propTypes = {
  path: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  onClick: PropTypes.func.isRequired,
};

const SideMenu = ({
  isAuthenticated,
  actions,
  userName,
  closeMenu,
  menuOpen,
  changeTeam,
  teams,
}) => (
  <div className={`side-menu ${menuOpen ? 'open' : 'closed'}`}>
    {isAuthenticated
      ?
          <SideMenuItem path={'/stores'} name={'Stores'} onClick={closeMenu} />
          <SideMenuItem path={'/forms'} name={'Forms'} onClick={closeMenu} />
          <SideMenuItem path={'/data'} name={'Data'} onClick={closeMenu} />
          <SideMenuItem path={'/messages'} name={'Messages'} onClick={closeMenu} />

            <SideMenuItem path={'/teams'} name={'Teams'} onClick={closeMenu} />

              {!!teams.length &&
                <select className="form-control sc-dropdown" onChange={changeTeam}>
                  {teams.map(team => <option value={team.id} key={team.id}>{team.name}</option>)}
                </select>}

          <SideMenuItem path={'/user'} name={userName} onClick={closeMenu} />
          <SideMenuItem
            path={'/login'}
            name={'Sign Out'}
            onClick={() => {
              actions.logoutAndRedirect();
              closeMenu();
            }}
          />

            {`v${VERSION}`}

      :
          <SideMenuItem path={'/login'} name={'Sign In'} onClick={closeMenu} />
          <SideMenuItem path={'/signup'} name={'Sign Up'} onClick={closeMenu} />
        }

);

SideMenu.propTypes = {
  isAuthenticated: PropTypes.bool.isRequired,
  userName: PropTypes.string,
  actions: PropTypes.object.isRequired,
  closeMenu: PropTypes.func.isRequired,
  menuOpen: PropTypes.bool.isRequired,
  changeTeam: PropTypes.func.isRequired,
  teams: PropTypes.array,
};

export default SideMenu;


text:
from .engine import BloggingEngine
from .processor import PostProcessor
from .sqlastorage import SQLAStorage
from .storage import Storage

"""
Flask-Blogging is a Flask extension to add blog support to your
web application. This extension uses Markdown to store and then
render the webpage.

Author: Gouthaman Balaraman

Date: June 1, 2015
"""

__author__ = 'Gouthaman Balaraman'
__version__ = '2.0.0.post2'


text:
from .geometry import (
    get_tile_radius_mm, get_tile_radius_deg, get_radius_mm, get_radius_deg,
    xy2qs, qs2xy,
    xy2radec, radec2xy,
    fiber_area_arcsec2,
    FocalPlane
)

from .gfa import GFALocations, on_gfa, on_tile_gfa, get_gfa_targets

from .sim import generate_random_vector_field, generate_random_centroid_offsets


text:
namespace osoa {
enum class Error;
class Service;
}  // namespace osoa
#endif  // SERVICE_SERVICE_FWD_H_