text:
module System.Console.Haskeline.Key(Key(..),
            Modifier(..),
            BaseKey(..),
            noModifier,
            simpleKey,
            simpleChar,
            metaChar,
            ctrlChar,
            metaKey,
            ctrlKey,
            parseKey
            ) where

import Data.Char
import Control.Monad
import Data.Maybe
import Data.Bits

data Key = Key Modifier BaseKey
            deriving (Show,Eq,Ord)

data Modifier = Modifier {hasControl, hasMeta, hasShift :: Bool}
            deriving (Eq,Ord)

instance Show Modifier where
    show m = show $ catMaybes [maybeUse hasControl "ctrl"
                        , maybeUse hasMeta "meta"
                        , maybeUse hasShift "shift"
                        ]
        where
            maybeUse f str = if f m then Just str else Nothing

noModifier :: Modifier
noModifier = Modifier False False False

data BaseKey = KeyChar Char
             | FunKey Int
             | LeftKey | RightKey | DownKey | UpKey
             -- TODO: is KillLine really a key?
             | KillLine | Home | End | PageDown | PageUp
             | Backspace | Delete
            deriving (Show,Eq,Ord)

simpleKey :: BaseKey -> Key
simpleKey = Key noModifier

metaKey :: Key -> Key
metaKey (Key m bc) = Key m {hasMeta = True} bc

ctrlKey :: Key -> Key
ctrlKey (Key m bc) = Key m {hasControl = True} bc

simpleChar, metaChar, ctrlChar :: Char -> Key
simpleChar = simpleKey . KeyChar
metaChar = metaKey . simpleChar

ctrlChar = simpleChar . setControlBits

setControlBits :: Char -> Char
setControlBits '?' = toEnum 127
setControlBits c = toEnum $ fromEnum c .&. complement (bit 5 .|. bit 6)

specialKeys :: [(String,BaseKey)]
specialKeys = [("left",LeftKey)
              ,("right",RightKey)
              ,("down",DownKey)
              ,("up",UpKey)
              ,("killline",KillLine)
              ,("home",Home)
              ,("end",End)
              ,("pagedown",PageDown)
              ,("pageup",PageUp)
              ,("backspace",Backspace)
              ,("delete",Delete)
              ,("return",KeyChar '\n')
              ,("enter",KeyChar '\n')
              ,("tab",KeyChar '\t')
              ,("esc",KeyChar '\ESC')
              ,("escape",KeyChar '\ESC')
              ]

parseModifiers :: [String] -> BaseKey -> Key
parseModifiers strs = Key mods
    where mods = foldl1 (.) (map parseModifier strs) noModifier

parseModifier :: String -> (Modifier -> Modifier)
parseModifier str m = case map toLower str of
    "ctrl" -> m {hasControl = True}
    "control" -> m {hasControl = True}
    "meta" -> m {hasMeta = True}
    "shift" -> m {hasShift = True}
    _ -> m

breakAtDashes :: String -> [String]
breakAtDashes "" = []
breakAtDashes str = case break (=='-') str of
    (xs,'-':rest) -> xs : breakAtDashes rest
    (xs,_) -> [xs]

parseKey :: String -> Maybe Key
parseKey str = fmap canonicalizeKey $
    case reverse (breakAtDashes str) of
        [ks] -> liftM simpleKey (parseBaseKey ks)
        ks:ms -> liftM (parseModifiers ms) (parseBaseKey ks)
        [] -> Nothing

parseBaseKey :: String -> Maybe BaseKey
parseBaseKey ks = lookup (map toLower ks) specialKeys
                `mplus` parseFunctionKey ks
                `mplus` parseKeyChar ks
    where
        parseKeyChar [c] | isPrint c = Just (KeyChar c)
        parseKeyChar _ = Nothing

        parseFunctionKey (f:ns) | f `elem` "fF" = case reads ns of
            [(n,"")]    -> Just (FunKey n)
            _           -> Nothing
        parseFunctionKey _ = Nothing

canonicalizeKey :: Key -> Key
canonicalizeKey (Key m (KeyChar c))
    | hasControl m = Key m {hasControl = False}
                        (KeyChar (setControlBits c))
    | hasShift m = Key m {hasShift = False} (KeyChar (toUpper c))
canonicalizeKey k = k


text:
\section{The \protect\EcoLab{} Model}\label{model}

The \EcoLab{} model is but one model implemented using the \EcoLab{}
software. This section documents the model itself, and may be skipped
if your intention is to use \EcoLab{} for other models.

We start with a generalised form of the Lotka-Volterra equation
\begin{equation}\label{lotka-volterra}
\dot{\bn} = \br*\bn + \bn*\bbeta\bn.
\end{equation}
Here \bn\ is the population density, the component $n_i$ being the
number of individuals of species $i$, \br\ is the difference
between reproduction and death, \bbeta\ is the interaction matrix,
with $\beta_{ij}$ being the interaction between species $i$ and $j$, *
referring to elementwise multiplication and {\tt mutate} is the
mutation operator.

\subsection{Lotka-Volterra Dynamics}

The most obvious thing about equation (\ref{lotka-volterra}) is its
fixed point
\begin{equation}\label{fixed point}
\hat{\bn} = -\bbeta^{-1}\br,
\end{equation}
where $\dot{\bn}=0$. For this point to be biologically meaningful, all
components of $\hat{\bn}$ must be positive, giving rise to the following
inequalities:
\begin{equation}\label{positive species}
\hat n_i = \left(\bbeta^{-1}\br\right)_i>0, \forall i
\end{equation}
The stability of this point is related to the
negative definiteness of derivative of $\dot{\bn}$ at $\hat{\bn}$. The
components of the derivative are given by
\begin{equation}\label{derivative}
\frac{\partial\dot{n}_i}{\partial n_j} =
\delta_{ij}\left(r_i+\sum_k\beta_{ik}n_k\right) + \beta_{ij}n_i
\end{equation}
Substituting eq (\ref{fixed point}) gives
\begin{equation}
\left.\frac{\partial\dot{n}_i}{\partial n_j}\right|_{\hat{\bn}}=
-\beta_{ij}\left(\bbeta^{-1}\br\right)_i
\end{equation}

Stability of the fixed point requires that this matrix should be
negative definite. Since the $\left(\bbeta^{-1}\br\right)_i$ are
all negative by virtue of (\ref{positive species}), each minor
determinant of this matrix is equal to a minor determinant of \bbeta\
multiplied by a positive number, stability of the equilibrium is
equivalent to \bbeta\ being negative definite.

A weaker condition is to require that the system remain bounded with
time:
\begin{equation}\label{boundedness}
\sum_i\dot{n_i}=\br\cdot\bn + \bn\cdot\bbeta\bn < 0, \;\forall \bn:
\sum_in_i>N \;\exists N
\end{equation}

As \bn\ becomes large in any direction, this functional is dominated
by the quadratic term, so this implies that  $\bn\cdot\bbeta\bn\leq0
\; \forall\bn: n_i>0$. Negative definiteness of \bbeta\ is sufficient,
but not necessary for this condition. For example, the predator-prey
relations (heavily normalised) have the following matrix as \bbeta:
\begin{math}
\bbeta=\left(\begin{array}{cc}
-1 & 2\\
-2 & 0\\
\end{array}\right)
\end{math}
which has eigenvalues $3/2, -5/2$. If we let $\bn=(x,y), x,y\geq0$, then
$\bn\cdot\bbeta\bn=-2x^2$, which is clearly non-positive
for all $x$.

Consider adding a new row and column to \bbeta. What is condition is
the new row and column required to satisfy such that equation
(\ref{boundedness}) is satisfied. Break up \bbeta\ in the following
way:
\begin{displaymath}
\left(
  \mbox{
     \begin{tabular}{c|c}
       $\begin{array}{ccc}\ddots\\&{\bf A}\\&&\ddots\end{array}$ &
       $\begin{array}{c}\vdots\\{\bf B}\\\vdots\end{array}$ \\
       \hline
       $\begin{array}{ccc}\cdots&{\bf C}&\cdots\end{array}$ & D
     \end{tabular}
   }
\right)
\left(
  \mbox{
     \begin{tabular}{c}
     $\begin{array}{c}\vdots\\{\bf n_1}\\\vdots\end{array}$\\
     \hline
     $n_2$
     \end{tabular}
    }
\right)
\end{displaymath}

Condition (\ref{boundedness}) becomes:
\begin{equation}\label{boundedness2}
{\bf n_1}\cdot{\bf A}{\bf n_1} + {\bf n_1}\cdot({\bf B}+{\bf C})n_2 +
Dn_2^2 \leq 0
\end{equation}

Let
\begin{displaymath}
a=\max_{n=1} \bn\cdot A\bn,\mbox{ and } b=\max_{i}B_i+C_i.
\end{displaymath}
 Then a sufficient but
not necessary condition for condition (\ref{boundedness2}) is
\begin{displaymath}
an_1^2+bn_1n_2+Dn_2^2\leq0
\end{displaymath}

The maximum value with respect to $n_2$ is $an_1^2-(bn_1)^2/4D$, so
this requires that
\begin{equation}\label{boundedness3}
b \geq 2\sqrt{aD}
\end{equation}

\subsection{Mutation}\label{mutation}

With mutation, equation (\ref{lotka-volterra}) reads
\begin{equation}
\dot{\bn} = \br*\bn + \bn*\bbeta\bn + {\tt mutate}(\bmu,\br,\bn).
\end{equation}

The difficulty with adding mutation to this model is how to define the
mapping between genotype space and phenotype space, or in other words,
what defines the {\em embryology}. A few studies, including Ray's
Tierra world, do this with an explicit mapping from the genotype to to
some particular organism property (e.g. interpreted as machine language
instructions, or as weight in a neural net). These organisms then
interact with one another to determine the population dynamics. In
this model, however, we are doing away with the organismal layer, and
so an explicit embryology is impossible. The only possibility left is
to use a statistical model of embryology. The mapping between
genotype space and the population parameters $\br$,
$\bbeta{}$  is expected to look like a rugged
landscape, however, if two genotypes are close together (in a Hamming
sense) then one might expect that the phenotypes are likely to be
similar, as would the population parameters. This I call {\em random
embryology with locality}.

In the simple case of point mutations, the probability $P(x)$ of any
child lying distance $x$ in genotype space from its parent follows a
Poisson distribution. Random embryology with locality implies that the
phenotypic parameters are distributed randomly about the parent
species, with a standard deviation that depends monotonically on the
genotypic displacement. The simplest such model is to distribute the
phenotypic parameters in a Gaussian fashion about the parent's values,
with standard deviation proportional to the genotypic displacement.
This constant of proportionality can be conflated with the species'
intrinsic mutation rate, to give rise another phenotypic parameter
$\bmu$.  It is assumed that the probability of a mutation generating a
previously existing species is negligible, and can be ignored. We also
need another arbitrary parameter $\rho$, ``species radius'', or
\verb+ecolab.sp_sep+,\index{sp\_sep} which can be understood as the
minimum genotypic distance separating species, conflated with the same
constant of proportionality as $\bmu$.

In summary, the mutation algorithm is as follows:
\begin{enumerate}
\item The number of mutant species arising from species $i$ within a
timestep is $\mu_i\alpha_in_i/\rho$. This number is rounded
stochastically to the nearest integer, e.g. 0.25 is rounded up to 1
25\% of the time and down to 0 75\% of the time.

\item Roll a random number from a Poisson distribution
$e^{-x/\mu+\rho}$ to determine the standard deviation $\sigma$ of phenotypic
variation.

\item Vary $\br$ according to a Gaussian distribution about the
  parents' values, with $\sigma\alpha_0$ as the standard deviation,
  where $\alpha_0$ is the range of values that $\br$ is initialised to,
  ie $\alpha_0$=\verb|ecolab.repro_max|\index{ecolab.repro\_max}$-$
  \verb|ecolab.repro_min|\index{ecolab.repro\_min}

\item The diagonal part of $\bbeta$ must be negative, so vary $\bbeta$
according to a log-normal distribution. This means that if the old
value is $\beta$, the new value becomes
$\beta'=-\exp(\log_e(\beta)+\sigma)$. These values cannot become
arbitrarily small, however, as this would imply that some species make
arbitrarily small demands on the environment, and will become infinite
in number. In \EcoLab{}, the diagonal interactions terms are prevented from
becoming larger than $-r/(.1*{\tt INT\_MAX})$.

\item The offdiagonal components of $\bbeta$, are varied in a similar
fashion to $\br$. However new connections are added, or old ones
removed according to $\lfloor 1/r\rfloor$, where $r\in(-2,2)$ is
chosen from a stepped uniform distribution
\begin{displaymath}
P(x)=\left\{
\begin{array}{ll}
0.25(1-g) & \mathrm{if}\; x\leq0\\
0.25(1+g) & \mathrm{if}\; x>0\\
\end{array}
\right.
\end{displaymath}
where $g\in[-1,1]$ (default of 0) is specified by the TCL variable
\verb+generalization_bias+\index{generalization\_bias}. The values on
the new connections are chosen from the same initial distribution that
the offdiagonal values where originally set with, ie the range
\verb|ecolab.odiag_min|\index{ecolab.odiag\_min} to
\verb|ecolab.odiag_max|\index{ecolab.odiag\_max}. Since $a$ in
condition (\ref{boundedness3}) is computationally expensive, we use a
slightly stronger criterion that is sufficient, computationally
tractable yet still allows ``interesting'' non-definite matrix
behaviour namely that the sum $\beta_{ij}+\beta_{ji}$ should be
nonpositive.

\item $\bmu$ must be positive, so should evolve according to the
  log-normal distribution like the diagonal components of $\bbeta$.
  Similar to $\bbeta$, it is a catastrophe to allow $\bmu$ to become
  arbitrarily large. In the real world, mutation normally exists at
  some fixed background rate --- species can reduce the level of
  mutation by improving their genetic repair algorithms. In \EcoLab{},
  this ceiling on $\bmu$ is given by the
  \verb|ecolab.mut_max|\index{ecolab.mut\_max} variable.

\end{enumerate}

\subsection{Input Parameters}\label{input parameters}

The model's parameters are set by TCL variables in {\tt model.tcl}.
The actual data structures of the model are initialised the first time
the model's generate step is called. An example input set is:
\begin{verbatim}
# initial condition
ecolab.species {1 2}
ecolab.density {100 100}
ecolab.create {0 0}
ecolab.repro_rate {.1 -.1}
ecolab.interaction.diag {-.0001 -1e-5}
ecolab.interaction.val {-0.001 0.001}
ecolab.interaction.row {0 1}
ecolab.interaction.col {1 0}
ecolab.migration {.1 .1}

# mutation parameters
ecolab.mutation {.01 .01}
ecolab.sp_sep .1
ecolab.repro_min -.1
ecolab.repro_max .1
ecolab.odiag_min -1e-3
ecolab.odiag_max 1e-3
ecolab.mut_max .01
\end{verbatim}

Model variables define a TCL command of the same name as they appear
in the C++ source. So in the \EcoLab{} model, the C++ object {\tt
  ecolab} defines a set of TCL commands such as {\tt ecolab.density}
that can be used for setting or querying the values of {\tt ecolab}'s
members.  If an argument is specified, then that argument is used to
set the variable's value, otherwise, the variable's value is returned.
Array members in the model are initialised by specifying an TCL list
argument to the variables name, and return TCL lists when no argument
is specified. The above example starts the ecology off with a single
predator and prey (based on {\tt pred-prey.tcl}\index{pred-prey.tcl}).

\subsection{\protect\EcoLab{} Model commands}

\subsubsection{generate}\index{generate}

This implements the basic Lotka-Volterra equations:

\begin{math}
\dot{\bn} = \br*\bn + \bn*\bbeta\bn
\end{math}

with \br\ being the reproduction rate and \bbeta\ being the
interspecies interaction. This is implemented as a single line:

\begin{verbatim}
  density += repro_rate * density + (interaction * density) * density;
\end{verbatim}

This command also increments the timestep counter {\tt tstep}.

An optional argument specifies a number of timesteps to run the
generate step. This improves the speed by amortising the real to
integer conversion operation over a number of timesteps. The downside
is that computation may fail if the problem is ill-conditioned
(offdiagonal elements of \bbeta\ too large with respect to the
diagonal elements).

\subsubsection{condense}\label{condense}\index{condense}

This command compacts the systems of equations by removing extinct
species where $n_i=0$.

\subsubsection{mutate}\label{mutate}\index{mutate}

This applies the point mutations to the system. The precise algorithm
is described in \S\ref{mutation}.

\subsubsection{migrate}\label{migrate}\index{migrate}

This operator implements migration within cellular \EcoLab{}. This
updates density values according to the difference with the 4 nearest
neighbours: $\bn+=\bgamma*(0.25(\bn_n+\bn_e+\bn_s+\bn_w)-\bn)$, where the
$n,e,s,w$ index the north, east, south and west neigbouring cells.

\subsubsection{maxeig}\label{maxeig}\index{maxeig}

\verb|maxeig| returns the maximum eigenvalue of \bbeta. If this number
is negative, the equilibrium point is stable, if positive, it is
unstable. As reported in Standish (1994)\cite{Standish94}, the mutation
drives the maximum eigenvalue slightly positive, then instabilities
act to push the eigenvalue back to zero. This command requires LAPACK\index{LAPACK}).

\subsubsection{lifetimes}\label{lifetimes}\index{lifetimes}

\verb|lifetimes| records the timestep when a
species passes a threshold (hardwired at 10) in the {\tt create}\index{create}
iarray. If a species has yet to pass the threshold, or has gone
extinct, the value in {\tt create} is zero. Upon return, this routine
returns the lifetime of the species that have gone extinct. This can
then be passed to a histogram routine, or written to a file.

\subsubsection{random\_interaction}\label{random_interaction}
\index{random\_interaction}

Calls \hyperref{{\protect\tt sparse\_mat::init\_rand()}}{(See \S}{)}{sparse_mat} to randomly initialising the nonzero pattern of
the offdiagonal elements. The average number of nonzeros per row is
{\tt conn}, and the standard deviation of the number of nonzeros is
{\tt sigma}.

\subsubsection{set\_grid}

Synopsis

{\tt ecolab.set\_grid} {\em x} {\em y}

\noindent Set up an $x\times y$ grid in spatial \EcoLab. See
\verb+ecolab_spatial.tcl+ for an example using this.

\subsubsection{get}

Synopsis

{\tt ecolab.get} {\em x} {\em y}

\noindent Create TCL method for accessing the internals of cell $x$
$y$. The new commands look like array elements, eg
\begin{verbatim}
ecolab(1,0).density
\end{verbatim}

\subsubsection{forall}

Synopsis

{\tt ecolab.forall ecolab.}{\em command} {\em args}

Run {\em command} on all cells.

\subsection{Spatial Variation}\label{spatial}

The ecolab model can run in multicellular mode by calling
\verb+ecolab.set_grid+ from TCL, specifying the dimensions of the
grid.\index{set\_grid}. See
\verb+ecolab_spatial.tcl+\index{ecolab\_spatial} for an example.

Only population density varies between the cells --- all other
variables are members of the ecolab variable so can be set or queried
in the usual way.

The usual ecolab model methods (generate, mutate, condense and
lifetimes)\index{generate}\index{mutate}\index{condense}\index{lifetimes}
can now be called, but operate on the entire grid. A new {\tt
migrate}\index{migrate} is defined to handle migration between
cells. You can also call a method of the ecolab cell on all cells
using the \verb+forall+\index{forall} command. For instance, to set
all cells to same initial density, use:
\begin{verbatim}
ecolab.forall ecolab.density [constant $nsp 100]
\end{verbatim}

Access to the individual cells can obtain by creating a TCL\_obj to
refer to it by using the \verb+ecolab.get+\index{get} method, which
creates commands like {\tt ecolab({\em x},{\em y})} to refer to the
cell. These can be fed to visualisers in the usual way.

\subsubsection{Parallel Execution}

Since the cells are pins in a \hyperref{graphcode Graph}{graphcode
  Graph (\S}{)}{graphcode}\index{graphcode}, they are distributed over
parallel processes if available.

Remember to call the \verb+gather+\index{gather} method to ensure node
0 is updated before running a visualiser on global data.

\begin{description}
\item[ecolab.gather] Bring processor 0's data up to date with the rest
  of the grid
\item[ecolab.distribute\_cells] Broadcast processor 0's data out to the
  rest of the grid.
\end{description}

\section{Palauan Jellyfish model}\label{jellyfish}

This is a model being developed by Mike Dawson and Russell Standish to
model the behaviour of jellyfish in a number of lakes on the island of
Palau. Jellyfish are photosynthetic animals, so have have a preference
for the sun and avoiding shadows. In this model, the jellyfish are
represented by agents that have a position and velocity. If the
jellyfish moves into shadow, or bumps into the side of the lake, it
will reverse its direction. From time to time, the jellyfish will
change direction and speed. The random generators governing these are
selectable at runtime through the experimental script. Also, jellyfish
do bump into each other. In the model display, a jellyfish will flash
green if it bumps into another one.

To run the jellyfish model, run the jellyfish.tcl script (located in
the models directory), specifying the lake as an argument, eg:
\begin{verbatim}
jellyfish.tcl lakes/OTM
\end{verbatim}

You can choose whether to compile the 2D version of the model or the
3D version, by (not) defining the preprocessor flag
\verb+THREE_D+\index{THREE\_D} (see Makefile).

The lake itself is represented by a Tk pixmap, with the blue component
representing water. The lake shapes were scanned into a GIF file, and
edited with a run-of-the-mill paint program to produce the lakes.

Visualising the lake involved creating a Tk canvas widget, displaying
the lake image in it, then overlaying it with shadow lines extending
from the pixels lying on the boundary, and finally representing the
jellyfish with arrow symbols (to indicate position and velocity).

This model illustrates the use of probes. Mouse clicks in the canvas
region are bound to a short method that determines which agent is
closest to the mouse position. It then colours that agent red (for
tracking purposes), creates a TCL\_obj representing that agent, and
returns the name back to TCL. TCL then calls the object browser
(\S\ref{object-browser}) on that TCL\_obj. In all, 14 lines of C++
code, and 3 lines of TCL code. The result is very effective.

The jellyfish model is written to be run in parallel using
\hyperref{Graphcode}{Graphcode
  (\S}{)}{graphcode}\index{graphcode}. The strategy is effectively a
{\em particle-in-cell} method. The lake is subdivided into a Cartesion
grid of cells, and each Jellyfish only needs to consult the cell that
it is in, as well as neighbouring cells to determine if it will
collide with any other jellyfish.

redpajama_set_name: RedPajamaGithub


text:
using namespace cocos2d;
FlowTile::FlowTile()
{
}

typedef std::vector<FlowTask> FlowTaskVec;

FlowTask getTask(unsigned int N)
{
    static std::vector<bool> loaded(15, false);
    static std::map<unsigned int, FlowTaskVec> tables;

    if(loaded[N] == false)
    {
        CCLog("Load started");
        //Load task
        std::stringstream fname;
        loaded[N] = true;
        fname << "puzzle_" << N << "x" << N << ".ad";

        std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(fname.str().c_str());
        unsigned long size = 0;
        unsigned char* file_cont = CCFileUtils::sharedFileUtils()->getFileData(fullPath.c_str(), "r", &size);

        CCLog("File readed: %d", size);

        std::stringstream ss(std::ios::in | std::ios::out | std::ios::binary);
        ss.write((char*)file_cont, size);

        for(unsigned int i=0; i<40; ++i)
        {
            CCLog("%d,", file_cont[i]);
        }

        InputBinaryStream is(ss);

        CCLog("Start task read");
        FlowTaskVec& inp = tables[N];
        CCLog("Start task read++");
        is >> inp;

        CCLog("Task readed %d", inp.size());
    }

    const FlowTaskVec& vec = tables[N];
    if(vec.size() == 0)
        return FlowTask();
    FlowTask task = vec[rand() % vec.size()];
    std::random_shuffle(task.begin(), task.end());

    CCLog("Task returned");
    return task;
}

void FlowTile::init(const MTilePosition& pos, const MTileSize& size,FlowGame::DelegatePtr d)
{
    //MTileBlock rs(pos,size);
    MTile::init("black.png", pos, size, 0, 0);
    MTile* tile = this;
    unsigned int N = 5 + rand() % 3;

    FlowTable table(N,N);
    FlowTask task = getTask(N);

    for(FlowTask::iterator it = task.begin(); it!=task.end(); ++it)
    {
        FlowStartEnd& s = *it;
        if(s.size() == 2)
        {
            table.addColor(s[0], s[1]);
        }
    }

    FlowGame* render = FlowGame::create(table, d);
    CCSize render_size = render->getContentSize();
    CCSize tile_size = tile->getInnerContentSize();

    render->setScale(MIN(tile_size.width / render_size.width,
                         tile_size.height / render_size.height));

    tile->addChild(render, Aligment::HCenter, Aligment::VCenter);

}

FlowTile* FlowTile::create(const MTilePosition& position,
                             const MTileSize& size, FlowGame::DelegatePtr d)
{
    FlowTile* obj = new FlowTile();
    if(obj)
    {
        obj->autorelease();
        obj->init(position, size, d);
    }
    return obj;
}


text:
namespace DfBAdminToolkit.View {

    using BrightIdeasSoftware;
    using DfBAdminToolkit.Common.DataExchange;
    using DfBAdminToolkit.Common.Utils;
    using DfBAdminToolkit.Model;
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Threading;
    using System.Windows.Forms;

    public partial class DumpUserContentView : Form, IDumpUserContentView {
        private bool _suppressErrorMessage = false;
        private bool _contextMenuInitialized = false;
        private ContextMenu _menu;

        public event EventHandler DataChanged;
        public event EventHandler CommandListMembers;
        public event EventHandler CommandDumpFiles;
        public event EventHandler<DataUpdatedEventArgs> CommandContextMenuClicked;

        public SynchronizationContext SyncContext { get; set; }

        public bool ComponentEventsWired { get; set; }

        public string UserAccessToken { get; set; }

        public List<TeamListViewItemModel> MemberList { get; set; }

        public string OutputFolder { get; set; }

        public string[] ContextMenuItemText { get; set; }

        public bool ZipFiles { get; set; }

        public bool SuspendUser { get; set; }

        public bool DeleteUser { get; set; }

        public bool KeepAccount { get; set; }

        public enum OlvTeamIndex : int
        {
            Email,
            TeamId,
            FilePath,
            FileName,
            FileSize
        }

        public DumpUserContentView()
        {
            InitializeComponent();
            Initialize();
            WireComponentEvents();
        }

        ~DumpUserContentView()
        {
            UnWireContextMenuEvent();
            UnWireComponentEvents();
        }

        #region Initialization

        public void Initialize()
        {
            ComponentEventsWired = false;
            SyncContext = SynchronizationContext.Current;
            TopLevel = false;
            Dock = DockStyle.Fill;
            UserAccessToken = string.Empty;
            MemberList = new List<TeamListViewItemModel>();

            textBox_DumpUserContentOutputDir.AllowDrop = true;
        }

        public void WireComponentEvents()
        {
            if (!ComponentEventsWired)
            {
                this.textBox_MemberListAccessToken.TextChanged += TextBox_MemberListAccessToken_TextChanged;
                this.buttonEx_DumpUserContentDisplayMembers.Click += Button_MemberListView_Click;
                this.textBox_DumpUserContentOutputDir.OnDragDropEnd += TextBox_DumpUserContentOutputDir_OnDragDropEnd;
                this.buttonEx_DumpUserContentSelect.Click += Button_DumpUserContentOutputDir_Click;
                this.buttonEx_DumpUserContentDump.Click += Button_DumpUserContentDump_Click;
                this.objectListView_MemberList.ItemChecked += ObjectListView_MemberList_ItemChecked;
                this.objectListView_MemberList.HeaderCheckBoxChanging += ObjectListView_MemberList_HeaderCheckBoxChanging;
                this.objectListView_MemberList.ItemCheck += ObjectListView_MemberList_ItemCheck;
                this.checkBoxDumpToZip.CheckedChanged += CheckBoxDumpToZip_CheckedChanged;
                this.checkBoxSuspendUser.CheckedChanged += CheckBoxSuspendUser_CheckedChanged;
                this.checkBoxDeleteUser.CheckedChanged += CheckBoxDeleteUser_CheckedChanged;
                this.checkBoxKeepAccount.CheckedChanged += CheckBoxKeepAccount_CheckedChanged;
                ComponentEventsWired = true;
            }
        }

        public void UnWireComponentEvents()
        {
            if (ComponentEventsWired)
            {
                this.textBox_MemberListAccessToken.TextChanged -= TextBox_MemberListAccessToken_TextChanged;
                this.buttonEx_DumpUserContentDisplayMembers.Click -= Button_MemberListView_Click;
                this.textBox_DumpUserContentOutputDir.OnDragDropEnd -= TextBox_DumpUserContentOutputDir_OnDragDropEnd;
                this.buttonEx_DumpUserContentSelect.Click -= Button_DumpUserContentOutputDir_Click;
                this.buttonEx_DumpUserContentDump.Click -= Button_DumpUserContentDump_Click;
                this.objectListView_MemberList.ItemChecked -= ObjectListView_MemberList_ItemChecked;
                this.objectListView_MemberList.HeaderCheckBoxChanging -= ObjectListView_MemberList_HeaderCheckBoxChanging;
                this.objectListView_MemberList.ItemCheck -= ObjectListView_MemberList_ItemCheck;
                this.checkBoxDumpToZip.CheckedChanged -= CheckBoxDumpToZip_CheckedChanged;
                this.checkBoxSuspendUser.CheckedChanged -= CheckBoxSuspendUser_CheckedChanged;
                this.checkBoxDeleteUser.CheckedChanged -= CheckBoxDeleteUser_CheckedChanged;
                this.checkBoxKeepAccount.CheckedChanged -= CheckBoxKeepAccount_CheckedChanged;
                ComponentEventsWired = false;
            }
        }

        private void WireUpContextMenuEvent()
        {
            if (!_contextMenuInitialized)
            {
                foreach (MenuItem item in _menu.MenuItems)
                {
                    item.Click += Item_Click;
                }
                _contextMenuInitialized = true;
            }
        }

        private void UnWireContextMenuEvent()
        {
            if (_contextMenuInitialized)
            {
                foreach (MenuItem item in _menu.MenuItems)
                {
                    item.Click -= Item_Click;
                }
                _contextMenuInitialized = false;
            }
        }

        private void InitializeOLVMembers()
        {
            // don't allow edit
            this.objectListView_MemberList.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.None;
            this.objectListView_MemberList.UseExplorerTheme = false;
            this.objectListView_MemberList.UseTranslucentHotItem = false;
            this.objectListView_MemberList.FullRowSelect = true;
            this.objectListView_MemberList.HotTracking = true;
            this.objectListView_MemberList.ShowGroups = false;
            this.objectListView_MemberList.HeaderToolTip.IsBalloon = false;
            this.objectListView_MemberList.HotItemStyle.BackColor = Color.AliceBlue;
            this.objectListView_MemberList.HotItemStyle.ForeColor = Color.MediumBlue;

            TypedObjectListView<TeamListViewItemModel> olv = new TypedObjectListView<TeamListViewItemModel>(
                this.objectListView_MemberList
            );

            olv.GetColumn((int)OlvTeamIndex.Email).AspectGetter
                = delegate (TeamListViewItemModel model)
                {
                    return (model != null) ? model.Email : string.Empty;
                };

            olv.GetColumn((int)OlvTeamIndex.TeamId).AspectGetter
                = delegate (TeamListViewItemModel model)
                {
                    return (model != null) ? model.TeamId : string.Empty;
                };

            olv.GetColumn((int)OlvTeamIndex.FilePath).AspectGetter
                = delegate (TeamListViewItemModel model)
                {
                    return (model != null) ? model.FilePath : string.Empty;
                };

            olv.GetColumn((int)OlvTeamIndex.FileName).AspectGetter
                = delegate (TeamListViewItemModel model)
                {
                    return (model != null) ? model.FileName : string.Empty;
                };

            olv.GetColumn((int)OlvTeamIndex.FileSize).AspectGetter
                = delegate (TeamListViewItemModel model)
                {
                    return (model != null) ? model.FileSize : string.Empty;
                };
        }

        #endregion Initialization

        public void ShowView()
        {
            this.Show();
        }

        public void HideView()
        {
            this.Hide();
        }

        #region Slots

        public void EnableContextMenuItems(bool enable)
        {
            foreach (MenuItem item in _menu.MenuItems)
            {
                item.Enabled = enable;
            }
        }

        public void RenderMembersSearchResult()
        {
            this.objectListView_MemberList.SetObjects(
                MemberList
            );
            // disable row if file doesn't exist
            foreach (Object item in this.objectListView_MemberList.Objects)
            {
                TeamListViewItemModel model = item as TeamListViewItemModel;
                if (model != null)
                {
                    if (string.IsNullOrEmpty(model.FileName))
                    {
                        // force disable row.
                        //this.objectListView_MemberList.DisableObject(item);
                    }
                }
            }

            if (this.objectListView_MemberList.GetItemCount() == this.objectListView_MemberList.CheckedObjects.Count)
            {
                this.objectListView_MemberList.CheckHeaderCheckBox(olvColumnContent_Email);
            }
        }

        public void RenderMembersFileSearchResult()
        {
            this.objectListView_MemberList.SetObjects(
                MemberList
            );
            foreach (Object item in this.objectListView_MemberList.Objects)
            {
                TeamListViewItemModel model = item as TeamListViewItemModel;
                if (model != null)
                {
                    if (string.IsNullOrEmpty(model.FileName))
                    {
                        // remove all excpet the files that were located under that users group
                        this.objectListView_MemberList.RemoveObject(item);
                    }
                }
            }

            if (this.objectListView_MemberList.GetItemCount() == this.objectListView_MemberList.CheckedObjects.Count)
            {
                this.objectListView_MemberList.CheckHeaderCheckBox(olvColumnContent_Email);
            }
        }

        public void EnableDumpControl(bool enable)
        {
            this.tableLayoutPanel_DumpUserContentFileCommandGroup.Enabled = enable;
            this.tableLayoutPanel_DumpUserContentFileCommandGroup.Update();
        }

        public void EnableDumpButton(bool enable)
        {
            this.buttonEx_DumpUserContentDump.Enabled = enable;
            this.buttonEx_DumpUserContentDump.Update();
        }

        public void RefreshAccessToken()
        {
            this.textBox_MemberListAccessToken.Text = this.UserAccessToken;
        }

        public void SetContextMenuItemText(string[] menuItemsText)
        {
            ContextMenuItemText = menuItemsText;
        }

        private void UncheckHeaderCheckbox(ObjectListView olv, OLVColumn col)
        {
            // unbind event temporarily and uncheck header box
            olv.HeaderCheckBoxChanging -= ObjectListView_MemberList_HeaderCheckBoxChanging;
            olv.UncheckHeaderCheckBox(col);
            olv.HeaderCheckBoxChanging += ObjectListView_MemberList_HeaderCheckBoxChanging;
        }

        public void ShowGroups(bool show)
        {
            this.objectListView_MemberList.ShowGroups = show;
            this.objectListView_MemberList.Refresh();
        }

        public void LazyInitializeContextMenu()
        {
            // bind context menu to OLV
            // has to be run after OLV is initialized
            if (!_contextMenuInitialized) {
                _menu = new ContextMenu();
                foreach (string text in ContextMenuItemText)
                {
                    _menu.MenuItems.Add(new MenuItem(text));
                }
                this.objectListView_MemberList.ContextMenu = _menu;
                WireUpContextMenuEvent();
                _contextMenuInitialized = true;
            }
        }

        #endregion Slots

        #region Events

        private void Item_Click(object sender, EventArgs e)
        {
            UnWireContextMenuEvent();
            if (CommandContextMenuClicked != null) {
                CommandContextMenuClicked(sender, new DataUpdatedEventArgs(
                    this.objectListView_MemberList.SelectedObjects)
                );
            }
            WireUpContextMenuEvent();
        }

        private void Button_MemberListView_Click(object sender, EventArgs e)
        {
            InvokeDataChanged(sender, e);
            if (CommandListMembers != null) {
                CommandListMembers(sender, e);
            }
        }

        private void TextBox_MemberListAccessToken_TextChanged(object sender, EventArgs e)
        {
            UserAccessToken = this.textBox_MemberListAccessToken.Text;
        }

        private void TextBox_DumpUserContentOutputDir_OnDragDropEnd(object sender, EventArgs e)
        {
            OutputFolder = this.textBox_DumpUserContentOutputDir.Text;
            this.EnableDumpButton(true);
        }

        private void Button_DumpUserContentDump_Click(object sender, EventArgs e)
        {
            InvokeDataChanged(sender, e);
            if (CommandDumpFiles != null) {
                CommandDumpFiles(sender, e);
            }
        }

        private void Button_DumpUserContentOutputDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog outputFolderDlg = new FolderBrowserDialog();
            outputFolderDlg.Description = "Please select an output folder";
            outputFolderDlg.ShowNewFolderButton = true;
            DialogResult result = outputFolderDlg.ShowDialog();

            if (result == DialogResult.OK)
            {
                textBox_DumpUserContentOutputDir.Text = outputFolderDlg.SelectedPath;
                OutputFolder = outputFolderDlg.SelectedPath;
                this.EnableDumpButton(true);
            }
        }

        private void ObjectListView_MemberList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            // first of all, if user tries to check mark item which files were NOT loaded yet,
            // show warning and don't allow user to check mark
            ObjectListView olv = sender as ObjectListView;
            TeamListViewItemModel item = olv.GetModelObject(e.Index) as TeamListViewItemModel;
            if (item != null)
            {
                if (string.IsNullOrEmpty(item.FileName))
                {
                    if (!_suppressErrorMessage)
                    {
                        MessageBoxUtil.ShowError(this, ErrorMessages.MISSING_FILES);
                    }
                    e.NewValue = CheckState.Unchecked;
                }
            }
        }

        private void ObjectListView_MemberList_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            ObjectListView olv = sender as ObjectListView;

            if (olv.GetItemCount() == olv.CheckedObjects.Count)
            {
                olv.CheckHeaderCheckBox(olvColumnContent_Email);
            }
            else
            {
                UncheckHeaderCheckbox(olv, olvColumnContent_Email);
            }
        }

        private void ObjectListView_MemberList_HeaderCheckBoxChanging(object sender, HeaderCheckBoxChangingEventArgs e)
        {
            ObjectListView olv = sender as ObjectListView;
            CheckState newState = e.NewCheckState;
            if (newState == CheckState.Checked)
            {
                // suppress message box
                _suppressErrorMessage = true;
                if (olv.Objects != null)
                {
                    olv.CheckAll();
                }
                _suppressErrorMessage = false;
            }
            else if (newState == CheckState.Unchecked)
            {
                if (olv.Objects != null && olv.CheckedObjects.Count > 0)
                {
                    olv.UncheckAll();
                }
            }
        }

        private void InvokeDataChanged(object sender, EventArgs e)
        {
            if (DataChanged != null)
            {
                DataChanged(sender, e);
            }
        }

        #endregion Events

        private void CheckBoxDumpToZip_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBoxDumpToZip.Checked)
            {
                this.ZipFiles = true;
            }
            if (!this.checkBoxDumpToZip.Checked)
            {
                this.ZipFiles = false;
            }
        }

        private void CheckBoxSuspendUser_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBoxSuspendUser.Checked)
            {
                this.SuspendUser = true;
            }
            if (!this.checkBoxSuspendUser.Checked)
            {
                this.SuspendUser = false;
            }
        }

        private void CheckBoxDeleteUser_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBoxDeleteUser.Checked)
            {
                this.DeleteUser = true;
            }
            if (!this.checkBoxDeleteUser.Checked)
            {
                this.DeleteUser = false;
            }
        }

        private void CheckBoxKeepAccount_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBoxKeepAccount.Checked)
            {
                this.KeepAccount = true;
            }
            if (!this.checkBoxKeepAccount.Checked)
            {
                this.KeepAccount = false;
            }
        }
    }
}


text:
package com.wci.umls.server.rest.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;

import org.apache.log4j.Logger;

import com.wci.umls.server.ValidationResult;
import com.wci.umls.server.helpers.ConfigUtility;
import com.wci.umls.server.jpa.ValidationResultJpa;
import com.wci.umls.server.jpa.content.AtomJpa;
import com.wci.umls.server.jpa.content.AttributeJpa;
import com.wci.umls.server.jpa.content.ConceptRelationshipJpa;
import com.wci.umls.server.jpa.services.rest.MetaEditingServiceRest;

/**
 * A client for connecting to a content REST service.
 */
public class MetaEditingClientRest extends RootClientRest
    implements MetaEditingServiceRest {

  /** The config. */
  private Properties config = null;

  /**
   * Instantiates a {@link MetaEditingClientRest} from the specified parameters.
   *
   * @param config the config
   */
  public MetaEditingClientRest(Properties config) {
    this.config = config;
  }

  /* see superclass */
  @Override
  public ValidationResult addSemanticType(Long projectId, Long conceptId,
    String activityId, Long lastModified, String semanticType,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - add semantic type to concept" + projectId
            + ", " + conceptId + ", " + semanticType.toString() + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/sty/add?projectId=" + projectId + "&conceptId=" + conceptId
        + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified + "&semanticType=" + semanticType
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(null);

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult removeSemanticType(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long semanticTypeComponentId,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - remove semantic type from concept "
            + projectId + ", " + conceptId + ", " + semanticTypeComponentId
            + ", " + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/sty/remove/" + semanticTypeComponentId + "?projectId="
        + projectId + "&conceptId=" + conceptId
        + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(null);

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);

  }

  /* see superclass */
  @Override
  public ValidationResult addAttribute(Long projectId, Long conceptId,
    String activityId, Long lastModified, AttributeJpa attribute,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - add attribute to concept " + projectId
            + ", " + conceptId + ", " + attribute.toString() + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/attribute/add?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final String attributeString = ConfigUtility
        .getJsonForGraph(attribute == null ? new AttributeJpa() : attribute);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(attributeString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);

  }

  /* see superclass */
  @Override
  public ValidationResult removeAttribute(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long attributeId,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - remove attribute from concept " + projectId
            + ", " + conceptId + ", " + attributeId + ", " + lastModified + ", "
            + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(
        config.getProperty("base.url") + "/meta/attribute/remove/" + attributeId
            + "?projectId=" + projectId + "&conceptId=" + conceptId
            + (activityId == null ? "" : "&activityId=" + activityId)
            + "&lastModified=" + lastModified
            + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(null);

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult addAtom(Long projectId, Long conceptId,
    String activityId, Long lastModified, AtomJpa atom,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - add atom to concept " + projectId + ", "
            + conceptId + ", " + atom.toString() + ", " + lastModified + ", "
            + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/atom/add?projectId=" + projectId + "&conceptId=" + conceptId
        + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final String atomString =
        ConfigUtility.getJsonForGraph(atom == null ? new AtomJpa() : atom);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(atomString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult removeAtom(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long atomId, boolean overrideWarnings,
    String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - remove atom from concept " + projectId
            + ", " + conceptId + ", " + atomId + ", " + lastModified + ", "
            + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target =
        client.target(config.getProperty("base.url") + "/meta/atom/remove/"
            + atomId + "?projectId=" + projectId + "&conceptId=" + conceptId
            + (activityId == null ? "" : "&activityId=" + activityId)
            + "&lastModified=" + lastModified
            + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(null);

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult updateAtom(Long projectId, Long conceptId,
    String activityId, Long lastModified, AtomJpa atom,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - update atom on concept " + projectId + ", "
            + conceptId + ", " + atom.toString() + ", " + lastModified + ", "
            + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/atom/update?projectId=" + projectId + "&conceptId=" + conceptId
        + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final String atomString =
        ConfigUtility.getJsonForGraph(atom == null ? new AtomJpa() : atom);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(atomString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult addRelationship(Long projectId, Long conceptId,
    String activityId, Long lastModified, ConceptRelationshipJpa relationship,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - add relationship to concept " + projectId
            + ", " + conceptId + ", " + relationship.toString() + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/relationship/add?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    String relString = ConfigUtility.getJsonForGraph(
        relationship == null ? new ConceptRelationshipJpa() : relationship);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(relString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult addRelationships(Long projectId, Long conceptId,
    String activityId, Long lastModified,
    List<ConceptRelationshipJpa> relationships, boolean overrideWarnings,
    String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - add relationship to concept " + projectId
            + ", " + conceptId + ", " + relationships.toString() + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/relationships/add?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    String relString = ConfigUtility.getJsonForGraph(relationships == null
        ? new ArrayList<ConceptRelationshipJpa>() : relationships);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(relString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult removeRelationship(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long relationshipId,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - remove relationship from concept "
            + projectId + ", " + conceptId + ", " + relationshipId + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/relationship/remove/" + relationshipId + "?projectId="
        + projectId + "&conceptId=" + conceptId
        + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(null);

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult addDemotion(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long conceptId2, Long atomId,
    Long atomId2, boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - add demotion " + projectId + ", "
            + conceptId + ", atomId: " + atomId + ", atomId2: " + atomId2 + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");
    validateNotEmpty(conceptId2, "conceptId2");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/demotion/add?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified + "&conceptId2=" + conceptId2
        + "&atomdId=" + atomId + "&atomId2=" + atomId2
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(null);

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult mergeConcepts(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long conceptId2,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - merge concept " + conceptId
            + " with concept " + conceptId2 + ", " + lastModified + ", "
            + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");
    validateNotEmpty(conceptId2, "conceptId2");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/concept/merge?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified + "&conceptId2=" + conceptId2
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(null));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult moveAtoms(Long projectId, Long conceptId,
    String activityId, Long lastModified, Long conceptId2, List<Long> atomIds,
    boolean overrideWarnings, String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - move atoms " + atomIds + " from concept "
            + conceptId + " to concept " + conceptId2 + ", " + lastModified
            + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");
    validateNotEmpty(conceptId2, "conceptId2");
    validateNotEmpty(atomIds.toString(), "atoms");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/atom/move?projectId=" + projectId + "&conceptId=" + conceptId
        + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified + "&conceptId2=" + conceptId2
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    String atomIdsString = ConfigUtility
        .getJsonForGraph(atomIds == null ? new ArrayList<Long>() : atomIds);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(atomIdsString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult splitConcept(Long projectId, Long conceptId,
    String activityId, Long lastModified, List<Long> atomIds,
    boolean overrideWarnings, boolean copyRelationships,
    boolean copySemanticTypes, String relationshipType, String authToken)
    throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - splitting " + atomIds
            + " atoms out of concept " + conceptId + " into new concept, "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/concept/split?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : "")
        + (copyRelationships ? "&copyRelationships=true" : "")
        + (copySemanticTypes ? "&copySemanticTypes=true" : "")
        + "&relationshipType=" + relationshipType);

    String atomIdsString = ConfigUtility
        .getJsonForGraph(atomIds == null ? new ArrayList<Long>() : atomIds);

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(atomIdsString));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  /* see superclass */
  @Override
  public ValidationResult approveConcept(Long projectId, Long conceptId,
    String activityId, Long lastModified, boolean overrideWarnings,
    String authToken) throws Exception {
    Logger.getLogger(getClass())
        .debug("MetaEditing Client - approve concept " + conceptId + ", "
            + lastModified + ", " + overrideWarnings + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(conceptId, "conceptId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client.target(config.getProperty("base.url")
        + "/meta/concept/approve?projectId=" + projectId + "&conceptId="
        + conceptId + (activityId == null ? "" : "&activityId=" + activityId)
        + "&lastModified=" + lastModified
        + (overrideWarnings ? "&overrideWarnings=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(null));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  @Override
  public ValidationResult undoAction(Long projectId, Long molecularActionId,
    String activityId, boolean force, String authToken) throws Exception {
    Logger.getLogger(getClass()).debug("MetaEditing Client - undo action "
        + molecularActionId + ", " + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(molecularActionId, "molecularActionId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client
        .target(config.getProperty("base.url") + "/meta/action/undo?projectId="
            + projectId + "&molecularActionId=" + molecularActionId
            + (activityId == null ? "" : "&activityId=" + activityId)
            + (force ? "&force=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(null));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

  @Override
  public ValidationResult redoAction(Long projectId, Long molecularActionId,
    String activityId, boolean force, String authToken) throws Exception {
    Logger.getLogger(getClass()).debug("MetaEditing Client - redo action "
        + molecularActionId + ", " + ", " + authToken);

    validateNotEmpty(projectId, "projectId");
    validateNotEmpty(molecularActionId, "molecularActionId");

    final Client client = ClientBuilder.newClient();
    final WebTarget target = client
        .target(config.getProperty("base.url") + "/meta/action/redo?projectId="
            + projectId + "&molecularActionId=" + molecularActionId
            + (activityId == null ? "" : "&activityId=" + activityId)
            + (force ? "&force=true" : ""));

    final Response response = target.request(MediaType.APPLICATION_XML)
        .header("Authorization", authToken).post(Entity.json(null));

    final String resultString = response.readEntity(String.class);
    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      // n/a
    } else {
      throw new Exception(response.toString());
    }

    // converting to object
    return ConfigUtility.getGraphForString(resultString,
        ValidationResultJpa.class);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="2dp">

    </corners>

    <solid android:color="@android:color/white">

    </solid>

    <stroke android:width="1dp"
             android:color="@color/colorPrimary">

    </stroke>
</shape>


text:
package com.reason.ide.reference;

import com.intellij.psi.*;
import com.reason.ide.*;
import com.reason.lang.core.psi.PsiType;
import com.reason.lang.core.psi.*;
import com.reason.lang.core.psi.impl.*;

public class ResolveLowerElementRMLTest extends ORBasePlatformTestCase {
    @Override
    protected String getTestDataPath() {
        return "testData/com/reason/ide/reference";
    }

    public void test_let_basic() {
        configureCode("A.re", "let x = 1; let z = x<caret> + 1;");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.x", e.getQualifiedName());
    }

    public void test_let_in_module_binding() {
        configureCode("A.re", "let foo = 2; module X = { let foo = 1; let z = foo<caret>; };");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.X.foo", e.getQualifiedName());
    }

    public void test_let_inner_scope() {
        configureCode("A.re", "let x = 1; let a = { let x = 2; x<caret> + 10 };");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.a.x", e.getQualifiedName());
    }

    public void test_inner_scope_in_function() {
        configureCode("A.re", "let x = 1; let fn = { let x = 2; fn1(x<caret>); };");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.fn.x", e.getQualifiedName());
    }

    public void test_inner_scope_in_impl() {
        configureCode("A.rei", "let x:int;");
        configureCode("A.re", "let x = 1; let fn = { let foo = 2; fn1(foo<caret>); };");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.fn.foo", e.getQualifiedName());
        assertEquals("A.re", e.getContainingFile().getName());
    }

    public void test_let_local_module_alias() {
        configureCode("A.rei", "let x:int;");
        configureCode("B.re", "let x = 1; module X = A; X.x<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.x", e.getQualifiedName());
    }

    public void test_alias_path() {
        configureCode("A.re", "module W = { module X = { module Y = { module Z = { let z = 1; }; }; }; };");
        configureCode("B.re", "module C = A.W.X; module D = C.Y.Z; D.z<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.W.X.Y.Z.z", e.getQualifiedName());
    }

    public void test_alias_x() {
        configureCode("A.re", "module Mode = { type t; };");
        configureCode("B.re", "module B1 = { module Mode = A.Mode; };");
        configureCode("C.re", "B.B1.Mode.t<caret>");        // B.B1.Mode.t -> A.Mode.t

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("A.Mode.t", e.getQualifiedName());
    }

    public void test_open() {
        configureCode("B.re", "let x = 1;");
        configureCode("A.re", "let x = 2; open B; x<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("B.x", e.getQualifiedName());
    }

    public void test_alias_open() {
        configureCode("B.re", "let x = 1;");
        configureCode("A.re", "let x = 2; module C = B; open C; x<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("B.x", e.getQualifiedName());
    }

    public void test_let_local_open_parens() {
        configureCode("A.re", "module A1 = { let a = 1; };");
        configureCode("B.re", "let a = 2; let b = A.(A1.a<caret>);");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.A1.a", e.getQualifiedName());
    }

    public void test_let_local_open_parens_2() {
        configureCode("A.re", "module A1 = { let a = 3; };");
        configureCode("B.re", "let a = A.A1.(a<caret>);");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.A1.a", e.getQualifiedName());
    }

    public void test_type() {
        configureCode("A.re", "type t; type t' = t<caret>;");

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("A.t", e.getQualifiedName());
        assertTrue(e.isAbstract());
    }

    public void test_type_with_path() {
        configureCode("A.re", "type t;");
        configureCode("B.re", "type t = A.t<caret>;");

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("A.t", e.getQualifiedName());
    }

    public void test_type_with_path_2() {
        configureCode("A.re", "type t; type y = X.Y.t<caret>");

        assertThrows(AssertionError.class, "element not found in file A.re", () -> {
            PsiElement e = myFixture.getElementAtCaret();
        });
    }

    public void test_function() {
        configureCode("A.re", "module B = { let bb = 1; }; module C = { let cc = x => x; }; let z = C.cc(B.bb<caret>);");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.B.bb", e.getQualifiedName());
    }

    public void test_function_open() {
        configureCode("B.re", "module C = { let make = x => x; let convert = x => x; }");
        configureCode("A.re", "open B; C.make([| C.convert<caret> |]);");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("B.C.convert", e.getQualifiedName());
    }

    public void test_param_parenLess() {
        configureCode("A.re", "let add10 = x => x<caret> + 10;");

        PsiParameterDeclaration e = (PsiParameterDeclaration) myFixture.getElementAtCaret();
        assertEquals("A.add10[x]", e.getQualifiedName());
    }

    public void test_local_open_parens() {
        configureCode("A.re", "module A1 = { external a : int = \"\"; };");
        configureCode("B.re", "let b = A.(A1.a<caret>);");

        PsiExternal e = (PsiExternal) myFixture.getElementAtCaret();
        assertEquals("A.A1.a", e.getQualifiedName());
    }

    public void test_local_open_parens_2() {
        configureCode("A.re", "module A1 = { external a : int = \"\"; };");
        configureCode("B.re", "let a = A.A1.(a<caret>);");

        PsiExternal e = (PsiExternal) myFixture.getElementAtCaret();
        assertEquals("A.A1.a", e.getQualifiedName());
    }

    public void test_local_open_parens_3() {
        configureCode("A.re", "module A1 = { type t = | Variant; let toString = x => x; };");
        configureCode("B.re", "A.A1.(Variant->toString<caret>);");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.A1.toString", e.getQualifiedName());
    }

    public void test_include() {
        configureCode("A.re", "module B = { type t; }; module C = B; include C; type x = t<caret>;");

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("A.B.t", e.getQualifiedName());
    }

    public void test_include_2() {
        configureCode("Css_AtomicTypes.rei", "module Visibility: { type t = [ | `visible | `hidden | `collapse]; };");
        configureCode("Css_Legacy_Core.re", "module Types = Css_AtomicTypes;");
        configureCode("Css.re", "include Css_Legacy_Core;");
        configureCode("A.re", "type layoutRule; let visibility: [< Css.Types.Length.t | Css.Types.Visibility.t<caret> ] => layoutRule;");

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("Css_AtomicTypes.Visibility.t", e.getQualifiedName());
    }

    public void test_include_qualified() {
        configureCode("A.re", "module B = { module C = { type t; }; }; module D = B; include D.C;");
        configureCode("C.re", "type t = A.t<caret>;");

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("A.B.C.t", e.getQualifiedName());
    }

    public void test_module_signature() {
        configureCode("A.re", "module B: { type t; let toString: t => string; }; module C: { type t; let toString: t<caret> => string; };");

        PsiType e = (PsiType) myFixture.getElementAtCaret();
        assertEquals("A.C.t", e.getQualifiedName());
    }

    public void test_let_Local_open_pipe_first() {
        configureCode("A.re", "module A1 = { let add = x => x + 3; };");
        configureCode("B.re", "let x = A.A1.(x->add<caret>);");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.A1.add", e.getQualifiedName());
    }

    public void test_external_local_open_pipe_first() {
        configureCode("A.re", "module A1 = { external add : int => int = \"\"; };");
        configureCode("B.re", "let x = A.A1.(x->add<caret>);");

        PsiExternal e = (PsiExternal) myFixture.getElementAtCaret();
        assertEquals("A.A1.add", e.getQualifiedName());
    }

    public void test_pipe_first() {
        configureCode("Css.mli", "val px: int => string;");
        configureCode("A.re", "Dimensions.spacing.small->Css.px<caret>");

        PsiVal e = (PsiVal) myFixture.getElementAtCaret();
        assertEquals("Css.px", e.getQualifiedName());
    }

    public void test_pipe_first_open() {
        configureCode("Css.mli", "val px: int => string;");
        configureCode("A.re", "let make = () => { open Css; Dimensions.spacing.small->px<caret>; }");

        PsiVal e = (PsiVal) myFixture.getElementAtCaret();
        assertEquals("Css.px", e.getQualifiedName());
    }

    public void test_pipe_first_open_2() {
        configureCode("Core.re", "module Async = { let get = x => x; };");
        configureCode("A.re", "open Core.Async; request->get<caret>(\"windows/settings\")");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("Core.Async.get", e.getQualifiedName());
    }

    public void test_pipe_first_open_with_path() {
        configureCode("Css.mli", "module Rule = { val px: int => string; };");
        configureCode("A.re", "let make = () => { open Css; Dimensions.spacing.small->Rule.px<caret>; }");

        PsiVal e = (PsiVal) myFixture.getElementAtCaret();
        assertEquals("Css.Rule.px", e.getQualifiedName());
    }

    public void test_multiple_module() {
        configureCode("Command.re", "module Settings = { module Action = { let convert = x => x; }; };");
        configureCode("A.re", "module C = Y; open Command; Settings.Action.convert<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("Command.Settings.Action.convert", e.getQualifiedName());
    }

    public void test_variant_constructor() {
        configureCode("B.re", "let convert = x => x;");
        configureCode("A.re", "X.Variant(B.convert<caret>())");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("B.convert", e.getQualifiedName());
    }

    public void test_variant_constructor_tuple() {
        configureCode("B.re", "type t('a) = | Variant('a, 'b);");
        configureCode("A.re", "let x = 1; B.Variant(X.Y, x<caret>)");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.x", e.getQualifiedName());
    }

    public void test_open_include() {
        configureCode("Css_Core.re", "let fontStyle = x => x;");
        configureCode("Css.re", "include Css_Core;");
        configureCode("A.re", "open Css; fontStyle<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("Css_Core.fontStyle", e.getQualifiedName());
    }

    public void test_open_include_deep() {
        configureCode("Css_Rule.re", "let fontStyle = x => x;");
        configureCode("Css_Core.re", "module Rules = { include Css_Rule; }");
        configureCode("Css.re", "include Css_Core;");
        configureCode("A.re", "open Css.Rules; fontStyle<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("Css_Rule.fontStyle", e.getQualifiedName());
    }

    public void test_resolution_1() {
        configureCode("Belt_MapString.mli", "val get: 'v t -> key -> 'v option");
        configureCode("Belt_Map.ml", "module String = Belt_MapString;");
        configureCode("Belt_Option.mli", "val flatMap : 'a option -> ('a -> 'b option) -> 'b option");
        configureCode("Belt.re", "module Option = Belt_Option; module Map = Belt_Map;");
        configureCode("A.re", "let x = (dict, locale) => locale->Belt.Option.flatMap<caret>(dict->Belt.Map.String.get);");

        PsiVal e = (PsiVal) myFixture.getElementAtCaret();
        assertEquals("Belt_Option.flatMap", e.getQualifiedName());
    }

    public void test_resolution_2() {
        configureCode("Belt_MapString.mli", "val get: 'v t -> key -> 'v option");
        configureCode("Belt_Map.ml", "module String = Belt_MapString;");
        configureCode("Belt_Option.mli", "val flatMap : 'a option -> ('a -> 'b option) -> 'b option");
        configureCode("Belt.re", "module Option = Belt_Option; module Map = Belt_Map;");
        configureCode("A.re", "let x = (dict, locale) => locale->Belt.Option.flatMap(dict->Belt.Map.String.get<caret>);");

        PsiVal e = (PsiVal) myFixture.getElementAtCaret();
        assertEquals("Belt_MapString.get", e.getQualifiedName());
    }

    /* zzz functor
    public void test_functor_body() {
        configureCode("A.re", "module Make = (M:I) => { let a = 3; };");
        configureCode("B.re", "module Instance = A.Make({}); let b = Instance.a<caret>;");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.Make.a", e.getQualifiedName());
    }

    public void test_file_include_functor() {
        configureCode("A.re", "module Make = (M:I) => { let a = 3; }; include Make({})");
        configureCode("B.re", "let b = A.a<caret>;");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.Make.a", e.getQualifiedName());
    }

    public void test_functor_result_with_alias() {
        configureCode("A.re", "module type Result = { let a: int; };");
        configureCode("B.re", "module T = A; module Make = (M:Intf): T.Result => { let b = 3; };");
        configureCode("C.re", "module Instance = Make({}); let c = Instance.a<caret>;");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.Result.a", e.getQualifiedName());
    }
    */

    public void test_path_functor() {
        configureCode("pervasives.mli", "external compare : 'a -> 'a -> int = \"%compare\"");
        configureCode("A.re", "module B = X.Functor({ let cmp = Pervasives.compare<caret>; })");

        PsiExternal e = (PsiExternal) myFixture.getElementAtCaret();
        assertEquals("Pervasives.compare", e.getQualifiedName());
    }

    //region record
    public void test_record() {
        configureCode("B.re", "let b = { a: 1, b: 2 }; b<caret>");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("B.b", e.getQualifiedName());
    }

    public void test_record_l1() {
        configureCode("B.re", "let b = { a: 1, b: 2 }; b.b<caret>");

        PsiRecordField e = (PsiRecordField) myFixture.getElementAtCaret();
        assertEquals("B.b.b", e.getQualifiedName());
    }

    public void test_record_l3() {
        configureCode("A.re", "let a = { b: { c: { d: 1 } } }; a.b.c.d<caret>");

        PsiRecordField e = (PsiRecordField) myFixture.getElementAtCaret();
        assertEquals("A.a.b.c.d", e.getQualifiedName());
    }
    //endregion

    //region object
    public void test_object_l1() {
        configureCode("A.re", "let a = { \"b\": 1, \"c\": 2 }; a##b<caret>");

        PsiObjectField e = (PsiObjectField) myFixture.getElementAtCaret();
        assertEquals("A.a.b", e.getQualifiedName());
    }

    public void test_object_l3() {
        configureCode("A.re", "let a = { \"b\": { \"c\": { \"d\": 1 } } }; a##b##c##d<caret>");

        PsiObjectField e = (PsiObjectField) myFixture.getElementAtCaret();
        assertEquals("A.a.b.c.d", e.getQualifiedName());
    }
    //endregion

    public void test_GH_167_deconstruction_first() {
        configureCode("A.re", "let (count, setCount) = React.useState(() => 0); count<caret>(1);");

        PsiElement elementAtCaret = myFixture.getElementAtCaret();
        assertEquals(5, elementAtCaret.getTextOffset());
    }

    public void test_GH_167_deconstruction_second() {
        configureCode("A.re", "let (count, setCount) = React.useState(() => 0); setCount<caret>(1);");

        PsiElement elementAtCaret = myFixture.getElementAtCaret();
        assertEquals(12, elementAtCaret.getTextOffset());
    }

    public void test_GH_303() {
        configureCode("B.re", "type t1 = {bar: string};");
        configureCode("A.re", "type t = {bar: string}; let bar = item => item.bar<caret>;");

        PsiRecordField e = (PsiRecordField) myFixture.getElementAtCaret();
        assertEquals("A.t.bar", e.getQualifiedName());
    }

    public void test_GH_303_2() {
        configureCode("B.re", "type t1 = {bar:string};");
        configureCode("A.re", "type t = {bar: string}; let bar<caret> = item => item.bar;");

        PsiLet e = (PsiLet) myFixture.getElementAtCaret();
        assertEquals("A.bar", e.getQualifiedName());
    }
}


text:
package com.google.gerrit.server.restapi.change;

import com.google.common.flogger.FluentLogger;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.extensions.common.Input;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.extensions.webui.UiAction;
import com.google.gerrit.server.StarredChangesUtil;
import com.google.gerrit.server.StarredChangesUtil.IllegalLabelException;
import com.google.gerrit.server.StarredChangesUtil.MutuallyExclusiveLabelsException;
import com.google.gerrit.server.change.ChangeResource;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class Ignore implements RestModifyView<ChangeResource, Input>, UiAction<ChangeResource> {
  private static final FluentLogger logger = FluentLogger.forEnclosingClass();

  private final StarredChangesUtil stars;

  @Inject
  Ignore(StarredChangesUtil stars) {
    this.stars = stars;
  }

  @Override
  public Description getDescription(ChangeResource rsrc) {
    return new UiAction.Description()
        .setLabel("Ignore")
        .setTitle("Ignore the change")
        .setVisible(canIgnore(rsrc));
  }

  @Override
  public Response<String> apply(ChangeResource rsrc, Input input)
      throws RestApiException, IllegalLabelException {
    try {
      if (rsrc.isUserOwner()) {
        throw new BadRequestException("cannot ignore own change");
      }

      if (!isIgnored(rsrc)) {
        stars.ignore(rsrc);
      }
      return Response.ok("");
    } catch (MutuallyExclusiveLabelsException e) {
      throw new ResourceConflictException(e.getMessage());
    }
  }

  private boolean canIgnore(ChangeResource rsrc) {
    return !rsrc.isUserOwner() && !isIgnored(rsrc);
  }

  private boolean isIgnored(ChangeResource rsrc) {
    try {
      return stars.isIgnored(rsrc);
    } catch (StorageException e) {
      logger.atSevere().withCause(e).log("failed to check ignored star");
    }
    return false;
  }
}


text:
package net.therore.spring.mockito.xmlconfigurationtest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Alfredo Diaz
 * @see https://github.com/alfredodiaz/therore-spring-mockito
 **/
@Component
@Profile("!unit-test")
public class BasicHelloWorldService {

    @Value("${name:Spring-Boot}")
    private String name;

    public String getHelloMessage() {
        return "Hello " + this.name;
    }

}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;
using Extensions.Pager;
using ViewModels.Entities;

namespace BLL.IService
{
    public interface ITemplateService
    {
        Task<IPagedList<TemplateEntityViewModel>> GetWithPagingAsync(int? page, int pageSize);
        Task<IEnumerable<SelectListItem>> GetCountriesDropdownAsync();
        Task<TemplateEntityViewModel> GetByIdAsync(int id);
        Task<bool> AddOrUpdateAsync(TemplateEntityViewModel template);
        Task<bool> DeleteAsync(int id);
    }
}


text:
package com.simplaapliko.trips.presentation.fragment;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.widget.TimePicker;

import java.util.Calendar;
import java.util.Date;

public class SelectTimeDialog extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    public interface OnTimeChangedListener {
        void onTimeChanged(Date date);
    }

    private static final String DATE_KEY = "com.simplaapliko.trips.DATE_KEY";

    private Calendar mCalendar;
    private OnTimeChangedListener mOnTimeChangedListener;

    public static SelectTimeDialog newInstance() {
        return newInstance(new Date());
    }

    public static SelectTimeDialog newInstance(Date date) {
        SelectTimeDialog fragment = new SelectTimeDialog();
        Bundle args = new Bundle();
        args.putSerializable(DATE_KEY, date);
        fragment.setArguments(args);
        return fragment;
    }

    public SelectTimeDialog() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initializeState();

        setCancelable(false);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final TimePickerDialog pickerDialog = new TimePickerDialog(
                getActivity(),
                this,
                mCalendar.get(Calendar.HOUR_OF_DAY),
                mCalendar.get(Calendar.MINUTE),
                DateFormat.is24HourFormat(getActivity())
        );

        pickerDialog.setOnKeyListener((dialog, keyCode, event) -> {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    dialog.cancel();
                    dialog.dismiss();
                    return true;
                default:
                    return false;
            }
        });

        return pickerDialog;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mOnTimeChangedListener = null;
    }

    @Override
    public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        mCalendar.set(Calendar.MINUTE, minute);

        sendResult();
    }

    public void setOnTimeChangedListener(OnTimeChangedListener onTimeChangedListener) {
        mOnTimeChangedListener = onTimeChangedListener;
    }

    private void initializeState() {
        mCalendar = Calendar.getInstance();

        Bundle args = getArguments();
        if (args != null) {
            Date date = (Date) args.getSerializable(DATE_KEY);
            initializeCalendar(date);
        }
    }

    private void initializeCalendar(Date date) {
        if (date != null) {
            mCalendar.setTime(date);
        }
    }

    private void sendResult() {
        if (mOnTimeChangedListener != null) {
            mOnTimeChangedListener.onTimeChanged(mCalendar.getTime());
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface WDECCameraAccessLabel : WDECLabel

@end

NS_ASSUME_NONNULL_END


text:
// Copyright 2020 The Bazel Authors. 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.
package com.google.devtools.build.lib.skylarkbuildapi.platform;

import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.StarlarkIndexable;
import com.google.devtools.build.lib.syntax.StarlarkValue;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkDocumentationCategory;
import net.starlark.java.annot.StarlarkMethod;

/** Stores {@link com.google.devtools.build.lib.packages.ExecGroup}s available to a given rule. */
@StarlarkBuiltin(
    name = "ExecGroupCollection",
    category = StarlarkDocumentationCategory.BUILTIN,
    // TODO(b/151742236) update this doc when this becomes non-experimental.
    doc = "experimental Stores exec groups available to a given rule.")
public interface ExecGroupCollectionApi extends StarlarkValue, StarlarkIndexable {

  /**
   * Stores information about a single ExecGroup. The StarlarkMethod functions in this module should
   * be a subset of the StarlarkMethod functions available for the default exec group via {@link
   * com.google.devtools.build.lib.skylarkbuildapi.StarlarkRuleContextApi}. This allows a user to
   * pass in a rule ctx to the same places that take an exec group ctx to have them operate on the
   * default exec group.
   */
  @StarlarkBuiltin(
      name = "ExecGroupContext",
      category = StarlarkDocumentationCategory.BUILTIN,
      // TODO(b/151742236) update this doc when this becomes non-experimental.
      doc = "experimental Stores information about an exec group.")
  interface ExecGroupContextApi extends StarlarkValue {
    @StarlarkMethod(
        name = "toolchains",
        structField = true,
        // TODO(b/151742236) update this doc when this becomes non-experimental.
        doc = "experimental Toolchains required for this exec group")
    ToolchainContextApi toolchains() throws EvalException;
  }
}


text:
<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <title>flask-strap</title>
        <meta name="generator" content="Bootply" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/superhero/bootstrap.min.css" rel="stylesheet">

        <link rel="shortcut icon" href="/bootstrap/img/favicon.ico">
        <link rel="apple-touch-icon" href="/bootstrap/img/apple-touch-icon.png">
        <link rel="apple-touch-icon" sizes="72x72" href="/bootstrap/img/apple-touch-icon-72x72.png">
        <link rel="apple-touch-icon" sizes="114x114" href="/bootstrap/img/apple-touch-icon-114x114.png">

        {% with messages = get_flashed_messages() %}
        {% if messages %}
        {% for message in messages %}

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            {{ message }}

        {% endfor %}
        {% endif %}
        {% endwith %}

        {% if registererror %}

        {% endif %}

Sign In

Forgot password?

                        <form id="loginform" class="form-horizontal" role="form" method="post" action="">
                            {{ loginform.hidden_tag() }}

                                        {{ loginform.username(class_='form-control', placeholder='username or email')}}

                                        {% for error in loginform.errors.username %}
                                        {{ error }}
                                        {% endfor %}

                                        {{ loginform.password(class_='form-control', placeholder='password')}}

                                        {% for error in loginform.errors.password %}
                                        {{ error }}
                                        {% endfor %}

                                          {{ loginform.remember_me }} Remember me

<input type="submit" value="SignIn" class="btn btn-success" method="post" name="button">

                                      Login with Facebook

                                            Don't have an account!

                                            Sign Up Here

                            </form>

Sign Up

Sign In

                            <form id="signupform" class="form-horizontal" role="form" action="" method="POST">
                                {{ registerform.hidden_tag() }}

Error:

                                    Username

                                        {{ registerform.username(class_='form-control', placeholder='username') }}

                                        {% for error in registerform.errors.username %}
                                        {{ error }}
                                        {% endfor %}

                                    Email

                                        {{ registerform.email(class_='form-control', placeholder='email') }}

                                        {% for error in registerform.errors.email %}
                                        {{ error }}
                                        {% endfor %}

                                    Password

                                        {{ registerform.password(class_='form-control', placeholder='password') }}

                                        {% for error in registerform.errors.password %}
                                        {{ error }}
                                        {% endfor %}

<input type="submit" value="Register" class="btn btn-success" method="post" name="button">

                                        or

                                        <button id="btn-fbsignup" type="button" class="btn btn-primary">   Sign Up with Facebook</button>

                            </form>