text:
"""Functions concerning tournament graphs.

A `tournament graph`_ is a complete oriented graph. In other words, it
is a directed graph in which there is exactly one directed edge joining
each pair of distinct nodes. For each function in this module that
accepts a graph as input, you must provide a tournament graph. The
responsibility is on the caller to ensure that the graph is a tournament
graph.

To access the functions in this module, you must access them through the
:mod:`networkx.algorithms.tournament` module::

    >>> import networkx as nx
    >>> from networkx.algorithms import tournament
    >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
    >>> tournament.is_tournament(G)
    True

.. _tournament graph: https://en.wikipedia.org/wiki/Tournament_%28graph_theory%29

"""
from itertools import combinations
import random

import networkx as nx
from networkx.utils import arbitrary_element
from networkx.utils import is_path
from networkx.utils import not_implemented_for

__all__ = ['hamiltonian_path', 'is_reachable', 'is_strongly_connected',
           'is_tournament', 'random_tournament', 'score_sequence']

def index_satisfying(iterable, condition):
    """Returns the index of the first element in `iterable` that
    satisfies the given condition.

    If no such element is found (that is, when the iterable is
    exhausted), this returns the length of the iterable (that is, one
    greater than the last index of the iterable).

    `iterable` must not be empty. If `iterable` is empty, this
    function raises :exc:`ValueError`.

    """
    # Pre-condition: iterable must not be empty.
    for i, x in enumerate(iterable):
        if condition(x):
            return i
    # If we reach the end of the iterable without finding an element
    # that satisfies the condition, return the length of the iterable,
    # which is one greater than the index of its last element. If the
    # iterable was empty, `i` will not be defined, so we raise an
    # exception.
    try:
        return i + 1
    except NameError:
        raise ValueError('iterable must be non-empty')

@not_implemented_for('undirected')
@not_implemented_for('multigraph')
def is_tournament(G):
    """Returns True if and only if `G` is a tournament.

    A tournament is a directed graph, with neither self-loops nor
    multi-edges, in which there is exactly one directed edge joining
    each pair of distinct nodes.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph representing a tournament.

    Returns
    -------
    bool
        Whether the given graph is a tournament graph.

    Notes
    -----
    Some definitions require a self-loop on each node, but that is not
    the convention used here.

    """
    # In a tournament, there is exactly one directed edge joining each pair.
    return (all((v in G[u]) ^ (u in G[v]) for u, v in combinations(G, 2)) and
            G.number_of_selfloops() == 0)

@not_implemented_for('undirected')
@not_implemented_for('multigraph')
def hamiltonian_path(G):
    """Returns a Hamiltonian path in the given tournament graph.

    Each tournament has a Hamiltonian path. If furthermore, the
    tournament is strongly connected, then the returned Hamiltonian path
    is a Hamiltonian cycle (by joining the endpoints of the path).

    Parameters
    ----------
    G : NetworkX graph
        A directed graph representing a tournament.

    Returns
    -------
    bool
        Whether the given graph is a tournament graph.

    Notes
    -----
    This is a recursive implementation with an asymptotic running time
    of `O(n^2)`, ignoring multiplicative polylogarithmic factors, where
    `n` is the number of nodes in the graph.

    """
    if len(G) == 0:
        return []
    if len(G) == 1:
        return [arbitrary_element(G)]
    v = arbitrary_element(G)
    hampath = hamiltonian_path(G.subgraph(set(G) - {v}))
    # Get the index of the first node in the path that does *not* have
    # an edge to `v`, then insert `v` before that node.
    index = index_satisfying(hampath, lambda u: v not in G[u])
    hampath.insert(index, v)
    return hampath

def random_tournament(n):
    r"""Returns a random tournament graph on `n` nodes.

    Parameters
    ----------
    n : int
        The number of nodes in the returned graph.

    Returns
    -------
    bool
        Whether the given graph is a tournament graph.

    Notes
    -----
    This algorithm adds, for each pair of distinct nodes, an edge with
    uniformly random orientation. In other words, `\binom{n}{2}` flips
    of an unbiased coin decide the orientations of the edges in the
    graph.

    """
    # Flip an unbiased coin for each pair of distinct nodes.
    coins = (random.random() for i in range((n * (n - 1)) // 2))
    pairs = combinations(range(n), 2)
    edges = ((u, v) if r < 0.5 else (v, u) for (u, v), r in zip(pairs, coins))
    return nx.DiGraph(edges)

@not_implemented_for('undirected')
@not_implemented_for('multigraph')
def score_sequence(G):
    """Returns the score sequence for the given tournament graph.

    The score sequence is the sorted list of the out-degrees of the
    nodes of the graph.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph representing a tournament.

    Returns
    -------
    list
        A sorted list of the out-degrees of the nodes of `G`.

    """
    return sorted(d for v, d in G.out_degree())

@not_implemented_for('undirected')
@not_implemented_for('multigraph')
def tournament_matrix(G):
    r"""Returns the tournament matrix for the given tournament graph.

    This function requires SciPy.

    The *tournament matrix* of a tournament graph with edge set *E* is
    the matrix *T* defined by

    .. math::

       T_{i j} =
       \begin{cases}
       +1 & \text{if } (i, j) \in E \\
       -1 & \text{if } (j, i) \in E \\
       0 & \text{if } i == j.
       \end{cases}

    An equivalent definition is `T = A - A^T`, where *A* is the
    adjacency matrix of the graph `G`.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph representing a tournament.

    Returns
    -------
    SciPy sparse matrix
        The tournament matrix of the tournament graph `G`.

    Raises
    ------
    ImportError
        If SciPy is not available.

    """
    A = nx.adjacency_matrix(G)
    return A - A.T

@not_implemented_for('undirected')
@not_implemented_for('multigraph')
def is_reachable(G, s, t):
    """Decides whether there is a path from `s` to `t` in the
    tournament.

    This function is more theoretically efficient than the reachability
    checks than the shortest path algorithms in
    :mod:`networkx.algorithms.shortest_paths`.

    The given graph **must** be a tournament, otherwise this function's
    behavior is undefined.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph representing a tournament.

    s : node
        A node in the graph.

    t : node
        A node in the graph.

    Returns
    -------
    bool
        Whether there is a path from `s` to `t` in `G`.

    Notes
    -----
    Although this function is more theoretically efficient than the
    generic shortest path functions, a speedup requires the use of
    parallelism. Though it may in the future, the current implementation
    does not use parallelism, thus you may not see much of a speedup.

    This algorithm comes from [1].

    References
    ----------
    .. [1] Tantau, Till.
           "A note on the complexity of the reachability problem for
           tournaments."
           *Electronic Colloquium on Computational Complexity*. 2001.
           <http://eccc.hpi-web.de/report/2001/092/>

    """
    def two_neighborhood(G, v):
        """Returns the set of nodes at distance at most two from `v`.

        `G` must be a graph and `v` a node in that graph.

        The returned set includes the nodes at distance zero (that is,
        the node `v` itself), the nodes at distance one (that is, the
        out-neighbors of `v`), and the nodes at distance two.

        """
        # TODO This is trivially parallelizable.
        return {x for x in G
                if x == v or x in G[v] or any(is_path(G, v, z, x) for z in G)}

    def is_closed(G, nodes):
        """Decides whether the given set of nodes is closed.

        A set *S* of nodes is *closed* if for each node *u* in the graph
        not in *S* and for each node *v* in *S*, there is an edge from
        *u* to *v*.

        """
        # TODO This is trivially parallelizable.
        return all(v in G[u] for u in set(G) - nodes for v in nodes)

    # TODO This is trivially parallelizable.
    neighborhoods = [two_neighborhood(G, v) for v in G]
    return all(not (is_closed(G, S) and s in S and t not in S)
               for S in neighborhoods)

@not_implemented_for('undirected')
@not_implemented_for('multigraph')
def is_strongly_connected(G):
    """Decides whether the given tournament is strongly connected.

    This function is more theoretically efficient than the
    :func:`~networkx.algorithms.components.is_strongly_connected`
    function.

    The given graph **must** be a tournament, otherwise this function's
    behavior is undefined.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph representing a tournament.

    Returns
    -------
    bool
        Whether the tournament is strongly connected.

    Notes
    -----
    Although this function is more theoretically efficient than the
    generic strong connectivity function, a speedup requires the use of
    parallelism. Though it may in the future, the current implementation
    does not use parallelism, thus you may not see much of a speedup.

    This algorithm comes from [1].

    References
    ----------
    .. [1] Tantau, Till.
           "A note on the complexity of the reachability problem for
           tournaments."
           *Electronic Colloquium on Computational Complexity*. 2001.
           <http://eccc.hpi-web.de/report/2001/092/>

    """
    # TODO This is trivially parallelizable.
    return all(is_reachable(G, u, v) for u in G for v in G)


text:
layout: post
title: Hellish Bricks DevBlog 2
---

This is an update on what I have recently done to Hellish Bricks.

# Progression Curves

The game got progression curves for running speed and initial jump speed.

![Speed Curve]({{ site.baseurl }}/assets/hellish-bricks/devblog-2/speed.svg)

![Jump Speed Curve]({{ site.baseurl }}/assets/hellish-bricks/devblog-2/jump-speed.svg)

These are important so that the character evolves, creating more gameplay
possibilities as the game progresses.

# Colored Lights

I've also enabled lantern and ambient light commands so that the player can
change the lantern and the ambient light colors during the game or during
initialization, through the boot script.

## Default Boot Script

```
# Set lantern to a light yellow.
lantern #EEEEBB
# Set ambient to a dark red.
ambient #443322
```

## White and Colored Lights Comparison

![White Lights]({{ site.baseurl }}/assets/hellish-bricks/devblog-2/white-lights.png)

![Colored Lights]({{ site.baseurl }}/assets/hellish-bricks/devblog-2/colored-lights.png)

redpajama_set_name: RedPajamaGithub


text:
package mcjty.lib;

public class CompatLayerClient {

}


text:
Minio is a distributed object storage server written in Golang. Source is available under free software / open source [Apache license 2.0](./LICENSE). API compatible with Amazon S3 cloud storage service.

## Description

Micro services environment provisions one Minio server per application instance. Scalability is achieved through large number of smaller personalized instances. This version of the Minio binary is built using Filesystem storage backend for magnetic and solid state disks.

Minio currently implements two backends

  - Filesystem (FS) - is available and ready for general purpose use.
  - ErasureCoded (XL) - is work in progress and not ready for general purpose use.

## Minio Client

[Minio Client (mc)](https://github.com/minio/mc#minio-client-mc-) provides a modern alternative to Unix commands like ``ls``, ``cat``, ``cp``, ``sync``, and ``diff``. It supports POSIX compatible filesystems and Amazon S3 compatible cloud storage systems. It is entirely written in Golang.

## Amazon S3 Compatible Client Libraries
- [Golang Library](https://github.com/minio/minio-go)
- [Java Library](https://github.com/minio/minio-java)
- [Nodejs Library](https://github.com/minio/minio-js)
- [Python Library](https://github.com/minio/minio-py)
- [.Net Library](https://github.com/minio/minio-dotnet)

### Install [![Build Status](https://travis-ci.org/minio/minio.svg?branch=master)](https://travis-ci.org/minio/minio)[![Build status](https://ci.appveyor.com/api/projects/status/royh137dni8yevep/branch/master?svg=true)](https://ci.appveyor.com/project/harshavardhana/minio-qxbjq/branch/master)

#### GNU/Linux

Download ``minio`` for:

- ``64-bit Intel`` from https://dl.minio.io/server/minio/release/linux-amd64/minio
- ``32-bit Intel`` from https://dl.minio.io/server/minio/release/linux-386/minio
- ``32-bit ARM`` from https://dl.minio.io/server/minio/release/linux-arm/minio

~~~
$ chmod +x minio
$ ./minio --help
~~~

#### OS X

Download ``minio`` from https://dl.minio.io/server/minio/release/darwin-amd64/minio

~~~
$ chmod 755 minio
$ ./minio --help
~~~

#### Microsoft Windows

Download ``minio`` for:

- ``64-bit`` from https://dl.minio.io/server/minio/release/windows-amd64/minio.exe
- ``32-bit`` from https://dl.minio.io/server/minio/release/windows-386/minio.exe

~~~
C:\Users\Username\Downloads> minio.exe --help
~~~

#### Docker container

Download ``minio`` for docker.

~~~
$ docker pull minio/minio
~~~

Read more here on [How to configure data volume containers for Minio?](./Docker.md)

#### Source

NOTE: Source installation is intended for only developers and advanced users.  For general use, please download official releases from https://minio.io/download.

If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md).

~~~
$ go get -d github.com/minio/minio
$ cd $GOPATH/src/github.com/minio/minio
$ make
~~~

### How to use Minio?

```
NAME:
  minio server - Start Minio cloud storage server.

USAGE:
  minio server [OPTION VALUE] PATH

  OPTION = expiry        VALUE = NN[h|m|s] [DEFAULT=Unlimited]
  OPTION = min-free-disk VALUE = NN% [DEFAULT: 10%]

EXAMPLES:
  1. Start minio server on Linux.
        $ minio server /home/shared

  2. Start minio server on Windows.
        $ minio server C:\MyShare

  3. Start minio server bound to a specific IP:PORT, when you have multiple network interfaces.
        $ minio --address 192.168.1.101:9000 server /home/shared

  4. Start minio server with minimum free disk threshold to 5%
        $ minio server min-free-disk 5% /home/shared/Pictures

  5. Start minio server with minimum free disk threshold to 15% with auto expiration set to 1h
        $ minio server min-free-disk 15% expiry 1h /home/shared/Documents
```

#### Start Minio server.

~~~
$ minio server ~/Photos
AccessKey: WLGDGYAQYIGI833EV05A  SecretKey: BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF  Region: us-east-1

Minio Object Storage:
    http://127.0.0.1:9000
    http://10.0.0.3:9000

Minio Browser:
    http://127.0.0.1:9000
    http://10.0.0.3:9000

To configure Minio Client:
    $ wget https://dl.minio.io/client/mc/release/darwin-amd64/mc
    $ chmod 755 mc
    $ ./mc config host add myminio http://localhost:9000 WLGDGYAQYIGI833EV05A BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF
~~~

#### How to use AWS CLI with Minio?

This section assumes that you have already installed aws-cli, if not please visit https://aws.amazon.com/cli/

To configure `aws-cli`, type `aws configure` and follow below steps.

```
$ aws configure
AWS Access Key ID [None]: YOUR_ACCESS_KEY_HERE
AWS Secret Access Key [None]: YOUR_SECRET_KEY_HERE
Default region name [None]: us-east-1
Default output format [None]: ENTER
```

Additionally enable `aws-cli` to use AWS Signature Version '4' for Minio server.

```
$ aws configure set default.s3.signature_version s3v4
```

To list your buckets.
```
$ aws --endpoint-url http://localhost:9000 s3 ls
2016-01-07 16:38:23 testbucket
```

To list contents inside bucket.
```
$ aws --endpoint-url http://localhost:9000 s3 ls s3://testbucket
                           PRE test/
2015-12-17 08:46:41   12232928 vim
2016-01-07 16:38:23   32232928 emacs
2015-12-09 08:05:24     138504 s3cmd
```

#### How to use AWS SDK with Minio?

Please follow the documentation here - [Using aws-sdk-go with Minio server](./AWS-SDK-GO.md)

#### How to use s3cmd with Minio?

This section assumes that you have already installed s3cmd, if not please visit http://s3tools.org/s3cmd

Edit the following fields in your s3cmd configuration file `~/.s3cfg` .

```
host_base = localhost:9000
host_bucket = localhost:9000
access_key = YOUR_ACCESS_KEY_HERE
secret_key = YOUR_SECRET_KEY_HERE
```

To list your buckets.
```
$ s3cmd ls s3://
2015-12-09 16:12  s3://testbbucket
```

To list contents inside buckets.
```
$ s3cmd ls s3://testbucket/
                       DIR   s3://testbucket/test/
2015-12-09 16:05    138504   s3://testbucket/newfile
```

## Contribute to Minio Project
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)

### Jobs
If you think in Lisp or Haskell and hack in go, you would blend right in. Send your github link to callhome@minio.io.


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>WebSockets Demo</title>

  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/emojify.min.css">
  <link rel="stylesheet" href="css/iframe.css">
  <link rel="stylesheet" type="text/css" href="css/sidebar.css">


text:
<template>
    <button disabled={disabled}>
        {label}
    </button>
</template>


text:
using System;
using System.Linq;
using MediatR;
using PeriodConcept.Models;

namespace PeriodConcept.Commands
{
    public class PeriodDeleteCommandHandler : IRequestHandler<PeriodDeleteCommand, Period>
    {
        private readonly ICommonDbContext dbContext;

        public PeriodDeleteCommandHandler(ICommonDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        Period IRequestHandler<PeriodDeleteCommand, Period>.Handle(PeriodDeleteCommand message)
        {
            var period =
                dbContext.Periods
                    .Single(t => t.PeriodID == message.PeriodID);

            period.IsArchived = true;
            period.LastUpdated = DateTimeOffset.Now;

            return period;
        }
    }
}


text:
import chai from "chai";
import chaiAsPromised from "chai-as-promised";
import sinon from "sinon";
import sinonChai from "sinon-chai";
import request from "request-promise";
import * as roote from "../src";
import * as router from "../src/router";
import GetRoute from "./fixtures/get-route";

let port = process.env.PORT || 3215;
let server;
const should = chai.should();
chai.use(chaiAsPromised);
chai.use(sinonChai);

describe("Routes", function()
{
	it("should register route", function()
	{
		// we required GetRoute, so it should have GET /
		router.routes.should.have.property("/").with.property("GET");
	});

	it("should change context when handler is called", function()
	{
		let ctx = {};
		let orig = {};
		router.routes["/"]["GET"](ctx);
		ctx.should.be.an("object").and.not.equal(orig);
	});
});

describe("Server", function()
{
	afterEach(() => server ? server.server.close() : 0);

	it("should call callback when listen is called", function()
	{
		let cb = sinon.spy();
		server = new roote.Server();
		server.listen(port, cb);
		cb.should.have.been.calledOnce;
	});

	it("should respond to defined routes", function()
	{
		server = new roote.Server();
		server.listen(port);
		return request(`http://localhost:${port}/`).should.eventually.equal("Hello world!");
	});
});


text:
import { LayerProperty, ILayerManager, ILayerInfo, IParseFeaturesFromFileOptions, IAddLayerFromParsedFeaturesOptions, SourceProperty, IWmsLayerExtensions, LayerExtensions, Dictionary } from './common';
import olSourceVector from "ol/source/Vector";
import olMap from "ol/Map";
import olLayerBase from "ol/layer/Base";
import olPoint from "ol/geom/Point";
import { setOLVectorLayerStyle } from './ol-style-helpers';
import olTileLayer from "ol/layer/Tile";
import olImageLayer from "ol/layer/Image";
import olWmsSource from "ol/source/ImageWMS";
import olTileWmsSource from "ol/source/TileWMS";
import olVectorLayer from "ol/layer/Vector";
import olHeatmapLayer from "ol/layer/Heatmap";
import { getFormatDrivers } from './layer-manager/driver-registry';
import { IFormatDriver } from './layer-manager/format-driver';
import { tr } from './i18n';
import { IParsedFeatures } from './layer-manager/parsed-features';
import { LayerSetGroupBase } from './layer-set-group-base';
import { IInitialExternalLayer } from '../actions/defs';
import { IVectorLayerStyle, DEFAULT_VECTOR_LAYER_STYLE, IClusterSettings, ClusterClickAction, DEFAULT_CLUSTERED_LAYER_STYLE, IBasicVectorPointStyle, IBasicVectorPolygonStyle, IBasicVectorLineStyle, IVectorLabelSettings, ExprOr, IVectorFeatureStyle, IHeatmapSettings } from './ol-style-contracts';
import { OLStyleMapSet } from './ol-style-map-set';
import { clusterSourceIfRequired } from '../components/external-layer-factory';
import colorbrewer from "colorbrewer";
import { strIsNullOrEmpty } from '../utils/string';
import { getMaxRamp } from '../components/layer-manager/color-brewer';

function cloneObject<T>(obj: T) {
    return JSON.parse(JSON.stringify(obj)) as T;
}

function clonePointWithFill(baseTemplate: IBasicVectorPointStyle | undefined, fillColor: string) {
    if (!baseTemplate) {
        return undefined;
    }
    const clone = cloneObject(baseTemplate);
    switch (clone.type) {
        case "Circle":
            clone.fill.color = fillColor;
            break;
    }
    return clone;
}
function cloneLineWithFill(baseTemplate: IBasicVectorLineStyle | undefined, fillColor: string) {
    if (!baseTemplate) {
        return undefined;
    }
    const clone = cloneObject(baseTemplate);
    clone.color = fillColor;
    return clone;
}
function clonePolyWithFill(baseTemplate: IBasicVectorPolygonStyle | undefined, fillColor: string) {
    if (!baseTemplate) {
        return undefined;
    }
    const clone = cloneObject(baseTemplate);
    clone.fill.color = fillColor;
    return clone;
}
function ensureLabelText(style: IVectorLabelSettings, expr: ExprOr<string>, isLine: boolean = false) {
    if (!style.label) {
        style.label = {
            text: expr,
            textAlign: "left",
            offsetX: 15,
            fill: {
                color: "#000000",
                alpha: 255
            },
            stroke: {
                color: "#ffffff",
                alpha: 255,
                width: 3
            }
        };
        if (isLine) {
            style.label.placement = "line";
        }
    } else {
        style.label.text = expr;
    }
}
function ensureLabelTextForStyle(fstyle: IVectorFeatureStyle, expr: ExprOr<string>) {
    if (fstyle.line) {
        ensureLabelText(fstyle.line, expr, true);
    }
    if (fstyle.point) {
        ensureLabelText(fstyle.point, expr);
    }
    if (fstyle.polygon) {
        ensureLabelText(fstyle.polygon, expr);
    }
}

export function getLayerInfo(layer: olLayerBase, isExternal: boolean): ILayerInfo {
    let vectorStyle: IVectorLayerStyle | undefined;
    let cs: IClusterSettings | undefined;
    let ext: LayerExtensions | undefined;
    let hs: IHeatmapSettings | undefined;
    if (layer instanceof olImageLayer || layer instanceof olTileLayer) {
        const source = layer.getSource();
        if (layer.get(LayerProperty.HAS_WMS_LEGEND) == true && (source instanceof olWmsSource || source instanceof olTileWmsSource)) {
            ext = {
                type: "WMS",
                getLegendUrl: (res?: number) => source.getLegendUrl(res)
            } as IWmsLayerExtensions;
        }
    }
    if (layer instanceof olVectorLayer) {
        const vs: OLStyleMapSet | undefined = layer.get(LayerProperty.VECTOR_STYLE);
        if (vs) {
            vectorStyle = vs.toVectorLayerStyle();
            cs = vs.toClusterSettings();
        }
    }
    if (layer instanceof olHeatmapLayer) {
        hs = {
            blur: layer.getBlur(),
            radius: layer.getRadius()
        };
    }
    return {
        visible: layer.getVisible(),
        selectable: layer.get(LayerProperty.IS_SELECTABLE) == true,
        name: layer.get(LayerProperty.LAYER_NAME),
        displayName: layer.get(LayerProperty.LAYER_DISPLAY_NAME) ?? layer.get(LayerProperty.LAYER_NAME),
        description: layer.get(LayerProperty.LAYER_DESCRIPTION),
        type: layer.get(LayerProperty.LAYER_TYPE),
        opacity: layer.getOpacity(),
        isExternal: isExternal,
        extensions: ext,
        vectorStyle,
        cluster: cs,
        heatmap: hs,
        busyWorkerCount: layer.get(LayerProperty.BUSY_WORKER_COUNT) ?? 0,
        metadata: layer.get(LayerProperty.LAYER_METADATA)
    }
}

export class LayerManager implements ILayerManager {
    private _olFormats: IFormatDriver[];
    constructor(private map: olMap, private layerSet: LayerSetGroupBase) {
        this._olFormats = getFormatDrivers();
    }
    tryGetSubjectLayer(): olLayerBase | undefined {
        return this.layerSet.tryGetSubjectLayer();
    }
    /**
     * INTERNAL API
     * @param {IInitialExternalLayer} extLayer
     * @returns
     * @memberof LayerManager
     */
    addExternalLayer(extLayer: IInitialExternalLayer, onlyAddIfNotExists: boolean, appSettings: Dictionary<string>) {
        if (onlyAddIfNotExists && this.hasLayer(extLayer.name)) {
            return undefined;
        }
        return this.layerSet.addExternalLayer(this.map, extLayer, appSettings);
    }
    getLayers(): ILayerInfo[] {
        return this.layerSet.getCustomLayers(this.map);
    }
    hasLayer(name: string): boolean {
        return this.layerSet.hasLayer(name);
    }
    addLayer<T extends olLayerBase>(name: string, layer: T, allowReplace?: boolean | undefined): ILayerInfo {
        return this.layerSet.addLayer(this.map, name, layer, allowReplace);
    }
    removeLayer(name: string): olLayerBase | undefined {
        return this.layerSet.removeLayer(this.map, name);
    }
    getLayer<T extends olLayerBase>(name: string): T | undefined {
        return this.layerSet.getLayer(name);
    }
    apply(layers: ILayerInfo[]): void {
        this.layerSet.apply(this.map, layers);
    }
    parseFeaturesFromFile(options: IParseFeaturesFromFileOptions): Promise<IParsedFeatures> {
        const { file, name: layerName, locale } = options;
        const that = this;
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            const handler = async function (e: ProgressEvent<FileReader>) {
                const result = e.target?.result;
                if (result && typeof (result) == 'string') {
                    const formats = that._olFormats;
                    if (formats.length == 0) {
                        reject(new Error(tr("ADD_LOCAL_FILE_LAYER_FAILURE_NO_FORMATS", locale)));
                    }
                    let loadedType: IParsedFeatures | undefined;
                    let bLoaded = false;
                    for (let i = 0, ii = formats.length; i < ii; ++i) {
                        const format = formats[i];
                        try {
                            loadedType = await format.tryParse(file.size, result);
                        } catch (e) {
                            //console.log(e);
                        }
                        if (loadedType && loadedType.hasFeatures()) {
                            loadedType.name = layerName;
                            bLoaded = true;
                            break;
                        }
                    }
                    if (bLoaded && loadedType) {
                        resolve(loadedType);
                    } else {
                        reject(new Error(tr("ADD_LOCAL_FILE_LAYER_FAILURE", locale)));
                    }
                } else {
                    reject(new Error(tr("ADD_LOCAL_FILE_LAYER_FAILURE_NOT_TEXT", locale)));
                }
            };
            reader.addEventListener("load", handler);
            reader.readAsText(file);
        });
    }
    async addLayerFromParsedFeatures(options: IAddLayerFromParsedFeaturesOptions): Promise<ILayerInfo> {
        const { features, projection, defaultStyle, extraOptions, labelOnProperty, selectedPopupTemplate, metadata, defn } = options;

        let proj = projection;
        if (!proj) {
            const view = this.map.getView();
            proj = view.getProjection();
        }
        const source = new olSourceVector();
        source.set(SourceProperty.SUPPRESS_LOAD_EVENTS, true);

        let csArgs;
        if (extraOptions?.kind == "Cluster") {
            csArgs = {
                distance: extraOptions.clusterDistance
            };
        }
        let layer: olLayerBase;
        if (extraOptions?.kind == "Heatmap") {
            layer = new olHeatmapLayer({
                source: source as olSourceVector<olPoint>,
                weight: extraOptions.weightProperty
            });
        } else {
            layer = new olVectorLayer({
                source: clusterSourceIfRequired(source, { cluster: csArgs }),
                className: "external-vector-layer", //This is to avoid false positives for map.forEachLayerAtPixel
                declutter: true
            });
        }
        await features.addTo(source, this.map.getView().getProjection(), proj);
        layer.set(LayerProperty.LAYER_NAME, features.name);
        layer.set(LayerProperty.LAYER_DISPLAY_NAME, features.name);
        layer.set(LayerProperty.LAYER_TYPE, features.type);
        layer.set(LayerProperty.LAYER_DEFN, defn);
        if (extraOptions?.kind == "Heatmap") {
            layer.set(LayerProperty.IS_HEATMAP, true);
        } else {
            layer.set(LayerProperty.IS_SELECTABLE, true);
        }
        layer.set(LayerProperty.IS_EXTERNAL, true);
        layer.set(LayerProperty.IS_GROUP, false);
        if (metadata) {
            layer.set(LayerProperty.LAYER_METADATA, metadata);
        }
        if (selectedPopupTemplate) {
            layer.set(LayerProperty.SELECTED_POPUP_CONFIGURATION, selectedPopupTemplate);
        }

        let clusterSettings: IClusterSettings | undefined;
        if (extraOptions?.kind == "Cluster") {
            clusterSettings = {
                distance: extraOptions.clusterDistance,
                onClick: extraOptions.onClusterClickAction ?? ClusterClickAction.ShowPopup,
                style: cloneObject(extraOptions.clusterStyle ?? defaultStyle ?? DEFAULT_CLUSTERED_LAYER_STYLE)
            };
            if (!strIsNullOrEmpty(labelOnProperty)) {
                for (const k in clusterSettings.style) {
                    ensureLabelTextForStyle(clusterSettings.style[k], { expr: `if (arr_size(features) == 1, feat_property(features[0], '${labelOnProperty}'), '')` });
                }
            }
        }
        // Delete irrelevant styles based on geometry types encountered
        const bStyle: IVectorLayerStyle = defaultStyle ?? cloneObject(DEFAULT_VECTOR_LAYER_STYLE);
        if (!features.geometryTypes.includes("Point")) {
            delete bStyle.default.point;
            delete clusterSettings?.style.default.point;
        }
        if (!features.geometryTypes.includes("LineString")) {
            delete bStyle.default.line;
            delete clusterSettings?.style.default.line;
        }
        if (!features.geometryTypes.includes("Polygon")) {
            delete bStyle.default.polygon;
            delete clusterSettings?.style.default.polygon;
        }

        if (!strIsNullOrEmpty(labelOnProperty)) {
            ensureLabelTextForStyle(bStyle.default, { expr: labelOnProperty });
        }

        if (extraOptions?.kind == "Theme") {
            const values = await features.getDistinctValues(extraOptions.themeOnProperty);
            let baseTemplatePoint = bStyle.default.point;
            let baseTemplateLine = bStyle.default.line;
            let baseTemplatePoly = bStyle.default.polygon;

            const th = extraOptions.colorBrewerTheme;
            let ramp = colorbrewer[th];
            if (!ramp) {
                ramp = colorbrewer.Blues;
            }
            const chosenRamp = getMaxRamp(ramp);
            const ruleCount = Math.min(values.length, chosenRamp.length);
            const palette = ramp[ruleCount];
            for (let i = 0; i < ruleCount; i++) {
                const v = values[i];
                const filter = `${extraOptions.themeOnProperty} == '${v}'`;
                const style = {
                    label: v,
                    point: clonePointWithFill(baseTemplatePoint, palette[i]),
                    line: cloneLineWithFill(baseTemplateLine, palette[i]),
                    polygon: clonePolyWithFill(baseTemplatePoly, palette[i]),
                };
                if (!strIsNullOrEmpty(labelOnProperty)) {
                    ensureLabelTextForStyle(style, { expr: labelOnProperty });
                }
                (bStyle as any)[filter] = style;
            }
        }
        if (layer instanceof olVectorLayer) {
            setOLVectorLayerStyle(layer, bStyle, clusterSettings);
        }
        const layerInfo = this.addLayer(features.name, layer);
        return layerInfo;
    }
}


text:
package com.xinxin.wotplus.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xinxin.wotplus.R;
import com.xinxin.wotplus.model.DaylistEntityForRecent;
import com.xinxin.wotplus.util.CommonUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by xinxin on 2016/5/23.
 * 近日数据Adapter
 */
public class XvmDaylistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private LayoutInflater layoutInflater;

    List<DaylistEntityForRecent> daylist = new ArrayList();
    List<String> daylistdate = new ArrayList();

    public XvmDaylistAdapter(Context mContext, Map map) {
        layoutInflater = LayoutInflater.from(mContext);
        this.mContext = mContext;

        // 将map数据分解到两个list中
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            daylistdate.add(key);
            daylist.add((DaylistEntityForRecent) map.get(key));
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.item_xvm_daylist, parent, false);

        return new DayListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        DecimalFormat df = new DecimalFormat("0.0");

        // 时间
        ((DayListViewHolder) holder).xvm_daylist_date.setText(daylistdate.get(position).substring(5));

        DaylistEntityForRecent day = daylist.get(position);
        // 场次
        ((DayListViewHolder) holder).xvm_daylist_battles.setText(day.getBattles() + "");
        // 胜率
        float winrate = (float) day.getWins() * 100 / day.getBattles();
        ((DayListViewHolder) holder).xvm_daylist_wins.setText(df.format(winrate) + "%");
        // 胜率的颜色设置
        ((DayListViewHolder) holder).xvm_daylist_wins.setTextColor(mContext.getResources().getColor(CommonUtil.getWRClass(winrate)));

        // 效率
        // ((DayListViewHolder) holder).xvm_daylist_effect.setText((day.getDaypower() + day.getWinpower()) * 100 / day.getWeight());
        ((DayListViewHolder) holder).xvm_daylist_effect.setText((int) (CommonUtil.addDouble(day.getDaypower(), day.getWinpower()) * 100 / day.getWeight()) + "%");
        // 击杀
        ((DayListViewHolder) holder).xvm_daylist_kill.setText(df.format((float) day.getFrags() / day.getBattles()));
        // 伤害
        ((DayListViewHolder) holder).xvm_daylist_hit.setText(Math.round(day.getDamage() / day.getBattles()) + "");
        // 助攻
        ((DayListViewHolder) holder).xvm_daylist_assist.setText(Math.round(day.getAssist() / day.getBattles()) + "");

    }

    @Override
    public int getItemCount() {
        return daylist.size();
    }

    class DayListViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.xvm_daylist_date)
        TextView xvm_daylist_date;
        @BindView(R.id.xvm_daylist_battles)
        TextView xvm_daylist_battles;
        @BindView(R.id.xvm_daylist_wins)
        TextView xvm_daylist_wins;
        @BindView(R.id.xvm_daylist_effect)
        TextView xvm_daylist_effect;
        @BindView(R.id.xvm_daylist_kill)
        TextView xvm_daylist_kill;
        @BindView(R.id.xvm_daylist_hit)
        TextView xvm_daylist_hit;
        @BindView(R.id.xvm_daylist_assist)
        TextView xvm_daylist_assist;

        public DayListViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}


text:
using MessageLib.Math;

namespace MessageLib.Packets.Out
{
    public class PacketPlayerHologram : IOutboundPacket
    {
        private IntVector position;

        public IntVector Position
        {
            get { return this.position; }
        }

        // ----------------------------------- Constructor
        public PacketPlayerHologram(IntVector position)
        {
            this.position = position;
        }

        // ----------------------------------- IOutboundPacket
        public string MessageType
        {
            get { return "hologramtouch"; }
        }

        public void Write(PlayerIOClient.Message message)
        {
            message.Add(this.position.X); message.Add(this.position.Y);
        }
    }
}


text:
<?php

namespace AEMR\Bundle\MarketResearchBundle\Repository;

use AEMR\Bundle\MarketResearchBundle\Repository\AEMREntityRepository AS  EntityRepository;

/**
 * GeoModelParameterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GeoModelParameterRepository extends EntityRepository
{
}


text:
package com.mtools.core.plugin.service;

import com.mtools.core.plugin.db.CoreDao;
import com.mtools.core.plugin.helper.SpringUtil;
import com.mtools.core.plugin.notify.AsyncNotify;

/**
 * @author zhang
 * 系统服务组件
 */
public final class MTSystemService {

	static MTSystemService self;

	public CoreDao getCoreDao(String beanName){
		CoreDao dao = (CoreDao) SpringUtil.getBean(beanName);
		return dao;
	}
	public AsyncNotify getNotifyService(){
		AsyncNotify nofity = (AsyncNotify) SpringUtil.getBean("sysRunningNotify");
		return nofity;
	}

	public static MTSystemService getInstance(){
		if(self==null){
			self=new MTSystemService();
		}
		return self;
	}
}


text:
object Test {
  opaque type A[T] = T match { case Int => Int } // error: Modifier `opaque` is not allowed for this definition
}


text:
package srl.graffiti.messages.sketch;

import srl.distributed.messages.Request;
import srl.distributed.messages.Response;

public class GetMyPositionedSketchesRequest extends Request {

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using Omnius.Base;

namespace Omnius.Io
{
    public class RecyclableMemoryStream : Stream
    {
        private BufferManager _bufferManager;

        private long _position;
        private long _length;

        private List<byte[]> _buffers = new List<byte[]>();
        private int _bufferSize = 32;

        private int _currentBufferIndex;
        private int _currentBufferPosition;

        private bool _isDisposed;

        public RecyclableMemoryStream(BufferManager bufferManager)
        {
            _bufferManager = bufferManager;
        }

        public override bool CanRead
        {
            get
            {
                if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

                return true;
            }
        }

        public override bool CanWrite
        {
            get
            {
                if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

                return true;
            }
        }

        public override bool CanSeek
        {
            get
            {
                if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

                return true;
            }
        }

        public override long Position
        {
            get
            {
                if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

                return _position;
            }
            set
            {
                if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
                if (value < 0 || this.Length < value) throw new ArgumentOutOfRangeException(nameof(value));

                if (_position == value) return;

                {
                    _currentBufferIndex = -1;
                    _currentBufferPosition = -1;
                }

                _position = value;
            }
        }

        public override long Length
        {
            get
            {
                if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

                return _length;
            }
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

            if (origin == SeekOrigin.Begin)
            {
                return this.Position = offset;
            }
            else if (origin == SeekOrigin.Current)
            {
                return this.Position += offset;
            }
            else if (origin == SeekOrigin.End)
            {
                return this.Position = this.Length + offset;
            }
            else
            {
                throw new NotSupportedException();
            }
        }

        public override void SetLength(long value)
        {
            if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);

            this.Position = Math.Min(_position, value);
            _length = value;
        }

        private void Search()
        {
            if (_currentBufferIndex == -1 && _currentBufferPosition == -1)
            {
                _currentBufferIndex = 0;
                _currentBufferPosition = 0;

                for (long position = 0; _currentBufferIndex < _buffers.Count; _currentBufferIndex++)
                {
                    position += _buffers[_currentBufferIndex].Length;

                    if (_position < position)
                    {
                        _currentBufferPosition = _buffers[_currentBufferIndex].Length - (int)(position - _position);
                        break;
                    }
                }
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (offset < 0 || buffer.Length < offset) throw new ArgumentOutOfRangeException(nameof(offset));
            if (count < 0 || (buffer.Length - offset) < count) throw new ArgumentOutOfRangeException(nameof(count));

            count = (int)Math.Min(count, this.Length - this.Position);
            if (count == 0) return 0;

            this.Search();

            int readSumLength = 0;

            while (count > 0)
            {
                int length = Math.Min(_buffers[_currentBufferIndex].Length - _currentBufferPosition, count);

                Unsafe.Copy(_buffers[_currentBufferIndex], _currentBufferPosition, buffer, offset, length);
                _currentBufferPosition += length;

                offset += length;
                count -= length;
                readSumLength += length;

                if (_currentBufferPosition == _buffers[_currentBufferIndex].Length)
                {
                    _currentBufferIndex++;
                    _currentBufferPosition = 0;
                }
            }

            _position += readSumLength;
            return readSumLength;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (offset < 0 || buffer.Length < offset) throw new ArgumentOutOfRangeException(nameof(offset));
            if (count < 0 || (buffer.Length - offset) < count) throw new ArgumentOutOfRangeException(nameof(count));
            if (count == 0) return;

            this.Search();

            int writeSumLength = 0;

            while (count > 0)
            {
                if (_currentBufferIndex >= _buffers.Count)
                {
                    var tempBuffer = _bufferManager.TakeBuffer(_bufferSize);
                    if (_bufferSize < 1024 * 32) _bufferSize *= 2;

                    _buffers.Add(tempBuffer);
                }

                int length = Math.Min(_buffers[_currentBufferIndex].Length - _currentBufferPosition, count);

                Unsafe.Copy(buffer, offset, _buffers[_currentBufferIndex], _currentBufferPosition, length);
                _currentBufferPosition += length;

                offset += length;
                count -= length;
                writeSumLength += length;

                if (_currentBufferPosition == _buffers[_currentBufferIndex].Length)
                {
                    _currentBufferIndex++;
                    _currentBufferPosition = 0;
                }
            }

            _position += writeSumLength;
            _length = Math.Max(_length, _position);
        }

        public override void Flush()
        {
            if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
        }

        protected override void Dispose(bool isDisposing)
        {
            try
            {
                if (_isDisposed) return;
                _isDisposed = true;

                if (isDisposing)
                {
                    if (_buffers != null)
                    {
                        try
                        {
                            for (int i = 0; i < _buffers.Count; i++)
                            {
                                _bufferManager.ReturnBuffer(_buffers[i]);
                            }
                        }
                        catch (Exception)
                        {

                        }

                        _buffers = null;
                    }
                }
            }
            finally
            {
                base.Dispose(isDisposing);
            }
        }

        public ArraySegment<byte> ToArray()
        {
            var buffer = _bufferManager.TakeBuffer((int)this.Length);
            long position = this.Position;

            this.Seek(0, SeekOrigin.Begin);
            this.Read(buffer, 0, (int)this.Length);
            this.Position = position;

            return new ArraySegment<byte>(buffer, 0, (int)this.Length);
        }
    }
}


text:
package org.infinispan.configuration.cache;

public interface CacheStoreConfiguration extends CacheLoaderConfiguration {

   /**
    * Configuration for the async cache loader. If enabled, this provides you with asynchronous
    * writes to the cache store, giving you 'write-behind' caching.
    */
   AsyncStoreConfiguration async();

   /**
    * SingletonStore is a delegating cache store used for situations when only one instance in a
    * cluster should interact with the underlying store. The coordinator of the cluster will be
    * responsible for the underlying CacheStore. SingletonStore is a simply facade to a real
    * CacheStore implementation. It always delegates reads to the real CacheStore.
    */
   SingletonStoreConfiguration singletonStore();

   /**
    * If true, purges this cache store when it starts up.
    */
   boolean purgeOnStartup();

   /**
    * If true, CacheStore#purgeExpired() call will be done synchronously
    */
   boolean purgeSynchronously();

   /**
    * The number of threads to use when purging asynchronously.
    */
   int purgerThreads();

   /**
    * If true, fetch persistent state when joining a cluster. If multiple cache stores are chained,
    * only one of them can have this property enabled. Persistent state transfer with a shared cache
    * store does not make sense, as the same persistent store that provides the data will just end
    * up receiving it. Therefore, if a shared cache store is used, the cache will not allow a
    * persistent state transfer even if a cache store has this property set to true. Finally,
    * setting it to true only makes sense if in a clustered environment, and only 'replication' and
    * 'invalidation' cluster modes are supported.
    */
   boolean fetchPersistentState();

   /**
    * If true, any operation that modifies the cache (put, remove, clear, store...etc) won't be
    * applied to the cache store. This means that the cache store could become out of sync with the
    * cache.
    */
   boolean ignoreModifications();

}


text:
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { Cascader } from 'antd';

@observer
export default class CategoryCascader extends Component{
  loadData = (selectedOptions) => {
    const { category } = this.props;
    category.getCategory({ level: selectedOptions.length + 1 });
  }

  render(){
    const { category, ...rest } = this.props;
    return <Cascader {...rest} loadData={this.loadData} changeOnSelect
      options={category.categoriesTree} />;
  }
};


text:
#ifndef ZEPHYR_INCLUDE_TOOLCHAIN_STDINT_H_
#define ZEPHYR_INCLUDE_TOOLCHAIN_STDINT_H_

/*
 * Some gcc versions and/or configurations as found in the Zephyr SDK
 * (questionably) define __INT32_TYPE__ and derivatives as a long int
 * which makes the printf format checker to complain about long vs int
 * mismatch when %u is given a uint32_t argument, and uint32_t pointers not
 * being compatible with int pointers. Let's redefine them to follow
 * common expectations and usage.
 */

#if __SIZEOF_INT__ != 4
#error "unexpected int width"
#endif

#undef __INT32_TYPE__
#undef __UINT32_TYPE__
#undef __INT_FAST32_TYPE__
#undef __UINT_FAST32_TYPE__
#undef __INT_LEAST32_TYPE__
#undef __UINT_LEAST32_TYPE__
#undef __INT64_TYPE__
#undef __UINT64_TYPE__
#undef __INT_FAST64_TYPE__
#undef __UINT_FAST64_TYPE__
#undef __INT_LEAST64_TYPE__
#undef __UINT_LEAST64_TYPE__

#define __INT32_TYPE__ int
#define __UINT32_TYPE__ unsigned int
#define __INT_FAST32_TYPE__ __INT32_TYPE__
#define __UINT_FAST32_TYPE__ __UINT32_TYPE__
#define __INT_LEAST32_TYPE__ __INT32_TYPE__
#define __UINT_LEAST32_TYPE__ __UINT32_TYPE__
#define __INT64_TYPE__ long long int
#define __UINT64_TYPE__ unsigned long long int
#define __INT_FAST64_TYPE__ __INT64_TYPE__
#define __UINT_FAST64_TYPE__ __UINT64_TYPE__
#define __INT_LEAST64_TYPE__ __INT64_TYPE__
#define __UINT_LEAST64_TYPE__ __UINT64_TYPE__

/*
 * The confusion also exists with __INTPTR_TYPE__ which is either an int
 * (even when __INT32_TYPE__ is a long int) or a long int. Let's redefine
 * it to a long int to get some uniformity. Doing so also makes it compatible
 * with LP64 (64-bit) targets where a long is always 64-bit wide.
 */

#if __SIZEOF_POINTER__ != __SIZEOF_LONG__
#error "unexpected size difference between pointers and long ints"
#endif

#undef __INTPTR_TYPE__
#undef __UINTPTR_TYPE__
#define __INTPTR_TYPE__ long int
#define __UINTPTR_TYPE__ long unsigned int

/*
 * Re-define the INTN_C(value) integer constant expression macros to match the
 * integer types re-defined above.
 */

#undef __INT32_C
#undef __UINT32_C
#undef __INT64_C
#undef __UINT64_C
#define __INT32_C(c) c
#define __UINT32_C(c) c ## U
#define __INT64_C(c) c ## LL
#define __UINT64_C(c) c ## ULL

#endif /* ZEPHYR_INCLUDE_TOOLCHAIN_STDINT_H_ */


text:
/**
 * @module outputToPlotly
 */

/**
 * @namespace Typedefs
 */

/**
 * @typedef {Object} GenderObjectType
 * @property {Number} boys - Number of something related to boys
 * @property {Number} girls - Number of something related to girls
 * @memberOf Typedefs
 */

/**
 * @typedef {Object} TeamObjectType
 * @property {String} size - Indicates the number of teams in object.
 * @property {GenderObjectType[]} genderTotals - Array of gender totals
 * @property {GenderObjectType[]} skillByGenderTotals - Array of skill totals for each gender
 * @memberOf Typedefs
 */

/**
 * Export team metrics to Plotly web service
 * @param	{String}	username  - created by opening Plotly account
 * @param	{String}	key - generated when opening Plotly account
 * @param	{TeamObjectType[]}	teamMetricsArray object that contains size,
 * gender totals, and skill by gender totals
 * @param	{Function}	called when error occurs or operation complete.
 * First parameter is error that is propagated from Plotly API, or null if
 * not error occurred.
 */
module.exports = function(username, key, teamMetricsArray, callback){
	var plotly = require('plotly')(username, key);

	plotSums('Gender Totals', teamMetricsArray.genderTotals, 'Player Sums');
	plotSums('Skill By Gender Totals', teamMetricsArray.skillByGenderTotals, 'Skill Sums');

	/**
	 * Main plotting function that adapts data to Plotly format and applies common
	 * layout settings
	 * @param	{String} filename - name of chart and what it will be saved as
	 * @param	{TeamObjectType} totals - object that contains gender data
	 * @param	{String} yAxisTitle - unique title for Y-axis
	 * @private
	 */
	function plotSums(filename, totals, yAxisTitle){

		var teamNames = [];
		for (var i=0; i<teamMetricsArray.size; i++){
			teamNames.push(i+1);
		}

		var boyTotals = [];
		for (i=0; i<teamMetricsArray.size; i++){
			boyTotals.push(totals[i].boys);
		}

		var girlTotals = [];
		for (i=0; i<teamMetricsArray.size; i++){
			girlTotals.push(totals[i].girls);
		}

		var trace1 = {
			x: teamNames,
			y: boyTotals,
			name: 'Boys',
			type: 'bar'
		};

		var trace2 = {
			x: teamNames,
			y: girlTotals,
			name: 'Girls',
			type: 'bar'
		};

		var data = [trace1, trace2];
		var layout = {
			xaxis: {
				title: 'Teams'
			},
			yaxis: {
				title: yAxisTitle
			},
			title: filename,
			barmode: 'stack'
		};

		var graph_options = {layout: layout, filename: filename, fileopt: 'overwrite'};

		plotly.plot(data, graph_options, function(err, msg){
			if (err){
				console.log('failed to post Plotly data');
				callback(err);
			} else {
				callback(null);
			}
		});
	}
};


text:
function setcont(hfile, bc)
% xff::setcont  - override entire contents of object
%
% FORMAT:       setcont(obj, content)
%
% Input fields:
%
%       obj         non-ROOT xff object
%       content     1x1 content struct
%
% No output fields.

% Version:  v0.9d
% Build:    14061918
% Date:     Jun-19 2014, 6:29 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/

% Copyright (c) 2010, 2011, 2014, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% argument check
if nargin ~= 2 || ...
    numel(hfile) ~= 1 || ...
    numel(bc) ~= 1 || ...
   ~xffisobject(hfile, true) || ...
    hfile.L == -1
    error( ...
        'xff:BadArgument', ...
        'Invalid object for assignment.' ...
    );
end

% get content first
cc = xffgetcont(hfile.L);
if numel(fieldnames(cc)) ~= numel(fieldnames(bc)) || ...
   ~all(strcmp(fieldnames(cc), fieldnames(cc)))
    error( ...
        'xff:BadArgument', ...
        'Mismatching fieldnames, content not set.' ...
    );
end

% assignment
try
    xffsetcont(hfile.L, bc);
catch ne_eo;
    rethrow(ne_eo);
end


text:
typedef const struct __clockid *clockid_t;

#endif


text:
package com.javarush.task.task07.task0705;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/*
Один большой массив и два маленьких
*/

public class Solution {
    public static void main(String[] args) throws Exception {
        int[] bigArray = new int[20], leftSmallArray = new int[10], rightSmallArray = new int[10];

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        for (int i = 0; i < bigArray.length; i++) {
            bigArray[i] = Integer.parseInt(reader.readLine());
            if (i < 10) {
                leftSmallArray[i] = bigArray[i];
            } else {
                rightSmallArray[i - 10] = bigArray[i];
            }
        }

        for (int elem : rightSmallArray) {
            System.out.println(elem);
        }
    }
}


text:
package com.microfocus.application.automation.tools.model;

import com.microfocus.application.automation.tools.settings.AlmServerSettingsBuilder;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;

import java.util.List;

/**
 * Created by barush on 21/10/2014.
 */
public class AutEnvironmentModel extends AbstractDescribableImpl<AutEnvironmentModel> {

    private final String almServerName;
    private String almServerUrl;
    private final String almUserName;
    private final SecretContainer almPassword;
    private final String almDomain;
    private final String almProject;
    private final String clientType;

    private final String autEnvironmentId;
    private final boolean useExistingAutEnvConf;
    private final String existingAutEnvConfId;
    private final boolean createNewAutEnvConf;
    private final String newAutEnvConfName;

    private List<AutEnvironmentParameterModel> autEnvironmentParameters;

    private final String pathToJsonFile;
    private final String outputParameter;

    @DataBoundConstructor
    public AutEnvironmentModel(
            String almServerName,
            String almUserName,
            String almPassword,
            String almDomain,
            String almProject,
            String clientType,
            String autEnvironmentId,
            boolean useExistingAutEnvConf,
            String existingAutEnvConfId,
            boolean createNewAutEnvConf,
            String newAutEnvConfName,
            List<AutEnvironmentParameterModel> autEnvironmentParameters,
            String pathToJsonFile,
            String outputParameter) {

        this.almServerName = almServerName;
        this.almUserName = almUserName;
        this.almPassword = setPassword(almPassword);
        this.almDomain = almDomain;
        this.almProject = almProject;
        this.clientType = clientType;
        this.autEnvironmentId = autEnvironmentId;
        this.useExistingAutEnvConf = useExistingAutEnvConf;
        this.existingAutEnvConfId = existingAutEnvConfId;
        this.createNewAutEnvConf = createNewAutEnvConf;
        this.newAutEnvConfName = newAutEnvConfName;
        this.autEnvironmentParameters = autEnvironmentParameters;
        this.pathToJsonFile = pathToJsonFile;
        this.outputParameter = outputParameter;

    }

    protected SecretContainer setPassword(String almPassword) {

        SecretContainer secretContainer = new SecretContainerImpl();
        secretContainer.initialize(almPassword);

        return secretContainer;
    }

    public String getPathToJsonFile() {
        return pathToJsonFile;
    }

    public boolean isCreateNewAutEnvConf() {
        return createNewAutEnvConf;
    }

    public boolean isUseExistingAutEnvConf() {
        return useExistingAutEnvConf;
    }

    public String getAlmServerName() {

        return almServerName;
    }

    public String getAlmServerUrl() {

        return almServerUrl;
    }

    public void setAlmServerUrl(String almServerUrl) {

        this.almServerUrl = almServerUrl;
    }

    public String getAlmUserName() {

        return almUserName;
    }

    public String getAlmPassword() {

        return almPassword.toString();
    }

    public String getAlmDomain() {

        return almDomain;
    }

    public String getAlmProject() {

        return almProject;
    }

    public String getClientType() {
        return clientType;
    }

    public String getOutputParameter() {
        return outputParameter;
    }

    public String getAutEnvironmentId() {
        return autEnvironmentId;
    }

    public String getExistingAutEnvConfId() {
        return existingAutEnvConfId;
    }

    public String getNewAutEnvConfName() {
        return newAutEnvConfName;
    }

    public List<AutEnvironmentParameterModel> getAutEnvironmentParameters() {
        return autEnvironmentParameters;
    }

    @Extension
    public static class DescriptorImpl extends Descriptor<AutEnvironmentModel> {

        public String getDisplayName() {
            return "UFT ALM AUT Environment Preparation Model";
        }

        public AlmServerSettingsModel[] getAlmServers() {

            return Hudson.getInstance().getDescriptorByType(
                    AlmServerSettingsBuilder.DescriptorImpl.class).getInstallations();
        }

        public FormValidation doCheckAlmUserName(@QueryParameter String value) {

            return generalCheckWithError(value, "User name must be set");
        }

        public FormValidation doCheckAlmDomain(@QueryParameter String value) {

            return generalCheckWithError(value, "Domain must be set");
        }

        public FormValidation doCheckAlmProject(@QueryParameter String value) {

            return generalCheckWithError(value, "Project must be set");
        }

        public FormValidation doCheckAutEnvironmentId(@QueryParameter String value) {

            return generalCheckWithError(value, "AUT Environment ID must be set");
        }

        public FormValidation doCheckAlmPassword(@QueryParameter String value) {

            FormValidation ret = FormValidation.ok();
            if (StringUtils.isBlank(value)) {
                ret = FormValidation.warning("Password for ALM server is empty");
            }

            return ret;
        }

        public FormValidation doCheckOutputParameter(@QueryParameter String value) {

            FormValidation ret = FormValidation.ok();
            if (StringUtils.isBlank(value)) {
                ret =
                        FormValidation.warning("AUT Environment Configuration ID isn't assigned to any environment variable");
            }

            return ret;
        }

        private FormValidation generalCheckWithError(String value, String errorMessage) {

            FormValidation ret = FormValidation.ok();
            if (StringUtils.isBlank(value)) {
                ret = FormValidation.error(errorMessage);
            }

            return ret;
        }

    }

}


text:
package org.apache.reef.runtime.common.client.parameters;

import org.apache.reef.annotations.audience.ClientSide;
import org.apache.reef.tang.annotations.Name;
import org.apache.reef.tang.annotations.NamedParameter;

/**
 * A Tang named parameter that indicates whether or not a client (handler for the various Job events) is present.
 */
@ClientSide
@NamedParameter(doc = "Indicates whether or not a client is present", default_value = ClientPresent.NO)
public final class ClientPresent implements Name<String> {
  public static final String YES = "YES";
  public static final String NO = "NO";
}


text:
package org.docksidestage.hangar.dbflute.bsentity.dbmeta;

import java.util.List;
import java.util.Map;

import org.dbflute.Entity;
import org.dbflute.optional.OptionalEntity;
import org.dbflute.dbmeta.AbstractDBMeta;
import org.dbflute.dbmeta.info.*;
import org.dbflute.dbmeta.name.*;
import org.dbflute.dbmeta.property.PropertyGateway;
import org.dbflute.dbway.DBDef;
import org.docksidestage.hangar.dbflute.allcommon.*;
import org.docksidestage.hangar.dbflute.exentity.*;

/**
 * The DB meta of WHITE_BASE_ONE04_BONVO. (Singleton)
 * @author DBFlute(AutoGenerator)
 */
public class WhiteBaseOne04BonvoDbm extends AbstractDBMeta {

    // ===================================================================================
    //                                                                           Singleton
    //                                                                           =========
    private static final WhiteBaseOne04BonvoDbm _instance = new WhiteBaseOne04BonvoDbm();
    private WhiteBaseOne04BonvoDbm() {}
    public static WhiteBaseOne04BonvoDbm getInstance() { return _instance; }

    // ===================================================================================
    //                                                                       Current DBDef
    //                                                                       =============
    public String getProjectName() { return DBCurrent.getInstance().projectName(); }
    public String getProjectPrefix() { return DBCurrent.getInstance().projectPrefix(); }
    public String getGenerationGapBasePrefix() { return DBCurrent.getInstance().generationGapBasePrefix(); }
    public DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); }

    // ===================================================================================
    //                                                                    Property Gateway
    //                                                                    ================
    // -----------------------------------------------------
    //                                       Column Property
    //                                       ---------------
    protected final Map<String, PropertyGateway> _epgMap = newHashMap();
    { xsetupEpg(); }
    protected void xsetupEpg() {
        setupEpg(_epgMap, et -> ((WhiteBaseOne04Bonvo)et).getBonvoId(), (et, vl) -> ((WhiteBaseOne04Bonvo)et).setBonvoId(cti(vl)), "bonvoId");
        setupEpg(_epgMap, et -> ((WhiteBaseOne04Bonvo)et).getBonvoName(), (et, vl) -> ((WhiteBaseOne04Bonvo)et).setBonvoName((String)vl), "bonvoName");
        setupEpg(_epgMap, et -> ((WhiteBaseOne04Bonvo)et).getParksideId(), (et, vl) -> ((WhiteBaseOne04Bonvo)et).setParksideId(cti(vl)), "parksideId");
        setupEpg(_epgMap, et -> ((WhiteBaseOne04Bonvo)et).getStationsideId(), (et, vl) -> ((WhiteBaseOne04Bonvo)et).setStationsideId(cti(vl)), "stationsideId");
    }
    public PropertyGateway findPropertyGateway(String prop)
    { return doFindEpg(_epgMap, prop); }

    // -----------------------------------------------------
    //                                      Foreign Property
    //                                      ----------------
    protected final Map<String, PropertyGateway> _efpgMap = newHashMap();
    { xsetupEfpg(); }
    @SuppressWarnings("unchecked")
    protected void xsetupEfpg() {
        setupEfpg(_efpgMap, et -> ((WhiteBaseOne04Bonvo)et).getWhiteBaseOne04BonvoParkside(), (et, vl) -> ((WhiteBaseOne04Bonvo)et).setWhiteBaseOne04BonvoParkside((OptionalEntity<WhiteBaseOne04BonvoParkside>)vl), "whiteBaseOne04BonvoParkside");
        setupEfpg(_efpgMap, et -> ((WhiteBaseOne04Bonvo)et).getWhiteBaseOne04BonvoStationside(), (et, vl) -> ((WhiteBaseOne04Bonvo)et).setWhiteBaseOne04BonvoStationside((OptionalEntity<WhiteBaseOne04BonvoStationside>)vl), "whiteBaseOne04BonvoStationside");
    }
    public PropertyGateway findForeignPropertyGateway(String prop)
    { return doFindEfpg(_efpgMap, prop); }

    // ===================================================================================
    //                                                                          Table Info
    //                                                                          ==========
    protected final String _tableDbName = "WHITE_BASE_ONE04_BONVO";
    protected final String _tableDispName = "WHITE_BASE_ONE04_BONVO";
    protected final String _tablePropertyName = "whiteBaseOne04Bonvo";
    protected final TableSqlName _tableSqlName = new TableSqlName("MAIHAMADB.PUBLIC.WHITE_BASE_ONE04_BONVO", _tableDbName);
    { _tableSqlName.xacceptFilter(DBFluteConfig.getInstance().getTableSqlNameFilter()); }
    public String getTableDbName() { return _tableDbName; }
    public String getTableDispName() { return _tableDispName; }
    public String getTablePropertyName() { return _tablePropertyName; }
    public TableSqlName getTableSqlName() { return _tableSqlName; }

    // ===================================================================================
    //                                                                         Column Info
    //                                                                         ===========
    protected final ColumnInfo _columnBonvoId = cci("BONVO_ID", "BONVO_ID", null, null, Integer.class, "bonvoId", null, true, false, true, "INTEGER", 10, 0, null, null, false, null, null, null, "whiteBaseList", null, false);
    protected final ColumnInfo _columnBonvoName = cci("BONVO_NAME", "BONVO_NAME", null, null, String.class, "bonvoName", null, false, false, true, "VARCHAR", 200, 0, null, null, false, null, null, null, null, null, false);
    protected final ColumnInfo _columnParksideId = cci("PARKSIDE_ID", "PARKSIDE_ID", null, null, Integer.class, "parksideId", null, false, false, false, "INTEGER", 10, 0, null, null, false, null, null, "whiteBaseOne04BonvoParkside", null, null, false);
    protected final ColumnInfo _columnStationsideId = cci("STATIONSIDE_ID", "STATIONSIDE_ID", null, null, Integer.class, "stationsideId", null, false, false, false, "INTEGER", 10, 0, null, null, false, null, null, "whiteBaseOne04BonvoStationside", null, null, false);

    /**
     * BONVO_ID: {PK, NotNull, INTEGER(10)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnBonvoId() { return _columnBonvoId; }
    /**
     * BONVO_NAME: {NotNull, VARCHAR(200)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnBonvoName() { return _columnBonvoName; }
    /**
     * PARKSIDE_ID: {IX, INTEGER(10), FK to WHITE_BASE_ONE04_BONVO_PARKSIDE}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnParksideId() { return _columnParksideId; }
    /**
     * STATIONSIDE_ID: {IX, INTEGER(10), FK to WHITE_BASE_ONE04_BONVO_STATIONSIDE}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnStationsideId() { return _columnStationsideId; }

    protected List<ColumnInfo> ccil() {
        List<ColumnInfo> ls = newArrayList();
        ls.add(columnBonvoId());
        ls.add(columnBonvoName());
        ls.add(columnParksideId());
        ls.add(columnStationsideId());
        return ls;
    }

    { initializeInformationResource(); }

    // ===================================================================================
    //                                                                         Unique Info
    //                                                                         ===========
    // -----------------------------------------------------
    //                                       Primary Element
    //                                       ---------------
    protected UniqueInfo cpui() { return hpcpui(columnBonvoId()); }
    public boolean hasPrimaryKey() { return true; }
    public boolean hasCompoundPrimaryKey() { return false; }

    // ===================================================================================
    //                                                                       Relation Info
    //                                                                       =============
    // cannot cache because it uses related DB meta instance while booting
    // (instead, cached by super's collection)
    // -----------------------------------------------------
    //                                      Foreign Property
    //                                      ----------------
    /**
     * WHITE_BASE_ONE04_BONVO_PARKSIDE by my PARKSIDE_ID, named 'whiteBaseOne04BonvoParkside'.
     * @return The information object of foreign property. (NotNull)
     */
    public ForeignInfo foreignWhiteBaseOne04BonvoParkside() {
        Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnParksideId(), WhiteBaseOne04BonvoParksideDbm.getInstance().columnParksideId());
        return cfi("FK_WHITE_BASE_ONE04_BONVO_WHITE_BASE_ONE04_BONVO_PARKSIDE", "whiteBaseOne04BonvoParkside", this, WhiteBaseOne04BonvoParksideDbm.getInstance(), mp, 0, org.dbflute.optional.OptionalEntity.class, false, false, false, false, null, null, false, "whiteBaseOne04BonvoList", false);
    }
    /**
     * WHITE_BASE_ONE04_BONVO_STATIONSIDE by my STATIONSIDE_ID, named 'whiteBaseOne04BonvoStationside'.
     * @return The information object of foreign property. (NotNull)
     */
    public ForeignInfo foreignWhiteBaseOne04BonvoStationside() {
        Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnStationsideId(), WhiteBaseOne04BonvoStationsideDbm.getInstance().columnStationsideId());
        return cfi("FK_WHITE_BASE_ONE04_BONVO_WHITE_BASE_ONE04_BONVO_STATIONSIDE", "whiteBaseOne04BonvoStationside", this, WhiteBaseOne04BonvoStationsideDbm.getInstance(), mp, 1, org.dbflute.optional.OptionalEntity.class, false, false, false, false, null, null, false, "whiteBaseOne04BonvoList", false);
    }

    // -----------------------------------------------------
    //                                     Referrer Property
    //                                     -----------------
    /**
     * WHITE_BASE by BONVO_ID, named 'whiteBaseList'.
     * @return The information object of referrer property. (NotNull)
     */
    public ReferrerInfo referrerWhiteBaseList() {
        Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnBonvoId(), WhiteBaseDbm.getInstance().columnBonvoId());
        return cri("FK_WHITE_BASE_WHITE_BASE_ONE04_BONVO", "whiteBaseList", this, WhiteBaseDbm.getInstance(), mp, false, "whiteBaseOne04Bonvo");
    }

    // ===================================================================================
    //                                                                        Various Info
    //                                                                        ============

    // ===================================================================================
    //                                                                           Type Name
    //                                                                           =========
    public String getEntityTypeName() { return "org.docksidestage.hangar.dbflute.exentity.WhiteBaseOne04Bonvo"; }
    public String getConditionBeanTypeName() { return "org.docksidestage.hangar.dbflute.cbean.WhiteBaseOne04BonvoCB"; }
    public String getBehaviorTypeName() { return "org.docksidestage.hangar.dbflute.exbhv.WhiteBaseOne04BonvoBhv"; }

    // ===================================================================================
    //                                                                         Object Type
    //                                                                         ===========
    public Class<WhiteBaseOne04Bonvo> getEntityType() { return WhiteBaseOne04Bonvo.class; }

    // ===================================================================================
    //                                                                     Object Instance
    //                                                                     ===============
    public WhiteBaseOne04Bonvo newEntity() { return new WhiteBaseOne04Bonvo(); }

    // ===================================================================================
    //                                                                   Map Communication
    //                                                                   =================
    public void acceptPrimaryKeyMap(Entity et, Map<String, ? extends Object> mp)
    { doAcceptPrimaryKeyMap((WhiteBaseOne04Bonvo)et, mp); }
    public void acceptAllColumnMap(Entity et, Map<String, ? extends Object> mp)
    { doAcceptAllColumnMap((WhiteBaseOne04Bonvo)et, mp); }
    public Map<String, Object> extractPrimaryKeyMap(Entity et) { return doExtractPrimaryKeyMap(et); }
    public Map<String, Object> extractAllColumnMap(Entity et) { return doExtractAllColumnMap(et); }
}


text:
package com.cloud.network.element;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;

import org.apache.cloudstack.resourcedetail.dao.VpcDetailsDao;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import com.cloud.NuageTest;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.deploy.DeployDestination;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.CloudException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.UnsupportedServiceException;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.network.Network;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.NuageVspDeviceVO;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.NuageVspDao;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkVO;
import com.cloud.network.manager.NuageVspManager;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.StaticNat;
import com.cloud.network.vpc.NetworkACLItem;
import com.cloud.network.vpc.Vpc;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.resource.ResourceManager;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.user.Account;
import com.cloud.util.NuageVspEntityBuilder;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.dao.DomainRouterDao;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

public class NuageVspElementTest extends NuageTest {

    @InjectMocks
    private NuageVspElement _nuageVspElement = new NuageVspElement();

    @Mock private NetworkServiceMapDao _networkServiceMapDao;
    @Mock private AgentManager _agentManager;
    @Mock private HostDao _hostDao;
    @Mock private NuageVspDao _nuageVspDao;
    @Mock private DomainDao _domainDao;
    @Mock private NetworkOfferingDao _networkOfferingDao;
    @Mock private NetworkOfferingServiceMapDao _networkOfferingServiceMapDao;
    @Mock private NuageVspManager _nuageVspManager;
    @Mock private FirewallRulesDao _firewallRulesDao;
    @Mock private IPAddressDao _ipAddressDao;
    @Mock private PhysicalNetworkDao _physicalNetworkDao;
    @Mock private NuageVspEntityBuilder _nuageVspEntityBuilder;
    @Mock private VpcDetailsDao _vpcDetailsDao;
    @Mock private DomainRouterDao _domainRouterDao;
    @Mock private ResourceManager _resourceManager;
    @Mock private ResourceTagDao _resourceTagDao;
    @Mock private NetworkDao _networkDao;

    @Before
    public void setUp() throws Exception {
        super.setUp();
        _nuageVspElement._nuageVspEntityBuilder = _nuageVspEntityBuilder;
        _nuageVspElement._vpcDetailsDao = _vpcDetailsDao;
        _nuageVspElement._routerDao = _domainRouterDao;
        _nuageVspElement._networkDao = _networkDao;

        when(_networkServiceMapDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NuageVsp)).thenReturn(true);
        when(_networkServiceMapDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.SourceNat, Provider.NuageVsp)).thenReturn(true);

        _nuageVspElement.configure("NuageVspTestElement", Collections.<String, Object>emptyMap());
    }

    @Test
    public void testCanHandle() {
        final Network net = mock(Network.class);
        when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vsp);
        when(net.getId()).thenReturn(NETWORK_ID);
        when(net.getNetworkOfferingId()).thenReturn(NETWORK_ID);

        final NetworkOfferingVO ntwkoffer = mock(NetworkOfferingVO.class);
        when(ntwkoffer.getId()).thenReturn(NETWORK_ID);
        when(ntwkoffer.isPersistent()).thenReturn(true);
        when(_networkOfferingDao.findById(NETWORK_ID)).thenReturn(ntwkoffer);

        // Golden path
        assertTrue(_nuageVspElement.canHandle(net, Service.Connectivity));

        when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
        // Only broadcastdomaintype Vsp is supported
        assertFalse(_nuageVspElement.canHandle(net, Service.Connectivity));

        when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vsp);
        when(_networkServiceMapDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NuageVsp)).thenReturn(false);
        // No NuageVsp provider in the network
        assertFalse(_nuageVspElement.canHandle(net, Service.Connectivity));

        when(_networkModel.isProviderForNetwork(Provider.NuageVsp, NETWORK_ID)).thenReturn(false);
        when(_networkServiceMapDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NuageVsp)).thenReturn(true);
        // NusageVsp provider does not provide Connectivity for this network
        assertFalse(_nuageVspElement.canHandle(net, Service.Connectivity));

        when(_networkModel.isProviderForNetwork(Provider.NuageVsp, NETWORK_ID)).thenReturn(true);
        // Only service Connectivity is supported
        assertFalse(_nuageVspElement.canHandle(net, Service.Dhcp));

        // Can't handle network offerings with specify vlan = true
        when(ntwkoffer.isSpecifyVlan()).thenReturn(true);
        assertFalse(_nuageVspElement.canHandle(net, Service.Connectivity));
    }

    @Test
    public void testImplement() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, URISyntaxException {
        final Network network = mock(NetworkVO.class, withSettings().extraInterfaces(Network.class));
        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vsp);
        when(network.getId()).thenReturn(NETWORK_ID);
        when(network.getVpcId()).thenReturn(null);
        when(network.getBroadcastUri()).thenReturn(new URI(""));
        when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
        when(network.getDomainId()).thenReturn(NETWORK_ID);
        when(network.getDataCenterId()).thenReturn(NETWORK_ID);
        when(_networkModel.isProviderForNetwork(Provider.NuageVsp, NETWORK_ID)).thenReturn(true);

        final NetworkVO networkVO = mock(NetworkVO.class);
        when(network.getUuid()).thenReturn("aaaaaa");

        when(_networkDao.findById(NETWORK_ID)).thenReturn(networkVO);

        final NetworkOffering offering = mock(NetworkOffering.class);
        when(offering.getId()).thenReturn(NETWORK_ID);
        when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
        when(offering.getGuestType()).thenReturn(GuestType.Isolated);

        DeployDestination deployDest = mock(DeployDestination.class);

        final DomainVO dom = mock(DomainVO.class);
        when(dom.getName()).thenReturn("domain");
        when(_domainDao.findById(NETWORK_ID)).thenReturn(dom);
        final Account acc = mock(Account.class);
        when(acc.getAccountName()).thenReturn("accountname");
        final ReservationContext context = mock(ReservationContext.class);
        when(context.getDomain()).thenReturn(dom);
        when(context.getAccount()).thenReturn(acc);

        final HostVO host = mock(HostVO.class);
        when(host.getId()).thenReturn(NETWORK_ID);
        final NuageVspDeviceVO nuageVspDevice = mock(NuageVspDeviceVO.class);
        when(nuageVspDevice.getHostId()).thenReturn(NETWORK_ID);
        when(_nuageVspDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NuageVspDeviceVO[]{nuageVspDevice}));
        when(_hostDao.findById(NETWORK_ID)).thenReturn(host);
        when(_nuageVspManager.getNuageVspHost(NETWORK_ID)).thenReturn(host);

        when(_firewallRulesDao.listByNetworkPurposeTrafficType(NETWORK_ID, FirewallRule.Purpose.Firewall, FirewallRule.TrafficType.Ingress)).thenReturn(new ArrayList<FirewallRuleVO>());
        when(_firewallRulesDao.listByNetworkPurposeTrafficType(NETWORK_ID, FirewallRule.Purpose.Firewall, FirewallRule.TrafficType.Egress)).thenReturn(new ArrayList<FirewallRuleVO>());
        when(_ipAddressDao.listStaticNatPublicIps(NETWORK_ID)).thenReturn(new ArrayList<IPAddressVO>());
        when(_nuageVspManager.getDnsDetails(network.getDataCenterId())).thenReturn(new ArrayList<String>());
        when(_networkDao.findById(network.getId())).thenReturn((NetworkVO)network);

        assertTrue(_nuageVspElement.implement(network, offering, deployDest, context));
    }

    @Test
    public void testVerifyServiceCombination() {

        Set<Service> services = Sets.newHashSet(
            Service.Dhcp,
            Service.StaticNat,
            Service.SourceNat,
            Service.Connectivity,
            Service.Firewall);
        assertTrue(_nuageVspElement.verifyServicesCombination(services));

        services = Sets.newHashSet(
                Service.Dhcp,
                Service.StaticNat,
                Service.Connectivity,
                Service.Firewall);
        assertTrue(_nuageVspElement.verifyServicesCombination(services));

        services = Sets.newHashSet(
                Service.Dhcp,
                Service.StaticNat,
                Service.Firewall);
        try {
            _nuageVspElement.verifyServicesCombination(services);
            fail("Expected Exception");
        } catch (UnsupportedServiceException e) {
            assertThat(e.getMessage(), is("Provider Network.Provider[name=NuageVsp] requires services: [Network.Service[name=Connectivity]]"));
        }
    }

    @Test
    public void testApplyStaticNats() throws CloudException {
        final Network network = mock(Network.class);
        when(network.getUuid()).thenReturn("aaaaaa");
        when(network.getVpcId()).thenReturn(null);
        when(network.getNetworkOfferingId()).thenReturn(NETWORK_ID);
        when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
        when(network.getDomainId()).thenReturn(NETWORK_ID);

        final DomainVO domVo = mock(DomainVO.class);
        when(_domainDao.findById(41l)).thenReturn(domVo);

        final NetworkOfferingVO ntwkoffer = mock(NetworkOfferingVO.class);
        when(ntwkoffer.getId()).thenReturn(NETWORK_ID);
        when(_networkOfferingDao.findById(NETWORK_ID)).thenReturn(ntwkoffer);

        final HostVO host = mock(HostVO.class);
        when(host.getId()).thenReturn(NETWORK_ID);
        final NuageVspDeviceVO nuageVspDevice = mock(NuageVspDeviceVO.class);
        when(nuageVspDevice.getHostId()).thenReturn(NETWORK_ID);
        when(_nuageVspDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NuageVspDeviceVO[]{nuageVspDevice}));
        when(_hostDao.findById(NETWORK_ID)).thenReturn(host);
        when(_nuageVspManager.getNuageVspHost(NETWORK_ID)).thenReturn(host);

        when(_domainDao.findById(NETWORK_ID)).thenReturn(mock(DomainVO.class));
        final Answer answer = mock(Answer.class);
        when(answer.getResult()).thenReturn(true);
        when(_agentManager.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
        assertTrue(_nuageVspElement.applyStaticNats(network, new ArrayList<StaticNat>()));
    }

    @Test
    public void testApplyFWRules() throws Exception {
        final Network network = mock(Network.class);
        when(network.getUuid()).thenReturn("aaaaaa");
        when(network.getVpcId()).thenReturn(null);
        when(network.getNetworkOfferingId()).thenReturn(NETWORK_ID);
        when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
        when(network.getDomainId()).thenReturn(NETWORK_ID);

        final NetworkOfferingVO ntwkoffer = mock(NetworkOfferingVO.class);
        when(ntwkoffer.getId()).thenReturn(NETWORK_ID);
        when(ntwkoffer.isEgressDefaultPolicy()).thenReturn(true);
        when(_networkOfferingDao.findById(NETWORK_ID)).thenReturn(ntwkoffer);

        final HostVO host = mock(HostVO.class);
        when(host.getId()).thenReturn(NETWORK_ID);
        final NuageVspDeviceVO nuageVspDevice = mock(NuageVspDeviceVO.class);
        when(nuageVspDevice.getHostId()).thenReturn(NETWORK_ID);
        when(_nuageVspDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NuageVspDeviceVO[]{nuageVspDevice}));
        when(_hostDao.findById(NETWORK_ID)).thenReturn(host);
        when(_nuageVspManager.getNuageVspHost(NETWORK_ID)).thenReturn(host);

        when(_domainDao.findById(NETWORK_ID)).thenReturn(mock(DomainVO.class));

        final Answer answer = mock(Answer.class);
        when(answer.getResult()).thenReturn(true);
        when(_agentManager.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
        assertTrue(_nuageVspElement.applyFWRules(network, new ArrayList<FirewallRule>()));
    }

    @Test
    public void testApplyNetworkACL() throws Exception {
        final Network network = mock(Network.class);
        when(network.getUuid()).thenReturn("aaaaaa");
        when(network.getVpcId()).thenReturn(null);
        when(network.getNetworkOfferingId()).thenReturn(NETWORK_ID);
        when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
        when(network.getDomainId()).thenReturn(NETWORK_ID);

        final NetworkOfferingVO ntwkoffer = mock(NetworkOfferingVO.class);
        when(ntwkoffer.getId()).thenReturn(NETWORK_ID);
        when(ntwkoffer.isEgressDefaultPolicy()).thenReturn(true);
        when(_networkOfferingDao.findById(NETWORK_ID)).thenReturn(ntwkoffer);

        final HostVO host = mock(HostVO.class);
        when(host.getId()).thenReturn(NETWORK_ID);
        final NuageVspDeviceVO nuageVspDevice = mock(NuageVspDeviceVO.class);
        when(nuageVspDevice.getHostId()).thenReturn(NETWORK_ID);
        when(_nuageVspDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NuageVspDeviceVO[]{nuageVspDevice}));
        when(_hostDao.findById(NETWORK_ID)).thenReturn(host);
        when(_nuageVspManager.getNuageVspHost(NETWORK_ID)).thenReturn(host);

        when(_domainDao.findById(NETWORK_ID)).thenReturn(mock(DomainVO.class));
        final Answer answer = mock(Answer.class);
        when(answer.getResult()).thenReturn(true);
        when(_agentManager.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
        assertTrue(_nuageVspElement.applyNetworkACLs(network, new ArrayList<NetworkACLItem>()));
    }

    @Test
    public void testShutdownVpc() throws Exception {
        final Vpc vpc = mock(Vpc.class);
        when(vpc.getUuid()).thenReturn("aaaaaa");
        when(vpc.getState()).thenReturn(Vpc.State.Inactive);
        when(vpc.getDomainId()).thenReturn(NETWORK_ID);
        when(vpc.getZoneId()).thenReturn(NETWORK_ID);
        when(vpc.getId()).thenReturn(NETWORK_ID);

        final DomainVO dom = mock(DomainVO.class);
        when(dom.getName()).thenReturn("domain");
        when(_domainDao.findById(NETWORK_ID)).thenReturn(dom);
        final Account acc = mock(Account.class);
        when(acc.getAccountName()).thenReturn("accountname");
        final ReservationContext context = mock(ReservationContext.class);
        when(context.getDomain()).thenReturn(dom);
        when(context.getAccount()).thenReturn(acc);

        PhysicalNetworkVO physNet = mock(PhysicalNetworkVO.class);
        when(physNet.getIsolationMethods()).thenReturn(Lists.newArrayList("VSP"));
        when(physNet.getId()).thenReturn(NETWORK_ID);
        when(_physicalNetworkDao.listByZone(NETWORK_ID)).thenReturn(Lists.newArrayList(physNet));

        final HostVO host = mock(HostVO.class);
        when(host.getId()).thenReturn(NETWORK_ID);
        final NuageVspDeviceVO nuageVspDevice = mock(NuageVspDeviceVO.class);
        when(nuageVspDevice.getHostId()).thenReturn(NETWORK_ID);
        when(_nuageVspDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Lists.newArrayList(nuageVspDevice));
        when(_hostDao.findById(NETWORK_ID)).thenReturn(host);
        when(_nuageVspManager.getNuageVspHost(NETWORK_ID)).thenReturn(host);

        DomainRouterVO domainRouter = mock(DomainRouterVO.class);
        when(domainRouter.getUuid()).thenReturn("aaaaaa");
        when(_domainRouterDao.listByVpcId(NETWORK_ID)).thenReturn(Lists.newArrayList(domainRouter));

        final Answer answer = mock(Answer.class);
        when(answer.getResult()).thenReturn(true);
        when(_agentManager.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
        assertTrue(_nuageVspElement.shutdownVpc(vpc, context));
    }
}


text:
namespace Bookshelf.Tests.Controllers
{
    using System;
    using Bookshelf.Controllers;
    using Bookshelf.Services;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;

    [TestClass]
    public class BooksControllerTests
    {
        private readonly Mock<IBookService> bookService = new Mock<IBookService>();

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void BooksController_BookServiceIsNull()
        {
            var given = new Prior
            {
                HasBookService = false
            };

            this.CreateBooksController(given);
        }

        private BooksController CreateBooksController(Prior given)
        {
            return new BooksController(
                given.HasBookService ? this.bookService.Object : null);
        }

        internal class Prior
        {
            public bool HasBookService { get; set; } = true;
        }
    }
}


text:
<?php

namespace Core\View;

use Core\Contracts\View\ViewFactoryInterface;
use Core\Contracts\View\ViewInterface;
use Twig_Environment;
use Twig_Loader_Filesystem;

class TwigViewFactory implements ViewFactoryInterface
{
    /**
     * @var Twig_Environment
     */
    private $twigEnv;

    /**
     * TwigView constructor.
     * @param string $viewsFolderPath
     */
    public function __construct(string $viewsFolderPath)
    {
        $loader = new Twig_Loader_Filesystem($viewsFolderPath);
        $this->twigEnv = new Twig_Environment($loader);
    }

    /**
     * Find the specified view.
     * @param string $name
     * @return ViewInterface
     */
    public function view(string $name): ViewInterface
    {
        $name = \preg_replace('/\./', '/', $name);
        $name .= '.twig';

        $template = $this->twigEnv->load($name);

        return new TwigView($template);
    }

    /**
     * Register function for using it in templates.
     */
    public function registerFunction(string $alias, callable $function)
    {
        $this->twigEnv->addFunction(new \Twig_Function($alias, $function));
    }

    /**
     * Register global for using it in templates.
     */
    public function registerGlobal(string $alias, $global)
    {
        $this->twigEnv->addGlobal($alias, $global);
    }
}