text:
interface IItemsScope extends ng.IScope {
	metrics: string[];
	hosts: string[];
	filterMetrics: string;
	filterHosts: string;
	status: string;
}

bosunControllers.controller('ItemsCtrl', ['$scope', '$http', function($scope: IItemsScope, $http: ng.IHttpService) {
	$http.get('/api/metric')
		.success(function(data: string[]) {
			$scope.metrics = data;
		})
		.error(function(error) {
			$scope.status = 'Unable to fetch metrics: ' + error;
		});
	$http.get('/api/tagv/host?since=default')
		.success(function(data: string[]) {
			$scope.hosts = data;
		})
		.error(function(error) {
			$scope.status = 'Unable to fetch hosts: ' + error;
		});
}]);


text:
import {applyMiddleware, createStore} from 'redux'
import {CANCEL} from 'khufu-runtime'
import {fork, take, cancel, race, put} from 'redux-saga/effects'

var sleep = (num) => new Promise((accept) => setTimeout(accept, num))

export function delay(action) {
    return {type: 'delay', action: action}
}

function* guard(generator) {
    let task = yield fork(generator)
    yield take(CANCEL)
    yield cancel(task)
}

export function delay_saga(msec) {
    function* debounce() {
        console.log("VALUE")
        while(true) {
            let action = yield take('delay')
            let deadline = Date.now() + msec
            let diff
            while ((diff = deadline - Date.now()) > 0) {
                let {event} = yield race({
                    event: take('delay'),
                    timeout: sleep(diff),
                })
                if(event) action = event;
            }
            yield put(action.action)
        }
    }
    return {saga: debounce}
}

redpajama_set_name: RedPajamaGithub


text:
//
//  PPOcrResultView.h
//  PhotoPayFramework
//
//  Created by Jura on 01/02/14.
//  Copyright (c) 2014 MicroBlink Ltd. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "PPOverlaySubview.h"

NS_ASSUME_NONNULL_BEGIN

@class PPOcrLayout;

/**
 * Overlay subview presenting status of OCR detection. OCR results are displayed as green characters over detected locations.
 */
PP_CLASS_AVAILABLE_IOS(6.0) @interface PPOcrResultOverlaySubview : PPOverlaySubview

@end

NS_ASSUME_NONNULL_END


text:
Welcome to PCAT's documentation!
================================

When testing hypotheses or inferring their free parameters, a recurring problem is to compare models that contain a number of elements whose multiplicity is itself unknown. Therefore, given some data, it is desirable to be able to compare models with different numbers of parameters. One way of achieving this is to obtain a point estimate (usually the most likely point) in the parameter space of each model and, then, rely on some information criterion to penalize more complex models for excess degrees of freedom. Another way is to sample from the parameter space of each model and compare their Bayesian evidences. Yet another is to take samples from the union of these models using a set of transdimensional jumps across models. This is what the Probabilistic Cataloger (PCAT) is designed for.

PCAT is a hierarchical, transdimensional, Bayesian inference framework. It's theoretical framework is introduced in `Daylan, Portillo & Finkbeiner (2016) <https://arxiv.org/abs/1607.04637>`_, accepted to ApJ. In astrophysical applications, given the output of a photon counting experiment, it can be used to sample from **the catalog space**. In a more general context, it can be used as a mixture sampler to infer the posterior distribution of a metamodel given some Poisson distributed data.

In what follows, we assume that **the metamodel** is the union of models with different dimensionality. All such models have a certain number of common, **fixed-dimensional** parameters. In addition, each model has a different number of **elements**. An element is a collection of parameters that only exist together, and characterize an entity in the model. Examples are:

- A light source such as a star or galaxy, in an astrophysical emission model,
- A light deflecting dark matter subhalo in an gravitational lensing model,
- A term in the polynomial used to perform linear regression,

.. toctree::
   :maxdepth: 4

.. _sectinst:

Installation
-------------
To install PCAT you can use pip

.. code::

    pip install pcat

or download `the latest release <https://github.com/tdaylan/pcat/releases/>`_ and run

.. code::

    python setup.py install

.. _sectinpt:

Features
----------
Compared to mainstream Bayesian inference methods, PCAT has a series of desirable features. It

- samples from the space of catalogs given some observation, unlike conventional cataloging, which estimates the most likely catalog,
- allows marginalization over all relevant nuisance parameters in the problem, including the dimensionality of the nuisance,
- reveals potentially non-Gaussian within and across model covariances,
- constrains element population characteristics via hierarchical priors,
- is a Bayesian framework, because point estimates fail in nearly degenerate likelihood topologies,
- implements Occam's razor (model parsimony) through natural priors on the number of degrees of freedom,
- strictly respects detailed across models,
- does not discard information contained in low-significance :math:`(< 5 \sigma)` fluctuations in the observed dataset,
- reduces to a deterministic cataloger when the labeling degeneracy is explicitly broken,
- simultaneously infers the Point Spread Function (PSF) and the level of diffuse background.

Transdimensionality
+++++++++++++++++++

PCAT takes steps across models by proposing to add elements whose parameters are drawn from the prior, or to kill randomly chosen elements, while respecting detailed balance in the metamodel.

Hierarchical priors
+++++++++++++++++++++

When there are multiple model elements, each with a set of parameters, it is natural to put priors on the **distribution** of these parameters, as opposed to placing individual priors separately on each element parameter. This assumes that a certain type of parameter of all elements, are drawn from a single probability distribution. This is particularly useful when such a parameter is subject to inference, and individual elements can be marginalized over. This results in a hierarchical prior structure, where the prior is placed on the distribution of element parameters, i.e., **hyperparameters**, and the prior on the individual element parameters are made conditional on these hyperparameters.

Labeling degeneracy
++++++++++++++++++++++

Due to **hairlessness** of the elements, the likelihood function is invariant to their permutations in the parameter vector, i.e., exchanging the labels of two elements leaves the likelihood invariant. This fact has consequences for **nonpersistent** elements, which get born or killed at least once during an MCMC run. Because of label changes, the posterior of these parameters look the same, which makes them useless for inferring their properties. In order to constrain such elements, the degeneracy must be broken in postprocessing of the samples. Note that, if the sampling is continued sufficiently long, e.g., for a Hubble time, the posterior of all transdimensional parameters will eventually look similar.

.. Breaking the labeling degeneracy
.. +++++++++++++++++++

Proposal optimization
+++++++++++++++++

Construction of an MCMC chain requires a choice of proposal scale, which must remain constant (or strictly decrease) during sampling in order to respect detailed balance. In transdimensional inference, the choice of proposal scale includes both within and across model jumps. PCAT chooses the proposal scale for a particular sampling problem based on an initial calculation of the Fisher information at the maximum likelihood solution, in the beginning of each run, yielding an estimate of the model covariance. The tighter a parameter is constrained, the smaller the proposal scale for that parameter becomes. This ensures that the acceptance ratio is around 25% and minimizes the autocorrelation time of the resulting chain.

PCAT takes heavy-tailed within-model steps in a space, where the prior is uniformly distributed.

In order to ensure that the chains start from a well mixed state, the first ``numbburn`` samples are discarded and the resulting chain is thinned by  a factor of ``factthin``.

Performance
+++++++++++++++++++

The above features are made possible by enlarging the hypothesis space so as to minimize mismodeling of the observed data. This is, however, at the expense of seriously slowing down inference.

PCAT alleviates the performance issues in two ways:

- Use of parallelism via bypassing Python's Global Interpreter Lock (GIL) by employing independent processes as opposed to threads. The parent process spawns multiple, (almost) noninteracting processes, which collect samples in parallel and report back to the parent process, which aggregates and postprocesses the samples.

- Locality approximation in the likelihood evaluation. The most time consuming part of the inference is the model evaluation, which can be prohibitively slow (for large datasets and many elements) if no approximations are made. PCAT assumes that the contribution of the elements to the model vanishes outside some circle around the element.

Input
--------------
PCAT expects input data in the folder ``pathbase/data/inpt/``. The typical inputs are the data and exposure data cubes, background template(s) (if applicable), element kernel template(s) and the PSF (if applicable).

Supplying data
+++++++++++++++
Input dataset is provided through the ``strgexprflux`` argument. This should be the name of a FITS file (including the ``.fits`` extension), which contains a numpy array of dimension :math:`N_e \times N_{pix} \times N_{psf}`, where :math:`N_e` is the number of energy bins, :math:`N_{pix}` is the number of spatial pixels and :math:`N_{psf}` is the number of PSF classes. The units should be photons per cm :math:`^2` per seconds per GeV.

The exposure map is suppled via the ``strgexpo`` argument. This should be the name of a FITS file (including the ``.fits`` extension). The format should be the same as ``strgexprflux``, whereas units should be cm :math:`^2` s.

Similarly, background templates can be provided via the ``back`` argument. ``back`` should be a list of FITS file names (including the ``.fits`` extension), whose format should be same as that of ``strgexprflux``.

Specifying the model and placing priors
+++++++++++++++++++++++++

The prior structure of the model is set by the relevant arguments to ``pcat.main.init()``. PCAT allows the following fixed dimensional parameters in each member of the metamodel:

- Background prediction

    Given an observed count map, the number of counts in each pixel can be modeled as a Poisson realization of the total counts from a number of elements. In practice, however, this number can be prohibitively large, when there are many more **faint** elements compared to bright ones. Therefore, it is computationally more favorable to represent the overall contribution of faint elements (those that negligibly affect the likelihood) with **background** templates. PCAT allows a list of spatially and spectrally distinct background templates to be in the model simultaneously.

- PSF

    PSF defines a how a delta function in the position space projects onto the observed count maps. When the elements are count sources, PCAT assumes that the projection of all elements to the count maps are characterized by the same PSF. PSF convolution of the model prediction is only applicable for applications, where the observed count map has been collected with an instrument with a finite PSF.

Distributions of element features
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All features of elements are assumed to have been drawn from an underlying probability distribution, and cross-correlations between element features are assumed to be zero. The 1-point function of the element features are controlled by the function arguments to ``pcat.main.init()``. Furthermore, elements are divided into **populations**, where each population admits its own set of hyperparameters. Therefore the input to these arguments should be a ``list`` of strings.

- Spatial distribution (``spatdisttype``)

+ ``'unif'``
Both horizontal positions, :math:`\theta_1`, and vertical positions, :math:`\theta_2`, are uniformly distributed between :math:`-\theta_{max}` and :math:`\theta_{max}`, where :math:`2\theta_{max}` is the side of the square in which model elements can exist.

.. math::

    P(\theta_1) &= \frac{1}{2\theta_{max}} \\
    P(\theta_2) &= \frac{1}{2\theta_{max}}

+ ``'disc'``
Horizontal positions, :math:`\theta_1`, are assumed to be uniformly distributed, whereas the vertical positions, :math:`\theta_2`, are drawn from the exponential distribution.

.. math::

    P(\theta_1) &= \frac{1}{2\theta_{max}} \\
    P(\theta_2) &= \frac{1}{\theta_{2s}} \exp \Bigg( -\frac{\theta_2}{\theta_{2s}}\Bigg)

The scale of the exponential distribution, :math:`\theta_{2s}`, is a hyperparameter subject to inference and set by ``bgaldistscal``.

+ ``'gang'``
Radial positions, :math:`\theta_r`, are assumed to follow an exponential distribution with an angular scale, :math:`\theta_{rs}`, controlled by ``gangdistscal``. The azimuthal positions, :math:`\phi`, are uniformly distributed.

.. math::

    P(\phi) &= \frac{1}{2\pi} \\
    P(\theta_r) &= \frac{1}{\theta_{rs}} \exp \Bigg( -\frac{\theta_r}{\theta_{rs}}\Bigg)

+ ``'gaus'``
The prior spatial distribution is the sum of a certain number of Gaussians and a spatially constant floor.

.. math::

    P(\theta_1, \theta_2) \propto \alpha_c + c \sum_k \exp \Bigg(-\frac{1}{2}\frac{(\theta_1 - \theta_k)^2}{\sigma_c^2}\Bigg) \exp \Bigg(-\frac{1}{2}\frac{(\theta_2 - \theta_k)^2}{\sigma_c^2}\Bigg)

:math:`c` is a normalizing constant that brings the maximum of the second term to unity. The amplitude of the floor, :math:`\alpha_c`, is set by the hyperparameter ``spatdistcons``. It roughly parametrizes the degree of belief in the provided catalog. This spatial model is useful is there is a strong prior belief that elements exist at certain locations. An example is searching for elements at the positions of a earlier (deterministic) catalog.

- Flux distribution (``fluxdisttype``)

+ ``'powr'``
Power law between ``minmflux`` and ``maxmflux`` with the slope ``fluxdistslop``.

- Spectral index distribution

Spectral index distribution of elements can be set with the argument ``sinddisttype``.

+ ``'atan'``
Spectral indices :math:`s_a` are distributed such that :math:`\arctan(s_a)` follow the uniform distribution between :math:`\arctan(s_{min})` and :math:`\arctan(s_{max})`. :math:`s_{min}` and :math:`s_{max}` can be set by ``minmsind`` and ``maxmflux``, respectively.

+ ``'gaus'``
Spectral indices :math:`s_a` follow a Gaussian distribution with mean :math:`\lambda_s` and variance :math:`\sigma_s^2`.

Generating mock data
+++++++++++++++++++++
PCAT ships with a mock (simulated) data generator. Mock data is randomly drawn from a generative metamodel, not to be confused with the metamodel subject to inference, (hereafter, **the fitting metamodel**). Once the user configures the prior probability density of the fitting metamodel, PCAT samples from this metamodel given the simulated dataset. Some of the generative metamodel parameters can be fixed, i.e., assigned delta function priors. These are

- the number of mock elements, ``truenumbpnts``,
- hyperparameters controlling the population characteristics of these elements.

All other generative metamodel parameters are fair draws from the hierarchical prior.

When working on variations of a certain problem or different analyses on the same dataset, it is useful to have default priors. PCAT allows unique defaults for different built-in experiments, controlled by the argument ``exprtype``. Currently the built-in experimental types are

- ``ferm``: Fermi-LAT (Default)
- ``chan``: Chandra
- ``hubb``: Hubble Space Telescope
- ``sdss``: SDSS
- ``gaia``: Gaia

By setting ``exprtype`` the user imposes the default prior structure for the chosen experimental type. However, it is also desirable to be able to change the prior of a specific parameter. This is accomplished by setting the :ref:`relevant argument(s) <sectoutp>`.

.. note::

    PCAT has a built-in fudicial (default) generative metamodel for each experiment type. The user can change parts of this model by providing arguments with the parameter names with a preceeding string ``'true'`` (indicating the fudicial model). The model subject to inference defaults to the resulting fudicial model. The user can also change parts of the fitting metamodel by setting arguments with the relevant parameter names (this time, without ``'true'``, indicating the fitting metamodel). In other words, if the user does not specify any parameters, the fudicial model will be used to generate data, and the same model will be fitted to the data. In most cases, however, one is be interested in studying mismodeling, i.e., when the mock data is generated from a model different from that used to fit the data. This can be achieved by forcing the prior structure of the fitting metamodel to be different from the generator model.

Selecting the initial state
+++++++++++++++++++++++++++++
The initial state of the chain is drawn randomly from the prior.

.. _sectoutp:

Output
-------------
A function call to ``pcat.main.init()`` returns the collected samples as well as postprocessed variables in an object that we will refer to as ``gdat``. Any output (as well as many internal variables of the sampler) can be accessed via the attributes of this global object.

Furthermore, PCAT offers extensive routines to visualize the output chain. The output plots are placed in the relevant subfolders ``pathbase/data/outp/rtag`` and ``pathbase/imag/rtag``, respectively, where ``rtag`` is the run tag. The ``pathbase`` folder is created if it does not already exist. It defaults to the value of the environment variable ``$PCAT_DATA_PATH``. Therefore ``pathbase`` can be omitted by setting the environment variable ``$PCAT_DATA_PATH``.

.. _sectplot:

Plots
+++++
If not explicitly disabled by the user, PCAT produces plots in every stage of a run. Some plots are produced in the initial setup, frame plots are generated at predetermined times during the sampling and others are made in the postprocessing after all chains have run. The plot path, ``pathbase/imag/rtag``, has the following structure:

- ``init`` Problem setup
- ``prio`` Plots regarding the sampling of the prior
- ``post`` Plots regarding the sampling of the posterior
- ``info`` Information gain

.. _note:

    Note that running the sampler on the prior probability distribution is optional and serves two purposes:

    - diagnostic check that the imposed prior makes sense
    - to calculate the KL divergence on all metamodel parameters and derived quantities

In turn, each of ``prio`` and ``post`` contain the following folders:

- ``opti`` Proposal scale optimization
- ``fram`` Frame plots, giving snapshots of the MCMC state
- ``finl`` Posterior distribution of model parameters and derived quantities
- ``anim`` GIF animations made from the frame plots in ``fram`` that are produced during sampling.

- ``diag`` Diagnostic plots

.. _sectchan:

Chain
+++++
``pcat.main.init()`` returns a pointer to the object that contains the output chain. It also writes the output chain to ``$PCAT_DATA_PATH/outp/rtag/pcat.h5``, which is an HDF5 file. Each dataset (or object attribute as in the former case) is an ``ndarray`` of samples, either of the parameters or of quantities derived from the parameters, as well as diagnostic and utility variables.

In overall, the output folder contains the following files:

- ``args.txt``

The list of arguments to ``pcat.main.init()``.

- ``pcat.h5``

HDF5 file containing samples from the hypothesis space, with the following fields:

=================  ==========================================================================
Field              Explanation
=================  ==========================================================================
``sampvarb``       Parameter vector

``samp``           Scaled parameter vector (uniformly distributed with respect to the prior)

``deltllikpopl``   Delta loglikelihood of the :math:`l^{th}` population

``lgalpopl``       Horizontal coordinates of the :math:`l^{th}` population

``bgalpopl``       Vertical coordinates of the :math:`l^{th}` population

``fluxpopl``       Flux of the :math:`l^{th}` population

``sindpopl``       Spectral index of the :math:`l^{th}` population

``curvpopl``       Spectral curvature of the :math:`l^{th}` population

``expopopl``       Spectral cutoff energy of the :math:`l^{th}` population

In order to reduce inter-process communication, PCAT writes its internal state to the disc before child processes are spawned and after individual workers have finished their tasks. These intermediate files, in the form of python pickle objects, are temporarily written to the output folder, but deleted before the run ends.

Diagnostics
------------

Autocorrelation
+++++++++++++++++++++++++++++

A chain of states needs to be Markovian (memoryless) in order to be interpreted as fair draws from a target probability density. The autocorrelation of the chain shows whether the chain is self-similar along the simulation time (either due to low acceptance rate or small step size). Therefore the autocorrelation plots should be monitored after each run.

In a transdimensional setting, the autocorrelation of a parameter is ill-defined, since parameters can be born, killed or change identity. Therefore, for such parameters, we calculate the autocorrelation of the model count map.

The acceptance rate of the birth and death moves shows whether the prior on the element parameters are appropriate. If the acceptance rate of birth and deaths proposals is too low, this indicates that an element randomly drawn from the prior is very unlikely to fit the data. In contrast, if it is too high, it means that most of the prior volume is insensitive to the data. Therefore the prior should be adjusted such that the birth and death acceptance rate is between :math:`\sim 5%% - \sim30%%`. This allows efficient jumps and minimizes autocorrelation across models.

Gelman-Rubin test
+++++++++++++++++++++++++++++
PCAT nominally runs multiple, noninteracting chains, whose samples are aggregated at the end. In order to ensure convergence, therefore, one can compare within-chain variance with across-chain variance. This is known as the Gelman-Rubin test. PCAT outputs the GR test statistics in ``gdat.gmrb`` and plots the relevant diagnostics in ``$PCAT_DATA_PATH/imag/rtag/diag/``.

.. note:: Make sure to run PCAT with the argument ``diagmode=False`` for reasonable time performance. ``diagmode=True`` option puts the sampler in a conservative diagnostic mode and performs extensive checks on the state of critical data structures to ensure that the model and proposals are self consistent, largely slowing down execution.

Tutorial
--------------
In this tutorial, we will illustrate how to run PCAT during a typical science analysis. Assuming that you have :ref:`installed <sectinst>` PCAT, let us run it on mock data.

All user interaction with PCAT can be performed through the ``pcat.main.init()`` function. Because arguments to this function have hierarchically defined defaults, even the default call (without arguments) starts a valid PCAT run. The default call generates mock Fermi-LAT data with an isotropic background and point source distribution and takes samples from the catalog space of the generated data. Therefore it assumes that you have the necessary Instrument Response Function (IRF) file as well as exposure, data and background flux files in ``pathbase/data/inpt/``.

.. In case you don't, here is a script that should get you the necessary files.

The default run collects a single chain of 100000 samples, discards the initial 20% of the samples and thins the remaining samples to obtain a chain of 1000 samples. The number of processes, total number of samples per process, the number of samples to be discarded and the factor by which to thin the chain can be set using the arguments ``numbproc``, ``numbswep``, ``numbburn`` and ``factthin``, respectively. After initialization, PCAT collects samples, produces frame plots (snapshots of the sampler state during the execution) and postprocesses the samples at the end. The run should finish in under half an hour with the message

.. code-block:: none

    >> The ensemble of catalogs is at $PCAT_DATA_PATH/data/outp/rtag/

While the sampler is running, you can check ``$PCAT_DATA_PATH/imag/rtag/`` to inspect :ref:`the output plots <sectplot>`.

Although PCAT visualizes the ensemble of catalogs in various projections to the data and model spaces, the user can also work directly on :ref:`the output chain <sectchan>`.

API
---------

All user interaction with PCAT is accomplished through the ``pcat.main.init()`` function. Below is a list of its function arguments.

.. function:: pcat.main.init(...)

    Given an observed dataset, sample from the hypothesis space.

    **Sampler settings**

    :param numbswep: Number of samples to be taken by each process

    :type numbswep: int

    :param numbburn: Number of samples to be discarded from the beginning of each chain

    :type numbburn: int

    :param factthin: Factor by which to thin each chain. Only one sample out of ``factthin`` samples is saved.

    :type factthin: int

    :param numbproc: Number of processes. The total number of samples before thinning and burn-in, will be ``numbproc`` times ``numbswep``.

    :type numbproc: int

    **Input**

    :param indxenerincl: Indices of energy bins to be taken into account. It is only effective if data is provided by the user, i.e., for non-simulation runs, where it defaults to all available energy bins. Other energy bins are discarded.

    :type indxenerincl: ndarray int

    :param indxevttincl: Indices of PSF class bins to be taken into account. Works similar to ``indxenerincl``.

    :type indxevttincl: ndarray int

    **Output**

    :param verbtype: Verbosity level

        - ``0`` No standard output
        - ``1`` Minimal standard output including status of progress (Default)
        - ``2`` Diagnostic verbose standard output

    :type verbtype: int

    :param pathbase: Data path of PCAT. See :ref:`sectoutp`.

    :type pathbase: str

    **Associations with the reference catalog**

    :param anglassc: Radius of the circle within which sample catalog elements can be associated with the elements in the reference catalog.

    :type anglassc: float

    :param margfactcomp: The ratio of the side of the square in which the sample elements are associated with the reference catalog, to the size of the image.

    :type margfactcomp: float

    :param nameexpr: A string that describes the provided reference catalog to be shown in the plot legends.

    :type nameexpr: str

    :param cntrpnts: Force the mock data to a single PS at the center of the image. Defaults to ``False``.

    :type cntrpnts: bool

    **General**

    :param elemtype: Functional type of elements.

        - ``'lght'`` Elements are light sources
        - ``'lens'`` Elements are lenses.

    :type elemtype: str

    :param evalcirc: Flag to evaluate the likelihood only inside a circle of a certain radius around elements.

    :type evalcirc: str

    **Initial state**

    :param randinit: Force the initial state to be randomly drawn from the prior. Default behavior for mock data is to initialize the chain with the true state.

    :type randinit: bool

    **Adaptivity**

    :param optiprop: Optimize the scale of each proposal by acceptance rate feedback. All samples during the tuning are discarded.

    :type optiprop: bool

    **Post processing**

    :param strgexprflux: Name of the FITS file (without the extension) in ``pathdata`` containing the observed data as an ``ndarray``.

    :type strgexprflux: str

    :param strgcatl: A descriptive name for the provided reference catalog to be shown in the plot legends.

    :type strgcatl: str

    :param strgback: A list of FITS file names (without the extension) in ``pathdata`` each containing a spatial template for the background prediction as an ``ndarray``. See ``strgexprflux`` for the content of the file and its unit. One element of the list can be a float, indicating an isotropic template with the provided amplitude.

    :type strgback: list of str or int

    :param lablback: a list of axis labels for the spatial background templates to be shown in plots.

    :type lablback: list of str

    :param strgexpo: Name of the FITS file (without the extension) in ``pathdata`` containing the exposure map. See ``strgexprflux`` for the format of the numpy array. ``strgexpo`` can also be a float, in which case the exposure map will be assumed to be uniform across along all data dimensions.

    :type strgexpo: str or float

    :param liketype: Type of the likelihood.

        - ``'pois'`` Poisson probability of getting the observed number of counts given the model prediction (default).
        - ``'gaus'`` Gaussian approximation of the above. This may accelerate the execution in cases, where the bottle neck of the sampler time budget is likelihood evaluation.

    :type liketype: strg

    :param exprtype: Name of the experiment used to collect the observed data. ``exprtype`` can be used to set other options to their default values for the particular experiment.
        - ``'ferm'`` Fermi-LAT
        - ``'chan'`` Chandra
        - ``'hubb'`` HST
        - ``'sdss'`` SDSS

    :type exprtype: str

    :param lgalcntr: Galactic longitude of the image center. ``lgalcntr`` and ``bgalcntr`` are used to rotate the observed data, exposure and background maps as well as the provided reference catalog to the center of the ROI. They are only effective when pixelization is HealPix, i.e, ``pixltype='heal'``.

    :type lgalcntr: float

    :param bgalcntr: Galactic latitude of the image center. See ``lgalcntr``.

    :type bgalcntr: float

    :param maxmangl: Maximum angular separation at which PSF can be interpolated. It defaults to three times the diagonal legth of the image, enough to evaluate the PSF across the whole image.

    :type maxmangl: float

    :param pixltype: Type of the pixelization.

        - ``heal`` HealPix
        - ``chan`` Cartesian

    **Plotting**

    :param makeplot: Make output plots, which is the default behavior. If ``False``, no output plots are produced.

    :type makeplot: bool

    :param numbswepplot: Number of samples (before thinning and burn-in) for which one set of frame plots will be produced. Frame plots reveal individual samples in detail and are later used for producing animations.

    :type numbswepplot: int

    :param scalmaps: A string that sets the stretch of the count maps

        - ``'asnh'`` Arcsinh (default)
        - ``'self'`` Linear
        - ``'logt'`` Log 10

    :type scalmaps: str

    :param satumaps: Saturate the count maps

    :type satumaps: bool

    :param exprinfo: Overplot the provided reference catalog on the output plots.

    :type exprinfo: bool

    :param makeanim: Make animations of the frame plots. Defaults to ``True``.

    :type makeanim: bool

    :param anotcatl: Anotate the catalog members on the plots, if an annotation text is provided along with the reference catalog. (Default: ``False``)

    :type anotcatl: bool

    :param strgbinsener: A string holding the label for the energy axis.

    :type strgbinsener: str

    :param asscmetrtype: Type of metric used to associate the sample catalogs with the reference catalog

    :type asscmetrtype: str

    :param strgexprname: A string describing the experiment used to collect the observed data.

    :type strgexprname: str

    :param strganglunit: Label for the spatial axes.

    :type strganglunit: str

    :param labllgal: Label for the horizontal axis

    :type labllgal: str

    :param lablbgal: Label for the vertical axis

    :type lablbgal: str

    **Diagnostics**

    :param emptsamp: Perform a futile run without collecting any samples, but creating all data structures and producing all visualizations as if in a normal run. Defaults to ``False``.

    :type emptsamp: bool

    :param diagmode: Start the run in diagnostic mode. Defaults to ``False``.

    :type diagmode: bool

    **Model**

    :param spatdisttype: Type of spatial distribution of elements for each population

    :type spatdisttype: list of str

    :param fluxdisttype: Type of flux distribution of elements for each population

    :type fluxdisttype: list of str

    :param spectype: Type of energy spectrum of elements for each population

    :type spectype: list of str

    :param psfntype: Type of PSF radial profile

    :type psfntype: str

    :param oaxitype: Type of PSF off-axis profile

    :type oaxitype: str

..
    :param maxmgangdata: Half size of the image in radians

    :type maxmgangdata: float

.. ## PSF
         specfraceval=0.1, \
         numbangl=1000, \
         binsangltype='logt', \
         numbsidepntsprob=400, \
         strgfluxunit=None, \
         strgflux=None, \
         strgenerunit=None, \
         indxenerfull=None, \
         indxevttfull=None, \
         binsenerfull=None, \
         maxmnumbpnts=array([1000]), \
         psfninfoprio=True, \
         ## spectral
         # prior
         priotype='logt', \
         priofactdoff=0., \
         margfactmodl=0.9, \
         bindprio=False, \

         meanpnts=None, \
         maxmgang=None, \
         gangdistscal=None, \
         bgaldistscal=None, \
         curvdistmean=None, \
         curvdiststdv=None, \
         flux=None, \
         fluxdistslop=None, \
         fluxbrek=None, \
         fluxdistbrek=None, \
         fluxdistsloplowr=None, \
         fluxdistslopuppr=None, \
         sinddistmean=None, \
         sinddiststdv=None, \

         minmsigm=None, \
         meansigm=None, \
         stdvsigm=None, \
         minmgamm=None, \
         meangamm=None, \
         stdvgamm=None, \
         minmpsff=None, \
         meanpsff=None, \
         stdvpsff=None, \

         bacp=None, \
         fluxsour=None, \
         fluxsour=None, \
         sizesour=None, \
         sizesour=None, \
         ratisour=None, \
         ratisour=None, \
         ellphost=None, \
         ellphost=None, \
         sherhost=None, \
         sherhost=None, \
         beinhost=None, \
         beinhost=None, \

         stdvprophypr=0.1, \
         stdvproppsfp=0.01, \
         stdvpropbacp=0.01, \
         stdvproplenp=0.01, \
         stdvlbhl=0.1, \
         stdvlbhlvari=True, \
         stdvflux=0.15, \
         stdvspep=0.15, \
         stdvspmrsind=0.2, \

         probrand=0.05, \
         probtran=None, \
         probbrde=1., \

         propfluxdist=True, \
         propfluxdistbrek=True, \
         prophypr=True, \
         proppsfp=True, \
         propbacp=True, \
         proplenp=True, \
         propcomp=True, \

         radispmr=None, \
         numbsidecart=200, \
         numbsideheal=256, \
         numbdatasamp=100, \

    **Unfunctional**

    :param numbspatdims: Number of spatial dimensions. Currently not functional.

    :type numbspatdims: None

.. note::

    The generative metamodel parameters can be set by preceeding the parameter name with ``true``. For example, in order to set the mock number of elements, you can specify ``truenumbpnts=array([10])``.

Garbage collection
-------------------

PCAT produces two folders for the output of each run, one for plots and the other to contain the chain saved to the disc. Given that many test and intermediate runs may be needed before each science run, the number of folders (and files therein) may increase quickly. In order to avoid this, the script ``gcol.py`` is provided to the user as a convenience. When executed, it erases the output from all runs that

- have not run to completion, i.e., does not have the animations, which are produced at the very end, or
- has collected less than 100000 samples per chain.


text:
import functools

KEY = '_rons_generator'

def save_generator(fun):
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        assert not hasattr(self, KEY), "Tornado runs one handler per instance, right?"
        gen = fun(self, *args, **kwargs)
        setattr(self, KEY, gen)
        return gen
    return wrapper

def stop_generator(self):
    if hasattr(self, KEY):
        getattr(self, KEY).close()


text:
namespace Envoy {
namespace {

const std::string RBAC_CONFIG = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.config.filter.http.rbac.v2.RBAC
  rules:
    policies:
      foo:
        permissions:
          - header: { name: ":method", exact_match: "GET" }
        principals:
          - any: true
)EOF";

const std::string RBAC_CONFIG_WITH_DENY_ACTION = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.config.filter.http.rbac.v2.RBAC
  rules:
    action: DENY
    policies:
      "deny policy":
        permissions:
          - header: { name: ":method", exact_match: "GET" }
        principals:
          - any: true
)EOF";

const std::string RBAC_CONFIG_WITH_PREFIX_MATCH = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.config.filter.http.rbac.v2.RBAC
  rules:
    policies:
      foo:
        permissions:
          - header: { name: ":path", prefix_match: "/foo" }
        principals:
          - any: true
)EOF";

const std::string RBAC_CONFIG_WITH_PATH_EXACT_MATCH = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.config.filter.http.rbac.v2.RBAC
  rules:
    policies:
      foo:
        permissions:
          - url_path:
              path: { exact: "/allow" }
        principals:
          - any: true
)EOF";

const std::string RBAC_CONFIG_WITH_PATH_IGNORE_CASE_MATCH = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.config.filter.http.rbac.v2.RBAC
  rules:
    policies:
      foo:
        permissions:
          - url_path:
              path: { exact: "/ignore_case", ignore_case: true }
        principals:
          - any: true
)EOF";

const std::string RBAC_CONFIG_WITH_LOG_ACTION = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC
  rules:
    action: LOG
    policies:
      foo:
        permissions:
          - header: { name: ":method", exact_match: "GET" }
        principals:
          - any: true
)EOF";

const std::string RBAC_CONFIG_HEADER_MATCH_CONDITION = R"EOF(
name: rbac
typed_config:
  "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC
  rules:
    policies:
      foo:
        permissions:
          - any: true
        principals:
          - any: true
        condition:
          call_expr:
            function: _==_
            args:
            - select_expr:
                operand:
                  select_expr:
                    operand:
                      ident_expr:
                        name: request
                    field: headers
                field: xxx
            - const_expr:
               string_value: {}
)EOF";

using RBACIntegrationTest = HttpProtocolIntegrationTest;

INSTANTIATE_TEST_SUITE_P(Protocols, RBACIntegrationTest,
                         testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()),
                         HttpProtocolIntegrationTest::protocolTestParamsToString);

TEST_P(RBACIntegrationTest, Allowed) {
  useAccessLog("%RESPONSE_CODE_DETAILS%");
  config_helper_.addFilter(RBAC_CONFIG);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "GET"},
          {":path", "/"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);
  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
  EXPECT_THAT(waitForAccessLog(access_log_name_), testing::HasSubstr("via_upstream"));
}

TEST_P(RBACIntegrationTest, Denied) {
  useAccessLog("%RESPONSE_CODE_DETAILS%");
  config_helper_.addFilter(RBAC_CONFIG);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);
  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("403", response->headers().getStatusValue());
  EXPECT_THAT(waitForAccessLog(access_log_name_),
              testing::HasSubstr("rbac_access_denied_matched_policy[none]"));
}

TEST_P(RBACIntegrationTest, DeniedWithDenyAction) {
  useAccessLog("%RESPONSE_CODE_DETAILS%");
  config_helper_.addFilter(RBAC_CONFIG_WITH_DENY_ACTION);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "GET"},
          {":path", "/"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);
  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("403", response->headers().getStatusValue());
  // Note the whitespace in the policy id is replaced by '_'.
  EXPECT_THAT(waitForAccessLog(access_log_name_),
              testing::HasSubstr("rbac_access_denied_matched_policy[deny_policy]"));
}

TEST_P(RBACIntegrationTest, DeniedWithPrefixRule) {
  config_helper_.addConfigModifier(
      [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
             cfg) { cfg.mutable_normalize_path()->set_value(false); });
  config_helper_.addFilter(RBAC_CONFIG_WITH_PREFIX_MATCH);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/foo/../bar"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);
  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

TEST_P(RBACIntegrationTest, RbacPrefixRuleUseNormalizePath) {
  config_helper_.addConfigModifier(
      [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
             cfg) { cfg.mutable_normalize_path()->set_value(true); });
  config_helper_.addFilter(RBAC_CONFIG_WITH_PREFIX_MATCH);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/foo/../bar"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("403", response->headers().getStatusValue());
}

TEST_P(RBACIntegrationTest, DeniedHeadReply) {
  config_helper_.addFilter(RBAC_CONFIG);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "HEAD"},
          {":path", "/"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);
  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("403", response->headers().getStatusValue());
  ASSERT_TRUE(response->headers().ContentLength());
  EXPECT_NE("0", response->headers().getContentLengthValue());
  EXPECT_THAT(response->body(), ::testing::IsEmpty());
}

TEST_P(RBACIntegrationTest, RouteOverride) {
  config_helper_.addConfigModifier(
      [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
             cfg) {
        envoy::extensions::filters::http::rbac::v3::RBACPerRoute per_route_config;
        TestUtility::loadFromJson("{}", per_route_config);

        auto* config = cfg.mutable_route_config()
                           ->mutable_virtual_hosts()
                           ->Mutable(0)
                           ->mutable_typed_per_filter_config();

        (*config)[Extensions::HttpFilters::HttpFilterNames::get().Rbac].PackFrom(per_route_config);
      });
  config_helper_.addFilter(RBAC_CONFIG);

  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);

  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

TEST_P(RBACIntegrationTest, PathWithQueryAndFragment) {
  config_helper_.addFilter(RBAC_CONFIG_WITH_PATH_EXACT_MATCH);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  const std::vector<std::string> paths{"/allow", "/allow?p1=v1&p2=v2", "/allow?p1=v1#seg"};

  for (const auto& path : paths) {
    auto response = codec_client_->makeRequestWithBody(
        Http::TestRequestHeaderMapImpl{
            {":method", "POST"},
            {":path", path},
            {":scheme", "http"},
            {":authority", "host"},
            {"x-forwarded-for", "10.0.0.1"},
        },
        1024);
    waitForNextUpstreamRequest();
    upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

    response->waitForEndStream();
    ASSERT_TRUE(response->complete());
    EXPECT_EQ("200", response->headers().getStatusValue());
  }
}

TEST_P(RBACIntegrationTest, PathIgnoreCase) {
  config_helper_.addFilter(RBAC_CONFIG_WITH_PATH_IGNORE_CASE_MATCH);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  const std::vector<std::string> paths{"/ignore_case", "/IGNORE_CASE", "/ignore_CASE"};

  for (const auto& path : paths) {
    auto response = codec_client_->makeRequestWithBody(
        Http::TestRequestHeaderMapImpl{
            {":method", "POST"},
            {":path", path},
            {":scheme", "http"},
            {":authority", "host"},
            {"x-forwarded-for", "10.0.0.1"},
        },
        1024);
    waitForNextUpstreamRequest();
    upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

    response->waitForEndStream();
    ASSERT_TRUE(response->complete());
    EXPECT_EQ("200", response->headers().getStatusValue());
  }
}

TEST_P(RBACIntegrationTest, LogConnectionAllow) {
  config_helper_.addFilter(RBAC_CONFIG_WITH_LOG_ACTION);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/"},
          {":scheme", "http"},
          {":authority", "host"},
          {"x-forwarded-for", "10.0.0.1"},
      },
      1024);
  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

// Basic CEL match on a header value.
TEST_P(RBACIntegrationTest, HeaderMatchCondition) {
  config_helper_.addFilter(fmt::format(RBAC_CONFIG_HEADER_MATCH_CONDITION, "yyy"));
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/path"},
          {":scheme", "http"},
          {":authority", "host"},
          {"xxx", "yyy"},
      },
      1024);
  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

// CEL match on a header value in which the header is a duplicate. Verifies we handle string
// copying correctly inside the CEL expression.
TEST_P(RBACIntegrationTest, HeaderMatchConditionDuplicateHeaderNoMatch) {
  config_helper_.addFilter(fmt::format(RBAC_CONFIG_HEADER_MATCH_CONDITION, "yyy"));
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/path"},
          {":scheme", "http"},
          {":authority", "host"},
          {"xxx", "yyy"},
          {"xxx", "zzz"},
      },
      1024);
  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("403", response->headers().getStatusValue());
}

// CEL match on a header value in which the header is a duplicate. Verifies we handle string
// copying correctly inside the CEL expression.
TEST_P(RBACIntegrationTest, HeaderMatchConditionDuplicateHeaderMatch) {
  config_helper_.addFilter(fmt::format(RBAC_CONFIG_HEADER_MATCH_CONDITION, "yyy,zzz"));
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{
          {":method", "POST"},
          {":path", "/path"},
          {":scheme", "http"},
          {":authority", "host"},
          {"xxx", "yyy"},
          {"xxx", "zzz"},
      },
      1024);
  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  response->waitForEndStream();
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

} // namespace
} // namespace Envoy


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>WinPcap: wpcap_tut8.txt File Reference</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Data Structures

Files

Related Pages

File List

Globals

wpcap_tut8.txt File Reference

documentation. Copyright (c) 2002-2005 Politecnico di Torino. Copyright (c) 2005-2007
CACE Technologies. All rights reserved.


text:
Planmill rest api client for api version 1.0

````php
<?php
$api = new codaone\Planmill\Api(
    "https://online.planmill.com/[yourcompany]/",
    new codaone\Planmill\Api\Authentication\Basic("userid", "apikey")
);

$projects = $api->getProjects();
$tasks = $api->getTasks($projects[0]->getId());
````

# License

MIT License

# Planmill Rest API Documentation

http://wiki.planmill.com/display/HELPEN/PlanMill+REST+API


text:
angular.module("mdl")
.directive("mdlFabDisabled",function FabDisabledDirective(){
	var stl=angular.element('<style id="mdlFabDisabled">\n\
		</style>\n\
	');

	function applyStyle(_style){
		var style=document.querySelectorAll("style#"+_style.id);
		if(style.length==0){
			try{
				document.body.appendChild(_style);
			}catch(err){
				setTimeout(function(){applyStyle(_style)},1000);
			}
		}
	}
	applyStyle(stl[0]);

	return {
			priority: 1,
			restrict: 'E',
			transclude: {
			},
			template:'\
<!-- Disabled FAB button -->\
<button class="mdl-button mdl-js-button mdl-button--fab" disabled>\
  <i class="material-icons">add</i>\
</button>\
\
',
			compile:function(tElm,tAttrs,transclude){
			  	console.debug("FabDisabled-compile",tElm.html())
				return {
				  pre:function(scope, elm, attrs,ctrl,transcludeFn){
				  	console.debug("FabDisabled-pre",elm.html(),(transcludeFn(scope)));
				  },
				  post:function(scope, elm, attrs,ctrl,transcludeFn){
				  	console.debug("FabDisabled-post",elm.html(),(transcludeFn(scope)));

			  }
			}
		}
	}
})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RSSE
{
    public class SubsystemsManager
    {
        public List<Subsystem> subsystems;

        public SubsystemsManager()
        {
            subsystems = new List<Subsystem>();
        }

        public SubsystemsManager(List<Subsystem> subsystemList)
        {
            subsystems = subsystemList;
        }
    }
}


text:
namespace ghostshockey.it.app.Droid
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.Content.Res;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;

    using AdMaiora.AppKit.UI;

    #pragma warning disable CS4014
    [Activity(
        Label = "Ghosts",
        MainLauncher = true,
        Theme = "@style/AppTheme.Splash",
        ScreenOrientation = ScreenOrientation.Portrait,
        NoHistory = true,
        ConfigurationChanges =
            ConfigChanges.Orientation | ConfigChanges.ScreenSize |
            ConfigChanges.KeyboardHidden | ConfigChanges.Keyboard
    )]
    public class SplashActivity : AdMaiora.AppKit.UI.App.AppCompactActivity
    {
        #region Inner Classes
        #endregion

        #region Constants and Fields

        // This flag check if we are already calling the login REST service
        private bool _isLogginUser;
        // This cancellation token is used to cancel the rest login request
        private CancellationTokenSource _cts;

        #endregion

        #region Widgets

        [Widget]
        private ImageView LogoImage;

        [Widget]
        private TextView TitleLabel;

        [Widget]
        private TextView VersionLabel;

        #endregion

        #region Constructors and Destructors

        public SplashActivity()
        {
        }

        #endregion

        #region Properties
        #endregion

        #region Activity Methods

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            #region Desinger Stuff

            SetContentView(Resource.Layout.ActivitySplash);

            #endregion

            string osVersion = null;
            string appVersion = "1.0.0";
            string appBuild = "1";
            AppController.Utility.GetContextInfo(out osVersion, out appVersion, out appBuild);
            this.VersionLabel.Text = string.Format("v{0} ({1})", appVersion, appBuild);

            DateTime beginTime = DateTime.Now;
            AppController.Utility.ExecuteOnAsyncTask(CancellationToken.None,
                () =>
                {
                    // Do background stuff here...

                    // Check if we must wait at least splash screen timeout
                    TimeSpan loadSpan = DateTime.Now - beginTime;
                    Thread.Sleep(Math.Max(0, AppController.Globals.SplashScreenTimeout - (int)loadSpan.TotalMilliseconds));
                },
                () =>
                {

                    //if (!RestoreUser())
                        MakeRoot(typeof(MainActivity));
                });
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();

            if (_cts != null)
                _cts.Cancel();
        }

        #endregion

        #region Public Methods
        #endregion

        #region Methods

        private bool RestoreUser()
        {
            //if (!AppController.IsUserRestorable)
            //    return false;

            //if (_isLogginUser)
            //    return true;

            //_isLogginUser = true;

            //// Create a new cancellation token for this request
            //_cts = new CancellationTokenSource();
            //AppController.RestoreUser(_cts, AppController.Settings.AuthAccessToken,
            //    // Service call success
            //    (data) =>
            //    {
            //        Bundle b = new Bundle();
            //        b.PutBoolean("UserRestored", true);
            //        b.PutInt("UserId", data.UserId);
            //        MakeRoot(typeof(MainActivity), b);
            //    },
            //    // Service call error
            //    (error) =>
            //    {
            //        Toast.MakeText(this.Application, error, ToastLength.Long).Show();

                    MakeRoot(typeof(MainActivity));
            //    },
            //    // Service call finished
            //    () =>
            //    {
            //        _isLogginUser = false;
            //    });

            return true;
        }

        #endregion

        #region Event Handlers
        #endregion
    }
}


text:
package com.palantir.atlasdb.schema.indexing;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.hash.Hashing;
import com.palantir.atlasdb.AtlasDbTestCase;
import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.atlasdb.schema.indexing.generated.DataTable;
import com.palantir.atlasdb.schema.indexing.generated.DataTable.Index1IdxTable.Index1IdxRow;
import com.palantir.atlasdb.schema.indexing.generated.IndexTestTableFactory;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable.Bar;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable.Foo;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable.FooToIdIdxTable;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable.FooToIdIdxTable.FooToIdIdxRowResult;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable.TwoColumnsNamedColumnValue;
import com.palantir.atlasdb.schema.indexing.generated.TwoColumnsTable.TwoColumnsRow;
import com.palantir.atlasdb.table.description.Schemas;
import com.palantir.atlasdb.table.description.ValueType;
import com.palantir.atlasdb.transaction.api.RuntimeTransactionTask;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;

public class IndexTest extends AtlasDbTestCase {

    @Before
    public void createSchema() {
        Schemas.truncateTablesAndIndexes(IndexTestSchema.getSchema(), keyValueService);
        Schemas.createTablesAndIndexes(IndexTestSchema.getSchema(), keyValueService);
    }

    @Test
    public void testAddDelete() {
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable table = getTableFactory().getDataTable(txn);
            table.putValue(DataTable.DataRow.of(1L), 2L);
            table.putValue(DataTable.DataRow.of(3L), 2L);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable.Index1IdxTable index1 =
                    DataTable.Index1IdxTable.of(getTableFactory().getDataTable(txn));
            DataTable.Index2IdxTable index2 =
                    DataTable.Index2IdxTable.of(getTableFactory().getDataTable(txn));
            DataTable.Index3IdxTable index3 =
                    DataTable.Index3IdxTable.of(getTableFactory().getDataTable(txn));
            assertThat(index1.getRange(RangeRequest.builder().build()).count()).isEqualTo(1L);
            assertThat(index2.getRange(RangeRequest.builder().build()).count()).isEqualTo(2L);
            assertThat(index3.getRange(RangeRequest.builder().build()).count()).isEqualTo(1L);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable table = getTableFactory().getDataTable(txn);
            table.delete(DataTable.DataRow.of(1L));
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable.Index1IdxTable index1 =
                    DataTable.Index1IdxTable.of(getTableFactory().getDataTable(txn));
            DataTable.Index2IdxTable index2 =
                    DataTable.Index2IdxTable.of(getTableFactory().getDataTable(txn));
            DataTable.Index3IdxTable index3 =
                    DataTable.Index3IdxTable.of(getTableFactory().getDataTable(txn));
            assertThat(index1.getRange(RangeRequest.builder().build()).count()).isEqualTo(1L);
            assertThat(index2.getRange(RangeRequest.builder().build()).count()).isEqualTo(1L);
            assertThat(index3.getRange(RangeRequest.builder().build()).count()).isEqualTo(1L);
            return null;
        });
    }

    @Test
    public void testUpdate() {
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable table = getTableFactory().getDataTable(txn);
            table.putValue(DataTable.DataRow.of(1L), 2L);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable.Index1IdxTable index1 =
                    DataTable.Index1IdxTable.of(getTableFactory().getDataTable(txn));
            assertThat(Iterables.getOnlyElement(index1.getRowColumns(Index1IdxRow.of(2L)))
                            .getColumnName()
                            .getId())
                    .isEqualTo(1L);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable table = getTableFactory().getDataTable(txn);
            table.putValue(DataTable.DataRow.of(1L), 3L);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            DataTable.Index1IdxTable index1 =
                    DataTable.Index1IdxTable.of(getTableFactory().getDataTable(txn));
            assertThat(index1.getRowColumns(Index1IdxRow.of(2L))).isEmpty();
            return null;
        });
    }

    @Test
    public void testTwoColumns() {
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            TwoColumnsTable table = getTableFactory().getTwoColumnsTable(txn);
            Multimap<TwoColumnsRow, TwoColumnsNamedColumnValue<?>> rows = HashMultimap.create();
            TwoColumnsRow key = TwoColumnsRow.of(1L);
            rows.put(key, Foo.of(2L));
            rows.put(key, Bar.of(5L));
            table.put(rows);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            TwoColumnsTable table = getTableFactory().getTwoColumnsTable(txn);
            table.putBar(TwoColumnsRow.of(1L), 6L);
            return null;
        });
        txManager.runTaskWithRetry((RuntimeTransactionTask<Void>) txn -> {
            FooToIdIdxTable index = FooToIdIdxTable.of(getTableFactory().getTwoColumnsTable(txn));
            List<FooToIdIdxRowResult> result = index.getAllRowsUnordered().immutableCopy();
            assertThat(Iterables.getOnlyElement(result).getRowName().getFoo()).isEqualTo(2L);
            return null;
        });
    }

    @Test
    public void testFirstRowComponentIsHashed() {
        long rawComponent = 1L;

        byte[] persistedRow = FooToIdIdxTable.FooToIdIdxRow.of(rawComponent).persistToBytes();

        long hashedValue = Hashing.murmur3_128()
                .hashBytes(ValueType.FIXED_LONG.convertFromJava(rawComponent))
                .asLong();
        byte[] expected = PtBytes.toBytes(Long.MIN_VALUE ^ hashedValue);

        byte[] firstComponentOfRow = Arrays.copyOf(persistedRow, 8); // We're only interested in the first 8 bytes.

        assertThat(firstComponentOfRow).isEqualTo(expected);
    }

    private IndexTestTableFactory getTableFactory() {
        return IndexTestTableFactory.of();
    }
}


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide utility routines for programming language literals.
//
//@CLASSES:
//  bdlb::LiteralUtil: utilities namespace for programming language literals
//
//@SEE_ALSO: hslc_lexer, hslc_parser
//
//@DESCRIPTION: This component provides a namespace, 'bdlb::LiteralUtil', for a
// set of utility routines that operate on (programming language) literals.

#include <bdlscm_version.h>

#include <bsls_libraryfeatures.h>

#include <bsl_string.h>
#include <bsl_string_view.h>

#include <string>           // 'std::string', 'std::pmr::string'

namespace BloombergLP {
namespace bdlb {

                             // ==================
                             // struct LiteralUtil
                             // ==================

struct LiteralUtil {
  private:
    // PRIVATE CLASS METHODS
    template <class OUT_STR>
    static void createQuotedEscapedCString_Impl(
                                               OUT_STR                 *result,
                                               const bsl::string_view&  input);
        // Load into the specified 'result' string the '"' delimited and
        // escaped C/C++ string literal equivalent representing the same value
        // as that of the specified 'input' string.  When the C string literal
        // equivalent is translated by a compiler having C-compatible string
        // literals, it will result in a string identical to the 'input'
        // string.  Note that this code uses the (ASCII) '\' character, rather
        // than Unicode code points for escapes.

  public:
    // CLASS METHODS
    static void createQuotedEscapedCString(bsl::string              *result,
                                           const bsl::string_view&   input);
    static void createQuotedEscapedCString(std::string              *result,
                                           const bsl::string_view&   input);
        // Load into the specified 'result' string the '"' delimited and
        // escaped C/C++ string literal equivalent representing the same value
        // as that of the specified 'input' string.  When the C string literal
        // equivalent is translated by a compiler having C-compatible string
        // literals, it will result in a string identical to the 'input'
        // string.  Note that this code uses the (ASCII) '\' character, rather
        // than Unicode code points for escapes.

#ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR
    static void createQuotedEscapedCString(std::pmr::string         *result,
                                           const bsl::string_view&   input);
        // Load into the specified 'result' string the '"' delimited and
        // escaped C/C++ string literal equivalent representing the same value
        // as that of the specified 'input' string.  When the C string literal
        // equivalent is translated by a compiler having C-compatible string
        // literals, it will result in a string identical to the 'input'
        // string.  Note that this code uses the (ASCII) '\' character, rather
        // than Unicode code points for escapes.
#endif
};

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2020 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package net.timbusproject.extractors.controllers;

import net.timbusproject.extractors.data.RequestHandler;
import net.timbusproject.extractors.data.ResponseConverter;
import net.timbusproject.extractors.osgi.OSGiClient;
import net.timbusproject.extractors.pojo.RequestExtraction;
import net.timbusproject.extractors.pojo.RequestExtractionList;
import net.timbusproject.extractors.pojo.ResponseJob;
import org.osgi.service.log.LogService;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Hashtable;

@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
@Path("/")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public class JerseyApiController {

    private static Hashtable<Long, RequestExtractionList> extractions;
    private static final Object LOCK = new Object();

    @Autowired
    private RequestHandler requestHandler;

    @Autowired
    ResponseConverter responseConverter;

    @Qualifier("jobLauncher")
    @Autowired
    private JobLauncher launcher;

    @Qualifier("extractionJob")
    @Autowired
    private Job job;

    @Autowired
    private LogService log;

    @Autowired
    private OSGiClient osgiClient;

    public JerseyApiController() {
        if (extractions == null) {
            extractions = new Hashtable<>();
        }
    }

    @GET
    @Path("/modules")
    public Response modulesList() {
        log.log(LogService.LOG_INFO, "modules list requested: " + osgiClient.getExtractors());
        return Response.ok(osgiClient.getExtractorsAsResponse()).build();
    }

    @GET
    @Path("/extractors")
    public Response extractorsList() {
        log.log(LogService.LOG_INFO, "extractors list requested");
        return modulesList();
    }

  /*  @POST
    @Path("/extract")
    public Response extract(RequestExtractionList extractionsList) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, IOException {
        log.log(LogService.LOG_INFO, "extraction requested" + extractionsList);
        long key;
        synchronized (LOCK) {
            key = extractions.keySet().size();
            extractions.put(key, extractionsList);
        }
        if (extractions.get(key).extractions.length == 1 && extractions.get(key).extractions[0].user == null && extractions.get(key).extractions[0].module != null && extractions.get(key).extractions[0].module.equals("Debian Software Extractor")) {
            // temporary fallback if clause
            extractions.get(key).extractions[0] = RequestExtraction.fromFile(getClass().getResourceAsStream("/default/debiansoftware"));
            extractions.get(key).extractions[0].module = "Debian Software Extractor";
        }
        for (RequestExtraction extraction : extractions.get(key).extractions) {
            if (extraction.wrap != null)
                log.log(LogService.LOG_INFO, extraction.wrap.toString());
            extraction.setJob(launcher.run(job,
                    new JobParametersBuilder()
                            .addString("user", extraction.user)
                            .addString("password", extraction.password != null && extraction.password.length() > 0 ? "" : null)
                            .addString("fqdn", extraction.fqdn) // newMachine (fqdn = fully qualified domain name)
                            .addString("knownHosts", extraction.knownHosts)
                            .addLong("port", (long) extraction.port) // newMachinePort
                            .addString("privateKey", extraction.privateKey)
                            .addString("wrapper", extraction.wrap != null ? extraction.wrap.toString() : null)
                            .addString("module", extraction.module) // selectedModule.name
                            .addLong("timestamp", System.currentTimeMillis())
                            .toJobParameters()));
            extraction.getJob().getExecutionContext().putString("password", extraction.password);
            extraction.unsetPassword();
        }
        return Response.status(Response.Status.ACCEPTED)
                .entity(getRequestInfo(key))
                .location(UriBuilder.fromPath("/requests/{id}").build(key))
                .build();
    }*/

    @POST
    @Path("/extract")
    public Response extract(RequestExtractionList extractionsList, @Context HttpServletRequest req) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, IOException {

//        System.out.println("REQUEST TYPE REQUESTED: " + extractionsList.getCallbackInfo().originRequestType);
        if (extractionsList.getCallbackInfo() != null && extractionsList.getCallbackInfo().endpointPath != null && extractionsList.getCallbackInfo().endpointPort != null) {
            String endpoint = req.getRemoteAddr() + ":" + extractionsList.getCallbackInfo().endpointPort;
            if (extractionsList.getCallbackInfo().endpointPath.startsWith("/"))
                endpoint += extractionsList.getCallbackInfo().endpointPath;
            else
                endpoint += "/" + extractionsList.getCallbackInfo().endpointPath;
            extractionsList.callback.setOriginEndpoint(endpoint);
            if (extractionsList.getCallbackInfo().originRequestType != null) {
                if (extractionsList.getCallbackInfo().originRequestType.trim().toLowerCase().equals("post")|| extractionsList.getCallbackInfo().originRequestType.trim().toLowerCase().equals("get")) {
                    extractionsList.getCallbackInfo().setFinalOriginRequestType(extractionsList.getCallbackInfo().originRequestType.toLowerCase());
                } else {
                    log.log(LogService.LOG_INFO, "Invalid HTTP Request type for origin host callback. Defaulting to GET type");
                    extractionsList.getCallbackInfo().setFinalOriginRequestType("get");
                }
            } else {
                log.log(LogService.LOG_INFO, "No HTTP Request type for origin host callback provided. Defaulting to GET type");
                extractionsList.getCallbackInfo().setFinalOriginRequestType("get");
            }
            if (extractionsList.getCallbackInfo().requestType != null) {
                if (extractionsList.getCallbackInfo().requestType.trim().toLowerCase().equals("post")|| extractionsList.getCallbackInfo().requestType.trim().toLowerCase().equals("get")) {
                    extractionsList.getCallbackInfo().setFinalRequestType(extractionsList.getCallbackInfo().requestType.toLowerCase());
                } else {
                    log.log(LogService.LOG_INFO, "Invalid HTTP Request type for callback. Defaulting to GET type");
                    extractionsList.getCallbackInfo().setFinalRequestType("get");
                }
            } else {
                log.log(LogService.LOG_INFO, "No HTTP Request type for callback provided. Defaulting to GET type");
                extractionsList.getCallbackInfo().setFinalRequestType("get");
            }
        }
        long key = requestHandler.requestExtraction(extractionsList);
        return Response.status(Response.Status.ACCEPTED)
                .entity(responseConverter.getRequestInfo(key))
                .location(UriBuilder.fromPath("/requests/{id}").build(key))
                .build();
    }

/*
    @POST
    @Path("/extract")
    public Response extract(@FormParam("extractions") String extractionsList) throws JSONException, JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, IOException {
        log.log(LogService.LOG_INFO, "extraction requested" + extractionsList);
        return extract(RequestExtractionList.fromJSON(new JSONArray(extractionsList)));
    }
*/

/*    @GET
    @Path("/extract/fallback")
    public Response extractFallback() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, IOException {
        log.log(LogService.LOG_INFO, "starting fallback extraction");
        RequestExtraction extraction = RequestExtraction.fromFile(getClass().getResourceAsStream("/default/debiansoftware"));
        extraction.module = "Debian Software Extractor";
        RequestExtractionList extractionsList = new RequestExtractionList();
        extractionsList.extractions = new RequestExtraction[]{extraction};
        return extract(extractionsList);
    }*/

    //UNCOMMENT THIS!! 5 MARÇO 2014
    /*@GET
    @Path("/extract/fallback")
    public Response extractFallback() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, IOException {
        log.log(LogService.LOG_INFO, "starting fallback extraction");
        long key = requestHandler.requestExtractionFallback();
        return Response.status(Response.Status.ACCEPTED)
                .entity(responseConverter.getRequestInfo(key))
                .location(UriBuilder.fromPath("/requests/{id}").build(key))
                .build();
    }*/

/*    @GET
    @Path("/requests")
    public Response allRequestsList() throws NoSuchJobException {
        log.log(LogService.LOG_INFO, "request list requested");
        List<ResponseJobsList> response = new ArrayList<>();
        for (Long id : extractions.keySet()) {
            response.add(getRequestInfo(id));
        }
        return Response.ok(response).build();
    }*/

    @GET
    @Path("/requests")
    public Response allRequestsList() throws NoSuchJobException {
        return Response.ok(responseConverter.allRequestsList()).build();
    }

    /*@GET
    @Path("/requests/{id}")
    public Response requestInfo(@PathParam("id") long id) {
        log.log(LogService.LOG_INFO, "request #" + id + " requested");
        return Response.ok(getRequestInfo(id)).build();
    }*/

    @GET
    @Path("/testcallback")
    public Response testCallbackGet() {
        log.log(LogService.LOG_INFO, "JerseyApiController: received http request from callback. extractions finished");
        return Response.ok().build();
    }

    @GET
    @Path("/requests/{id}")
    public Response requestInfo(@PathParam("id") long id) {
        log.log(LogService.LOG_INFO, MessageFormat.format("id: {0}", id));
        return Response.ok(responseConverter.getRequestInfo(id)).build();
    }

/*    private ResponseJobsList getRequestInfo(long id) {
        ResponseJobsList list = new ResponseJobsList();
        if (!extractions.containsKey(id)) {
            return list;
        }
        log.log(LogService.LOG_INFO, "packing request #" + id + " info");
        list.setId(id);
        for (RequestExtraction request : extractions.get(id).extractions) {
            list.add(request.getJob());
        }
        return list;
    }*/

    @GET
    @Path("/requests/{id}/finished")
    public Response requestInfoFinish(@PathParam("id") long id) {
        log.log(LogService.LOG_INFO, "finish polling received for extraction # " + id);
        if (!extractions.containsKey(id))
            return Response.status(Response.Status.NOT_FOUND).build();
        for (RequestExtraction extraction : extractions.get(id).extractions) {
            if (extraction.getJob() != null && extraction.getJob().getStatus().equals(BatchStatus.FAILED)) {
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(false).build();
            } else if (extraction.getJob() == null || !extraction.getJob().getStatus().equals(BatchStatus.COMPLETED)) {
                return Response.status(Response.Status.CREATED).entity(false).build();
            }
        }
        return Response.ok(true).build();
    }

    private ResponseJob getJobInfo(JobExecution execution) {
        if (execution == null)
            return new ResponseJob();
        log.log(LogService.LOG_INFO, "packing job's info. id: " + execution.getJobId());
        return new ResponseJob(execution);
    }

}


text:
drop table if exists customers;
create table customers (
	id integer primary key autoincrement,
	first_name string not null,
	last_name string not null,
	primary_card string
);

drop table if exists payments;
create table payments (
	id integer primary key autoincrement,
	customer_id integer,
	charge_id string,
	amount integer
);


text:
/**
 * Module Dependencies
 */

var Waterline = require('waterline');
var _ = require('lodash');
var async = require('async');
var assert = require('assert');

// Require Fixtures
var fixtures = {
    UserFixture: require('./fixtures/crud.fixture'),
    UniqueFixture: require('./fixtures/unique.fixture'),
    Customid: require('./fixtures/customid.fixture')
};

/////////////////////////////////////////////////////
// TEST SETUP
////////////////////////////////////////////////////

var waterline, ontology;

before(function (done) {

    waterline = new Waterline();

    Object.keys(fixtures).forEach(function (key) {
        waterline.loadCollection(fixtures[key]);
    });

    var connections = {semantic: _.clone(Connections.test)};

    waterline.initialize({adapters: {wl_tests: Adapter}, connections: connections}, function (err, _ontology) {
        if (err) return done(err);

        ontology = _ontology;

        Object.keys(_ontology.collections).forEach(function (key) {
            var globalName = key.charAt(0).toUpperCase() + key.slice(1);
            global.Semantic[globalName] = _ontology.collections[key];
        });

        done();
    });
});

after(function (done) {

    function dropCollection(item, next) {
        if (!Adapter.hasOwnProperty('drop')) return next();

        ontology.collections[item].drop(function (err) {
            if (err) return next(err);
            next();
        });
    }

    async.each(Object.keys(ontology.collections), dropCollection, function (err) {
        if (err) return done(err);
        waterline.teardown(done);
    });

});


text:
/*
 *  Delegates.h
 *  Box2D
 *
 *  Box2D iPhone port by Simon Oliver - http://www.simonoliver.com - http://www.handcircus.com
 *
 *
 */

@protocol TestSelectDelegate <NSObject>
	-(void) selectTest:(int) testIndex;
	-(void) leaveTest;

@end


text:
layout: doc
title: Введение
permalink: /ru/beginner/introduction/
lang: ru
category: beginner
---

Введение
============

> Проверено 2015-07-12

Знание -- сила. Благодаря качественным данным и глубокому пониманию, отдельные люди и сообщества способны в большей степени улучшать свою жизнь и принимать решения от которых зависит будущее. Существует множество людей и организаций, чьи решения влияют на нашу жизнь. Качественные данные позволяют этим  НПО (неправительственные организации), правительствам и гражданам принимать более оптимальные решения, ведущие, хочется верить, к улучшению нашей жизни. Карты -- отличный способ донести информацию.

![Деревня в Индонезии][]

Maps are visual symbols of our world. They can often demonstrate an idea better than words. This in turn can help us answer important questions. *Where is the closest school or hospital? Who has the least access to these facilities? Where is poverty the most problematic?* Questions like these can often best be expressed with maps, and maps can help find solutions to these questions.

As an exercise, get a pen and paper and draw a map of your town or village. What are the most important things to include on the map? What is the most important information? Spend a few minutes making your map, and when you're finished, think about why the information you included is important, and who it might be important to.

![Example of a hand-drawn map][]

If your town is like most, you may have drawn some lines to represent roads, possibly a river or stream. Perhaps you added important buildings such as schools and offices, fields, or boundaries. Whatever you drew, you probably used symbols – a line to symbolize a road, a square to symbolize a building, and so on. Your map is a representation of what is on the ground.

![Examples of symbols][]

Your map is informative. You might use a map like this to explain to someone where different places are, where problems are in your community, or merely to help someone find their way around. The use of your map is limited though - there is only one copy of the map.The way you drew it may make sense to you, but perhaps not to someone else who would have drawn their own map in a different way. Because your map is merely on paper, it is difficult to get that information to others.  This is why making your map on a computer, in such a way that anyone can access it, can be much more valuable.

![Mapping on Computer][]

OpenStreetMap is a tool for creating and sharing map information.  Anyone can contribute to OSM, and thousands of people add to the project every day. Users draw maps on computers, rather than paper, but as we will see in this guide, drawing a map on a computer is not all that different from drawing on paper. We still draw lines to represent roads, fields, and anything else, and we still represent schools and hospitals with symbols. The important thing is that OSM maps are saved on the internet, and anyone can access them at any time, totally free.

![Digital maps with OpenStreetMap][]

We hope that you will find OpenStreetMap useful and interesting in your work. By following this guide, you should be able to quickly start making digital maps with OpenStreetMap.

[A village in Indonesia]: /images/beginner/village-in-indonesia.png
[Example of a hand-drawn map]: /images/beginner/hand-drawn-map.png
[Examples of symbols]: /images/beginner/examples-of-symbols.png
[Mapping on Computer]: /images/beginner/mapping-on-computer.png
[Digital maps with OpenStreetMap]: /images/beginner/digital-maps-with-osm.png


text:
package org.springframework.boot.actuate.metrics.web.client;

import io.micrometer.core.instrument.Tag;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;

/**
 * Provides {@link Tag Tags} for an exchange performed by a {@link RestTemplate}.
 *
 * @author Jon Schneider
 * @author Andy Wilkinson
 * @since 2.0.0
 */
@FunctionalInterface
public interface RestTemplateExchangeTagsProvider {

	/**
	 * Provides the tags to be associated with metrics that are recorded for the given
	 * {@code request} and {@code response} exchange.
	 * @param urlTemplate the source URl template, if available
	 * @param request the request
	 * @param response the response (may be {@code null} if the exchange failed)
	 * @return the tags
	 */
	Iterable<Tag> getTags(String urlTemplate, HttpRequest request,
			ClientHttpResponse response);

}


text:
@class BaseResponse, NSString;

@interface GetPayFunctionListResponse : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse;
@property(nonatomic) unsigned int cacheTime; // @dynamic cacheTime;
@property(nonatomic) unsigned int notShowTutorial; // @dynamic notShowTutorial;
@property(retain, nonatomic) NSString *payFunctionList; // @dynamic payFunctionList;

@end


text:
require 'spec_helper'

describe Xpitality::Notifier do
  it 'has a version number' do
    expect(Xpitality::Notifier::VERSION).not_to be nil
  end

  context 'when multiple clients used' do

    before :each do
      Xpitality::Notifier::ChatNotifier.configure do |config|
        config.set_option :client, :slack
        config.set_option :channel, '#dev'
        config.set_option :username, 'tester'
      end

      Xpitality::Notifier::SmsNotifier.configure do |config|
        config.set_option :client, :nexmo
        config.set_option :from, 'Support dpt'
      end

      Xpitality::Notifier::ExceptionNotifier.configure do |config|
        config.set_option :client, :bugsnag
      end
    end

    it 'configures them correctly' do
      expect(Xpitality::Notifier::ChatNotifier.get_option(:client)).to eq :slack
      expect(Xpitality::Notifier::ChatNotifier.get_option(:channel)).to eq '#dev'
      expect(Xpitality::Notifier::ChatNotifier.get_option(:username)).to eq 'tester'
      expect(Xpitality::Notifier::ChatNotifier.get_option(:from)).to be_nil

      expect(Xpitality::Notifier::SmsNotifier.get_option(:client)).to eq :nexmo
      expect(Xpitality::Notifier::SmsNotifier.get_option(:from)).to eq 'Support dpt'
      expect(Xpitality::Notifier::SmsNotifier.get_option(:channel)).to be_nil
      expect(Xpitality::Notifier::SmsNotifier.get_option(:username)).to be_nil

      expect(Xpitality::Notifier::ExceptionNotifier.get_option(:client)).to eq :bugsnag
      expect(Xpitality::Notifier::ExceptionNotifier.get_option(:from)).to be_nil
      expect(Xpitality::Notifier::ExceptionNotifier.get_option(:channel)).to be_nil
      expect(Xpitality::Notifier::ExceptionNotifier.get_option(:username)).to be_nil
    end

  end

  context 'when client set to :specs' do
    before :each do
      Xpitality::Notifier::ChatNotifier.configure do |config|
        config.set_option :client, :specs
      end

      Xpitality::Notifier::SmsNotifier.configure do |config|
        config.set_option :client, :specs
      end

      Xpitality::Notifier::ExceptionNotifier.configure do |config|
        config.set_option :client, :specs
      end
    end

    [Xpitality::Notifier::ChatNotifier, Xpitality::Notifier::SmsNotifier, Xpitality::Notifier::ExceptionNotifier].each do |klass|

      context "when #{klass}" do
        it 'does not call client_class (skipping the notification)' do
          expect(klass).to receive(:sanity_check).and_return(false)
          expect(klass).not_to receive(:client_class)

          klass.notify('message', {})
        end
      end
    end
  end
end


text:
using UnityEngine;
using System.Collections;
using Grouping;

public class GUILoader : MonoBehaviour
{
    public Texture pixel;

    public string progressText = "Loading...";

    public float borderSize = 0.01f;
    public float barWidth = 0.5f;

    int count;

    ProgressBar progressBar;

    void Start()
    {
        GroupManager.main.group["Loading"].Add(this);

        progressBar = gameObject.AddComponent<ProgressBar>();
        progressBar.Init(pixel, progressText, borderSize, barWidth);
    }

    void Update()
    {
        progressBar.count = count;
    }

    void OnGUI()
    {
        GUI.Label(new Rect(0, Screen.height, Screen.width, Screen.height),
            "Force Preload",
            GUIManager.StyleList[count].style);

        // Check if the loading over
        if (Event.current.type.Equals(EventType.Repaint))
        {
            if (++count >= GUIManager.StyleList.Count)
            {
                GroupManager.main.activeGroup = GroupManager.main.group["Main Menu"];
                Destroy(progressBar);
                Destroy(this);
            }
        }
    }

    private class ProgressBar : MonoBehaviour
    {
        public int count;

        Texture pixel;
        string progressText;

        float borderSize;
        float barWidth = 0.5f;

        float progress;
        Vector2 textSize;

        public void Init(Texture pixel, string progressText, float borderSize, float barWidth)
        {
            this.pixel = pixel;
            this.progressText = progressText;
            this.borderSize = borderSize;
            this.barWidth = barWidth;
        }

        void Start()
        {
            GroupManager.main.group["Loading"].Add(this);

            textSize = GUIManager.Style.loading.CalcSize(new GUIContent(progressText));
        }

        void Update()
        {
            progress = Mathf.Min(1.0f, Mathf.Lerp(progress, ((float)count / (GUIManager.StyleList.Count - 1)), Time.deltaTime * 4));
        }

        void OnGUI()
        {
            // Loading text
            GUI.Label(
                new Rect(
                    0.5f * (Screen.width - textSize.x),
                    0.5f * (Screen.height - textSize.y) - textSize.y,
                    textSize.x,
                    textSize.y),
                progressText,
                GUIManager.Style.loading);

            // Progress bar
            if (progress > 0.0f)
            {
                Rect bar = new Rect(
                    0.5f * (Screen.width - barWidth * Screen.height),
                    0.5f * (Screen.height - textSize.y) + textSize.y * 0.5f,
                    barWidth * Screen.height,
                    0.5f * textSize.y);

                GUI.color = Color.white;
                GUI.DrawTexture(new Rect(
                    bar.x - 0.5f * borderSize * Screen.height,
                    bar.y - 0.5f * borderSize * Screen.height,
                    bar.width + borderSize * Screen.height,
                    bar.height + borderSize * Screen.height),
                    pixel);

                GUI.color = Color.black;
                GUI.DrawTexture(bar, pixel);

                GUI.color = new Color(0.1f, 0.6f, 0.2f);
                GUI.DrawTexture(new Rect(bar.x, bar.y, bar.width * progress, bar.height), pixel);
            }
        }
    }
}


text:
package com.tapglue.android;

import rx.Observer;

/**
 * Created by John on 4/6/16.
 */
public abstract class IntegrationObserver<T> implements Observer<T> {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        throw new AssertionError(e);
    }

    @Override
    public abstract void onNext(T t);
}


text:
require 'spec_helper'

describe Tree do
  it { should validate_presence_of :title }
  it { should have_many(:nodes) }
  it { should allow_value('publicdomain').for(:creative_commons) }
  it { should_not allow_value('something else').for(:creative_commons) }

  it "should know the children of a node inside it" do
    tree = create(:tree)

    parent = create(:node, tree: tree)
    child1 = create(:node, parent: parent, tree: tree)
    child2 = create(:node, parent: parent, tree: tree)

    tree.children_of(parent).should == [child1, child2]
    tree.children_of(parent.id).should == [child1, child2]
  end

  it "should automatically have a root node" do
    tree = create(:tree)
    nodes = Node.where(tree_id: tree.id)
    nodes.size.should == 1
    nodes[0].parent_id.should == nil
    nodes[0].name.name_string.should == Gnite::Config.root_node_name_string
  end

  it "should have one and only one root node" do
    tree = create(:tree)
    3.times { create(:node, tree: tree) }
    10.times do
      parent = Node.where(tree_id: tree.id).shuffle[0]
      create(:node, tree: tree, parent_id: parent.id)
    end
    roots = Node.where(tree_id: tree.id).where(parent_id: nil)
    roots.size.should == 1
    tree.root.should == roots[0]
  end

  it "should have an automatically generated uuid" do
    subject.uuid.should_not be_nil
  end

  it "should set a default value for creative commons" do
    subject.creative_commons.should == "cc0"
  end

  it "should not assign a new uuid to something with a uuid" do
    tree = create(:tree, uuid: "uuid monster")
    tree.save
    tree.uuid.should == "uuid monster"
  end

  it "should raise ActiveRecord::RecordNotFound when asking for the children of a node not in the tree" do
    tree = create(:tree)

    parent = create(:node, tree: tree)
    child1 = create(:node, parent: parent, tree: tree)
    child2 = create(:node, parent: parent, tree: tree)

    other_tree = create(:tree)

    lambda { other_tree.children_of(parent) }.should raise_error(ActiveRecord::RecordNotFound)
  end

  it "should know the roots inside it" do
    tree = create(:tree)
    root_real = tree.root
    root1 = create(:node, tree: tree)
    root2 = create(:node, tree: tree)
    child1 = create(:node, parent: root1, tree: tree)

    tree.children_of(nil).should == [root_real]
    tree.children_of(tree.root).should == [root1, root2]
  end
end

describe Tree, '#nuke_nodes' do
  it "should destroy all nodes, but not the tree and its root" do
    user = create(:user)
    tree = create(:tree)
    root = create(:node, tree: tree)
    child = create(:node, tree: tree, parent_id: root)
    grandchild = create(:node, tree: tree, parent_id: child)
    bookmark = create(:bookmark, node: child)
    vern = create(:vernacular_name, node: child)
    syn = create(:synonym, node: grandchild)
    tree_id = tree.id
    tree_count = Tree.count
    root = tree.root
    node_count = Node.count
    bookmark_count = Bookmark.count
    vern_count = VernacularName.count
    syn_count = Synonym.count
    tree.nuke_nodes
    (tree_count - Tree.count).should == 0
    tree.reload.root.should == root
    (node_count - Node.count).should == 3
    (bookmark_count - Bookmark.count).should == 1
    (vern_count - VernacularName.count).should == 1
    (syn_count - Synonym.count).should == 1
  end
end

describe Tree, '#nuke' do
  it "should destroy all nodes, bookmarks, synonyms and vernaculars" do
    user = create(:user)
    tree = create(:tree)
    root = create(:node, tree: tree)
    child = create(:node, tree: tree, parent_id: root)
    grandchild = create(:node, tree: tree, parent_id: child)
    bookmark = create(:bookmark, node: child)
    vern = create(:vernacular_name, node: child)
    syn = create(:synonym, node: grandchild)
    tree_id = tree.id
    tree_count = Tree.count
    node_count = Node.count
    bookmark_count = Bookmark.count
    vern_count = VernacularName.count
    syn_count = Synonym.count
    tree.nuke
    (tree_count - Tree.count).should == 1
    (node_count - Node.count).should == 4
    (bookmark_count - Bookmark.count).should == 1
    (vern_count - VernacularName.count).should == 1
    (syn_count - Synonym.count).should == 1
  end
end