text:
.. _install:

Install
=======

Requirements
------------

To compile RMPCDMD, the following software is required

  - A Fortran 2008 compiler (e.g. `gfortran <https://gcc.gnu.org/wiki/GFortran>`_ ≥ 4.7 with
    support for `OpenMP <https://gcc.gnu.org/wiki/openmp>`_ ≥ 3.1)
  - A Fortran-2003 enabled `HDF5 <https://www.hdfgroup.org/HDF5/>`_ installation
  - `CMake <http://cmake.org/>`_
  - `GNU Make <https://www.gnu.org/software/make/>`_
  - `git <http://git-scm.com/>`_

Other utilities, mostly Fortran code, will be downloaded automatically as part of the
installation process.

RMPCDMD has been developed on Linux, using both the GFortran and Intel Fortran
compilers. Compilation under OS X has been successfully achieved by users of RMPCMD. The
Windows platform is currently not tested.

If you encounter a configuration issue, it is often useful to remove all CMake data by
executing::

    rm -r CMake*

in the build directory (*not in the source directory*).

After successfully building the program, copy the file `rmpcdmd` in a location where
executables are found (i.e. ``$HOME/.local/bin`` or ``$HOME/bin`` for instance). This file
provides a unique interface to RMPCDMD.

To analyze simulation data, RMPCDMD provides the command ``rmpcdmd plot`` (see :ref:`run`)
that requires Python and a number of packages (see below).

.. note:: Once CMake has been executed, the RMPCDMD directory cannot be moved. If it is
          moved, the complete configuration procedure has to be restarted and the
          `rmpcdmd` program (in ``$HOME/.local/bin`` or ``$HOME/bin``) must be replaced
          by the newly created version.

.. note:: The `rmpcdmd` program does not contain the simulations programs themselves and
          relies on their presence at the location of compilation.

Building on Linux
-----------------

On a Debian distribution (or derivative, e.g. Ubuntu), as root::

    apt-get install gfortran libhdf5 cmake git

will install the dependencies. (See `install_hdf5`_ for Ubuntu 14.04 or problematic HDF5
installs).

At the command line, execute the following::

    git clone https://github.com/pdebuyl-lab/RMPCDMD
    cd RMPCDMD
    git submodule init
    git submodule update
    mkdir build
    cd build
    cmake ..
    make VERBOSE=1

This will first fetch RMPCDMD, then the related modules `ParseText`, `fortran_tester`,
`fortran_h5md` and `random_module`. The compilation is prepared by the ``cmake`` command and
executed by the ``make`` command.

If your HDF5 installation is properly setup, CMake should find it automatically. If this is
not the case, you may define the environment variable ``HDF5_ROOT=/path/to/hdf5`` before
invoking cmake (see the OS X installation notes for an example).

.. note:: When using compilers that are not the default one of the Linux distribution, such
          as the Intel compilers, the following settings must be used (change the compiler
          name if needed) *before* running cmake and *before* possibly building HDF5::

              export CC=icc
              export FC=ifort

Building on OS X
----------------

The first step is to install a development environment, and thus the `XCode
<https://developer.apple.com/xcode/>`_ software from Apple (we have tested RMPCDMD with
XCode 7.3.1 on OS X El Capitan).

We used `MacPorts <https://www.macports.org/>`_ for gcc, git, cmake and make. Install
MacPorts (a GUI installer is available at https://www.macports.org/install.php) and then
the dependencies::

    sudo port install gcc-5 cmake git

The rest is similar to Linux except that the name of the compiler has to be specified
manually at the command-line to prevent the automatic selection of Apple's provided
compiler. Also, HDF5 is built locally::

    git clone https://github.com/pdebuyl-lab/RMPCDMD
    cd RMPCDMD
    git submodule init
    git submodule update
    export CC=gcc-mp-5
    export FC=gfortran-mp-5
    ./scripts/download_and_build_hdf5.sh
    mkdir build
    cd build
    HDF5_ROOT=../_hdf5-1.8.17 cmake ..
    make

The compiler names given here may vary depending on your setup.

Building on Windows
-------------------

Installation on Windows is not tested at this time. The major difficulty is likely related
to a functional installation of HDF5 for Fortran under Windows, that is only provided for
the Intel compiler. Having no Windows computer with the Intel Fortran compiler at our
disposal, user feedback is welcome.

.. _install_hdf5:

HDF5
----

On OS X or with older Linux systems (such as Ubuntu 14.04 still in wide usage), it is
necessary to build HDF5 to enable the Fortran 2003 interface.

A script is provided to download and build HDF5 that has been tested on OS X and on
Ubuntu. It must be run from the main RMPCDMD directory::

    ./scripts/download_and_build_hdf5.sh

with compiler definitions ``CC`` and ``FC`` set when using OS X or a compiler that is not
the default one for the computer, such as ``icc`` and ``ifort``. This script must be run
only once and the environment variable ``HDF5_ROOT`` must be set when invoking cmake (also
see the OS X installation notes).

The script downloads HDF5 1.8.17 and installs it under ``_hdf5-1.8.17``. You can remove the
directory ``hdf5-1.8.17`` (no leading underscore) after the execution of the script.

.. _install_python:

Python
------

Several analysis scripts in the ``experiments/`` directory and a command-line tool ``rmpcdmd
plot`` are provided. They all rely on the Python programming language and the following
Python packages:

* `NumPy <http://numpy.org/>`_
* `SciPy <http://scipy.org/>`_
* `matplotlib <http://matplotlib.org/>`_
* `h5py <http://www.h5py.org/>`_

Optionally, you may wish to install `Mayavi <http://docs.enthought.com/mayavi/mayavi/>`_ for
the 3D visualization of the dimer simulation.

Installing those tools under Linux is straightforward::

    sudo apt-get install python-numpy python-scipy python-matplotlib python-h5py

for Debian-based systems or::

    sudo yum install numpy scipy h5py python-matplotlib

for Red-Hat based systems.

On OS X, we recommend to use a Python "super package" such as `Enthought Canopy
<https://www.enthought.com/products/canopy/>`_ or `Anaconda
<https://www.continuum.io/why-anaconda>`_ from Continuum that bundle the required software.


text:
title:  Ravnanje z zahtevnejšimi odlomki
date:   13/06/2020
---

### Preberi pred proučevanjem
2 Tim 2,10-15; 1 Krn 29,17; Jak 4,6-10; Gal 6,9; Apd 17,11

>
Ključno besedilo:

> Potrpežljivost našega Gospoda imejte za zveličanje; kakor vam je tudi naš ljubljeni brat Pavel pisal po dani mu modrosti, kakor tudi v vseh svojih listih, govoreč v njih o teh rečeh; ki je v njih nekaj težko umljivega, ki nevedni in neutrjeni zavijajo, kakor tudi druga Pisma, v lastno pogubo. 2 Pt 3,15-16

Apostol Peter omenja, da je v Pavlovih pismih in tudi drugod v Svetem pismu »nekaj težko umljivega«. (2 Pt 3,16) »Nevedni in neutrjeni« ljudje takšne odlomke izkrivljajo in pačijo »v lastno pogubo«. (2 Pt 3,16) Peter ni rekel, da so vse stvari zahtevne za razumevanje, temveč so takšne samo nekatere.

Tudi nam je to znano, mar ne? Kateri iskren bralec Svetega pisma še ni naletel na besedilo, ki se mu je zdelo čudno in težko razumljivo? V določenem trenutku smo vsi doživeli to izkušnjo.

Ta teden ne bomo proučevali zahtevnih svetopisemskih odlomkov, temveč razloge za težave, s katerimi se spopadamo pri branju Svetega pisma, in možne rešitve, s katerimi lahko zvesti iskalec resnice premaga te težave. Verjetno nekaterih zahtevnih odlomkov nikoli ne bomo mogli razvozlati, vsaj na tem svetu ne. Večina svetopisemskih besedil ni zahtevna, zato ni potrebe po tem, da majhnemu naboru zahtevnih odlomkov dovolimo zamajati naše zaupanje v zanesljivost in veljavo Božje besede kot celote.

redpajama_set_name: RedPajamaGithub


text:
package DDS;

public interface RESOURCELIMITS_QOS_POLICY_ID
{
    public static final int value = 14;
}


text:
function load_unitconv(ringmode, renamedIndexes)
dir = fileparts(mfilename('fullpath'));
cd(dir);
units_file = fullfile(dir, '..', 'data', ringmode, 'unitconv.csv');
poly_file = fullfile(dir, '..', 'data', ringmode, 'uc_poly_data.csv');
pchip_file = fullfile(dir, '..', 'data', ringmode, 'uc_pchip_data.csv');

fprintf('Loading unit conversions...\n');

% These variables are used throughout this file.
f_units = fopen(units_file, 'w');
f_poly = fopen(poly_file, 'w');
f_pchip = fopen(pchip_file, 'w');
uc_id = 0;

fprintf(f_units, 'el_id,field,uc_type,uc_id\n');
fprintf(f_poly, 'uc_id,coeff,val\n');
fprintf(f_pchip, 'uc_id,eng,phy\n');

quad_families = findmemberof('QUAD');
sext_families = findmemberof('SEXT');

for i = 1:length(quad_families)
    write_multipole_section(quad_families{i}, 'b1');
end

for i = 1:length(sext_families)
    write_multipole_section(sext_families{i}, 'b2');
end

bend_families = findmemberof('BEND');
for i = 1:length(bend_families)
    write_multipole_section(bend_families{i},'b0');
end

bpms = getfamilydata('BPMx');
bpm_uc_id = write_linear_data(0.001, 0);
for i = 1:length(bpms.AT.ATIndex)
    fprintf(f_units, '%d,%s,poly,%d\n', renamedIndexes(bpms.AT.ATIndex(i)), 'x', bpm_uc_id);
    fprintf(f_units, '%d,%s,poly,%d\n', renamedIndexes(bpms.AT.ATIndex(i)), 'y', bpm_uc_id);
end

% The skew quadrupoles are windings on the sextupoles, but there is no
% separate element so this works correctly (see below).
write_multipole_section('SQUAD', 'a1', renamedIndexes);

% If corrector magnets are windings on a sextupole, their AT Index is that
% of the sextupole whereas there is a separate element for those magnets.
% We have to use the index of the separate elements instead.
sext_data = getfamilydata('SEXT_');
sext_indices = sext_data.AT.ATIndex;

hcor = getfamilydata('HCM');
for i = 1:length(hcor.DeviceList)
    data = el_cal_data(hcor.Monitor.ChannelNames(i,:));
    hcor_index = hcor.AT.ATIndex(i);
    if any(hcor_index == sext_indices)
        hcor_index = hcor_index + 1;
    end
    id = write_linear_data(data.field(2) / data.current(2), 0);
    fprintf(f_units, '%d,%s,poly,%d\n', renamedIndexes(hcor_index), 'b0', id);
end

vcor = getfamilydata('VCM');
for i = 1:length(vcor.DeviceList)
    data = el_cal_data(vcor.Monitor.ChannelNames(i,:));
    vcor_index = vcor.AT.ATIndex(i);
    if any(vcor_index == sext_indices)
        vcor_index = vcor_index + 1;
    end
    id = write_linear_data(data.field(2) / data.current(2), 0);
    fprintf(f_units, '%d,%s,poly,%d\n', renamedIndexes(vcor_index), 'b0', id);
end

fclose(f_units);
fclose(f_poly);
fclose(f_pchip);

fprintf('Finished.\n');

    function id = write_linear_data(gradient, offset)
        uc_id = uc_id + 1;
        fprintf(f_poly, '%d,%d,%f\n', uc_id, 0, offset);
        fprintf(f_poly, '%d,%d,%f\n', uc_id, 1, gradient);
        id = uc_id;
    end

    function id = write_pchip_data(hw, phy)
        uc_id = uc_id + 1;
        for i = 1:length(hw)
            fprintf(f_pchip, '%d,%0.8f,%0.8f\n', uc_id, hw(i), phy(i));
        end
        id = uc_id;
    end

    function write_multipole_section(family, field, units)
        % We need to get our own device list so we can set the StatusFlag to 0,
        % this returns devices which are currently disabled.
        device_list = family2dev(family, 0);
        a = hw2physics(family, 'Monitor', 100, device_list);
        if all(a / a(1) == 1)  % All the magnets in the family have the same

            % unit conversion.
            caldata = fam_cal_data(family);
            bpm_uc_id = write_pchip_data(caldata.current, caldata.field);
            fdata = getfamilydata(family);
            for j = 1:length(fdata.AT.ATIndex)
                fprintf(f_units, '%d,%s,pchip,%d\n', renamedIndexes(fdata.AT.ATIndex(j)), field, bpm_uc_id);
            end
        else  % Need unit conversion data for each magnet in the family.
            irregular_mags = getfamilydata(family);
            for j = 1:length(irregular_mags.DeviceList)
                caldata = el_cal_data(irregular_mags.Monitor.ChannelNames(j,:));
                q_index = renamedIndexes(irregular_mags.AT.ATIndex(j));
                bpm_uc_id = write_pchip_data(caldata.current, caldata.field);
                fprintf(f_units, '%d,%s,pchip,%d\n', q_index, field, bpm_uc_id);
            end
        end
    end

    function caldata = el_cal_data(channel_name)
        global calibration_data;
        index = calibration_lookup2(channel_name);
        caldata = calibration_data{index};
    end

    function caldata = fam_cal_data(famname)
        fd = getfamilydata(famname);
        chan = fd.Monitor.ChannelNames(1,:);
        caldata = el_cal_data(chan);
    end

end


text:
The main goal of JAMShell is to facilitate managing JAMScript programs on a large number of nodes. Initially one must log in to all of the nodes to start the shell. Then one can manage programs in any subtree of nodes from a single node.

## Compiling

To compile the shell along with its utilities packaged into `jamshell.jxe` run:
```
./build.sh
```

## Running

The shell can be run with `jamrun` or `djamrun`. Here are examples with `jamrun`:
```
jamrun jamshell.jxe --app=jamsh --data=127.0.0.1:7000 --cloud  # start a cloud node
jamrun jamshell.jxe --app=jamsh --data=127.0.0.1:7001 --fog    # start a fog node
jamrun jamshell.jxe --app=jamsh --data=127.0.0.1:7002          # start a device node
```

## Commands

- `pwd` prints the current working directory of the current node.

- `cd` changes the current working directory in the current node's subtree.

- `ls` lists the contents of the current working directory of the current node.

- `exec` executes compiled JAMScript programs in a subtree.

  To execute in the current node's subtree run:
  ```
  exec prog1.jxe [> prog2.jxe ...] [< fileA] [> fileB]
  ```
  To execute in the entire tree run:
  ```
  exec prog1.jxe [> prog2.jxe ...] [< fileA] [> fileB] @cloud
  ```
  To execute in fog X's subtree or the subtree of the fog above the current node run:
  ```
  exec prog1.jxe [> prog2.jxe ...] [< fileA] [> fileB] @fog [X]
  ```
  To execute in device X's subtree run:
  ```
  exec prog1.jxe [> prog2.jxe ...] [< fileA] [> fileB] @device X
  ```
  In all cases, the arguments can be provided in any order.

- `jobs` lists all JAMScript programs spawned by the shell in the current node's subtree.

  Example of job listing:
  ```
  NODETYPE NODEID                               JOBID                                APP
  cloud    f17e42b0-efa8-4efa-b38a-af38ac43565c 0fc1c007-1594-4159-b9fb-639fef6c44e0 hello
  fog      8808436c-90dd-490d-9113-e111b915af75 0fc1c007-1594-4159-b9fb-639fef6c44e0 hello
  device   02c7fc4c-ea98-4ea9-88f3-b88fa01e7181 0fc1c007-1594-4159-b9fb-639fef6c44e0 hello
  ```
  The job listing is maintained across restarts of the shell. A user can exit the shell, start it again at a later time, and manage previously spawned programs.

- `kill` kills jobs in a subtree by APP (default) or JOBID.

  Example of killing by APP in the current node's subtree:
  ```
  kill hello
  ```
  Example of killing by JOBID in the current node's subtree:
  ```
  kill 0fc1c007-1594-4159-b9fb-639fef6c44e0 --id
  ```
  A particular subtree can be targeted as with the `exec` command.

- `info` displays information about the current node.


text:
using System;
using System.Collections.Generic;

using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;

namespace Amazon.DynamoDBv2.DataModel
{
    /// <summary>
    /// Context interface for using the DataModel mode of DynamoDB.
    /// Used to interact with the service, save/load objects, etc.
    /// </summary>
    public partial interface IDynamoDBContext : IDisposable
    {
        #region Save/serialize

        /// <summary>
        /// Serializes an object to a Document.
        /// </summary>
        /// <typeparam name="T">Type to serialize as.</typeparam>
        /// <param name="value">Object to serialize.</param>
        /// <returns>Document with attributes populated from object.</returns>
        Document ToDocument<T>(T value);

        /// <summary>
        /// Serializes an object to a Document.
        /// </summary>
        /// <typeparam name="T">Type to serialize as.</typeparam>
        /// <param name="value">Object to serialize.</param>
        /// <param name="operationConfig">Config object which can be used to override the table used.</param>
        /// <returns>Document with attributes populated from object.</returns>
        Document ToDocument<T>(T value, DynamoDBOperationConfig operationConfig);

        #endregion

        #region Load/deserialize

        /// <summary>
        /// Deserializes a document to an instance of type T.
        /// </summary>
        /// <typeparam name="T">Type to populate.</typeparam>
        /// <param name="document">Document with properties to use.</param>
        /// <returns>
        /// Object of type T, populated with properties from the document.
        /// </returns>
        T FromDocument<T>(Document document);

        /// <summary>
        /// Deserializes a document to an instance of type T.
        /// </summary>
        /// <typeparam name="T">Type to populate.</typeparam>
        /// <param name="document">Document with properties to use.</param>
        /// <param name="operationConfig">Config object which can be used to override the table used.</param>
        /// <returns>
        /// Object of type T, populated with properties from the document.
        /// </returns>
        T FromDocument<T>(Document document, DynamoDBOperationConfig operationConfig);

        /// <summary>
        /// Deserializes a collections of documents to a collection of instances of type T.
        /// </summary>
        /// <typeparam name="T">Type to populate.</typeparam>
        /// <param name="documents">Documents to deserialize.</param>
        /// <returns>
        /// Collection of items of type T, each populated with properties from a corresponding document.
        /// </returns>
        IEnumerable<T> FromDocuments<T>(IEnumerable<Document> documents);

        /// <summary>
        /// Deserializes a collections of documents to a collection of instances of type T.
        /// </summary>
        /// <typeparam name="T">Type to populate.</typeparam>
        /// <param name="documents">Documents to deserialize.</param>
        /// <param name="operationConfig">Config object which can be used to override the table used.</param>
        /// <returns>
        /// Collection of items of type T, each populated with properties from a corresponding document.
        /// </returns>
        IEnumerable<T> FromDocuments<T>(IEnumerable<Document> documents, DynamoDBOperationConfig operationConfig);

        #endregion

    }
}


text:
import abc
from watson.filesystem import Filesystem

class Backend(metaclass=abc.ABCMeta):

    """The abstract base class for filesystem backends.
    """

    def __init__(self, **kwargs):
        pass

    @classmethod
    def factory(cls, **kwargs):
        """Provides a convenient method of initializing the filesystem
        directly off the backend.
        """
        return Filesystem(cls(**kwargs))

    @abc.abstractmethod
    def read(self, file, options=None):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def exists(self, path):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def write(self, file, content, options=None):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def append(self, file, content, options=None):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def delete(self, path):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def move(self, path, new_path):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def copy(self, path, new_path):
        raise NotImplementedError  # pragma: no cover

    @abc.abstractmethod
    def create(self, path, is_dir=False):
        raise NotImplementedError  # pragma: no cover


text:
using MasterMemory.Internal;
using MessagePack;
using MessagePack.Formatters;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

namespace MasterMemory
{
    public abstract class MemoryDatabaseBase
    {
        protected MemoryDatabaseBase()
        {

        }

        public MemoryDatabaseBase(byte[] databaseBinary, bool internString = true, IFormatterResolver formatterResolver = null)
        {
            var formatter = new DictionaryFormatter<string, (int, int)>();
            var header = formatter.Deserialize(databaseBinary, 0, new HeaderFormatterResolver(), out var headerOffset);

            var resolver = formatterResolver ?? MessagePackSerializer.DefaultResolver;
            if (internString)
            {
                resolver = new InternStringResolver(resolver);
            }

            Init(header, headerOffset, databaseBinary, resolver);
        }

        protected static TView ExtractTableData<T, TView>(Dictionary<string, (int offset, int count)> header, int headerOffset, byte[] databaseBinary, IFormatterResolver resolver, Func<T[], TView> createView)
        {
            var tableName = typeof(T).GetCustomAttribute<MemoryTableAttribute>();
            if (tableName == null) throw new InvalidOperationException("Type is not annotated MemoryTableAttribute. Type:" + typeof(T).FullName);

            if (header.TryGetValue(tableName.TableName, out var segment))
            {
                var data = LZ4MessagePackSerializer.Deserialize<T[]>(new ArraySegment<byte>(databaseBinary, headerOffset + segment.offset, segment.count), resolver);
                return createView(data);
            }
            else
            {
                return default(TView);
            }
        }

        protected abstract void Init(Dictionary<string, (int offset, int count)> header, int headerOffset, byte[] databaseBinary, IFormatterResolver resolver);

        public static TableInfo[] GetTableInfo(byte[] databaseBinary, bool storeTableData = true)
        {
            var formatter = new DictionaryFormatter<string, (int, int)>();
            var header = formatter.Deserialize(databaseBinary, 0, new HeaderFormatterResolver(), out var headerOffset);

            return header.Select(x => new TableInfo(x.Key, x.Value.Item2, storeTableData ? databaseBinary : null, x.Value.Item1)).ToArray();
        }
    }

    /// <summary>
    /// Diagnostic info of MasterMemory's table.
    /// </summary>
    public class TableInfo
    {
        public string TableName { get; }
        public int Size { get; }
        byte[] binaryData;

        public TableInfo(string tableName, int size, byte[] rawBinary, int offset)
        {
            TableName = tableName;
            Size = size;
            if (rawBinary != null)
            {
                this.binaryData = new byte[size];
                Array.Copy(rawBinary, offset, binaryData, 0, size);
            }
        }

        public string DumpAsJson()
        {
            if (binaryData == null)
            {
                throw new InvalidOperationException("DumpAsJson can only call from GetTableInfo(storeTableData = true).");
            }
            return LZ4MessagePackSerializer.ToJson(binaryData);
        }
    }
}


text:
      {{nowPlaying.track.title}}
      {{nowPlaying.track.artist}}

          Next: {{getNextTrack().artist}} - {{getNextTrack().title}}

            <att-slider type="default"
                        min="{{nowPlaying.progress.min}}"
                        max="{{nowPlaying.progress.max}}"
                        ng-model="nowPlaying.progress.val"
                        text-left="{{nowPlaying.progress.elapsedTime}}"
                        text-right="{{nowPlaying.progress.remainingTime}}"
                        parent-control="time">
            </att-slider>

    VOLUME AT {{currentVolume}}%
    <att-slider type="default"
                min="{{minVolume}}"
                max="{{maxVolume}}"
                ng-model="currentVolume"
                text-left="{{minVolume}}"
                text-right="{{maxVolume}}"
                parent-control="volume">
    </att-slider>


text:
var React = require('react');

class Workspace extends React.Component {
    render() {
        return (
            <div>
                TOTO
            </div>
        );

    }
}

module.exports = Workspace;


text:
  Se quest'opzione è configurata, l'espressione regolare sarà applicata a tutti
  i nomi di processo. Quelli corrispondenti all'espressione regolare saranno
  visualizzati in questa vista. Suggerumento: per
  escludere
  determinati pattern, utilizzare il lookahead negativo. Ad esempio, per
  visualizzare tutti i processi che non hanno il nome
  <samp>
    test
    qualcosa
  </samp>
  , utilizzare:
  <samp>(?!test.*).*</samp>


text:
namespace drive {
namespace file_system {

class TruncateOperationTest : public OperationTestBase {
 protected:
  void SetUp() override {
    OperationTestBase::SetUp();

    operation_.reset(new TruncateOperation(
        blocking_task_runner(), delegate(), scheduler(),
        metadata(), cache(), temp_dir()));
  }

  std::unique_ptr<TruncateOperation> operation_;
};

TEST_F(TruncateOperationTest, Truncate) {
  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));
  const int64_t file_size = src_entry.file_info().size();

  // Make sure the file has at least 2 bytes.
  ASSERT_GE(file_size, 2);

  FileError error = FILE_ERROR_FAILED;
  operation_->Truncate(
      file_in_root,
      1,  // Truncate to 1 byte.
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  base::FilePath local_path;
  error = FILE_ERROR_FAILED;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner(),
      FROM_HERE,
      base::Bind(&internal::FileCache::GetFile,
                 base::Unretained(cache()),
                 GetLocalId(file_in_root), &local_path),
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  ASSERT_EQ(FILE_ERROR_OK, error);

  // The local file should be truncated.
  int64_t local_file_size = 0;
  base::GetFileSize(local_path, &local_file_size);
  EXPECT_EQ(1, local_file_size);
}

TEST_F(TruncateOperationTest, NegativeSize) {
  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));
  const int64_t file_size = src_entry.file_info().size();

  // Make sure the file has at least 2 bytes.
  ASSERT_GE(file_size, 2);

  FileError error = FILE_ERROR_FAILED;
  operation_->Truncate(
      file_in_root,
      -1,  // Truncate to "-1" byte.
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_INVALID_OPERATION, error);
}

TEST_F(TruncateOperationTest, HostedDocument) {
  base::FilePath file_in_root(FILE_PATH_LITERAL(
      "drive/root/Document 1 excludeDir-test.gdoc"));

  FileError error = FILE_ERROR_FAILED;
  operation_->Truncate(
      file_in_root,
      1,  // Truncate to 1 byte.
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_INVALID_OPERATION, error);
}

TEST_F(TruncateOperationTest, Extend) {
  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));
  const int64_t file_size = src_entry.file_info().size();

  FileError error = FILE_ERROR_FAILED;
  operation_->Truncate(
      file_in_root,
      file_size + 10,  // Extend to 10 bytes.
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  base::FilePath local_path;
  error = FILE_ERROR_FAILED;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner(),
      FROM_HERE,
      base::Bind(&internal::FileCache::GetFile,
                 base::Unretained(cache()),
                 GetLocalId(file_in_root), &local_path),
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  ASSERT_EQ(FILE_ERROR_OK, error);

  // The local file should be truncated.
  std::string content;
  ASSERT_TRUE(base::ReadFileToString(local_path, &content));

  EXPECT_EQ(file_size + 10, static_cast<int64_t>(content.size()));
  // All trailing 10 bytes should be '\0'.
  EXPECT_EQ(std::string(10, '\0'), content.substr(file_size));
}

}  // namespace file_system
}  // namespace drive


text:
homeassistant.helpers package
=============================

Submodules
----------

homeassistant.helpers.condition module
--------------------------------------

.. automodule:: homeassistant.helpers.condition
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.config_validation module
----------------------------------------------

.. automodule:: homeassistant.helpers.config_validation
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.discovery module
--------------------------------------

.. automodule:: homeassistant.helpers.discovery
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.entity module
-----------------------------------

.. automodule:: homeassistant.helpers.entity
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.entity_component module
---------------------------------------------

.. automodule:: homeassistant.helpers.entity_component
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.event module
----------------------------------

.. automodule:: homeassistant.helpers.event
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.event_decorators module
---------------------------------------------

.. automodule:: homeassistant.helpers.event_decorators
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.location module
-------------------------------------

.. automodule:: homeassistant.helpers.location
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.script module
-----------------------------------

.. automodule:: homeassistant.helpers.script
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.service module
------------------------------------

.. automodule:: homeassistant.helpers.service
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.state module
----------------------------------

.. automodule:: homeassistant.helpers.state
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.template module
-------------------------------------

.. automodule:: homeassistant.helpers.template
    :members:
    :undoc-members:
    :show-inheritance:

homeassistant.helpers.typing module
-----------------------------------

.. automodule:: homeassistant.helpers.typing
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: homeassistant.helpers
    :members:
    :undoc-members:
    :show-inheritance:


text: DROP TABLE v3_0_custom_ballots;


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.mapdemo.MessageSampleActivity" >
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        tools:showAsAction="never" />
</menu>


text:
<?php

namespace Puli\Manager\Discovery;

use Exception;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Puli\Discovery\Api\EditableDiscovery;
use Puli\Manager\Api\Context\ProjectContext;
use Puli\Manager\Api\Discovery\BindingDescriptor;
use Puli\Manager\Api\Discovery\BindingTypeDescriptor;
use Puli\Manager\Api\Discovery\DiscoveryManager;
use Puli\Manager\Api\Discovery\DiscoveryNotEmptyException;
use Puli\Manager\Api\Discovery\DuplicateBindingException;
use Puli\Manager\Api\Discovery\DuplicateTypeException;
use Puli\Manager\Api\Discovery\NoSuchBindingException;
use Puli\Manager\Api\Discovery\NoSuchTypeException;
use Puli\Manager\Api\Discovery\TypeNotEnabledException;
use Puli\Manager\Api\NonRootPackageExpectedException;
use Puli\Manager\Api\Package\InstallInfo;
use Puli\Manager\Api\Package\Package;
use Puli\Manager\Api\Package\PackageCollection;
use Puli\Manager\Api\Package\RootPackage;
use Puli\Manager\Api\Package\RootPackageFile;
use Puli\Manager\Assert\Assert;
use Puli\Manager\Discovery\Binding\AddBinding;
use Puli\Manager\Discovery\Binding\AddBindingDescriptorToPackageFile;
use Puli\Manager\Discovery\Binding\BindingDescriptorCollection;
use Puli\Manager\Discovery\Binding\DisableBindingUuid;
use Puli\Manager\Discovery\Binding\EnableBindingUuid;
use Puli\Manager\Discovery\Binding\LoadBindingDescriptor;
use Puli\Manager\Discovery\Binding\ReloadBindingDescriptorsByTypeName;
use Puli\Manager\Discovery\Binding\ReloadBindingDescriptorsByUuid;
use Puli\Manager\Discovery\Binding\RemoveBindingDescriptorFromPackageFile;
use Puli\Manager\Discovery\Binding\SyncBindingUuid;
use Puli\Manager\Discovery\Binding\UnloadBindingDescriptor;
use Puli\Manager\Discovery\Type\AddBindingType;
use Puli\Manager\Discovery\Type\AddTypeDescriptorToPackageFile;
use Puli\Manager\Discovery\Type\BindingTypeDescriptorCollection;
use Puli\Manager\Discovery\Type\LoadTypeDescriptor;
use Puli\Manager\Discovery\Type\RemoveTypeDescriptorFromPackageFile;
use Puli\Manager\Discovery\Type\SyncTypeName;
use Puli\Manager\Discovery\Type\UnloadTypeDescriptor;
use Puli\Manager\Discovery\Type\UpdateDuplicateMarksForTypeName;
use Puli\Manager\Package\PackageFileStorage;
use Puli\Manager\Transaction\InterceptedOperation;
use Puli\Manager\Transaction\Transaction;
use Rhumsaa\Uuid\Uuid;
use Webmozart\Expression\Expr;
use Webmozart\Expression\Expression;

/**
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class DiscoveryManagerImpl implements DiscoveryManager
{
    /**
     * @var ProjectContext
     */
    private $context;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var EditableDiscovery
     */
    private $discovery;

    /**
     * @var PackageCollection
     */
    private $packages;

    /**
     * @var PackageFileStorage
     */
    private $packageFileStorage;

    /**
     * @var RootPackage
     */
    private $rootPackage;

    /**
     * @var RootPackageFile
     */
    private $rootPackageFile;

    /**
     * @var BindingTypeDescriptorCollection
     */
    private $typeDescriptors;

    /**
     * @var BindingDescriptorCollection
     */
    private $bindingDescriptors;

    /**
     * Creates a tag manager.
     *
     * @param ProjectContext       $context
     * @param EditableDiscovery    $discovery
     * @param PackageCollection    $packages
     * @param PackageFileStorage   $packageFileStorage
     * @param LoggerInterface|null $logger
     */
    public function __construct(
        ProjectContext $context,
        EditableDiscovery $discovery,
        PackageCollection $packages,
        PackageFileStorage $packageFileStorage,
        LoggerInterface $logger = null
    ) {
        $this->context = $context;
        $this->discovery = $discovery;
        $this->packages = $packages;
        $this->packageFileStorage = $packageFileStorage;
        $this->rootPackage = $packages->getRootPackage();
        $this->rootPackageFile = $context->getRootPackageFile();
        $this->logger = $logger ?: new NullLogger();
    }

    /**
     * {@inheritdoc}
     */
    public function getContext()
    {
        return $this->context;
    }

    /**
     * {@inheritdoc}
     */
    public function addRootTypeDescriptor(BindingTypeDescriptor $typeDescriptor, $flags = 0)
    {
        Assert::integer($flags, 'The argument $flags must be a boolean.');

        $this->assertPackagesLoaded();
        $this->emitWarningForDuplicateTypes();

        $typeName = $typeDescriptor->getTypeName();

        if (!($flags & self::OVERRIDE) && $this->typeDescriptors->contains($typeName)) {
            throw DuplicateTypeException::forTypeName($typeName);
        }

        $tx = new Transaction();

        try {
            $syncBindingOps = array();

            foreach ($this->getUuidsByTypeName($typeName) as $uuid) {
                $syncBindingOp = $this->syncBindingUuid($uuid);
                $syncBindingOp->takeSnapshot();
                $syncBindingOps[] = $syncBindingOp;
            }

            $syncOp = $this->syncTypeName($typeName);
            $syncOp->takeSnapshot();

            $tx->execute($this->loadTypeDescriptor($typeDescriptor, $this->rootPackage));
            $tx->execute($this->addTypeDescriptorToPackageFile($typeDescriptor));
            $tx->execute($syncOp);

            foreach ($syncBindingOps as $syncBindingOp) {
                $tx->execute($syncBindingOp);
            }

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeRootTypeDescriptor($typeName)
    {
        // Only check that this is a string. The error message "not found" is
        // more helpful than e.g. "type name must contain /".
        Assert::string($typeName, 'The type name must be a string');

        $this->assertPackagesLoaded();

        if (!$this->typeDescriptors->contains($typeName, $this->rootPackage->getName())) {
            return;
        }

        $typeDescriptor = $this->typeDescriptors->get($typeName, $this->rootPackage->getName());
        $tx = new Transaction();

        try {
            $tx->execute($this->removeTypeDescriptorFromPackageFile($typeName));

            $syncBindingOps = array();

            foreach ($this->getUuidsByTypeName($typeName) as $uuid) {
                $syncBindingOp = $this->syncBindingUuid($uuid);
                $syncBindingOp->takeSnapshot();
                $syncBindingOps[] = $syncBindingOp;
            }

            $syncOp = $this->syncTypeName($typeName);
            $syncOp->takeSnapshot();

            $tx->execute($this->unloadTypeDescriptor($typeDescriptor));
            $tx->execute($syncOp);

            foreach ($syncBindingOps as $syncBindingOp) {
                $tx->execute($syncBindingOp);
            }

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }

        $this->emitWarningForDuplicateTypes();
    }

    /**
     * {@inheritdoc}
     */
    public function removeRootTypeDescriptors(Expression $expr)
    {
        $this->assertPackagesLoaded();

        $tx = new Transaction();
        $syncBindingOps = array();

        try {
            foreach ($this->getRootTypeDescriptors() as $typeDescriptor) {
                if ($expr->evaluate($typeDescriptor)) {
                    $typeName = $typeDescriptor->getTypeName();

                    $tx->execute($this->removeTypeDescriptorFromPackageFile($typeName));

                    foreach ($this->getUuidsByTypeName($typeName) as $uuid) {
                        $syncBindingOp = $this->syncBindingUuid($uuid);
                        $syncBindingOp->takeSnapshot();
                        $syncBindingOps[] = $syncBindingOp;
                    }

                    $syncOp = $this->syncTypeName($typeName);
                    $syncOp->takeSnapshot();

                    $tx->execute($this->unloadTypeDescriptor($typeDescriptor));
                    $tx->execute($syncOp);
                }
            }

            foreach ($syncBindingOps as $syncBindingOp) {
                $tx->execute($syncBindingOp);
            }

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }

        $this->emitWarningForDuplicateTypes();
    }

    /**
     * {@inheritdoc}
     */
    public function clearRootTypeDescriptors()
    {
        $this->removeRootTypeDescriptors(Expr::true());
    }

    /**
     * {@inheritdoc}
     */
    public function getRootTypeDescriptor($typeName)
    {
        return $this->getTypeDescriptor($typeName, $this->rootPackage->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function getRootTypeDescriptors()
    {
        $this->assertPackagesLoaded();

        $types = array();
        $rootPackageName = $this->rootPackage->getName();

        foreach ($this->typeDescriptors->toArray() as $typeName => $typesByPackage) {
            if (isset($typesByPackage[$rootPackageName])) {
                $types[] = $typesByPackage[$rootPackageName];
            }
        }

        return $types;
    }

    /**
     * {@inheritdoc}
     */
    public function findRootTypeDescriptors(Expression $expr)
    {
        $expr = Expr::method('getContainingPackage', Expr::same($this->rootPackage))
            ->andX($expr);

        return $this->findTypeDescriptors($expr);
    }

    /**
     * {@inheritdoc}
     */
    public function hasRootTypeDescriptor($typeName)
    {
        return $this->hasTypeDescriptor($typeName, $this->rootPackage->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function hasRootTypeDescriptors(Expression $expr = null)
    {
        $expr2 = Expr::method('getContainingPackage', Expr::same($this->rootPackage));

        if ($expr) {
            $expr2 = $expr2->andX($expr);
        }

        return $this->hasTypeDescriptors($expr2);
    }

    /**
     * {@inheritdoc}
     */
    public function getTypeDescriptor($typeName, $packageName)
    {
        Assert::string($typeName, 'The type name must be a string. Got: %s');
        Assert::string($packageName, 'The package name must be a string. Got: %s');

        $this->assertPackagesLoaded();

        if (!$this->typeDescriptors->contains($typeName, $packageName)) {
            throw NoSuchTypeException::forTypeName($typeName);
        }

        return $this->typeDescriptors->get($typeName, $packageName);
    }

    /**
     * {@inheritdoc}
     */
    public function getTypeDescriptors()
    {
        $this->assertPackagesLoaded();

        $types = array();

        foreach ($this->typeDescriptors->toArray() as $typeName => $typesByPackage) {
            foreach ($typesByPackage as $type) {
                $types[] = $type;
            }
        }

        return $types;
    }

    /**
     * {@inheritdoc}
     */
    public function findTypeDescriptors(Expression $expr)
    {
        $this->assertPackagesLoaded();

        $typeDescriptors = array();

        foreach ($this->typeDescriptors->toArray() as $typeName => $descriptorsByPackage) {
            foreach ($descriptorsByPackage as $typeDescriptor) {
                if ($expr->evaluate($typeDescriptor)) {
                    $typeDescriptors[] = $typeDescriptor;
                }
            }
        }

        return $typeDescriptors;
    }

    /**
     * {@inheritdoc}
     */
    public function hasTypeDescriptor($typeName, $packageName = null)
    {
        Assert::nullOrString($packageName, 'The package name must be a string or null. Got: %s');

        $this->assertPackagesLoaded();

        return $this->typeDescriptors->contains($typeName, $packageName);
    }

    /**
     * {@inheritdoc}
     */
    public function hasTypeDescriptors(Expression $expr = null)
    {
        $this->assertPackagesLoaded();

        if (!$expr) {
            return !$this->typeDescriptors->isEmpty();
        }

        foreach ($this->typeDescriptors->toArray() as $typeName => $descriptorsByPackage) {
            foreach ($descriptorsByPackage as $typeDescriptor) {
                if ($expr->evaluate($typeDescriptor)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function addRootBindingDescriptor(BindingDescriptor $bindingDescriptor, $flags = 0)
    {
        $this->assertPackagesLoaded();

        $typeName = $bindingDescriptor->getTypeName();
        $typeExists = $this->typeDescriptors->contains($typeName);

        if (!($flags & self::IGNORE_TYPE_NOT_FOUND) && !$typeExists) {
            throw NoSuchTypeException::forTypeName($typeName);
        }

        if (!($flags & self::IGNORE_TYPE_NOT_ENABLED) && $typeExists && !$this->typeDescriptors->getFirst($typeName)->isEnabled()) {
            throw TypeNotEnabledException::forTypeName($typeName);
        }

        $uuid = $bindingDescriptor->getUuid();
        $exists = $this->bindingDescriptors->contains($uuid);
        $existsInNonRoot = $exists
            ? !($this->bindingDescriptors->get($uuid)->getContainingPackage() instanceof RootPackage)
            : false;

        // We can only override bindings in the root package
        if ($existsInNonRoot || ($exists && !($flags & self::OVERRIDE))) {
            throw DuplicateBindingException::forUuid($uuid);
        }

        $tx = new Transaction();

        try {
            $syncOp = $this->syncBindingUuid($uuid);
            $syncOp->takeSnapshot();

            $tx->execute($this->loadBindingDescriptor($bindingDescriptor, $this->rootPackage));

            $this->assertBindingValid($bindingDescriptor);

            $tx->execute($this->addBindingDescriptorToPackageFile($bindingDescriptor));
            $tx->execute($syncOp);

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeRootBindingDescriptor(Uuid $uuid)
    {
        $this->assertPackagesLoaded();

        if (!$this->bindingDescriptors->contains($uuid)) {
            return;
        }

        $bindingDescriptor = $this->bindingDescriptors->get($uuid);

        if (!$bindingDescriptor->getContainingPackage() instanceof RootPackage) {
            return;
        }

        $tx = new Transaction();

        try {
            $syncOp = $this->syncBindingUuid($uuid);
            $syncOp->takeSnapshot();

            $tx->execute($this->unloadBindingDescriptor($bindingDescriptor));
            $tx->execute($syncOp);
            $tx->execute($this->removeBindingDescriptorFromPackageFile($uuid));

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeRootBindingDescriptors(Expression $expr)
    {
        $this->assertPackagesLoaded();

        $tx = new Transaction();

        try {
            foreach ($this->getRootBindingDescriptors() as $bindingDescriptor) {
                if ($expr->evaluate($bindingDescriptor)) {
                    $syncOp = $this->syncBindingUuid($bindingDescriptor->getUuid());
                    $syncOp->takeSnapshot();

                    $tx->execute($this->unloadBindingDescriptor($bindingDescriptor));
                    $tx->execute($syncOp);
                    $tx->execute($this->removeBindingDescriptorFromPackageFile($bindingDescriptor->getUuid()));
                }
            }

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clearRootBindingDescriptors()
    {
        $this->removeRootBindingDescriptors(Expr::true());
    }

    /**
     * {@inheritdoc}
     */
    public function getRootBindingDescriptor(Uuid $uuid)
    {
        $binding = $this->getBindingDescriptor($uuid);

        if (!$binding->getContainingPackage() instanceof RootPackage) {
            throw NoSuchBindingException::forUuidAndPackage($uuid, $this->rootPackage->getName());
        }

        return $binding;
    }

    /**
     * {@inheritdoc}
     */
    public function getRootBindingDescriptors()
    {
        $this->assertPackagesLoaded();

        $bindings = array();

        foreach ($this->bindingDescriptors->toArray() as $binding) {
            if ($binding->getContainingPackage() instanceof RootPackage) {
                $bindings[] = $binding;
            }
        }

        return $bindings;
    }

    /**
     * {@inheritdoc}
     */
    public function findRootBindingDescriptors(Expression $expr)
    {
        $expr = Expr::method('getContainingPackage', Expr::same($this->rootPackage))
            ->andX($expr);

        return $this->findBindingDescriptors($expr);
    }

    /**
     * {@inheritdoc}
     */
    public function hasRootBindingDescriptor(Uuid $uuid)
    {
        return $this->hasBindingDescriptor($uuid) && $this->getBindingDescriptor($uuid)->getContainingPackage() instanceof RootPackage;
    }

    /**
     * {@inheritdoc}
     */
    public function hasRootBindingDescriptors(Expression $expr = null)
    {
        $expr2 = Expr::method('getContainingPackage', Expr::same($this->rootPackage));

        if ($expr) {
            $expr2 = $expr2->andX($expr);
        }

        return $this->hasBindingDescriptors($expr2);
    }

    /**
     * {@inheritdoc}
     */
    public function enableBindingDescriptor(Uuid $uuid)
    {
        $this->assertPackagesLoaded();

        if (!$this->bindingDescriptors->contains($uuid)) {
            throw NoSuchBindingException::forUuid($uuid);
        }

        $bindingDescriptor = $this->bindingDescriptors->get($uuid);
        $package = $bindingDescriptor->getContainingPackage();

        if ($package instanceof RootPackage) {
            throw NonRootPackageExpectedException::cannotEnableBinding($uuid, $package->getName());
        }

        if ($bindingDescriptor->isTypeNotFound()) {
            throw NoSuchTypeException::forTypeName($bindingDescriptor->getTypeName());
        }

        if ($bindingDescriptor->isTypeNotEnabled()) {
            throw TypeNotEnabledException::forTypeName($bindingDescriptor->getTypeName());
        }

        if ($bindingDescriptor->isEnabled()) {
            return;
        }

        $tx = new Transaction();

        try {
            $syncOp = $this->syncBindingUuid($uuid);
            $syncOp->takeSnapshot();

            $tx->execute($this->enableBindingUuid($uuid, $package->getInstallInfo()));
            $tx->execute($syncOp);

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function disableBindingDescriptor(Uuid $uuid)
    {
        $this->assertPackagesLoaded();

        if (!$this->bindingDescriptors->contains($uuid)) {
            throw NoSuchBindingException::forUuid($uuid);
        }

        $bindingDescriptor = $this->bindingDescriptors->get($uuid);
        $package = $bindingDescriptor->getContainingPackage();

        if ($package instanceof RootPackage) {
            throw NonRootPackageExpectedException::cannotDisableBinding($uuid, $package->getName());
        }

        if ($bindingDescriptor->isTypeNotFound()) {
            throw NoSuchTypeException::forTypeName($bindingDescriptor->getTypeName());
        }

        if ($bindingDescriptor->isTypeNotEnabled()) {
            throw TypeNotEnabledException::forTypeName($bindingDescriptor->getTypeName());
        }

        if ($bindingDescriptor->isDisabled()) {
            return;
        }

        $tx = new Transaction();

        try {
            $syncOp = $this->syncBindingUuid($uuid);
            $syncOp->takeSnapshot();

            $tx->execute($this->disableBindingUuid($uuid, $package->getInstallInfo()));
            $tx->execute($syncOp);

            $this->saveRootPackageFile();

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeObsoleteDisabledBindingDescriptors()
    {
        $this->assertPackagesLoaded();

        $removedUuidsByPackage = array();

        try {
            foreach ($this->rootPackageFile->getInstallInfos() as $installInfo) {
                foreach ($installInfo->getDisabledBindingUuids() as $uuid) {
                    if (!$this->bindingDescriptors->contains($uuid)) {
                        $installInfo->removeDisabledBindingUuid($uuid);
                        $removedUuidsByPackage[$installInfo->getPackageName()][] = $uuid;
                    }
                }
            }

            $this->saveRootPackageFile();
        } catch (Exception $e) {
            foreach ($removedUuidsByPackage as $packageName => $removedUuids) {
                $installInfo = $this->rootPackageFile->getInstallInfo($packageName);

                foreach ($removedUuids as $uuid) {
                    $installInfo->addDisabledBindingUuid($uuid);
                }
            }

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getBindingDescriptor(Uuid $uuid)
    {
        $this->assertPackagesLoaded();

        if (!$this->bindingDescriptors->contains($uuid)) {
            throw NoSuchBindingException::forUuid($uuid);
        }

        return $this->bindingDescriptors->get($uuid);
    }

    /**
     * {@inheritdoc}
     */
    public function getBindingDescriptors()
    {
        $this->assertPackagesLoaded();

        return array_values($this->bindingDescriptors->toArray());
    }

    /**
     * {@inheritdoc}
     */
    public function findBindingDescriptors(Expression $expr)
    {
        $this->assertPackagesLoaded();

        $descriptors = array();

        foreach ($this->bindingDescriptors->toArray() as $descriptor) {
            if ($expr->evaluate($descriptor)) {
                $descriptors[] = $descriptor;
            }
        }

        return $descriptors;
    }

    /**
     * {@inheritdoc}
     */
    public function hasBindingDescriptor(Uuid $uuid)
    {
        $this->assertPackagesLoaded();

        return $this->bindingDescriptors->contains($uuid);
    }

    /**
     * {@inheritdoc}
     */
    public function hasBindingDescriptors(Expression $expr = null)
    {
        $this->assertPackagesLoaded();

        if (!$expr) {
            return !$this->bindingDescriptors->isEmpty();
        }

        foreach ($this->bindingDescriptors->toArray() as $bindingDescriptor) {
            if ($expr->evaluate($bindingDescriptor)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function buildDiscovery()
    {
        $this->assertPackagesLoaded();
        $this->emitWarningForDuplicateTypes();
        $this->emitWarningForInvalidBindings();

        if ($this->discovery->hasBindings() || $this->discovery->hasBindingTypes()) {
            throw new DiscoveryNotEmptyException('The discovery is not empty.');
        }

        $tx = new Transaction();

        try {
            foreach ($this->typeDescriptors->toArray() as $typeName => $descriptorsByPackage) {
                foreach ($descriptorsByPackage as $typeDescriptor) {
                    if ($typeDescriptor->isEnabled()) {
                        $tx->execute($this->addBindingType($typeDescriptor));
                    }
                }
            }

            foreach ($this->bindingDescriptors->toArray() as $bindingDescriptor) {
                if ($bindingDescriptor->isEnabled()) {
                    $tx->execute($this->addBinding($bindingDescriptor));
                }
            }

            $tx->commit();
        } catch (Exception $e) {
            $tx->rollback();

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clearDiscovery()
    {
        $this->discovery->removeBindingTypes();
    }

    private function assertPackagesLoaded()
    {
        if (!$this->typeDescriptors) {
            $this->loadPackages();
        }
    }

    private function assertBindingValid(BindingDescriptor $bindingDescriptor)
    {
        if ($bindingDescriptor->isTypeNotFound() || $bindingDescriptor->isTypeNotEnabled()) {
            return;
        }

        foreach ($bindingDescriptor->getLoadErrors() as $exception) {
            throw $exception;
        }
    }

    private function loadPackages()
    {
        $this->typeDescriptors = new BindingTypeDescriptorCollection();
        $this->bindingDescriptors = new BindingDescriptorCollection();

        // First load all the types
        foreach ($this->packages as $package) {
            if (null === $package->getPackageFile()) {
                continue;
            }

            foreach ($package->getPackageFile()->getTypeDescriptors() as $typeDescriptor) {
                $this->loadTypeDescriptor($typeDescriptor, $package)->execute();
            }
        }

        // Then the bindings for the loaded types
        foreach ($this->packages as $package) {
            if (null === $package->getPackageFile()) {
                continue;
            }

            foreach ($package->getPackageFile()->getBindingDescriptors() as $bindingDescriptor) {
                // This REALLY shouldn't happen
                if ($this->bindingDescriptors->contains($bindingDescriptor->getUuid())) {
                    throw DuplicateBindingException::forUuid($bindingDescriptor->getUuid());
                }

                $this->loadBindingDescriptor($bindingDescriptor, $package)->execute();
            }
        }
    }

    private function emitWarningForDuplicateTypes()
    {
        foreach ($this->typeDescriptors->getTypeNames() as $typeName) {
            $packageNames = $this->typeDescriptors->getPackageNames($typeName);

            if (count($packageNames) > 1) {
                $lastPackageName = array_pop($packageNames);

                $this->logger->warning(sprintf(
                    'The packages "%s" and "%s" contain type definitions for '.
                    'the same type "%s". The type has been disabled.',
                    implode('", "', $packageNames),
                    $lastPackageName,
                    $typeName
                ));
            }
        }
    }

    private function emitWarningForInvalidBindings()
    {
        foreach ($this->bindingDescriptors->toArray() as $binding) {
            foreach ($binding->getLoadErrors() as $exception) {
                $this->logger->warning(sprintf(
                    'The binding "%s" in package "%s" is invalid: %s',
                    $binding->getUuid()->toString(),
                    $binding->getContainingPackage()->getName(),
                    $exception->getMessage()
                ));
            }
        }
    }

    private function getUuidsByTypeName($typeName)
    {
        $uuids = array();

        foreach ($this->bindingDescriptors->getUuids() as $uuid) {
            if ($typeName === $this->bindingDescriptors->get($uuid)->getTypeName()) {
                $uuids[$uuid->toString()] = $uuid;
            }
        }

        return $uuids;
    }

    private function saveRootPackageFile()
    {
        $this->packageFileStorage->saveRootPackageFile($this->rootPackageFile);
    }

    private function addTypeDescriptorToPackageFile(BindingTypeDescriptor $typeDescriptor)
    {
        return new AddTypeDescriptorToPackageFile($typeDescriptor, $this->rootPackageFile);
    }

    private function removeTypeDescriptorFromPackageFile($typeName)
    {
        return new RemoveTypeDescriptorFromPackageFile($typeName, $this->rootPackageFile);
    }

    private function loadTypeDescriptor(BindingTypeDescriptor $typeDescriptor, Package $package)
    {
        $typeName = $typeDescriptor->getTypeName();

        return new InterceptedOperation(
            new LoadTypeDescriptor($typeDescriptor, $package, $this->typeDescriptors),
            array(
                new UpdateDuplicateMarksForTypeName($typeName, $this->typeDescriptors),
                new ReloadBindingDescriptorsByTypeName($typeName, $this->bindingDescriptors, $this->typeDescriptors),
            )
        );
    }

    private function unloadTypeDescriptor(BindingTypeDescriptor $typeDescriptor)
    {
        $typeName = $typeDescriptor->getTypeName();

        return new InterceptedOperation(
            new UnloadTypeDescriptor($typeDescriptor, $this->typeDescriptors),
            array(
                new UpdateDuplicateMarksForTypeName($typeName, $this->typeDescriptors),
                new ReloadBindingDescriptorsByTypeName($typeName, $this->bindingDescriptors, $this->typeDescriptors),
            )
        );
    }

    private function addBindingType(BindingTypeDescriptor $typeDescriptor)
    {
        return new AddBindingType($typeDescriptor, $this->discovery);
    }

    private function syncTypeName($typeName)
    {
        return new SyncTypeName($typeName, $this->discovery, $this->typeDescriptors);
    }

    private function addBindingDescriptorToPackageFile(BindingDescriptor $bindingDescriptor)
    {
        return new AddBindingDescriptorToPackageFile($bindingDescriptor, $this->rootPackageFile);
    }

    private function removeBindingDescriptorFromPackageFile(Uuid $uuid)
    {
        return new RemoveBindingDescriptorFromPackageFile($uuid, $this->rootPackageFile);
    }

    private function loadBindingDescriptor(BindingDescriptor $bindingDescriptor, Package $package)
    {
        return new LoadBindingDescriptor($bindingDescriptor, $package, $this->bindingDescriptors, $this->typeDescriptors);
    }

    private function unloadBindingDescriptor(BindingDescriptor $bindingDescriptor)
    {
        return new UnloadBindingDescriptor($bindingDescriptor, $this->bindingDescriptors);
    }

    private function enableBindingUuid(Uuid $uuid, InstallInfo $installInfo)
    {
        return new InterceptedOperation(
            new EnableBindingUuid($uuid, $installInfo),
            new ReloadBindingDescriptorsByUuid($uuid, $this->bindingDescriptors, $this->typeDescriptors)
        );
    }

    private function disableBindingUuid(Uuid $uuid, InstallInfo $installInfo)
    {
        return new InterceptedOperation(
            new DisableBindingUuid($uuid, $installInfo),
            new ReloadBindingDescriptorsByUuid($uuid, $this->bindingDescriptors, $this->typeDescriptors)
        );
    }

    private function addBinding(BindingDescriptor $bindingDescriptor)
    {
        return new AddBinding($bindingDescriptor, $this->discovery);
    }

    private function syncBindingUuid(Uuid $uuid)
    {
        return new SyncBindingUuid($uuid, $this->discovery, $this->bindingDescriptors);
    }
}


text:
if [ "${TRAVIS_OS_NAME}" != "osx" ]; then
    # https://www.ics.uci.edu/~pattis/common/handouts/macmingweclipse/allexperimental/mac-gdb-install.html
    echo "Cannot debug core files on macOS: ${1}"
    exit 1
fi

PHP_BINARY=`which php`
gdb -batch -ex "bt full" -ex "quit" "${PHP_BINARY}" "${1}"


text:
<?php
/**
 * Created by PhpStorm.
 * User: hat
 * Date: 29/12/2014
 * Time: 11:53.
 */
namespace Mission\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use User\Entity\User;

/**
 * @ORM\Entity
 * @ORM\Table(name="MissionCategory")
 */
class Category
{
    const BLOGS_PER_PAGE = 5;

    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=255, nullable=false, unique=true)
     */
    protected $urlKey;

    /**
     * @var \Blog\Entity\Locale
     * @ORM\ManyToOne(targetEntity="\Blog\Entity\Locale")
     * @ORM\JoinColumn(name="locale_id", referencedColumnName="id", nullable=true)
     */
    protected $locale;

    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="User\Entity\User")
     * @ORM\JoinTable(name="mission_user_category",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
     * )
     */
    protected $moderators;

    /**
     * @var \Mission\Entity\Category
     * @ORM\OneToOne(targetEntity="Mission\Entity\Category")
     */
    protected $category = null;

    public function __construct()
    {
        $this->moderators = new ArrayCollection();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * @param \Blog\Entity\Locale $locale
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;
    }

    public function setUrlKey($urlKey)
    {
        $this->urlKey = $urlKey;
    }

    public function getUrlKey()
    {
        return $this->urlKey;
    }

    public function getModerators()
    {
        return $this->moderators->getValues();
    }

    public function setModerators(array $moderators)
    {
        $this->moderators = $moderators;
    }

    public function getData()
    {
        $mods = $this->getModerators();
        $users = [];
        foreach ($mods as $mod) {
            $users[] = $mod->getData();
        }

        return [
            'id'         => $this->id,
            'name'       => $this->name,
            'locale'     => $this->locale->getData(),
            'urlKey'     => $this->urlKey,
            'moderators' => $users,
            'category'   => $this->category,
        ];
    }

    public function setData($data)
    {
        $keys = [
            'name',
            'urlKey',
            'locale',
            'category',
        ];
        foreach ($keys as $key) {
            if (isset($data[$key])) {
                $this->$key = $data[$key];
            }
        }
    }

    public function getUrl()
    {
        $url = '';
        if ($this->locale->getShortCode() == 'ar') {
            $url .= '/ar';
        }
        $url .= '/'.\Mission\Entity\Blog::BLOG_ROUTE.'/'.$this->urlKey;

        return $url;
    }

    public function getCategory()
    {
        return $this->category;
    }

    public function setCategory(\Mission\Entity\Category $category)
    {
        $this->category = $category;
    }

    public function getActiveBlogs($controller)
    {
        $em = $controller->getEntityManager();
        $qb = $em->getRepository('Mission\Entity\Blog')->createQueryBuilder('b');
        $queryBuilder = $qb
                    ->innerJoin('b.categories', 'c')
                    ->where('c.id='.$this->id)
                    ->orderBy('b.id', 'DESC');

        return $queryBuilder;
    }

    public function getChildPages($em)
    {
        $childPages = $em->getRepository('Mission\Entity\StaticPage')
            ->findBy(
                ['category' => $this],
                ['orderNumber' => 'ASC']
            );

        return $childPages;
    }
}


text:
package org.ifsoft.openlink.component;

import java.io.Serializable;
import java.util.*;
import org.xmpp.packet.JID;
import org.jivesoftware.util.Log;

import org.ifsoft.openlink.calllog.*;

public class OpenlinkUserInterest extends AbstractUserInterest
{

    private OpenlinkUser traderLyncUser;
    private OpenlinkInterest traderLyncInterest;
    private String defaultInterest;
	private String callFWD = "false";
	private String callFWDDigits = "";
    private Map<String, OpenlinkCall> traderLyncCalls;
	private Map<String, OpenlinkSubscriber> traderLyncSubscribers;
	private int maxNumCalls = 0;

    public OpenlinkUserInterest()
    {
        defaultInterest = "false";
        traderLyncCalls = Collections.synchronizedMap( new HashMap<String, OpenlinkCall>());
        traderLyncSubscribers = Collections.synchronizedMap( new HashMap<String, OpenlinkSubscriber>());
    }

	public String getInterestName() {
		return traderLyncInterest.getInterestId() + traderLyncUser.getUserNo();
	}

    public void handleCallInfo(String sCallNo, String sOpenlinkLineNo, String sOpenlinkLineName, String sNewLineState, String speakerCount, String handsetCount, String direction, String sPrivacyOn, String sRealDDI, String lineType, String sELC)
    {
        OpenlinkCall traderLyncCall = createCallById(sCallNo);
        traderLyncCall.start();
        traderLyncCall.line = sOpenlinkLineNo;
        traderLyncCall.label = sOpenlinkLineName;
		traderLyncCall.console = getUser().getDeviceNo();
		traderLyncCall.handset = getUser().getHandsetNo();
		traderLyncCall.direction = "I".equals(direction) ? "Incoming" : "Outgoing";
		traderLyncCall.setPrivacy(sPrivacyOn);

		if ("I".equals(sNewLineState))
		{
			traderLyncCall.setState("ConnectionCleared");
		}

		if ("R".equals(sNewLineState))
		{
			traderLyncCall.setState("CallDelivered");
        	traderLyncCall.direction = "Incoming";
		}

		if ("C".equals(sNewLineState) || "A".equals(sNewLineState))
		{
			traderLyncCall.setState("CallEstablished");
		}

		if ("H".equals(sNewLineState))
		{
			traderLyncCall.setState("CallHeld");
		}

		if ("F".equals(sNewLineState))
		{
			traderLyncCall.setState("CallConferenced");
		}

		traderLyncCall.setValidActions();
	}

    public void handleCallELC(String sCallNo, String sOpenlinkLineNo, String sOpenlinkLineName, String sOpenlinkConsoleNo, String sOpenlinkUserNo, String sHandsetNo, String sELC, String sConnectOrDisconnect)
    {
        OpenlinkCall traderLyncCall = createCallById(sCallNo);
        traderLyncCall.line = sOpenlinkLineNo;

		Log.info("handleCallELC " + traderLyncCall.callid + " "  + sConnectOrDisconnect);

        if("C".equals(sConnectOrDisconnect))
        {
            traderLyncCall.localConferenced = true;
        	traderLyncCall.setState("CallConferenced");

        } else {
            traderLyncCall.localConferenced = false;
 			traderLyncCall.setState("CallEstablished");
		}

		traderLyncCall.setValidActions();

    }

    public void handleBusyLine(String sCallNo, String sOpenlinkLineNo, String sOpenlinkLineName, String sOpenlinkConsoleNo, String sOpenlinkUserNo, String sOldLineState, String sNewLineState,
            String sHandsetOrSpeaker, String sSpeakerNo, String sHandsetNo, String sConnectOrDisconnect)
	{

    }

    public void handleConnectionCleared(String sCallNo)
    {
        OpenlinkCall traderLyncCall = createCallById(sCallNo);
        traderLyncCall.setState("ConnectionCleared");
        traderLyncCall.setValidActions();
        traderLyncCall.participation = "Inactive";
        traderLyncCall.endDuration();

        traderLyncCall.clear();

        getUser().setIntercom(false);
/*
        if ("1".equals(sHandsetNo))
        	getUser().setCurrentHS1Call(null);

 		else if ("2".equals(sHandsetNo))
        	getUser().setCurrentHS2Call(null);

 		else if ("65".equals(sSpeakerNo))
	        getUser().setCurrentICMCall(null);
*/
    }

    public void handleCallOutgoing(String state, String sCallNo, String sCLI, String sOpenlinkLabel)
    {
        OpenlinkCall traderLyncCall = createCallById(sCallNo);
		traderLyncCall.setCLI(sCLI);
		traderLyncCall.setCLILabel(sCLI);
        traderLyncCall.label = sOpenlinkLabel;
        traderLyncCall.direction = "Outgoing";
        traderLyncCall.connectState = state;
        traderLyncCall.setState(state);
		traderLyncCall.setValidActions();
        traderLyncCall.participation = "Active";
    }

    public void handleCallIncoming(String sCallNo, String from, String to)
    {
        OpenlinkCall traderLyncCall = createCallById(sCallNo);
        traderLyncCall.start();
        traderLyncCall.line = sCallNo;

        traderLyncCall.ddi = to;
        traderLyncCall.ddiLabel = to;
		traderLyncCall.setCLI(from);
		traderLyncCall.setCLILabel(from);

        traderLyncCall.label = getInterest().getInterestLabel();
        traderLyncCall.direction = "Incoming";
        traderLyncCall.connectState = "CallEstablished";
        traderLyncCall.setState("CallDelivered");
		traderLyncCall.setValidActions();
        traderLyncCall.participation = "Inactive";
    }

    public void handleCallConnected(String sCallNo)
    {
		Log.debug("setCurrentCall " + sCallNo);

        OpenlinkCall traderLyncCall = createCallById(sCallNo);
        traderLyncCall.start();
        traderLyncCall.label = getInterest().getInterestLabel();

		setCurrentCall(traderLyncCall);

        traderLyncCall.setState(traderLyncCall.connectState);
        traderLyncCall.setValidActions();
        traderLyncCall.startDuration();
        traderLyncCall.participation = "Active";
		traderLyncCall.startParticipation();
    }

    public void handleCallPrivate(String sCallNo, String sOpenlinkLineNo, String sOpenlinkConsoleNo, String sOpenlinkUserNo, String sHandsetNo, String sPrivacyOn)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.setPrivacy(sPrivacyOn);
			traderLyncCall.setValidActions();
		}
    }

    public void handleCallPrivateElsewhere(String sCallNo, String sOpenlinkLineNo, String sOpenlinkConsoleNo, String sOpenlinkUserNo, String sHandsetNo, String sPrivacyOn)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.setPrivacy(sPrivacyOn);
			traderLyncCall.setValidActions();
		}
    }

    public void handleCallAbandoned(String sCallNo)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.setState("CallMissed");
			traderLyncCall.setValidActions();
			traderLyncCall.clear();
		}
    }

    public void handleCallConferenced(String sCallNo)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			setCurrentCall(traderLyncCall);

			traderLyncCall.setState("CallConferenced");
			traderLyncCall.setValidActions();
			traderLyncCall.startDuration();
			traderLyncCall.participation = "Active";
			traderLyncCall.startParticipation();
		}
    }

	public OpenlinkCall getCurrentCall(String handset)
	{
		OpenlinkCall traderLyncCall = null;

		OpenlinkCall intercomCall = getUser().getCurrentICMCall();
		OpenlinkCall traderLyncCall1 = getUser().getCurrentHS1Call();
		OpenlinkCall traderLyncCall2 = getUser().getCurrentHS2Call();

		if ("1".equals(handset))
			traderLyncCall = traderLyncCall1;

		else if ("2".equals(handset))
			traderLyncCall = traderLyncCall2;

		else if ("0".equals(handset))
			traderLyncCall = intercomCall;

		else if ("3".equals(handset))
			traderLyncCall = traderLyncCall1;

        return traderLyncCall;
	}

	private void setCurrentCall(OpenlinkCall traderLyncCall)
	{
		Log.debug("setCurrentCall " + traderLyncCall.getCallID() + " " + traderLyncCall.handset + " " + traderLyncCall.speaker);

        traderLyncCall.console = getUser().getDeviceNo();

        if ("1".equals(traderLyncCall.handset))
        	getUser().setCurrentHS1Call(traderLyncCall);

        else if ("2".equals(traderLyncCall.handset))
        	getUser().setCurrentHS2Call(traderLyncCall);

        else if ("65".equals(traderLyncCall.speaker))
        	getUser().setCurrentICMCall(traderLyncCall);

        else if ("3".equals(traderLyncCall.handset))
        	getUser().setCurrentHS1Call(traderLyncCall);
	}

    public void handleCallBusy(String sCallNo)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.start();
			traderLyncCall.setState("CallBusy");
			traderLyncCall.delivered = true;
			traderLyncCall.setValidActions();
			traderLyncCall.participation = "Inactive";
		}
    }

    public void handleCallFailed(String sCallNo, String sOpenlinkLineNo, String sOpenlinkLineName, String sOpenlinkConsoleNo, String sOpenlinkUserNo, String sOldLineState, String sNewLineState,
            String sHandsetOrSpeaker, String sSpeakerNo, String sHandsetNo, String sConnectOrDisconnect)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.clear();

			traderLyncCall.line = sOpenlinkLineNo;
			traderLyncCall.label = sOpenlinkLineName;
			traderLyncCall.setState("CallFailed");
			traderLyncCall.setValidActions();
			traderLyncCall.participation = "Inactive";
		}
    }

    public void handleCallHeld(String sCallNo)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.setState("CallHeld");
			traderLyncCall.setValidActions();
			traderLyncCall.participation = "Inactive";
			traderLyncCall.endDuration();
		}
    }

    public void handleTransfer(String sCallNo, String sOpenlinkLineNo, String sOpenlinkConsoleNo, String sOpenlinkUserNo, String sTransferUserNo)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.traderLyncTransferFlag = true;
		}
    }

    public void handleIntercom(String sCallNo)
    {
        OpenlinkCall traderLyncCall = createCallById(sCallNo);
        traderLyncCall.platformIntercom = true;
        traderLyncCall.setState("CallEstablished");
        traderLyncCall.setValidActions();

        getUser().setIntercom(true);
    }

    public void handleCallProgress(String sCallNo, String sOpenlinkLineNo, String sChannelNo, String sOpenlinkFlag)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.setCallProgress(sOpenlinkFlag);

			if ("Outgoing".equals(traderLyncCall.direction))
			{
				if("CallOriginated".equals(traderLyncCall.getState()))
				{
					if("0".equals(sOpenlinkFlag))
					{
						if("D".equals(getInterest().getInterestType()))
						{
							traderLyncCall.setState("CallDelivered");

						} else
							traderLyncCall.setState("CallEstablished");

					} else if("4".equals(sOpenlinkFlag) || "1".equals(sOpenlinkFlag)) {

						traderLyncCall.setState("CallEstablished");

					} else
						traderLyncCall.setState("CallFailed");
				} else

				if("CallDelivered".equals(traderLyncCall.getState()))
				{
					if("2".equals(sOpenlinkFlag))
					{
						traderLyncCall.setState("CallEstablished");

					} else if("4".equals(sOpenlinkFlag) || "1".equals(sOpenlinkFlag)) {

						traderLyncCall.setState("CallEstablished");

					} else
						traderLyncCall.setState("CallFailed");
				}

				traderLyncCall.setValidActions();
			}

			if("CallEstablished".equals(traderLyncCall.getState()))
			{
				traderLyncCall.startDuration();
			}
		}
    }

    public void handleCallProceeding(OpenlinkComponent component, String sCallNo, String sOpenlinkLineNo, String sDigits, String sEndFlag)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			traderLyncCall.proceedingDigitsBuffer = (new StringBuilder()).append(traderLyncCall.proceedingDigitsBuffer).append(sDigits.trim()).toString();

			if("Y".equals(sEndFlag) && !"".equals(traderLyncCall.proceedingDigitsBuffer))
			{
				traderLyncCall.proceedingDigits = traderLyncCall.proceedingDigitsBuffer;
				traderLyncCall.proceedingDigitsBuffer = "";
				traderLyncCall.proceedingDigitsLabel = traderLyncCall.proceedingDigits;

				String cononicalNumber = traderLyncCall.proceedingDigits;

				try
				{
					cononicalNumber = component.formatCanonicalNumber(traderLyncCall.proceedingDigits);
				}
				catch(Exception e) { }

				//if(component.traderLyncLdapService.cliLookupTable.containsKey(cononicalNumber))
				//	traderLyncCall.proceedingDigitsLabel = (String)component.traderLyncLdapService.cliLookupTable.get(cononicalNumber);
			}
		}
    }

    public void handleCallMoved(String sCallNo, String sOpenlinkLineNo, String sOpenlinkLineNo2)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
        	traderLyncCall.line = sOpenlinkLineNo2;
		}
    }

    public void handleRecallTransfer(String sCallNo, String sOpenlinkLineNo, String sOpenlinkLineNo2, String transferStatusFlag)
    {
        OpenlinkCall traderLyncCall = getCallById(sCallNo);

        if (traderLyncCall != null)
        {
			if("0".equals(transferStatusFlag))
			{
				traderLyncCall.setState("CallTransferring");
				traderLyncCall.transferFlag = false;

			} else if("1".equals(transferStatusFlag)) {

				traderLyncCall.setState("CallEstablished");
				traderLyncCall.transferFlag = false;

				if (traderLyncCall.previousCalledNumber != null)
				{
					Iterator<OpenlinkUserInterest> it3 = getInterest().getUserInterests().values().iterator();

					while( it3.hasNext() )
					{
						OpenlinkUserInterest theUserInterest = (OpenlinkUserInterest)it3.next();
						OpenlinkCall theCall = theUserInterest.getCallByLine(traderLyncCall.getLine());

						if (theCall != null)
						{
							theCall.proceedingDigits = traderLyncCall.previousCalledNumber;
							theCall.proceedingDigitsLabel = traderLyncCall.previousCalledLabel;
						}
					}
				}

			} else if("2".equals(transferStatusFlag)) {

				traderLyncCall.setState("CallTransferred");

			}

			traderLyncCall.setValidActions();
		}
    }

    public String getDefault()
    {
        return defaultInterest;
    }

    public void setDefault(String defaultInterest)
    {
        this.defaultInterest = defaultInterest;
    }

    public OpenlinkUser getUser()
    {
        return traderLyncUser;
    }

    public void setUser(OpenlinkUser traderLyncUser)
    {
        this.traderLyncUser = traderLyncUser;
    }

    public Map<String, OpenlinkSubscriber> getSubscribers()
    {
        return traderLyncSubscribers;
    }

    public void setSubscribers(Map<String, OpenlinkSubscriber> traderLyncSubscribers)
    {
        this.traderLyncSubscribers = traderLyncSubscribers;
    }

    public boolean isSubscribed(JID subscriber)
    {
        return traderLyncSubscribers.containsKey(subscriber.getNode());
    }

    public OpenlinkSubscriber getSubscriber(JID subscriber)
    {
        OpenlinkSubscriber traderLyncSubscriber = null;

        if (traderLyncSubscribers.containsKey(subscriber.getNode()))
        {
            traderLyncSubscriber = (OpenlinkSubscriber)traderLyncSubscribers.get(subscriber.getNode());
        } else
        {
            traderLyncSubscriber = new OpenlinkSubscriber();
            traderLyncSubscriber.setJID(subscriber);
            traderLyncSubscribers.put(subscriber.getNode(), traderLyncSubscriber);
        }
        return traderLyncSubscriber;
    }

    public void removeSubscriber(JID subscriber)
    {
		traderLyncSubscribers.remove(subscriber.getNode());
	}

    public boolean canPublish(OpenlinkComponent component)
    {
		if (traderLyncSubscribers.size() == 0)
		{
			return false;
		}

		boolean anySubscriberOnline = false;

		Iterator<OpenlinkSubscriber> iter = traderLyncSubscribers.values().iterator();

		while( iter.hasNext() )
		{
			OpenlinkSubscriber subscriber = (OpenlinkSubscriber)iter.next();

			if (subscriber.getOnline() || component.isComponent(subscriber.getJID()))
			{
				anySubscriberOnline = true;
				break;
			}
		}

		return anySubscriberOnline;
    }

    public OpenlinkInterest getInterest()
    {
        return traderLyncInterest;
    }

    public void setInterest(OpenlinkInterest traderLyncInterest)
    {
        this.traderLyncInterest = traderLyncInterest;
    }

    public synchronized OpenlinkCall createCallById(String callID)
    {
		Log.debug("createCallById " + callID);

        OpenlinkCall traderLyncCall = null;

        if(traderLyncCalls.containsKey(callID))
        {
            traderLyncCall = (OpenlinkCall)traderLyncCalls.get(callID);

        } else {

            traderLyncCall = new OpenlinkCall();
            traderLyncCall.callid = callID;
            traderLyncCall.setOpenlinkUserInterest(this);

			if("D".equals(getInterest().getInterestType()))	// set default caller ID for directory numbers
			{
				traderLyncCall.ddi = getInterest().getInterestValue();
				traderLyncCall.ddiLabel = getInterest().getInterestLabel();
			}

            traderLyncCall.initialiseDuration();

            traderLyncCalls.put(callID, traderLyncCall);
        }
        return traderLyncCall;
    }

    public OpenlinkCall getCallById(String callID)
    {
        OpenlinkCall traderLyncCall = null;

        if(traderLyncCalls.containsKey(callID))
        {
            traderLyncCall = (OpenlinkCall)traderLyncCalls.get(callID);
		}
        return traderLyncCall;
	}

	public OpenlinkCall getCallByLine(String line)
	{
        OpenlinkCall lineCall = null;

		Iterator it2 = traderLyncCalls.values().iterator();

		while( it2.hasNext() )
		{
			OpenlinkCall traderLyncCall = (OpenlinkCall)it2.next();

			if (line.equals(traderLyncCall.line))
			{
				lineCall = traderLyncCall;
				break;
			}
		}

		return  lineCall;
	}

    public OpenlinkCall removeCallById(String callID)
    {
		OpenlinkCall traderLyncCall = null;

        if(traderLyncCalls.containsKey(callID))
        {
            traderLyncCall = (OpenlinkCall)traderLyncCalls.get(callID);
            traderLyncCalls.remove(callID);
        }

        return traderLyncCall;
	}

    public Map<String, OpenlinkCall> getCalls()
    {
        return traderLyncCalls;
    }

	public boolean isLineActive(String line)
	{
		OpenlinkCall traderLyncCall1 = getUser().getCurrentHS1Call();
		OpenlinkCall traderLyncCall2 = getUser().getCurrentHS2Call();

		boolean active = false;

		if (traderLyncCall1 != null && !"".equals(traderLyncCall1.line))
		{
			if (line.equals(String.valueOf(Long.parseLong(traderLyncCall1.line))))
				active = true;
		}

		if (traderLyncCall2 != null && !"".equals(traderLyncCall2.line))
		{
			if (line.equals(String.valueOf(Long.parseLong(traderLyncCall2.line))))
				active = true;
		}

		return active;
	}

	public boolean getHandsetBusyStatus()
	{
		OpenlinkCall traderLyncCall1 = getUser().getCurrentHS1Call();
		OpenlinkCall traderLyncCall2 = getUser().getCurrentHS2Call();

		if (traderLyncCall1 == null && traderLyncCall2 == null)
			return false;

		Iterator it2 = traderLyncCalls.values().iterator();
		boolean busy1 = false;
		boolean busy2 = false;

		while( it2.hasNext() )
		{
			OpenlinkCall traderLyncCall = (OpenlinkCall)it2.next();

			if (traderLyncCall1 != null && traderLyncCall.getCallID().equals(traderLyncCall1.getCallID()))
			{
				busy1 = true;
			}

			if (traderLyncCall2 != null && traderLyncCall.getCallID().equals(traderLyncCall2.getCallID()))
			{
				busy2 = true;
			}
		}

		return  busy1 && busy2;
	}

	public int getActiveCalls()
	{
		Iterator it2 = traderLyncCalls.values().iterator();
		int calls = 0;

		while( it2.hasNext() )
		{
			OpenlinkCall traderLyncCall = (OpenlinkCall)it2.next();

			if (! "ConnectionCleared".equals(traderLyncCall.getState()))
			{
				calls++;
			}
		}

		return calls;
	}

	public boolean getBusyStatus()
	{
		return (getActiveCalls() >= getMaxNumCalls());
	}

	public String getCallFWD() {
		return callFWD;
	}

	public void setCallFWD(String callFWD) {
		this.callFWD = callFWD;
	}

	public String getCallFWDDigits() {
		return callFWDDigits;
	}

	public void setCallFWDDigits(String callFWDDigits) {
		this.callFWDDigits = callFWDDigits;
	}

	public void setMaxNumCalls(int maxNumCalls) {
		this.maxNumCalls = maxNumCalls;
	}

	public int getMaxNumCalls() {
		return maxNumCalls;
	}

    public void logCall(OpenlinkCall traderLyncCall, String domain, long site)
    {
		String callId =  traderLyncCall.getCallID() + "-" + System.currentTimeMillis();
		String tscId = traderLyncCall.line;

		//if ("CallMissed".equals(traderLyncCall.getState()) || "CallEstablished".equals(traderLyncCall.getState()))
		//{
			Log.debug("writing call record " + callId + " " + traderLyncCall.getState());

			CallLogger.getLogger().logCall(tscId, callId, getUser().getProfileName(), getInterestName(), traderLyncCall.getState(), traderLyncCall.direction, traderLyncCall.creationTimeStamp, traderLyncCall.getDuration(), traderLyncCall.getCallerNumber(getInterest().getInterestType()), traderLyncCall.getCallerName(getInterest().getInterestType()), traderLyncCall.getCalledNumber(getInterest().getInterestType()), traderLyncCall.getCalledName(getInterest().getInterestType()));

			Iterator it3 = getInterest().getUserInterests().values().iterator();

			while( it3.hasNext() )
			{
				OpenlinkUserInterest traderLyncParticipant = (OpenlinkUserInterest)it3.next();

				OpenlinkCall participantCall = traderLyncParticipant.getCallByLine(traderLyncCall.getLine());

				if (participantCall != null)
				{
					Log.debug("writing call participant record " + callId + " " + traderLyncParticipant.getUser().getUserId());

					//if (("Active".equals(participantCall.firstParticipation) && "ConnectionCleared".equals(participantCall.getState())))
					//{
						CallLogger.getLogger().logParticipant(tscId, callId, traderLyncParticipant.getUser().getUserId() + "@" + traderLyncParticipant.getUser().getUserNo() + "." + domain, participantCall.direction, participantCall.firstParticipation, participantCall.firstTimeStamp, participantCall.getDuration());
					//}

					//if ("CallMissed".equals(participantCall.getState()))
					//{
					//	CallLogger.getLogger().logParticipant(tscId, callId, traderLyncParticipant.getUser().getUserId() + "@" + traderLyncParticipant.getUser().getUserNo() + "." + domain, participantCall.direction, participantCall.firstParticipation, participantCall.creationTimeStamp, participantCall.getRingDuration());
					//}

				}
			}
		//}
    }
}


text:
'use strict';

(function() {
	// Messages Controller Spec
	describe('Messages Controller Tests', function() {
		// Initialize global variables
		var MessagesController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Messages controller.
			MessagesController = $controller('MessagesController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Message object fetched from XHR', inject(function(Messages) {
			// Create sample Message using the Messages service
			var sampleMessage = new Messages({
				name: 'New Message'
			});

			// Create a sample Messages array that includes the new Message
			var sampleMessages = [sampleMessage];

			// Set GET response
			$httpBackend.expectGET('messages').respond(sampleMessages);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.messages).toEqualData(sampleMessages);
		}));

		it('$scope.findOne() should create an array with one Message object fetched from XHR using a messageId URL parameter', inject(function(Messages) {
			// Define a sample Message object
			var sampleMessage = new Messages({
				name: 'New Message'
			});

			// Set the URL parameter
			$stateParams.messageId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/messages\/([0-9a-fA-F]{24})$/).respond(sampleMessage);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.message).toEqualData(sampleMessage);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Messages) {
			// Create a sample Message object
			var sampleMessagePostData = new Messages({
				name: 'New Message'
			});

			// Create a sample Message response
			var sampleMessageResponse = new Messages({
				_id: '525cf20451979dea2c000001',
				name: 'New Message'
			});

			// Fixture mock form input values
			scope.name = 'New Message';

			// Set POST response
			$httpBackend.expectPOST('messages', sampleMessagePostData).respond(sampleMessageResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Message was created
			expect($location.path()).toBe('/messages/' + sampleMessageResponse._id);
		}));

		it('$scope.update() should update a valid Message', inject(function(Messages) {
			// Define a sample Message put data
			var sampleMessagePutData = new Messages({
				_id: '525cf20451979dea2c000001',
				name: 'New Message'
			});

			// Mock Message in scope
			scope.message = sampleMessagePutData;

			// Set PUT response
			$httpBackend.expectPUT(/messages\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/messages/' + sampleMessagePutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid messageId and remove the Message from the scope', inject(function(Messages) {
			// Create new Message object
			var sampleMessage = new Messages({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Messages array and include the Message
			scope.messages = [sampleMessage];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/messages\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleMessage);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.messages.length).toBe(0);
		}));
	});
}());