text:
from __future__ import annotations

import functools
import warnings
from copy import deepcopy
from typing import Any, Sequence

import numpy as np
import torch

import monai
from monai.config.type_definitions import NdarrayTensor
from monai.data.meta_obj import MetaObj, get_track_meta
from monai.data.utils import affine_to_spacing, decollate_batch, list_data_collate, remove_extra_metadata
from monai.utils import look_up_option
from monai.utils.enums import LazyAttr, MetaKeys, PostFix, SpaceKeys
from monai.utils.type_conversion import convert_data_type, convert_to_numpy, convert_to_tensor

__all__ = ["MetaTensor"]

@functools.lru_cache(None)
def _get_named_tuple_like_type(func):
    if (
        hasattr(torch, "return_types")
        and hasattr(func, "__name__")
        and hasattr(torch.return_types, func.__name__)
        and isinstance(getattr(torch.return_types, func.__name__), type)
    ):
        return getattr(torch.return_types, func.__name__)
    return None

def _not_requiring_metadata(ret):
    return isinstance(ret, (int, str, bytes, torch.Size, torch.dtype, torch.device, np.ndarray)) or not (
        isinstance(ret, MetaTensor) or (isinstance(ret, Sequence) and any(isinstance(x, MetaTensor) for x in ret))
    )

class MetaTensor(MetaObj, torch.Tensor):
    """
    Class that inherits from both `torch.Tensor` and `MetaObj`, adding support for metadata.

    Metadata is stored in the form of a dictionary. Nested, an affine matrix will be
    stored. This should be in the form of `torch.Tensor`.

    Behavior should be the same as `torch.Tensor` aside from the extended
    meta functionality.

    Copying of information:

        * For `c = a + b`, then auxiliary data (e.g., metadata) will be copied from the
          first instance of `MetaTensor` if `a.is_batch` is False
          (For batched data, the metadata will be shallow copied for efficiency purposes).

    Example:
        .. code-block:: python

            import torch
            from monai.data import MetaTensor

            t = torch.tensor([1,2,3])
            affine = torch.as_tensor([[2,0,0,0],
                                      [0,2,0,0],
                                      [0,0,2,0],
                                      [0,0,0,1]], dtype=torch.float64)
            meta = {"some": "info"}
            m = MetaTensor(t, affine=affine, meta=meta)
            m2 = m + m
            assert isinstance(m2, MetaTensor)
            assert m2.meta["some"] == "info"
            assert torch.all(m2.affine == affine)

    Notes:
        - Requires pytorch 1.9 or newer for full compatibility.
        - Older versions of pytorch (<=1.8), `torch.jit.trace(net, im)` may
          not work if `im` is of type `MetaTensor`. This can be resolved with
          `torch.jit.trace(net, im.as_tensor())`.
        - For pytorch < 1.8, sharing `MetaTensor` instances across processes may not be supported.
        - For pytorch < 1.9, next(iter(meta_tensor)) returns a torch.Tensor.
          see: https://github.com/pytorch/pytorch/issues/54457
        - A warning will be raised if in the constructor `affine` is not `None` and
          `meta` already contains the key `affine`.
        - You can query whether the `MetaTensor` is a batch with the `is_batch` attribute.
        - With a batch of data, `batch[0]` will return the 0th image
          with the 0th metadata. When the batch dimension is non-singleton, e.g.,
          `batch[:, 0]`, `batch[..., -1]` and `batch[1:3]`, then all (or a subset in the
          last example) of the metadata will be returned, and `is_batch` will return `True`.
        - When creating a batch with this class, use `monai.data.DataLoader` as opposed
          to `torch.utils.data.DataLoader`, as this will take care of collating the
          metadata properly.
    """

    @staticmethod
    def __new__(
        cls,
        x,
        affine: torch.Tensor | None = None,
        meta: dict | None = None,
        applied_operations: list | None = None,
        *args,
        **kwargs,
    ) -> MetaTensor:
        _kwargs = {"device": kwargs.pop("device", None), "dtype": kwargs.pop("dtype", None)} if kwargs else {}
        return torch.as_tensor(x, *args, **_kwargs).as_subclass(cls)  # type: ignore

    def __init__(
        self,
        x,
        affine: torch.Tensor | None = None,
        meta: dict | None = None,
        applied_operations: list | None = None,
        *_args,
        **_kwargs,
    ) -> None:
        """
        Args:
            x: initial array for the MetaTensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.
            affine: optional 4x4 array.
            meta: dictionary of metadata.
            applied_operations: list of previously applied operations on the MetaTensor,
                the list is typically maintained by `monai.transforms.TraceableTransform`.
                See also: :py:class:`monai.transforms.TraceableTransform`
            _args: additional args (currently not in use in this constructor).
            _kwargs: additional kwargs (currently not in use in this constructor).

        Note:
            If a `meta` dictionary is given, use it. Else, if `meta` exists in the input tensor `x`, use it.
            Else, use the default value. Similar for the affine, except this could come from
            four places, priority: `affine`, `meta["affine"]`, `x.affine`, `get_default_affine`.

        """
        super().__init__()
        # set meta
        if meta is not None:
            self.meta = meta
        elif isinstance(x, MetaObj):
            self.__dict__ = deepcopy(x.__dict__)
        # set the affine
        if affine is not None:
            if MetaKeys.AFFINE in self.meta:
                warnings.warn("Setting affine, but the applied meta contains an affine. This will be overwritten.")
            self.affine = affine
        elif MetaKeys.AFFINE in self.meta:
            # by using the setter function, we ensure it is converted to torch.Tensor if not already
            self.affine = self.meta[MetaKeys.AFFINE]
        else:
            self.affine = self.get_default_affine()
        # applied_operations
        if applied_operations is not None:
            self.applied_operations = applied_operations
        else:
            self.applied_operations = MetaObj.get_default_applied_operations()

        # if we are creating a new MetaTensor, then deep copy attributes
        if isinstance(x, torch.Tensor) and not isinstance(x, MetaTensor):
            self.copy_meta_from(self)

        if MetaKeys.SPACE not in self.meta:
            self.meta[MetaKeys.SPACE] = SpaceKeys.RAS  # defaulting to the right-anterior-superior space

    @staticmethod
    def update_meta(rets: Sequence, func, args, kwargs) -> Sequence:
        """
        Update the metadata from the output of `MetaTensor.__torch_function__`.

        The output of `torch.Tensor.__torch_function__` could be a single object or a
        sequence of them. Hence, in `MetaTensor.__torch_function__` we convert them to a
        list of not already, and then we loop across each element, processing metadata
        as necessary. For each element, if not of type `MetaTensor`, then nothing to do.

        Args:
            rets: the output from `torch.Tensor.__torch_function__`, which has been
                converted to a list in `MetaTensor.__torch_function__` if it wasn't
                already a `Sequence`.
            func: the torch function that was applied. Examples might be `torch.squeeze`
                or `torch.Tensor.__add__`. We need this since the metadata need to be
                treated differently if a batch of data is considered. For example,
                slicing (`torch.Tensor.__getitem__`) the ith element of the 0th
                dimension of a batch of data should return a ith tensor with the ith
                metadata.
            args: positional arguments that were passed to `func`.
            kwargs: keyword arguments that were passed to `func`.

        Returns:
            A sequence with the same number of elements as `rets`. For each element, if
            the input type was not `MetaTensor`, then no modifications will have been
            made. If global parameters have been set to false (e.g.,
            `not get_track_meta()`), then any `MetaTensor` will be converted to
            `torch.Tensor`. Else, metadata will be propagated as necessary (see
            :py:func:`MetaTensor._copy_meta`).
        """
        out = []
        metas = None
        is_batch = any(x.is_batch for x in MetaObj.flatten_meta_objs(args, kwargs.values()) if hasattr(x, "is_batch"))
        for idx, ret in enumerate(rets):
            # if not `MetaTensor`, nothing to do.
            if not isinstance(ret, MetaTensor):
                pass
            # if not tracking, convert to `torch.Tensor`.
            elif not get_track_meta():
                ret = ret.as_tensor()
            # else, handle the `MetaTensor` metadata.
            else:
                meta_args = MetaObj.flatten_meta_objs(args, kwargs.values())
                ret.is_batch = is_batch
                ret.copy_meta_from(meta_args, copy_attr=not is_batch)
                # the following is not implemented but the network arch may run into this case:
                # if func == torch.cat and any(m.is_batch if hasattr(m, "is_batch") else False for m in meta_args):
                #     raise NotImplementedError("torch.cat is not implemented for batch of MetaTensors.")

                # If we have a batch of data, then we need to be careful if a slice of
                # the data is returned. Depending on how the data are indexed, we return
                # some or all of the metadata, and the return object may or may not be a
                # batch of data (e.g., `batch[:,-1]` versus `batch[0]`).
                if is_batch:
                    # if indexing e.g., `batch[0]`
                    if func == torch.Tensor.__getitem__:
                        batch_idx = args[1]
                        if isinstance(batch_idx, Sequence):
                            batch_idx = batch_idx[0]
                        # if using e.g., `batch[:, -1]` or `batch[..., -1]`, then the
                        # first element will be `slice(None, None, None)` and `Ellipsis`,
                        # respectively. Don't need to do anything with the metadata.
                        if batch_idx not in (slice(None, None, None), Ellipsis, None) and idx == 0:
                            ret_meta = decollate_batch(args[0], detach=False)[batch_idx]
                            if isinstance(ret_meta, list):  # e.g. batch[0:2], re-collate
                                ret_meta = list_data_collate(ret_meta)
                            else:  # e.g. `batch[0]` or `batch[0, 1]`, batch index is an integer
                                ret_meta.is_batch = False
                            ret.__dict__ = ret_meta.__dict__.copy()
                    # `unbind` is used for `next(iter(batch))`. Also for `decollate_batch`.
                    # But we only want to split the batch if the `unbind` is along the 0th
                    # dimension.
                    elif func == torch.Tensor.unbind:
                        if len(args) > 1:
                            dim = args[1]
                        elif "dim" in kwargs:
                            dim = kwargs["dim"]
                        else:
                            dim = 0
                        if dim == 0:
                            if metas is None:
                                metas = decollate_batch(args[0], detach=False)
                            ret.__dict__ = metas[idx].__dict__.copy()
                            ret.is_batch = False

            out.append(ret)
        # if the input was a tuple, then return it as a tuple
        return tuple(out) if isinstance(rets, tuple) else out

    @classmethod
    def __torch_function__(cls, func, types, args=(), kwargs=None) -> Any:
        """Wraps all torch functions."""
        if kwargs is None:
            kwargs = {}
        ret = super().__torch_function__(func, types, args, kwargs)
        # if `out` has been used as argument, metadata is not copied, nothing to do.
        # if "out" in kwargs:
        #     return ret
        # we might have 1 or multiple outputs. Might be MetaTensor, might be something
        # else (e.g., `__repr__` returns a string).
        # Convert to list (if necessary), process, and at end remove list if one was added.
        if _not_requiring_metadata(ret):
            return ret
        if _get_named_tuple_like_type(func) is not None and isinstance(ret, _get_named_tuple_like_type(func)):
            # for torch.max(torch.tensor(1.0), dim=0), the return type is named-tuple like
            out_items = MetaTensor.update_meta(ret, func, args, kwargs)
            for idx in range(ret.n_fields):
                ret[idx].meta = out_items[idx].meta
                ret[idx].applied_operations = out_items[idx].applied_operations
            return ret
        if not isinstance(ret, Sequence):
            ret = [ret]
            unpack = True
        else:
            unpack = False
        ret = MetaTensor.update_meta(ret, func, args, kwargs)
        return ret[0] if unpack else ret

    @staticmethod
    def _convert(x):
        if isinstance(x, (MetaTensor, torch.Tensor, tuple, list)):
            return convert_data_type(x, output_type=np.ndarray, wrap_sequence=False)[0]
        return x

    def __array_function__(self, func, types, args, kwargs):
        """for numpy Interoperability, so that we can compute ``np.sum(MetaTensor([1.0]))``."""
        try:
            if not func.__module__.startswith("numpy"):
                return NotImplemented
        except AttributeError:
            return NotImplemented
        _args = list(map(MetaTensor._convert, args))
        _kwargs = {k: MetaTensor._convert(v) for k, v in kwargs.items()}
        return func(*_args, **_kwargs)

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        """
        For numpy interoperability, so that we can compute ``MetaTensor([1.0]) >= np.asarray([1.0])``.
        This is for pytorch > 1.8.
        """
        try:
            if not type(ufunc).__module__.startswith("numpy"):
                return NotImplemented
        except AttributeError:
            return NotImplemented
        if method != "__call__":
            return NotImplemented
        _inputs = map(MetaTensor._convert, inputs)
        _kwargs = {k: MetaTensor._convert(v) for k, v in kwargs.items()}
        if "out" in _kwargs:
            return NotImplemented  # not supported
        try:
            return getattr(ufunc, method)(*_inputs, **_kwargs)
        except AttributeError:
            return NotImplemented

    @staticmethod
    def get_default_affine(dtype=torch.float64) -> torch.Tensor:
        return torch.eye(4, device=torch.device("cpu"), dtype=dtype)

    def as_tensor(self) -> torch.Tensor:
        """
        Return the `MetaTensor` as a `torch.Tensor`.
        It is OS dependent as to whether this will be a deep copy or not.
        """
        return self.as_subclass(torch.Tensor)

    def get_array(self, output_type=np.ndarray, dtype=None, device=None, *_args, **_kwargs):
        """
        Returns a new array in `output_type`, the array shares the same underlying storage when the output is a
        numpy array. Changes to self tensor will be reflected in the ndarray and vice versa.

        Args:
            output_type: output type, see also: :py:func:`monai.utils.convert_data_type`.
            dtype: dtype of output data. Converted to correct library type (e.g.,
                `np.float32` is converted to `torch.float32` if output type is `torch.Tensor`).
                If left blank, it remains unchanged.
            device: if the output is a `torch.Tensor`, select device (if `None`, unchanged).
            _args: currently unused parameters.
            _kwargs: currently unused parameters.
        """
        return convert_data_type(self, output_type=output_type, dtype=dtype, device=device, wrap_sequence=True)[0]

    def set_array(self, src, non_blocking=False, *_args, **_kwargs):
        """
        Copies the elements from src into self tensor and returns self.
        The src tensor must be broadcastable with the self tensor.
        It may be of a different data type or reside on a different device.

        See also: `https://pytorch.org/docs/stable/generated/torch.Tensor.copy_.html`

        Args:
            src: the source tensor to copy from.
            non_blocking: if True and this copy is between CPU and GPU, the copy may occur
                asynchronously with respect to the host. For other cases, this argument has no effect.
            _args: currently unused parameters.
            _kwargs:  currently unused parameters.
        """
        src: torch.Tensor = convert_to_tensor(src, track_meta=False, wrap_sequence=True)
        try:
            return self.copy_(src, non_blocking=non_blocking)
        except RuntimeError:  # skip the shape checking
            self.data = src
            return self

    @property
    def array(self):
        """
        Returns a numpy array of ``self``. The array and ``self`` shares the same underlying storage if self is on cpu.
        Changes to ``self`` (it's a subclass of torch.Tensor) will be reflected in the ndarray and vice versa.
        If ``self`` is not on cpu, the call will move the array to cpu and then the storage is not shared.

        :getter: see also: :py:func:`MetaTensor.get_array()`
        :setter: see also: :py:func:`MetaTensor.set_array()`
        """
        return self.get_array()

    @array.setter
    def array(self, src) -> None:
        """A default setter using ``self.set_array()``"""
        self.set_array(src)

    def as_dict(self, key: str, output_type=torch.Tensor, dtype=None) -> dict:
        """
        Get the object as a dictionary for backwards compatibility.
        This method does not make a deep copy of the objects.

        Args:
            key: Base key to store main data. The key for the metadata will be determined using `PostFix`.
            output_type: `torch.Tensor` or `np.ndarray` for the main data.
            dtype: dtype of output data. Converted to correct library type (e.g.,
                `np.float32` is converted to `torch.float32` if output type is `torch.Tensor`).
                If left blank, it remains unchanged.

        Return:
            A dictionary consisting of three keys, the main data (stored under `key`) and the metadata.
        """
        if output_type not in (torch.Tensor, np.ndarray):
            raise ValueError(f"output_type must be torch.Tensor or np.ndarray, got {output_type}.")
        return {
            key: self.get_array(output_type=output_type, dtype=dtype),
            PostFix.meta(key): self.meta,
            PostFix.transforms(key): self.applied_operations,
        }

    def astype(self, dtype, device=None, *_args, **_kwargs):
        """
        Cast to ``dtype``, sharing data whenever possible.

        Args:
            dtype: dtypes such as np.float32, torch.float, "np.float32", float.
            device: the device if `dtype` is a torch data type.
            _args: additional args (currently unused).
            _kwargs: additional kwargs (currently unused).

        Returns:
            data array instance
        """
        if isinstance(dtype, str):
            mod_str, *dtype = dtype.split(".", 1)
            dtype = mod_str if not dtype else dtype[0]
        else:
            mod_str = getattr(dtype, "__module__", "torch")
        mod_str = look_up_option(mod_str, {"torch", "numpy", "np"}, default="numpy")
        if mod_str == "torch":
            out_type = torch.Tensor
        elif mod_str in ("numpy", "np"):
            out_type = np.ndarray
        else:
            out_type = None
        return self.get_array(output_type=out_type, dtype=dtype, device=device)

    @property
    def affine(self) -> torch.Tensor:
        """Get the affine. Defaults to ``torch.eye(4, dtype=torch.float64)``"""
        return self.meta.get(MetaKeys.AFFINE, self.get_default_affine())

    @affine.setter
    def affine(self, d: NdarrayTensor) -> None:
        """Set the affine."""
        self.meta[MetaKeys.AFFINE] = torch.as_tensor(d, device=torch.device("cpu"))

    @property
    def pixdim(self):
        """Get the spacing"""
        if self.is_batch:
            return [affine_to_spacing(a) for a in self.affine]
        return affine_to_spacing(self.affine)

    def peek_pending_shape(self):
        """Get the currently expected spatial shape as if all the pending operations are executed."""
        res = None
        if self.pending_operations:
            res = self.pending_operations[-1].get(LazyAttr.SHAPE, None)
        # default to spatial shape (assuming channel-first input)
        return tuple(convert_to_numpy(self.shape, wrap_sequence=True).tolist()[1:]) if res is None else res

    def peek_pending_affine(self):
        res = None
        if self.pending_operations:
            res = self.pending_operations[-1].get(LazyAttr.AFFINE, None)
        return self.affine if res is None else res

    def new_empty(self, size, dtype=None, device=None, requires_grad=False):
        """
        must be defined for deepcopy to work

        See:
            - https://pytorch.org/docs/stable/generated/torch.Tensor.new_empty.html#torch-tensor-new-empty
        """
        return type(self)(
            self.as_tensor().new_empty(size=size, dtype=dtype, device=device, requires_grad=requires_grad)
        )

    def clone(self):
        """returns a copy of the MetaTensor instance."""
        new_inst = MetaTensor(self.as_tensor().clone())
        new_inst.__dict__ = deepcopy(self.__dict__)
        return new_inst

    @staticmethod
    def ensure_torch_and_prune_meta(
        im: NdarrayTensor, meta: dict, simple_keys: bool = False, pattern: str | None = None, sep: str = "."
    ):
        """
        Convert the image to `torch.Tensor`. If `affine` is in the `meta` dictionary,
        convert that to `torch.Tensor`, too. Remove any superfluous metadata.

        Args:
            im: Input image (`np.ndarray` or `torch.Tensor`)
            meta: Metadata dictionary.
            simple_keys: whether to keep only a simple subset of metadata keys.
            pattern: combined with `sep`, a regular expression used to match and prune keys
                in the metadata (nested dictionary), default to None, no key deletion.
            sep: combined with `pattern`, used to match and delete keys in the metadata (nested dictionary).
                default is ".", see also :py:class:`monai.transforms.DeleteItemsd`.
                e.g. ``pattern=".*_code$", sep=" "`` removes any meta keys that ends with ``"_code"``.

        Returns:
            By default, a `MetaTensor` is returned.
            However, if `get_track_meta()` is `False`, a `torch.Tensor` is returned.
        """
        img = convert_to_tensor(im)  # potentially ascontiguousarray

        # if not tracking metadata, return `torch.Tensor`
        if not get_track_meta() or meta is None:
            return img

        # remove any superfluous metadata.
        if simple_keys:
            # ensure affine is of type `torch.Tensor`
            if MetaKeys.AFFINE in meta:
                meta[MetaKeys.AFFINE] = convert_to_tensor(meta[MetaKeys.AFFINE])  # bc-breaking
            remove_extra_metadata(meta)  # bc-breaking

        if pattern is not None:
            meta = monai.transforms.DeleteItemsd(keys=pattern, sep=sep, use_re=True)(meta)

        # return the `MetaTensor`
        return MetaTensor(img, meta=meta)

    def __repr__(self, *, tensor_contents=None):
        """
        Prints out a long representation of the MetaTensor object with metadata as well as content data.

        Args:
            tensor_contents: currently unused
        """
        return self.as_tensor().__repr__() + super().__repr__()

    def __str__(self):
        """
        Prints a simpler representation of the tensor identical to torch.Tensor.__str__.
        """
        return str(self.as_tensor())


text:
package edu.umass.ciir.kbbridge.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * Reads properties from a file in src/main/resources that is called with the following patterns (in that order)
 *
 * tacco<user>@<hostname>.properties
 *
 * tacco-<hostname>.properties
 *
 * tacco.properties
 */
public final class ConfigLoader {
    static final String resourcePath = "src/main/resources/";
    static final String project = "kbbridge";
    static final String username = System.getProperty("user.name","user");
    static final String manualProps = System.getProperty("kbbridge.props","");

    private static List<File> possibleFilenames() {
        String hostname;
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            hostname = "host";
        }
        // drop domain from hostname and lowercase
        int dotIdx = hostname.indexOf('.');
        if(dotIdx != -1) {
            hostname = hostname.substring(0, dotIdx).toLowerCase();
        }

        List<File> filenames = new ArrayList<File>();
        filenames.add(new File(resourcePath+project+".properties"));
        if(hostname.startsWith("compute")) {
            filenames.add(new File(resourcePath+project+"-blake.properties"));
        }
        filenames.add(new File(resourcePath+project+"-"+hostname+".properties"));
        if(hostname.startsWith("compute")) {
            filenames.add(new File( resourcePath+project+"-"+username+"@blake.properties"));
        }
        filenames.add(new File(resourcePath+project+"-"+username+"@"+hostname+".properties"));

        if(!manualProps.isEmpty()){
            filenames.add(new File(resourcePath+manualProps));
        }

        return(filenames);

    }

    private static void localReadProps(Properties properties, List<File> possibleFiles){
        Collections.reverse(possibleFiles);
        for (File propFile : possibleFiles) {
            System.out.println("try loading kbbridge loading properties: " + propFile);
            try {
                FileInputStream propStream = new FileInputStream(propFile);
                properties.load(propStream);
                System.out.println("...loaded from "+propFile);
                return;
            } catch (IOException e) {
                System.out.println("Unable to load file : " + propFile.getAbsolutePath() + " " + e.getMessage());
            }
        }

        throw new RuntimeException("Could not find property file for project "+project+". " +
                "Options (last preferred): "+  possibleFilenames()+
                "Local directory is "+(new File("").getAbsolutePath()));

    }
    public static Properties readProps() {
//        Properties properties = new Properties();
        Properties properties = System.getProperties();
        localReadProps(properties,possibleFilenames());
        return(properties);
    }

}

redpajama_set_name: RedPajamaGithub


text:
import {
    Claim, Prodline, ErrorType, ErrorDescriptionDim, Location,
    DiscardItem, DiscardItemPrint, EntityArray, EntityObj, User, Role, Permission, RolePermissionDim, RoleUserDim
} from '../shared/models';

export class BaseServiceInit {
    public entitySetting: EntityObj;
    defaultEntityLoadSettings(): EntityObj {
        // Pre-settings for loading stuff.
        this.entitySetting = new EntityObj();
        let claimsExpand = `&$expand=ErrorDescriptionDim($expand=ErrorDescription),` +
            `ErrorDescriptionDim($expand=ErrorType),Prodline,DiscardItem`;
        let rolePermisisonDimExpand = `&$expand=Role,Permission`;
        let claimsOrderBy = '&$orderby=ID desc';
        let prodlineOrderBy = '&$orderby=DESCRIPTION asc';
        let usersOrderBy = '&sort=created_at:-1';
        let discarditemsOrderBy = '&$orderby=ID desc';
        let errortypesOrderBy = '&$orderby=ID desc';
        let errordescriptiondimsExpand = '&$expand=ErrorDescription,ErrorInfoText,ErrorType';
        let expandDiscardItems = '&$expand=DiscardItem($expand=Claim)';
        let expandClaims = '&$expand=Claim';
        this.entitySetting.Claims.loadingSet =
            [{ apiName: 'ErrorDescriptionDims', name: 'errordescriptiondims', expand: errordescriptiondimsExpand, filter: false, defaultFilter: true },
            { apiName: 'ErrorTypes', name: 'errortypes', filter: false, defaultFilter: true },
            { apiName: 'Prodlines', orderBy: prodlineOrderBy, name: 'prodlines', filter: false, defaultFilter: true },
            { apiName: 'Locations', name: 'locations' },
            { apiName: 'Claims', name: 'claims', expand: claimsExpand, paging: true, orderBy: claimsOrderBy, count: true, filter: true },
            { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'Claims', name: 'claim', expand: claimsExpand, single: true, exclude: true }
            ];
        this.entitySetting.Claims.filterSet =
            [{ name: 'Error', colName: 'ERROR', dbName: 'ERRORDESCRIPTIONDIMID', type: 'errorComp', value: '' },
            { name: 'Date', colName: 'Date', dbName: 'CLAIMDATE', type: 'date' },
            { name: 'ID', colName: 'ID', dbName: 'ID', type: 'number', value: '' },
            {
                name: 'LINE', colName: 'ID', dbName: 'PRODLINEID', colToShow: ['DESCRIPTION'], type: 'select', value: ''
            },
            {
                name: 'LOCATION', colName: 'LOCATIONID', dbName: 'LOCATIONID',
                colToShow: ['DATAAREAID', 'INVENTLOCATIONID'], type: 'select', value: ''
            }];
        this.entitySetting.Claims.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'CLAIMDATE', desc: 'DATE' },
            { name: 'Prodline', desc: 'PRODLINE', expandProp: 'DESCRIPTION' },
            { name: 'ErrorDescriptionDim', desc: 'ERROR', expandProp: 'ErrorType', expandPropLevel2: 'ERRORTYPEDESCRIPTION' },
            { name: 'NUMBER', desc: 'Nr' },
            { name: 'CREATEDBY', desc: 'CREATEDBY' }];

        // ******************DISCARDITEMS****************** /

        this.entitySetting.DiscardItems.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            {
                apiName: 'DiscardItems', name: 'discarditems', expand: expandClaims,
                paging: true, orderBy: discarditemsOrderBy, count: true, filter: true
            },
            { apiName: 'DiscardItems', name: 'discarditem', expand: expandClaims, single: true, exclude: true }];
        this.entitySetting.DiscardItems.filterSet =
            [{
                name: 'LOCATION', colName: 'LOCATIONID', dbName: 'LOCATIONID',
                colToShow: ['DATAAREAID', 'INVENTLOCATIONID'], type: 'select', value: '',

            }, { name: 'EXTDISCARD', colName: 'EXTDISCARD', dbName: 'EXTDISCARD', type: 'checkbox', value: '' }]
        this.entitySetting.DiscardItems.colSet = [
            { name: 'ITEMID', desc: 'Itemid' },
            { name: 'NUMBER', desc: 'Number' }
        ];

        // ******************DISCARDITEMSPRINT****************** /

        this.entitySetting.DiscardItemPrints.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            { apiName: 'DiscardItems', name: 'discarditems', filter: true },
            {
                apiName: 'DiscardItemPrints', name: 'discarditemprints',
                paging: true, orderBy: discarditemsOrderBy, count: true, filter: true
            },
            { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'DiscardItemPrints', name: 'discarditemprint', expand: expandDiscardItems, single: true, exclude: true }];

        this.entitySetting.DiscardItemPrints.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'CREATED', desc: 'CREATED' },
            { name: 'CREATEDBY', desc: 'CREATEDBY' }];

        // ******************PRODLINES****************** /

        this.entitySetting.Prodlines.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            {
                apiName: 'Prodlines', name: 'prodlines', paging: true, orderBy: discarditemsOrderBy,
                count: true, filter: true
            }, { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'Prodlines', name: 'prodline', single: true, exclude: true }
            ];

        this.entitySetting.Prodlines.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'CREATED', desc: 'CREATED' },
            { name: 'CREATEDBY', desc: 'CREATEDBY' },
            { name: 'NAME', desc: 'NAME' },
            { name: 'DESCRIPTION', desc: 'DESCRIPTION' }];

        // ******************ERRORTYPES****************** /

        this.entitySetting.ErrorTypes.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            {
                apiName: 'ErrorTypes', name: 'errortypes', orderBy: errortypesOrderBy,
                count: true, filter: true
            }, { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'ErrorTypes', name: 'errortype', single: true, exclude: true }
            ];

        this.entitySetting.ErrorTypes.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'CREATED', desc: 'CREATED' },
            { name: 'CREATEDBY', desc: 'CREATEDBY' },
            { name: 'ITEMDEFECT', desc: 'ITEMDEFECT' },
            { name: 'ERRORTYPEDESCRIPTION', desc: 'ERRORTYPEDESCRIPTION' }];

        // ******************ERRORDESCRIPTION****************** /

        this.entitySetting.ErrorDescriptions.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            {
                apiName: 'ErrorDescriptions', name: 'errordescriptions', paging: true, orderBy: errortypesOrderBy,
                count: true, filter: true
            }, { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'ErrorDescriptions', name: 'errordescription', single: true, exclude: true }
            ];

        this.entitySetting.ErrorDescriptions.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'CREATED', desc: 'CREATED' },
            { name: 'CREATEDBY', desc: 'CREATEDBY' },
            { name: 'ERRORDESCRIPTIONTEXT', desc: 'ERRORDESCRIPTIONTEXT' }];

        // ******************ERRORDESCRIPTIONDIM****************** /

        this.entitySetting.ErrorDescriptionDims.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            { apiName: 'ErrorTypes', name: 'errortypes', filter: false },
            { apiName: 'ErrorInfoTexts', name: 'errorinfotexts', filter: false },
            { apiName: 'ErrorDescriptions', name: 'errordescriptions', filter: false },
            {
                apiName: 'ErrorDescriptionDims', name: 'errordescriptiondims', paging: true, orderBy: errortypesOrderBy,
                count: true, filter: true, expand: errordescriptiondimsExpand
            }, { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'ErrorDescriptionDims', name: 'errordescriptiondim', single: true, exclude: true }
            ];

        this.entitySetting.ErrorDescriptionDims.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'ErrorDescription', desc: 'ErrorDescription',expandProp:'ERRORDESCRIPTIONTEXT' },
            { name: 'ErrorType', desc: 'ErrorType',expandProp:'ERRORTYPEDESCRIPTION' },
            { name: 'ErrorInfoText', desc: 'ErrorInfoText',expandProp:'InfoText' }];

        // ******************ERRORINFOTEXT****************** /

        this.entitySetting.ErrorInfoTexts.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            {
                apiName: 'ErrorInfoTexts', name: 'errorinfotexts', paging: true, orderBy: errortypesOrderBy,
                count: true, filter: true
            }, { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'ErrorInfoTexts', name: 'errorinfotext', single: true, exclude: true }
            ];

        this.entitySetting.ErrorInfoTexts.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'CREATED', desc: 'CREATED' },
            { name: 'CREATEDBY', desc: 'CREATEDBY' },
            { name: 'InfoText', desc: 'InfoText' }];

        // ******************USERS****************** /

        this.entitySetting.Users.loadingSet =
            [{ apiName: 'Locations', name: 'locations' },
            { apiName: 'Users', name: 'users', loadFromUsersApi: true, paging: true, orderBy: usersOrderBy },
            { apiName: 'Users', name: 'user', loadFromUsersApi: true, single: true, exclude: true }
            ];

        this.entitySetting.Users.colSet = [
            { name: 'email', desc: 'UserId' },
            { name: 'user_metadata', desc: 'Firstname', expandProp: 'firstName' },
            { name: 'user_metadata', desc: 'Lastname', expandProp: 'lastName', }];

        // ******************Roles****************** /

        this.entitySetting.Roles.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'NAME', desc: 'NAME' },
        ];
        this.entitySetting.Roles.loadingSet = [
            { apiName: 'Locations', name: 'locations' },
            { apiName: 'Roles', name: 'roles', paging: true, orderBy: claimsOrderBy, count: true, },
            { apiName: 'Roles', name: 'role', single: true, exclude: true }
        ];

        // ******************Permissions****************** /

        this.entitySetting.Permissions.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'NAME', desc: 'NAME' },
        ];
        this.entitySetting.Permissions.loadingSet = [
            { apiName: 'Locations', name: 'locations' },
            { apiName: 'Permissions', name: 'permissions', paging: true, count: true, orderBy: claimsOrderBy, filter: true },
            { apiName: 'Permissions', name: 'permission', single: true, exclude: true }
        ];
        this.entitySetting.Permissions.filterSet =
            [];

        // ******************RolePermissionDims****************** /

        this.entitySetting.RolePermissionDims.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'Role', desc: 'ROLE', expandProp: 'NAME' },
            { name: 'Permission', desc: 'PERMISSION', expandProp: 'NAME' },
        ];

        this.entitySetting.RolePermissionDims.loadingSet = [
            { apiName: 'Locations', name: 'locations' },
            { apiName: 'Roles', name: 'roles' },
            { apiName: 'Permissions', name: 'permissions' },
            {
                apiName: 'RolePermissionDims', name: 'rolepermissiondims',
                expand: rolePermisisonDimExpand, paging: true, count: true, orderBy: claimsOrderBy, filter: true
            },
            { apiName: 'RolePermissionDims', name: 'rolepermissiondim', single: true, exclude: true }
        ];

        this.entitySetting.RolePermissionDims.filterSet =
            [];

        // ******************RoleUserDims****************** /

        this.entitySetting.RoleUserDims.colSet = [
            { name: 'ID', desc: 'ID' },
            { name: 'Role', desc: 'ROLE', expandProp: 'NAME' },
            { name: 'USERID', desc: 'USERID' },
        ];
        this.entitySetting.RoleUserDims.loadingSet = [
            { apiName: 'Users', name: 'users', loadFromUsersApi: true },
            { apiName: 'Locations', name: 'locations' },
            { apiName: 'Roles', name: 'roles' },
            { apiName: 'Permissions', name: 'permissions' },
            {
                apiName: 'RoleUserDims', name: 'roleuserdims',
                expand: '&$expand=Role', paging: true, count: true, orderBy: claimsOrderBy, filter: true
            },
            { apiName: 'RoleUserDims', name: 'roleuserdim', single: true, exclude: true }
        ];
        this.entitySetting.RoleUserDims.filterSet =
            [];
        // this.deleteGridSettings('Claims', 'loadingSet', 'name', 'users')
        return this.entitySetting;
    }
}


text:
<TITLE>Review for End of Days (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

End of Days (1999)

reviewed by
Lars Lindahl

By Lars Lindahl, High School Student
© 1999 Lars Lindahl
"End of Days" (1999)
Directed by Peter Hyams
Written by Andrew Marlowe
Starring Arnold Scwarzenegger, Gabriel Byrne, Kevin Pollak, Robin Tunney, Rod
Steiger, Miriam Margoyles, CCH Powder, Udo Kier

Grade: D

Well Arnold has completed the seemingly impossible task. He has made three
consecutive unsatisfactory action films. In a domain that he owns, it is very
surprising that this Goliath of an action star can not tell a good action
script from a bad one. Eraser, back in 1996, was a confused film that made no
attempt at all to make sense. Batman and Robin, in 1997, was the black sheep of
the Batman series with ridiculous acting, idiotic action scenes, and painfully
flashy costumes. Now in 1999, "End of Days" (not "The End of Days") is the
third strike in a tough at bat for Arnold. Is this the end of a powerful action
star's long-lived career? Will Arnold ever give us another unforgettable
performance in another unforgettable classic like those in the past
("Terminator", "Terminator 2: Judgement Day", "Predator")? Or an unforgettable
performance in a great guilty pleasure like those in the past ("Commando", "Red
Sonja", "True Lies")? It doesn't look that way.

"End of Days" begins with the birth of a baby girl in 1979 who inexorably, due
to the formation of the stars on that night, will be the carrier of Satan's
baby the hour before New Year's of 2000. Fortunately for the movie's sake, the
girl grows up and now resides in Manhattan with skyscrapers, subway trains in
dark tunnels, and a myriad of inept NYPD officers. It's an action film's dream
come true when the director is given tons of cool stuff to blow up. Imagine if
the girl had lived in Anytown, USA, where the only thing to destroy is a Dairy
Queen and a post office. Arnold Schwarzenegger (Jericho Cane), in a series of
boring events finds himself in the middle of a religious battle between the
church, who is trying to hide the girl (or in some cases trying to kill her),
and Satan (Gabriel Byrne) who is trying to make her pregnant. If the Devil is
successful, the world will no longer exist as we know it. Jericho feels it is
his duty to protect the girl from everyone because 1) he once had faith but no
longer does and 2) his wife and daughter were killed and he feels responsible
for it.

Jericho Cane is your cliched, by-the-numbers hero right up to his name. Arnold
fittingly plays the character as cliched as he can. He shouts at everyone, from
cops to priests, to the Devil. In one truly hilarious scene, which was supposed
to be the ultimate dramatic high point, Jericho screams to the Devil; "You are
a @#$^%!& choir boy! You are a choir boy!" Those two lines marked the high
points of this film.

A movie can still be enjoyable when the supporting cast is more effective than
the main actor. "End of Days" fails to contain any memorable performances with
the exception of Gabriel Byrne. Byrne, playing a man who has been made the
manifestation of the Devil, seems to be the only one who is having fun in this
whole movie. He wonderfully plays a manipulative villain with the power to
control everyone at any time. The annoying thing about his character, however,
is that he has the power to kill any human with a simple punch in the face, yet
he finds it impossible to seriously hurt Jericho. I can not count the number of
times he could have killed Jericho and taken the girl from his custody. The
other actors in the film give very weak and unconvincing performances. Kevin
Pollak, who plays the partner and close friend of Jericho, is the supposedly
funny character in the film (every action movie has one). The one problem is
that Pollak does not deliver one funny line. Robin Tunney plays the chosen
mother of Satan's baby with extreme annoyance. She gets no sympathy from any of
the characters in the film, except Arnold who pretends she is his wife and
daughter, or any of the viewers in the audience. In one unnecessary scene,
Tunney walks out of her room and takes her top off. Is this her job in the
film?

The actors are not to blame entirely because the script is terrible. You can
tell a script is terrible when you are able to predict what will happen minutes
before it does. This little prediction game is a very fun exception to trying
to sit through this nonsense of a movie. In a last attempt to make this movie
good, special effects are used to try to entertain the audience. But without a
memorable action scene in the whole film, the director has not done his job
successfully. This film would have gotten a C+ if Arnold stood in front of a
camera and shouted "You are a !$@^@*^ choir boy!!" for two hours.

© 1999 Lars Lindahl

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

namespace Comindware\Tracker\API\Service;

use Comindware\Tracker\API\Util\File\File;
use Psr\Http\Message\StreamInterface;

/**
 * Attachment service.
 *
 * @api
 * @since 0.1
 */
class AttachmentService extends Service
{
    /**
     * Get attached file content.
     *
     * @param string $revisionId {@see \Comindware\Tracker\API\Model\Attachment} revision ID.
     *
     * @return StreamInterface File content stream.
     *
     * @throws \Comindware\Tracker\API\Exception\RuntimeException In case of non-API errors.
     * @throws \Comindware\Tracker\API\Exception\WebApiClientException Ore one of descendants.
     * @throws \LogicException On internal errors.
     *
     * @since 0.2
     */
    public function getContent($revisionId)
    {
        return $this->client->sendRequest($this->getBase() . '/Content/' . $revisionId);
    }

    /**
     * Create {@see \Comindware\Tracker\API\Model\Attachment}.
     *
     * @param string $itemId {@see \Comindware\Tracker\API\Model\Item} ID.
     * @param File   $file   File to attach.
     *
     * @return string Created attachment ID.
     *
     * @throws \Comindware\Tracker\API\Exception\RuntimeException In case of non-API errors.
     * @throws \Comindware\Tracker\API\Exception\WebApiClientException Ore one of descendants.
     * @throws \LogicException On internal errors.
     *
     * @since 0.1
     */
    public function create($itemId, File $file)
    {
        return $this->client->sendRequest(
            $this->getBase() . '/' . $itemId,
            'POST',
            ['file' => $file]
        );
    }

    /**
     * Return base URI path.
     *
     * @return string
     *
     * @since 0.1
     */
    protected function getBase()
    {
        return '/Api/Attachment';
    }
}


text:
.class public final Lcom/tndev/common/R$id;
.super Ljava/lang/Object;
.source "SourceFile"

# static fields
.field public static final BalloonWrapper:I = 0x7f090026

.field public static final BtnApplyText:I = 0x7f09002b

.field public static final BtnBgColor:I = 0x7f090038

.field public static final BtnCancel:I = 0x7f090039

.field public static final BtnOK:I = 0x7f09003a

.field public static final BtnStrokeColor:I = 0x7f090037

.field public static final BtnTextColor:I = 0x7f09002d

.field public static final FontList:I = 0x7f090033

.field public static final LBL10:I = 0x7f090032

.field public static final Radio1:I = 0x7f09002f

.field public static final Radio2:I = 0x7f090030

.field public static final Radio3:I = 0x7f090031

.field public static final RadioElipse:I = 0x7f090029

.field public static final RadioGroup:I = 0x7f09002e

.field public static final RadioRectangle:I = 0x7f090028

.field public static final TailLengthSlider:I = 0x7f090034

.field public static final TailRotateSlider:I = 0x7f090036

.field public static final TailWidthSlider:I = 0x7f090035

.field public static final TextSizeSlider:I = 0x7f09002c

.field public static final TxtBalloonText:I = 0x7f09002a

.field public static final TypeRadioGroup:I = 0x7f090027

.field public static final back:I = 0x7f090046

.field public static final color_picker_view:I = 0x7f090023

.field public static final gameList:I = 0x7f090047

.field public static final imgGameLogo:I = 0x7f090041

.field public static final new_color_panel:I = 0x7f090025

.field public static final old_color_panel:I = 0x7f090024

.field public static final text1:I = 0x7f09003b

.field public static final txtGameDesc:I = 0x7f090043

.field public static final txtGameName:I = 0x7f090042

.field public static final txtTitle:I = 0x7f090045

# direct methods
.method public constructor <init>()V
    .registers 1

    .prologue
    .line 10
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
package us.nineworlds.xstreamer.ia.forms;

import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.ColumnLayout;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.ViewPart;

import us.nineworlds.xstreamer.eventbus.EventBus;
import us.nineworlds.xstreamer.ia.listeners.LoadMapImageSelectionListener;
import us.nineworlds.xstreamer.ia.lookup.SkirmishMapsLookup;

public class MapsFormPage extends ViewPart {

	protected FormToolkit toolkit;
	protected ScrolledForm form;
	private EventBus eventBus;
	protected ListViewer listViewer;

	public MapsFormPage() {
		super();
		eventBus = EventBus.getInstance();
		eventBus.register(this);
	}

	@Override
	public void createPartControl(Composite parent) {
		toolkit = new FormToolkit(parent.getDisplay());
		form = toolkit.createScrolledForm(parent);
		form.setText("Skirmish Maps");

		ColumnLayout layout = new ColumnLayout();
		form.getBody().setLayout(layout);

		createMapSection();

		getSite().setSelectionProvider(listViewer);
	}

	private void createMapSection() {
		Section mapSection = toolkit.createSection(form.getBody(),
				ExpandableComposite.TWISTIE | Section.DESCRIPTION | ExpandableComposite.TITLE_BAR);
		mapSection.setText("Skirmish Maps");

		mapSection.setExpanded(true);
		mapSection.setDescription("A list of available skirmish maps.");

		Composite mapComposite = toolkit.createComposite(mapSection);
		GridLayout squadGridLayout = new GridLayout();
		squadGridLayout.numColumns = 3;

		mapComposite.setLayout(squadGridLayout);

		listViewer = new ListViewer(mapComposite, SWT.WRAP | SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
		listViewer.add(SkirmishMapsLookup.getInstance().getMaps().toArray());
		listViewer.addSelectionChangedListener(new LoadMapImageSelectionListener());

		GridData mapSize = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 5);
		mapSize.minimumHeight = 300;
		mapSize.heightHint = 300;

		listViewer.getList().setLayoutData(mapSize);
		mapSection.setClient(mapComposite);
	}

	@Override
	public void setFocus() {
		form.setFocus();
	}
}


text:
package com.palantir.lock.client;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Streams;
import com.palantir.atlasdb.autobatch.Autobatchers;
import com.palantir.atlasdb.autobatch.BatchElement;
import com.palantir.atlasdb.autobatch.DisruptorAutobatcher;
import com.palantir.atlasdb.futures.AtlasFutures;
import com.palantir.atlasdb.timelock.api.GetCommitTimestampsResponse;
import com.palantir.lock.v2.LockToken;
import com.palantir.lock.watch.LockWatchCache;
import com.palantir.lock.watch.LockWatchVersion;
import com.palantir.lock.watch.TransactionUpdate;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import org.immutables.value.Value;

/**
 * This class batches getCommitTimestamps requests to TimeLock server for a single client/namespace.
 * */
final class BatchingCommitTimestampGetter implements CommitTimestampGetter {
    private final DisruptorAutobatcher<Request, Long> autobatcher;

    private BatchingCommitTimestampGetter(DisruptorAutobatcher<Request, Long> autobatcher) {
        this.autobatcher = autobatcher;
    }

    public static BatchingCommitTimestampGetter create(LockLeaseService leaseService, LockWatchCache cache) {
        DisruptorAutobatcher<Request, Long> autobatcher = Autobatchers.independent(consumer(leaseService, cache))
                .safeLoggablePurpose("get-commit-timestamp")
                .batchFunctionTimeout(Duration.ofSeconds(30))
                .build();
        return new BatchingCommitTimestampGetter(autobatcher);
    }

    @Override
    public long getCommitTimestamp(long startTs, LockToken commitLocksToken) {
        return AtlasFutures.getUnchecked(autobatcher.apply(ImmutableRequest.builder()
                .startTs(startTs)
                .commitLocksToken(commitLocksToken)
                .build()));
    }

    @VisibleForTesting
    static Consumer<List<BatchElement<Request, Long>>> consumer(LockLeaseService leaseService, LockWatchCache cache) {
        return batch -> {
            int count = batch.size();
            List<Long> commitTimestamps = new ArrayList<>();
            while (commitTimestamps.size() < count) {
                Optional<LockWatchVersion> requestedVersion =
                        cache.getEventCache().lastKnownVersion();
                GetCommitTimestampsResponse response =
                        leaseService.getCommitTimestamps(requestedVersion, count - commitTimestamps.size());
                commitTimestamps.addAll(process(batch.subList(commitTimestamps.size(), count), response, cache));
            }

            for (int i = 0; i < count; i++) {
                batch.get(i).result().set(commitTimestamps.get(i));
            }
        };
    }

    private static List<Long> process(
            List<BatchElement<Request, Long>> requests, GetCommitTimestampsResponse response, LockWatchCache cache) {
        List<Long> timestamps = LongStream.rangeClosed(response.getInclusiveLower(), response.getInclusiveUpper())
                .boxed()
                .collect(Collectors.toList());
        List<TransactionUpdate> transactionUpdates = Streams.zip(
                        timestamps.stream(), requests.stream(), (commitTs, batchElement) -> TransactionUpdate.builder()
                                .startTs(batchElement.argument().startTs())
                                .commitTs(commitTs)
                                .writesToken(batchElement.argument().commitLocksToken())
                                .build())
                .collect(Collectors.toList());
        cache.processCommitTimestampsUpdate(transactionUpdates, response.getLockWatchUpdate());
        return timestamps;
    }

    @Override
    public void close() {
        autobatcher.close();
    }

    @Value.Immutable
    interface Request {
        long startTs();

        LockToken commitLocksToken();
    }
}


text:
#ifndef _NPT_SOCKETS_H_
#define _NPT_SOCKETS_H_

/*----------------------------------------------------------------------
|   includes
+---------------------------------------------------------------------*/
#include "NptTypes.h"
#include "NptConstants.h"
#include "NptStreams.h"
#include "NptStrings.h"
#include "NptDataBuffer.h"
#include "NptNetwork.h"

/*----------------------------------------------------------------------
|   constants
+---------------------------------------------------------------------*/
const int NPT_ERROR_CONNECTION_RESET      = NPT_ERROR_BASE_SOCKET - 0;
const int NPT_ERROR_CONNECTION_ABORTED    = NPT_ERROR_BASE_SOCKET - 1;
const int NPT_ERROR_CONNECTION_REFUSED    = NPT_ERROR_BASE_SOCKET - 2;
const int NPT_ERROR_CONNECTION_FAILED     = NPT_ERROR_BASE_SOCKET - 3;
const int NPT_ERROR_HOST_UNKNOWN          = NPT_ERROR_BASE_SOCKET - 4;
const int NPT_ERROR_SOCKET_FAILED         = NPT_ERROR_BASE_SOCKET - 5;
const int NPT_ERROR_GETSOCKOPT_FAILED     = NPT_ERROR_BASE_SOCKET - 6;
const int NPT_ERROR_SETSOCKOPT_FAILED     = NPT_ERROR_BASE_SOCKET - 7;
const int NPT_ERROR_SOCKET_CONTROL_FAILED = NPT_ERROR_BASE_SOCKET - 8;
const int NPT_ERROR_BIND_FAILED           = NPT_ERROR_BASE_SOCKET - 9;
const int NPT_ERROR_LISTEN_FAILED         = NPT_ERROR_BASE_SOCKET - 10;
const int NPT_ERROR_ACCEPT_FAILED         = NPT_ERROR_BASE_SOCKET - 11;
const int NPT_ERROR_ADDRESS_IN_USE        = NPT_ERROR_BASE_SOCKET - 12;
const int NPT_ERROR_NETWORK_DOWN          = NPT_ERROR_BASE_SOCKET - 13;
const int NPT_ERROR_NETWORK_UNREACHABLE   = NPT_ERROR_BASE_SOCKET - 14;
const int NPT_ERROR_NOT_CONNECTED         = NPT_ERROR_BASE_SOCKET - 15;

const unsigned int NPT_SOCKET_FLAG_CANCELLABLE = 1; // make the socket cancellable

/*----------------------------------------------------------------------
|   forward references
+---------------------------------------------------------------------*/
class NPT_Socket;

/*----------------------------------------------------------------------
|   NPT_SocketAddress
+---------------------------------------------------------------------*/
class NPT_SocketAddress
{
public:
    // constructors and destructor
    NPT_SocketAddress() : m_Port(0) {}
    NPT_SocketAddress(const NPT_IpAddress& address, NPT_IpPort port) :
        m_IpAddress(address),
        m_Port(port) {}

    // methods
    NPT_Result SetIpAddress(const NPT_IpAddress& address) {
        m_IpAddress = address;
        return NPT_SUCCESS;
    }
    const NPT_IpAddress& GetIpAddress() const {
        return m_IpAddress;
    }
    NPT_Result SetPort(NPT_IpPort port) {
        m_Port = port;
        return NPT_SUCCESS;
    }
    NPT_IpPort GetPort() const {
        return m_Port;
    }
    NPT_String ToString() const;

    // operators
    bool operator==(const NPT_SocketAddress& other) const;

private:
    // members
    NPT_IpAddress m_IpAddress;
    NPT_IpPort    m_Port;
};

/*----------------------------------------------------------------------
|   NPT_SocketInfo
+---------------------------------------------------------------------*/
typedef struct {
    NPT_SocketAddress local_address;
    NPT_SocketAddress remote_address;
} NPT_SocketInfo;

/*----------------------------------------------------------------------
|   NPT_SocketInterface
+---------------------------------------------------------------------*/
class NPT_SocketInterface
{
 public:
    virtual ~NPT_SocketInterface() {}

    // interface methods
    virtual NPT_Result Bind(const NPT_SocketAddress& address, bool reuse_address = true) = 0;
    virtual NPT_Result Connect(const NPT_SocketAddress& address, NPT_Timeout timeout) = 0;
    virtual NPT_Result WaitForConnection(NPT_Timeout timeout) = 0;
    virtual NPT_Result GetInputStream(NPT_InputStreamReference& stream) = 0;
    virtual NPT_Result GetOutputStream(NPT_OutputStreamReference& stream) = 0;
    virtual NPT_Result GetInfo(NPT_SocketInfo& info) = 0;
    virtual NPT_Result SetReadTimeout(NPT_Timeout timeout) = 0;
    virtual NPT_Result SetWriteTimeout(NPT_Timeout timeout) = 0;
    virtual NPT_Result Cancel(bool shutdown=true) = 0;
};

/*----------------------------------------------------------------------
|   NPT_UdpSocketInterface
+---------------------------------------------------------------------*/
class NPT_UdpSocketInterface
{
 public:
    virtual ~NPT_UdpSocketInterface() {}

    // methods
    virtual NPT_Result Send(const NPT_DataBuffer&    packet,
                            const NPT_SocketAddress* address = NULL) = 0;
    virtual NPT_Result Receive(NPT_DataBuffer&    packet,
                               NPT_SocketAddress* address = NULL) = 0;
};

/*----------------------------------------------------------------------
|   NPT_UdpMulticastSocketInterface
+---------------------------------------------------------------------*/
class NPT_UdpMulticastSocketInterface
{
 public:
    virtual ~NPT_UdpMulticastSocketInterface() {}

    // methods
    virtual NPT_Result JoinGroup(const NPT_IpAddress& group,
                                 const NPT_IpAddress& iface) = 0;
    virtual NPT_Result LeaveGroup(const NPT_IpAddress& group,
                                  const NPT_IpAddress& iface) = 0;
    virtual NPT_Result SetTimeToLive(unsigned char ttl) = 0;
    virtual NPT_Result SetInterface(const NPT_IpAddress& iface) = 0;
};

/*----------------------------------------------------------------------
|   NPT_TcpServerSocketInterface
+---------------------------------------------------------------------*/
class NPT_TcpServerSocketInterface
{
 public:
    virtual ~NPT_TcpServerSocketInterface() {}

    // interface methods
    virtual NPT_Result Listen(unsigned int max_clients) = 0;
    virtual NPT_Result WaitForNewClient(NPT_Socket*& client,
                                        NPT_Timeout  timeout,
                                        NPT_Flags    flags) = 0;
};

/*----------------------------------------------------------------------
|   NPT_Socket
+---------------------------------------------------------------------*/
class NPT_Socket : public NPT_SocketInterface
{
public:
    // constructor and destructor
    explicit NPT_Socket(NPT_SocketInterface* delegate) : m_SocketDelegate(delegate) {}
    virtual ~NPT_Socket();

    // delegate NPT_SocketInterface methods
    NPT_Result Bind(const NPT_SocketAddress& address, bool reuse_address = true) {
        return m_SocketDelegate->Bind(address, reuse_address);
    }
    NPT_Result Connect(const NPT_SocketAddress& address,
                       NPT_Timeout timeout = NPT_TIMEOUT_INFINITE) {
       return m_SocketDelegate->Connect(address, timeout);
    }
    NPT_Result WaitForConnection(NPT_Timeout timeout = NPT_TIMEOUT_INFINITE) {
        return m_SocketDelegate->WaitForConnection(timeout);
    }
    NPT_Result GetInputStream(NPT_InputStreamReference& stream) {
        return m_SocketDelegate->GetInputStream(stream);
    }
    NPT_Result GetOutputStream(NPT_OutputStreamReference& stream) {
    return m_SocketDelegate->GetOutputStream(stream);
    }
    NPT_Result GetInfo(NPT_SocketInfo& info) {
        return m_SocketDelegate->GetInfo(info);
    }
    NPT_Result SetReadTimeout(NPT_Timeout timeout) {
        return m_SocketDelegate->SetReadTimeout(timeout);
    }
    NPT_Result SetWriteTimeout(NPT_Timeout timeout) {
        return m_SocketDelegate->SetWriteTimeout(timeout);
    }
    NPT_Result Cancel(bool shutdown=true) {
        return m_SocketDelegate->Cancel(shutdown);
    }

protected:
    // constructor
    NPT_Socket() {}

    // members
    NPT_SocketInterface* m_SocketDelegate;
};

typedef NPT_Reference<NPT_Socket> NPT_SocketReference;

/*----------------------------------------------------------------------
|   NPT_UdpSocket
+---------------------------------------------------------------------*/
class NPT_UdpSocket : public NPT_Socket,
                      public NPT_UdpSocketInterface
{
 public:
    // constructor and destructor
             NPT_UdpSocket(NPT_Flags flags=NPT_SOCKET_FLAG_CANCELLABLE);
    virtual ~NPT_UdpSocket();

    // delegate NPT_UdpSocketInterface methods
    NPT_Result Send(const NPT_DataBuffer&    packet,
                    const NPT_SocketAddress* address = NULL) {
        return m_UdpSocketDelegate->Send(packet, address);
    }
    NPT_Result Receive(NPT_DataBuffer&     packet,
                       NPT_SocketAddress*  address = NULL) {
        return m_UdpSocketDelegate->Receive(packet, address);
    }

protected:
    // constructor
    NPT_UdpSocket(NPT_UdpSocketInterface* delegate);

    // members
    NPT_UdpSocketInterface* m_UdpSocketDelegate;
};

/*----------------------------------------------------------------------
|   NPT_UdpMulticastSocket
+---------------------------------------------------------------------*/
class NPT_UdpMulticastSocket : public NPT_UdpSocket,
                               public NPT_UdpMulticastSocketInterface
{
public:
    // constructor and destructor
             NPT_UdpMulticastSocket(NPT_Flags flags=NPT_SOCKET_FLAG_CANCELLABLE);
    virtual ~NPT_UdpMulticastSocket();

    // delegate NPT_UdpMulticastSocketInterface methods
    NPT_Result JoinGroup(const NPT_IpAddress& group,
                         const NPT_IpAddress& iface =
                         NPT_IpAddress::Any) {
        return m_UdpMulticastSocketDelegate->JoinGroup(group, iface);
    }
    NPT_Result LeaveGroup(const NPT_IpAddress& group,
                          const NPT_IpAddress& iface =
                          NPT_IpAddress::Any) {
        return m_UdpMulticastSocketDelegate->LeaveGroup(group, iface);
    }
    NPT_Result SetTimeToLive(unsigned char ttl) {
        return m_UdpMulticastSocketDelegate->SetTimeToLive(ttl);
    }
    NPT_Result SetInterface(const NPT_IpAddress& iface) {
        return m_UdpMulticastSocketDelegate->SetInterface(iface);
    }

protected:
    // members
    NPT_UdpMulticastSocketInterface* m_UdpMulticastSocketDelegate;
};

/*----------------------------------------------------------------------
|   NPT_TcpClientSocket
+---------------------------------------------------------------------*/
class NPT_TcpClientSocket : public NPT_Socket
{
public:
    // constructors and destructor
             NPT_TcpClientSocket(NPT_Flags flags=NPT_SOCKET_FLAG_CANCELLABLE);
    virtual ~NPT_TcpClientSocket();
};

/*----------------------------------------------------------------------
|   NPT_TcpServerSocket
+---------------------------------------------------------------------*/
class NPT_TcpServerSocket : public NPT_Socket,
                            public NPT_TcpServerSocketInterface
{
public:
    // constructors and destructor
             NPT_TcpServerSocket(NPT_Flags flags=NPT_SOCKET_FLAG_CANCELLABLE);
    virtual ~NPT_TcpServerSocket();

    // delegate NPT_TcpServerSocketInterface methods
    NPT_Result Listen(unsigned int max_clients) {
        return m_TcpServerSocketDelegate->Listen(max_clients);
    }
    NPT_Result WaitForNewClient(NPT_Socket*& client,
                                NPT_Timeout  timeout = NPT_TIMEOUT_INFINITE,
                                NPT_Flags    flags = 0) {
        return m_TcpServerSocketDelegate->WaitForNewClient(client, timeout, flags);
    }

protected:
    // members
    NPT_TcpServerSocketInterface* m_TcpServerSocketDelegate;
};

#endif // _NPT_SOCKETS_H_


text:
/** Class: DefaultStrategy
 * The "daily use" <MouseStrategy>. The <CanvasWrapper> delegates handling of
 * native browser events to the specific methods of this <MouseStrategy>.
 *
 * Sequence Diagram:
 *     - http://www.websequencediagrams.com/?lz=dGl0bGUgTW91c2VTdHJhdGVneQoKVXNlci0-Q2FudmFzV3JhcHBlcjptb3VzZW1vdmUKAAsNLT5EZWZhdWx0ADYIACMGTW92ZWQoKQoADg8ARRBzZWFyY2hEZWVwZXN0V2lkZ2V0T25Qb3NpdGlvbgBaDwBYEiB3AC0FAFMSAEQGOiBkaXNwYXRjaDogAIE5BToAgToFAAUpZW50ZXIKAIEQBgBKCnN0b3AgYnViYmxpbmchACMreGl0AC0gAIJfG2RvdwCCARAAgmQWQnV0dG9uUHJlc3MAgW-BEwCBQgUAhEYadXAAgTkrUmVsZWEAUYEUdXAAgzMXY2xpY2sAgxsrQ2xpY2sAhTWBEwCBQwU&s=vs2010
 *
 * Inherits from:
 *     - <MouseStrategy>
 */
define(function(require, exports, module) {

	var MouseStrategy = require('./MouseStrategy');

	/** Constructor: DefaultStrategy()
	 * Creates a new instance of <DefaultStrategy>
	 */
	var DefaultStrategy = function DefaultStrategy(canvasWrapper) {

		/** PrivateMember: _self
		 * Keeps an internal reference on "this" for simplifying access to it.
		 */
		var _self = this;

		/** PrivateMember: _mouseOverWidgets
		 * To keep track on <Widget>s which have already dispatched a *mouse:enter*
		 * event, each of these gets added to this array. As soon as the user
		 * leaves the boundaries of such a <Widget>, it gets removed from here.
		 */
		var _mouseOverWidgets = [];

		/** PrivateMember: _dragndropData
		 * This object keeps several information about the status of the drag
		 * and drop initialisation.
		 */
		var _dragndropData = {
			mouseButtonPressed : false
			,mouseButtonPressedStartPosition : { left: 0, top: 0}
			,startThreshold : 2
			,started : false
		};

		MouseStrategy.call(this, canvasWrapper);

		/** Function: mouseMoved(absolutePosition)
		 * The <mouseMoved(absolutePosition)> method does three things during
		 * mouse movements:
		 *
		 * Drag And Drop Start:
		 * If the user moves the mouse during a mouse button is pressed down,
		 * the distance from the initial mouse down location and the current
		 * location is calculated. If the absolute value of this distance
		 * exceeds a threshold, <DefaultStrategy> emits a *defaultstrategy:startDrag*
		 * event which is usually catched by the <CanvasWrapper> for further
		 * processing.
		 *
		 * Dispatch Mouse Movement and Mouse Enter:
		 * The deepest <Widget> at the current location gets searched via
		 * <CanvasWrapper.searchDeepestWidgetOnPosition(absolutePosition)>. If
		 * a <Widget> was found, a *mouse:move* event gets emitted for dispatching.
		 * If the <Widget> is further not already contained in the _mouseOverWidgets
		 * array, it gets pushed to it and a *mouse:enter* event is dispatched
		 * by the <Widget>.
		 *
		 * Dispatch Mouse Exit:
		 * The last step is to inform <Widget>s which are not anymore beneath
		 * the cursor via a *mouse:exit* event.
		 *
		 * Parameters:
		 *     (Object) absolutePosition - { left: ?, top: ? }
		 */
		_self.mouseMoved = function mouseMoved(absolutePosition) {
			var canvasWrapper = _self.getCanvasWrapper();
			var deepestWidget = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);

			/* DragAndDrop: */
			if(_dragndropData.mouseButtonPressed && !_dragndropData.started) {
				var start = _dragndropData.mouseButtonPressedStartPosition;
				var distanceX = Math.abs(absolutePosition.left) - Math.abs(start.left);
				var distanceY = Math.abs(absolutePosition.top) - Math.abs(start.top);
				var distance = Math.sqrt(Math.pow(distanceX,2) + Math.pow(distanceY,2),2);

				if(distance >= _dragndropData.startThreshold) {
					_dragndropData.started = true;
					_self.emit('defaultstrategy:startdrag', absolutePosition);
				}
			}

			/* mouse:move & mouse:enter: */
			if(deepestWidget) {
				deepestWidget.dispatchEvent('mouse:move', {absolutePosition:absolutePosition});

				if(_mouseOverWidgets.indexOf(deepestWidget) === -1) {
					_mouseOverWidgets.push(deepestWidget);
					deepestWidget.dispatchEvent('mouse:enter', {absolutePosition: absolutePosition});
				}
			}

			/* mouse:exit: */
			canvasWrapper.searchWidgetsOnPosition(absolutePosition,undefined
				,function notFound(widget) {
					var index = _mouseOverWidgets.indexOf(widget);
					if(widget !== deepestWidget && index > -1) {
						_mouseOverWidgets.splice(index,1);
						widget.dispatchEvent('mouse:exit', {absolutePosition: absolutePosition});
					}
				}
			);
		};

		/** Function: mouseButtonPressed(button, absolutePosition)
		 * Looks for the deepest <Widget> at the given position and emits a
		 * *mouse:down* event for dispatching.
		 *
		 * Parameters:
		 *     (int) button
		 *     (Object) absolutePosition - { left: ?, top: ? }
		 */
		_self.mouseButtonPressed = function mouseButtonPressed(button, absolutePosition) {
			var canvasWrapper = _self.getCanvasWrapper();
			var deepestWidget = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);

			_dragndropData.mouseButtonPressed = true;
			_dragndropData.mouseButtonPressedStartPosition = absolutePosition;

			if(deepestWidget) {
				deepestWidget.dispatchEvent('mouse:down', {button:button, absolutePosition: absolutePosition});
			}
		};

		/** Function: mouseButtonReleased(button, absolutePosition)
		 * Looks for the deepest <Widget> at the given position and emits a
		 * *mouse:up* event for dispatching.
		 *
		 * Parameters:
		 *     (int) button
		 *     (Object) absolutePosition - { left: ?, top: ? }
		 */
		_self.mouseButtonReleased = function mouseButtonReleased(button, absolutePosition) {
			var canvasWrapper = _self.getCanvasWrapper();
			var deepestWidget = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);

			_dragndropData.mouseButtonPressed = false;

			if(deepestWidget) {
				deepestWidget.dispatchEvent('mouse:up', {button:button, absolutePosition: absolutePosition});
			}
		};

		/** Function: mouseClicked(button, absolutePosition)
		 * Looks for the deepest <Widget> at the given position and emits a
		 * *mouse:click* event for dispatching.
		 *
		 * Parameters:
		 *     (int) button
		 *     (Object) absolutePosition - { left: ?, top: ? }
		 */
		_self.mouseButtonClicked = function mouseButtonClicked(button, absolutePosition) {
			var canvasWrapper = _self.getCanvasWrapper();
			var deepestWidget = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);

			if(deepestWidget) {
				deepestWidget.dispatchEvent('mouse:click', {button:button, absolutePosition: absolutePosition});
			}
		};

	};

	DefaultStrategy.prototype = Object.create(MouseStrategy.prototype);
	DefaultStrategy.prototype.constructor = DefaultStrategy;

	return DefaultStrategy;
});


text:
MEDUSA_SCRIPT_BINDING_BEGIN;
bool Register_INode(IEventArg& e);
bool Register_ILayer(IEventArg& e);
bool Register_IScene(IEventArg& e);
bool Register_NormalLayer(IEventArg& e);
bool Register_Sprite(IEventArg& e);
bool Register_UIScene(IEventArg& e);

MEDUSA_SCRIPT_BINDING_END;

#endif


text:
module Domgen
  class Build
    def self.define_generate_xmi_task(options = {}, &block)
      buildr_project = options[:buildr_project]

      if buildr_project.nil? && Buildr.application.current_scope.size > 0
        buildr_project = Buildr.project(Buildr.application.current_scope.join(':')) rescue nil
      end

      Domgen::Xmi::GenerateXMITask.new(options[:repository_key], options[:key], options[:filename], buildr_project, &block)
    end
  end

  module Xmi
    class GenerateXMITask
      attr_accessor :description
      attr_accessor :namespace_key

      attr_reader :repository_key
      attr_reader :key
      attr_reader :filename

      attr_reader :task_name

      def initialize(repository_key = nil, key = nil, filename = nil, buildr_project = nil)
        @repository_key, @filename, @buildr_project = repository_key, filename, buildr_project
        @key = key || :xmi
        @namespace_key = :domgen
        yield self if block_given?
        define
      end

      private

      def full_task_name
        "#{self.namespace_key}:#{self.key}"
      end

      def define
        # Need to init emf now otherwise Buildr will not have jars loaded into classpath
        namespace self.namespace_key do
          desc self.description || "Generates the #{key} xmi artifacts."
          t = task self.key => ["#{self.namespace_key}:load"] do
            begin
              Domgen::Xmi.init_emf

              if self.repository_key
                repository = Domgen.repository_by_name(self.repository_key)
                if Domgen.repositories.size == 1
                  Domgen.warn("Domgen task #{full_task_name} specifies a repository_key parameter but it can be be derived as there is only a single repository. The parameter should be removed.")
                end
              elsif self.repository_key.nil?
                repositories = Domgen.repositories
                if repositories.size == 1
                  repository = repositories[0]
                else
                  Domgen.error("Domgen task #{full_task_name} does not specify a repository_key parameter and it can not be derived. Candidate repositories include #{repositories.collect { |r| r.name }.inspect}")
                end
              end

              filename = self.filename

              if filename.nil?
                local_filename = "#{Reality::Naming.underscore(repository.name)}.xmi"
                if @buildr_project.nil?
                  top_level_projects = Buildr.projects.select{|p| !(p.name =~ /:/) }
                  if top_level_projects.size == 1
                    filename = top_level_projects[0]._(:reports, 'domgen', local_filename)
                  end
                else
                  filename = @buildr_project._(:reports, 'domgen', local_filename)
                end
              end

              if filename.nil?
                Domgen.error('Domgen::Build.define_generate_xmi_task should specify a filename as it can not be derived from the context.')
              end

              FileUtils.mkdir_p File.dirname(filename)
              Domgen::Xmi.generate_xmi(repository.name, filename)
            rescue Exception => e
              print "An error occurred generating the xmi\n"
              puts $!
              puts $@
              raise e
            end
          end
          @task_name = t.name
        end
      end
    end

    def self.get_static_field_value(classname, field)
      ::Java.java.lang.Thread.currentThread.getContextClassLoader.loadClass(classname).getField(field).get(nil)
    end

    def self.generate_xmi(repository_key, filename)
      repository = Domgen.repository_by_name(repository_key)

      output_file = ::Java.java.io.File.new(filename).getAbsolutePath()

      registry = get_static_field_value('org.eclipse.emf.ecore.resource.Resource$Factory$Registry', 'INSTANCE')
      umlResource = get_static_field_value('org.eclipse.uml2.uml.resource.UMLResource$Factory', 'INSTANCE')
      ak_NONE_LITERAL = get_static_field_value('org.eclipse.uml2.uml.AggregationKind', 'NONE_LITERAL')
      ak_SHARED_LITERAL = get_static_field_value('org.eclipse.uml2.uml.AggregationKind', 'SHARED_LITERAL')
      ak_COMPOSITE_LITERAL = get_static_field_value('org.eclipse.uml2.uml.AggregationKind', 'COMPOSITE_LITERAL')
      lit_UNLIMITED = get_static_field_value('org.eclipse.uml2.uml.LiteralUnlimitedNatural', 'UNLIMITED')

      registry.getExtensionToFactoryMap().put(File.extname(output_file).gsub('.', ''), umlResource)

      model = ::Java.org.eclipse.uml2.uml.UMLFactory.eINSTANCE.createModel()
      model.setName(repository.name.to_s)

      output_uri = ::Java.org.eclipse.emf.common.util.URI.createFileURI(output_file)
      puts "Creating XMI for repository #{repository_key} at #{output_file}"
      resource = ::Java.org.eclipse.emf.ecore.resource.impl.ResourceSetImpl.new.create_resource(output_uri)
      resource.getContents().add(model)
      name(resource, model, repository)
      describe(model, repository)

      # As we process the schema set, we put all the packages that we discover inside this array
      # This is a map between package names and EMF package classes
      packages = {}

      # As we process the schema set, we put all the primitive types that we discover inside this map
      # This is a map between DB types to EMF primitive types
      primitive_types = {}

      # A map from fully qualified class names to EMF classes
      name_2_emf_map = {}

      # Phase 1: Package, primitive type, and enumeration type discovery.
      # Primitive types will be added to the top-level model but enumeration types
      # will be added to the package they belong to.
      #
      repository.data_modules.each do |data_module|
        package = model.createNestedPackage(data_module.name.to_s)
        name(resource, package, data_module)
        describe(package, data_module)

        packages[data_module.name] = package

        data_module.enumerations.each do |enumeration|
          enum = package.createOwnedEnumeration(enumeration.name.to_s)
          enumeration.values.each do |enum_literal|
            literal = enum.create_owned_literal(enum_literal.name)
            resource.setID(literal, "#{enumeration.qualified_name}.#{enum_literal.name}")
          end
          name(resource, enum, enumeration)
          describe(enum, enumeration)
          name_2_emf_map[enumeration.qualified_name] = enum
        end

        data_module.entities.each do |entity|
          entity.attributes.each do |attribute|
            if !attribute.reference?
              pn = primitive_name(attribute.attribute_type)
              if !primitive_types[pn]
                primitive_type = model.createOwnedPrimitiveType(pn)
                resource.setID(primitive_type, pn)
                primitive_types[pn] = primitive_type
              end
            end
          end
        end
      end

      # Phase 2: Class and association discovery. In this phase, we process the schema set and create a class
      # per each schema.
      repository.data_modules.each do |data_module|
        data_module.entities.each do |entity|
          package = packages[data_module.name]
          clazz = package.createOwnedClass(entity.name.to_s, false)
          name(resource, clazz, entity)
          describe(clazz, entity)
          name_2_emf_map[entity.qualified_name] ||= clazz
          entity.attributes.each do |attribute|
            define_attribute(resource, name_2_emf_map, primitive_types, clazz, attribute)
          end
        end
      end

      repository.data_modules.each do |data_module|
        data_module.structs.each do |struct|
          package = packages[data_module.name]
          clazz = package.createOwnedClass(struct.name.to_s, false)
          name(resource, clazz, struct)
          describe(clazz, struct)
          name_2_emf_map[struct.qualified_name] ||= clazz

          # Creating EMF attributes for each field
          struct.fields.each do |field|
            define_attribute(resource, name_2_emf_map, primitive_types, clazz, field)
          end
        end
      end

      # Phase 3: Association building. In this phase, we process the schema set and create EMF associations
      # corresponding to the references defined in it.
      repository.data_modules.each do |data_module|
        data_module.entities.each do |entity|
          entity.attributes.select { |attribute| attribute.reference? }.each do |attribute|
            end1 = name_2_emf_map[attribute.entity.qualified_name]
            end2 = name_2_emf_map[attribute.referenced_entity.qualified_name]
            name = attribute.name == attribute.referenced_entity.name ? '' : attribute.name.to_s

            aggregation_kind = ak_NONE_LITERAL
            aggregation_kind = ak_SHARED_LITERAL if attribute.inverse.relationship_kind == :aggregation
            aggregation_kind = ak_COMPOSITE_LITERAL if attribute.inverse.relationship_kind == :composition

            createAssociation = end1.getClass().getMethods().find{|m| m.getName() == 'createAssociation' }

            emf_association = createAssociation.invoke(end1,
                                                       [true,
                                                     aggregation_kind,
                                                     name,
                                                     attribute.nullable? ? 0 : 1,
                                                     1,
                                                     end2,
                                                     attribute.inverse.traversable?,
                                                     ak_NONE_LITERAL,
                                                     '',
                                                     0,
                                                     attribute.inverse.multiplicity == :many ? lit_UNLIMITED : 1])
            resource.setID(emf_association, attribute.qualified_name.to_s + '.Assoc')
            describe(emf_association, attribute)
          end
        end
      end

      # Phase 4: Service creation. In this phase, we process the repository and create a class or each service.
      repository.data_modules.each do |data_module|
        data_module.services.each do |service|
          package = packages[data_module.name]
          clazz = package.createOwnedClass(service.name.to_s, false)
          name(resource, clazz, service)
          describe(clazz, service)
          name_2_emf_map[service.qualified_name] ||= clazz

          service.methods.each do |method|
            names = ::Java.org.eclipse.emf.common.util.BasicEList.new(method.parameters.size)
            types = ::Java.org.eclipse.emf.common.util.BasicEList.new(method.parameters.size)

            method.parameters.each do |characteristic|
              names.add(characteristic.name.to_s)
              types.add(characteristic_type(name_2_emf_map, primitive_types, characteristic))
            end

            operation = if method.return_value.return_type != :void
              emf_type = characteristic_type(name_2_emf_map, primitive_types, method.return_value)
              clazz.createOwnedOperation(method.name.to_s, names, types, emf_type)
            else
              clazz.createOwnedOperation(method.name.to_s, names, types)
            end
            name(resource, operation, method)
            describe(operation, method)
          end
        end
      end

      # Phase 5: Message creation.
      repository.data_modules.each do |data_module|
        package = packages[data_module.name]
        data_module.messages.each do |message|
          msg_class_name = "#{message.name}Message"
          emf_class = package.createOwnedClass(msg_class_name, false)
          name(resource, emf_class, message)
          describe(emf_class, message)
          name_2_emf_map[message.qualified_name.to_s] ||= emf_class

          message.parameters.each do |parameter|
            define_attribute(resource, name_2_emf_map, primitive_types, emf_class, parameter)
          end
        end
      end

      resource.save(nil)

    end

    private

    @@init_emf = false

    def self.init_emf
      return if @@init_emf == true
      @@init_emf = true
      Buildr.artifacts(::Domgen::Xmi.dependencies).each do |artifact|
        artifact.invoke
        ::Java.classpath << artifact.to_s
      end
    end

    def self.dependencies
      [
        'org.eclipse.uml2:org.eclipse.uml2.uml:jar:3.1.0.v201006071150',
        'org.eclipse.uml2:org.eclipse.uml2.uml.resources:jar:3.1.0.v201005031530',
        'org.eclipse.uml2:org.eclipse.uml2.common:jar:1.5.0.v201005031530',
        'org.eclipse.emf:org.eclipse.emf.ecore:jar:2.6.0.v20100614-1136',
        'org.eclipse.emf:org.eclipse.emf.common:jar:2.6.0.v20100614-1136',
        'org.eclipse.emf:org.eclipse.emf.mapping.ecore2xml:jar:2.5.0.v20100521-1847',
        'org.eclipse.emf:org.eclipse.emf.ecore.xmi:jar:2.5.0.v20100521-1846',
      ]
    end

    def self.primitive_name(attribute_type)
      return 'string' if attribute_type == :text
      return 'int' if attribute_type == :integer
      return 'long' if attribute_type == :long
      return attribute_type.to_s
    end

    def self.define_attribute(resource, name_2_emf_map, primitive_types, emf_clazz, characteristic)
      emf_type = characteristic_type(name_2_emf_map, primitive_types, characteristic)
      emf_attr = emf_clazz.createOwnedAttribute(characteristic.name.to_s, emf_type)
      name(resource, emf_attr, characteristic)
      describe(emf_attr, characteristic)
    end

    def self.characteristic_type(name_2_emf_map, primitive_types, characteristic)
      if characteristic.enumeration?
        name_2_emf_map[characteristic.enumeration.qualified_name]
      elsif characteristic.struct?
        name_2_emf_map[characteristic.referenced_struct.qualified_name]
      else
        characteristic_type =
          characteristic.reference? ? characteristic.referenced_entity.primary_key.characteristic_type_key : characteristic.characteristic_type_key
        primitive_types[primitive_name(characteristic_type)]
      end
    end

    def self.name(resource, emf_element, domgen_element)
      resource.setID(emf_element, domgen_element.qualified_name.to_s)
    end

    def self.describe(emf_element, domgen_element)
      description = domgen_element.tag_as_html(:Description)
      if description
        emf_element.createOwnedComment().setBody(description)
      end
    end
  end
end


text:
namespace AngleSharp.Core.Tests.Xml
{
    using AngleSharp.Parser.Xml;
    using NUnit.Framework;

    [TestFixture]
    public class XmlTree
    {
        [Test]
        public void XmlValidDocumentWithoutDocType()
        {
            var xml = (@"<?xml version=""1.0"" encoding=""ISO-8859-1""?>

<note>
	<to>Tove</to>
	<from>Jani</from>
	<heading>Reminder</heading>
	Don't forget me this weekend!
</note>").ToXmlDocument();

            Assert.IsNotNull(xml);
            Assert.IsNotNull(xml.DocumentElement);
            Assert.AreEqual("note", xml.DocumentElement.TagName);
            Assert.AreEqual(4, xml.DocumentElement.ChildElementCount);
            Assert.AreEqual(4, xml.DocumentElement.Children.Length);
            Assert.AreEqual("to", xml.DocumentElement.Children[0].TagName);
            Assert.AreEqual("from", xml.DocumentElement.Children[1].TagName);
            Assert.AreEqual("heading", xml.DocumentElement.Children[2].TagName);
            Assert.AreEqual("body", xml.DocumentElement.Children[3].TagName);
        }

        [Test]
        [ExpectedException(typeof(XmlParseException))]
        public void XmlInvalidDocumentMismatchedEndTag()
        {
            var xml = (@"<?xml version=""1.0"" encoding=""ISO-8859-1""?>

<note>
	<to>Tove</to>
	<from>Jani</Ffrom>
	<heading>Reminder</heading>
	Don't forget me this weekend!
</note>").ToXmlDocument();
        }

        [Test]
        public void XmlValidDocumentFoodMenuInnerHTML()
        {
            var xml = Assets.food.ToXmlDocument();

            Assert.IsNotNull(xml);
            Assert.IsNotNull(xml.DocumentElement);
            Assert.AreEqual("breakfast_menu", xml.DocumentElement.TagName);
            Assert.AreEqual(5, xml.DocumentElement.ChildElementCount);
            Assert.AreEqual(5, xml.DocumentElement.Children.Length);
            Assert.AreEqual("food", xml.DocumentElement.Children[0].TagName);
            Assert.AreEqual(4, xml.DocumentElement.Children[0].Children.Length);
            Assert.AreEqual("name", xml.DocumentElement.Children[0].Children[0].TagName);
            Assert.AreEqual("$5.95", xml.DocumentElement.Children[0].Children[1].InnerHtml);
            Assert.AreEqual("$7.95", xml.DocumentElement.Children[1].Children[1].InnerHtml);
        }

        [Test]
        public void XmlValidDocumentBooksTree()
        {
            var xml = Assets.books.ToXmlDocument();

            Assert.IsNotNull(xml);
            Assert.IsNotNull(xml.DocumentElement);
            Assert.AreEqual("catalog", xml.DocumentElement.TagName);
            Assert.AreEqual(12, xml.DocumentElement.ChildElementCount);
            Assert.AreEqual(6, xml.DocumentElement.Children[2].ChildElementCount);
        }
    }
}


text:
class AddSelfManagedPrometheusAlerts < ActiveRecord::Migration[5.2]
  # Set this constant to true if this migration requires downtime.
  DOWNTIME = false

  def change
    create_table :self_managed_prometheus_alert_events do |t|
      t.references :project, index: false, foreign_key: { on_delete: :cascade }, null: false
      t.references :environment, index: true, foreign_key: { on_delete: :cascade }
      t.datetime_with_timezone :started_at, null: false
      t.datetime_with_timezone :ended_at

      t.integer :status, null: false, limit: 2
      t.string :title, null: false, limit: 255
      t.string :query_expression, limit: 255
      t.string :payload_key, null: false, limit: 255
      t.index [:project_id, :payload_key], unique: true, name: 'idx_project_id_payload_key_self_managed_prometheus_alert_events'
    end
  end
end


text:
"""Copyright 2013 Google Inc. All Rights Reserved.

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.
"""

import unittest

from pinject import provider_indirections

class ProviderIndirectionTest(unittest.TestCase):

    def test_returns_provider_fn(self):
        provide_fn = provider_indirections.INDIRECTION.StripIndirectionIfNeeded(
            lambda: 'provided-thing')
        self.assertEqual('provided-thing', provide_fn())

class NoProviderIndirectionTest(unittest.TestCase):

    def test_returns_provided_thing(self):
        self.assertEqual(
            'provided-thing',
            provider_indirections.NO_INDIRECTION.StripIndirectionIfNeeded(
                lambda: 'provided-thing'))


text:
using System;

namespace Northwind.Repository.Models
{
    public class CustomerOrder
    {
        public string CustomerId { get; set; }
        public string ContactName { get; set; }
        public int OrderId { get; set; }
        public DateTime? OrderDate { get; set; }
    }
}


text:
/* eslint-disable */

'use strict';

// @dataDrivenDependency RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name.user.innerRenderer {"branches":{"PlainUserNameRenderer":{"component":"PlainUserNameRenderer.react","fragment":"RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestPlainUserNameRenderer_name$normalization.graphql"}},"plural":false}

/*::
import type { Fragment, ReaderFragment } from 'relay-runtime';
type RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestPlainUserNameRenderer_name$fragmentType = any;
import type { FragmentType } from "relay-runtime";
declare export opaque type RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$fragmentType: FragmentType;
export type RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$data = {|
  +markdown: ?string,
  +user: ?{|
    +name: ?string,
    +innerRenderer: ?{|
      +__fragmentPropName?: ?string,
      +__module_component?: ?string,
      +$fragmentSpreads: RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestPlainUserNameRenderer_name$fragmentType,
    |},
  |},
  +__typename: "MarkdownUserNameRenderer",
  +$fragmentType: RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$fragmentType,
|};
export type RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$key = {
  +$data?: RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$data,
  +$fragmentSpreads: RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$fragmentType,
  ...
};
*/

var node/*: ReaderFragment*/ = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "__typename",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "markdown",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": "User",
      "kind": "LinkedField",
      "name": "user",
      "plural": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "name",
          "storageKey": null
        },
        {
          "alias": "innerRenderer",
          "args": null,
          "concreteType": null,
          "kind": "LinkedField",
          "name": "nameRenderer",
          "plural": false,
          "selections": [
            {
              "kind": "InlineFragment",
              "selections": [
                {
                  "args": null,
                  "documentName": "RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name",
                  "fragmentName": "RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestPlainUserNameRenderer_name",
                  "fragmentPropName": "name",
                  "kind": "ModuleImport"
                }
              ],
              "type": "PlainUserNameRenderer",
              "abstractKey": null
            }
          ],
          "storageKey": null
        }
      ],
      "storageKey": null
    }
  ],
  "type": "MarkdownUserNameRenderer",
  "abstractKey": null
};

if (__DEV__) {
  (node/*: any*/).hash = "e1edea1a63722ab6ea297694773c329c";
}

module.exports = ((node/*: any*/)/*: Fragment<
  RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$fragmentType,
  RelayModernEnvironmentExecuteWithSiblingAndNestedModuleTestMarkdownUserNameRenderer_name$data,
>*/);


text:
using BibleNote.Common.Exceptions;

namespace BibleNote.Services.ModulesManager.Models.Exceptions
{
    public class BaseVersePointerException : BusinessException
    {
        public enum Severity
        {
            Warning,
            Error
        }

        public Severity Level { get; set; }

        public bool IsChapterException { get; set; }

        public BaseVersePointerException(string message, Severity level)
            : base(message)
        {
            this.Level = level;
        }
    }
}