text:
package org.toobs.data.criteria;

import java.util.ArrayList;

@SuppressWarnings("unchecked")
public abstract class BaseCriteria {

  private java.lang.Boolean paged = new Boolean(false);
  private java.lang.Boolean activeInd;
  private ArrayList order;

  public java.lang.Boolean getPaged() {
    return this.paged;
  }

  public void setPaged(java.lang.Boolean paged) {
    this.paged = paged;
  }

  public ArrayList getOrder() {
    return order;
  }

  public void setOrder(ArrayList order) {
    this.order = new ArrayList();
    if (order != null) {
      for (int i = 0; i < order.size(); i++) {
        String orderInst = (String)order.get(i);
        if (orderInst != null) {
          String[] orderSplit = orderInst.split(";");
          for (int o = 0; o < orderSplit.length; o++) {
            this.order.add(orderSplit[o]);
          }
        }
      }
    }
  }

  public java.lang.Boolean getActiveInd() {
    return activeInd;
  }

  public void setActiveInd(java.lang.Boolean activeInd) {
    this.activeInd = activeInd;
  }

  public abstract java.lang.Integer getMaximumResultSize();

  public abstract java.lang.Integer getFirstResult();

  public abstract void setFirstResult(java.lang.Integer firstResult);

  public abstract void setTotalRows(java.lang.Integer totalRows);

  public boolean applyOrder(ICriteriaSearchParameter parameter, String attributeName) {
    if (this.getOrder() != null && this.getOrder().size() > 0) {
      if(this.getOrder().contains(attributeName + "_ASC")){
        parameter.setOrderDirection(ICriteriaSearchParameter.ORDER_ASC);
        parameter.setOrderRelevance(this.getOrder().indexOf(attributeName + "_ASC"));
        this.getOrder().remove(attributeName + "_ASC");
      }
      if(this.getOrder().contains(attributeName + "_DSC")){
        parameter.setOrderDirection(ICriteriaSearchParameter.ORDER_DESC);
        parameter.setOrderRelevance(this.getOrder().indexOf(attributeName + "_DSC"));
        this.getOrder().remove(attributeName + "_DSC");
      }
      return true;
    } else {
      return false;
    }
  }

}


text:
package edu.atilim.acma.ui;

public final class Actions {
	public static final String DESIGN_LOAD = "designLoad";
	public static final String DESIGN_UNLOAD = "designUnLoad";
	public static final String EXIT = "exit";
	public static final String CONFIG_RUN = "confRun";
	public static final String ABOUT = "about";
	public static final String CLEAR_CONSOLE = "clrConsole";
	public static final String SAVE_METRICS = "saveMetrics";

	// Config panel
	public static final String CONF_ADD = "confAdd";
	public static final String CONF_REMOVE = "confRemove";
	public static final String CONF_DUPLICATE = "confDuplicate";
}

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import numpy as np
sys.path.insert(0, os.path.abspath('..'))
from lily import k_means
from lily import utils
import logging

logging.basicConfig(level=logging.INFO, format="%(funcName)s\t%(message)s")

def bisecting_k_means():
    data_matrix = np.mat(utils.load_tsv_into_array('data/test_set_2.txt'))
    centroid_list, assessments = k_means.bisect_k_means(data_matrix, 3)
    return centroid_list, assessments

def main():
    data_array = utils.load_tsv_into_array('data/k_means_test_set.txt')
    data_matrix = np.mat(data_array)

    rand_cent = k_means.random_centroid(data_matrix, 2)
    logging.info("random centroid = {rand_cent}".format(rand_cent=rand_cent))

    euc = k_means.euclidean_distance(data_matrix[0], data_matrix[1])
    logging.info("Euclidean distance = {euc}".format(euc=euc))

    centroids, cluster_assignment = k_means.k_means(data_matrix, 4)
    logging.info("centroids = {cent}".format(cent=centroids))

    bisecting_k_means()

if __name__ == '__main__':
    main()


text:
#include "postgres.h"

#include "utils/builtins.h"
#include "windowapi.h"

/*
 * ranking process information
 */
typedef struct rank_context
{
	int64		rank;			/* current rank */
} rank_context;

/*
 * ntile process information
 */
typedef struct
{
	int32		ntile;			/* current result */
	int64		rows_per_bucket;	/* row number of current bucket */
	int64		boundary;		/* how many rows should be in the bucket */
	int64		remainder;		/* (total rows) % (bucket num) */
} ntile_context;

static bool rank_up(WindowObject winobj);
static Datum leadlag_common(FunctionCallInfo fcinfo,
			   bool forward, bool withoffset, bool withdefault);

/*
 * utility routine for *_rank functions.
 */
static bool
rank_up(WindowObject winobj)
{
	bool		up = false;		/* should rank increase? */
	int64		curpos = WinGetCurrentPosition(winobj);
	rank_context *context;

	context = (rank_context *)
		WinGetPartitionLocalMemory(winobj, sizeof(rank_context));

	if (context->rank == 0)
	{
		/* first call: rank of first row is always 1 */
		Assert(curpos == 0);
		context->rank = 1;
	}
	else
	{
		Assert(curpos > 0);
		/* do current and prior tuples match by ORDER BY clause? */
		if (!WinRowsArePeers(winobj, curpos - 1, curpos))
			up = true;
	}

	/* We can advance the mark, but only *after* acccess to prior row */
	WinSetMarkPosition(winobj, curpos);

	return up;
}

/*
 * row_number
 * just increment up from 1 until current partition finishes.
 */
Datum
window_row_number(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	int64		curpos = WinGetCurrentPosition(winobj);

	WinSetMarkPosition(winobj, curpos);
	PG_RETURN_INT64(curpos + 1);
}

/*
 * rank
 * Rank changes when key columns change.
 * The new rank number is the current row number.
 */
Datum
window_rank(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	rank_context *context;
	bool		up;

	up = rank_up(winobj);
	context = (rank_context *)
		WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
	if (up)
		context->rank = WinGetCurrentPosition(winobj) + 1;

	PG_RETURN_INT64(context->rank);
}

/*
 * dense_rank
 * Rank increases by 1 when key columns change.
 */
Datum
window_dense_rank(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	rank_context *context;
	bool		up;

	up = rank_up(winobj);
	context = (rank_context *)
		WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
	if (up)
		context->rank++;

	PG_RETURN_INT64(context->rank);
}

/*
 * percent_rank
 * return fraction between 0 and 1 inclusive,
 * which is described as (RK - 1) / (NR - 1), where RK is the current row's
 * rank and NR is the total number of rows, per spec.
 */
Datum
window_percent_rank(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	rank_context *context;
	bool		up;
	int64		totalrows = WinGetPartitionRowCount(winobj);

	Assert(totalrows > 0);

	up = rank_up(winobj);
	context = (rank_context *)
		WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
	if (up)
		context->rank = WinGetCurrentPosition(winobj) + 1;

	/* return zero if there's only one row, per spec */
	if (totalrows <= 1)
		PG_RETURN_FLOAT8(0.0);

	PG_RETURN_FLOAT8((float8) (context->rank - 1) / (float8) (totalrows - 1));
}

/*
 * cume_dist
 * return fraction betweeen 0 and 1 inclusive,
 * which is described as NP / NR, where NP is the number of rows preceding or
 * peers to the current row, and NR is the total number of rows, per spec.
 */
Datum
window_cume_dist(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	rank_context *context;
	bool		up;
	int64		totalrows = WinGetPartitionRowCount(winobj);

	Assert(totalrows > 0);

	up = rank_up(winobj);
	context = (rank_context *)
		WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
	if (up || context->rank == 1)
	{
		/*
		 * The current row is not peer to prior row or is just the first, so
		 * count up the number of rows that are peer to the current.
		 */
		int64		row;

		context->rank = WinGetCurrentPosition(winobj) + 1;

		/*
		 * start from current + 1
		 */
		for (row = context->rank; row < totalrows; row++)
		{
			if (!WinRowsArePeers(winobj, row - 1, row))
				break;
			context->rank++;
		}
	}

	PG_RETURN_FLOAT8((float8) context->rank / (float8) totalrows);
}

/*
 * ntile
 * compute an exact numeric value with scale 0 (zero),
 * ranging from 1 (one) to n, per spec.
 */
Datum
window_ntile(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	ntile_context *context;

	context = (ntile_context *)
		WinGetPartitionLocalMemory(winobj, sizeof(ntile_context));

	if (context->ntile == 0)
	{
		/* first call */
		int64		total;
		int32		nbuckets;
		bool		isnull;

		total = WinGetPartitionRowCount(winobj);
		nbuckets = DatumGetInt32(WinGetFuncArgCurrent(winobj, 0, &isnull));

		/*
		 * per spec: If NT is the null value, then the result is the null
		 * value.
		 */
		if (isnull)
			PG_RETURN_NULL();

		/*
		 * per spec: If NT is less than or equal to 0 (zero), then an
		 * exception condition is raised.
		 */
		if (nbuckets <= 0)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_ARGUMENT_FOR_NTILE),
					 errmsg("argument of ntile must be greater than zero")));

		context->ntile = 1;
		context->rows_per_bucket = 0;
		context->boundary = total / nbuckets;
		if (context->boundary <= 0)
			context->boundary = 1;
		else
		{
			/*
			 * If the total number is not divisible, add 1 row to leading
			 * buckets.
			 */
			context->remainder = total % nbuckets;
			if (context->remainder != 0)
				context->boundary++;
		}
	}

	context->rows_per_bucket++;
	if (context->boundary < context->rows_per_bucket)
	{
		/* ntile up */
		if (context->remainder != 0 && context->ntile == context->remainder)
		{
			context->remainder = 0;
			context->boundary -= 1;
		}
		context->ntile += 1;
		context->rows_per_bucket = 1;
	}

	PG_RETURN_INT32(context->ntile);
}

/*
 * leadlag_common
 * common operation of lead() and lag()
 * For lead() forward is true, whereas for lag() it is false.
 * withoffset indicates we have an offset second argument.
 * withdefault indicates we have a default third argument.
 */
static Datum
leadlag_common(FunctionCallInfo fcinfo,
			   bool forward, bool withoffset, bool withdefault)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	int32		offset;
	bool		const_offset;
	Datum		result;
	bool		isnull;
	bool		isout;

	if (withoffset)
	{
		offset = DatumGetInt32(WinGetFuncArgCurrent(winobj, 1, &isnull));
		if (isnull)
			PG_RETURN_NULL();
		const_offset = get_fn_expr_arg_stable(fcinfo->flinfo, 1);
	}
	else
	{
		offset = 1;
		const_offset = true;
	}

	result = WinGetFuncArgInPartition(winobj, 0,
									  (forward ? offset : -offset),
									  WINDOW_SEEK_CURRENT,
									  const_offset,
									  &isnull, &isout);

	if (isout)
	{
		/*
		 * target row is out of the partition; supply default value if
		 * provided.  otherwise it'll stay NULL
		 */
		if (withdefault)
			result = WinGetFuncArgCurrent(winobj, 2, &isnull);
	}

	if (isnull)
		PG_RETURN_NULL();

	PG_RETURN_DATUM(result);
}

/*
 * lag
 * returns the value of VE evaluated on a row that is 1
 * row before the current row within a partition,
 * per spec.
 */
Datum
window_lag(PG_FUNCTION_ARGS)
{
	return leadlag_common(fcinfo, false, false, false);
}

/*
 * lag_with_offset
 * returns the value of VE evelulated on a row that is OFFSET
 * rows before the current row within a partition,
 * per spec.
 */
Datum
window_lag_with_offset(PG_FUNCTION_ARGS)
{
	return leadlag_common(fcinfo, false, true, false);
}

/*
 * lag_with_offset_and_default
 * same as lag_with_offset but accepts default value
 * as its third argument.
 */
Datum
window_lag_with_offset_and_default(PG_FUNCTION_ARGS)
{
	return leadlag_common(fcinfo, false, true, true);
}

/*
 * lead
 * returns the value of VE evaluated on a row that is 1
 * row after the current row within a partition,
 * per spec.
 */
Datum
window_lead(PG_FUNCTION_ARGS)
{
	return leadlag_common(fcinfo, true, false, false);
}

/*
 * lead_with_offset
 * returns the value of VE evaluated on a row that is OFFSET
 * number of rows after the current row within a partition,
 * per spec.
 */
Datum
window_lead_with_offset(PG_FUNCTION_ARGS)
{
	return leadlag_common(fcinfo, true, true, false);
}

/*
 * lead_with_offset_and_default
 * same as lead_with_offset but accepts default value
 * as its third argument.
 */
Datum
window_lead_with_offset_and_default(PG_FUNCTION_ARGS)
{
	return leadlag_common(fcinfo, true, true, true);
}

/*
 * first_value
 * return the value of VE evaluated on the first row of the
 * window frame, per spec.
 */
Datum
window_first_value(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	Datum		result;
	bool		isnull;

	result = WinGetFuncArgInFrame(winobj, 0,
								  0, WINDOW_SEEK_HEAD, true,
								  &isnull, NULL);
	if (isnull)
		PG_RETURN_NULL();

	PG_RETURN_DATUM(result);
}

/*
 * last_value
 * return the value of VE evaluated on the last row of the
 * window frame, per spec.
 */
Datum
window_last_value(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	Datum		result;
	bool		isnull;

	result = WinGetFuncArgInFrame(winobj, 0,
								  0, WINDOW_SEEK_TAIL, true,
								  &isnull, NULL);
	if (isnull)
		PG_RETURN_NULL();

	PG_RETURN_DATUM(result);
}

/*
 * nth_value
 * return the value of VE evaluated on the n-th row from the first
 * row of the window frame, per spec.
 */
Datum
window_nth_value(PG_FUNCTION_ARGS)
{
	WindowObject winobj = PG_WINDOW_OBJECT();
	bool		const_offset;
	Datum		result;
	bool		isnull;
	int32		nth;

	nth = DatumGetInt32(WinGetFuncArgCurrent(winobj, 1, &isnull));
	if (isnull)
		PG_RETURN_NULL();
	const_offset = get_fn_expr_arg_stable(fcinfo->flinfo, 1);

	if (nth <= 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_ARGUMENT_FOR_NTH_VALUE),
				 errmsg("argument of nth_value must be greater than zero")));

	result = WinGetFuncArgInFrame(winobj, 0,
								  nth - 1, WINDOW_SEEK_HEAD, const_offset,
								  &isnull, NULL);
	if (isnull)
		PG_RETURN_NULL();

	PG_RETURN_DATUM(result);
}


text:
.. pid.rst
.. py:module:: dit.pid

*********************************
Partial Information Decomposition
*********************************

The *partial information decomposition* (PID), put forth by Williams & Beer :cite:`williams2010nonnegative`, is a framework for decomposing the information shared between a set of variables we will refer to as *inputs*, :math:`X_0, X_1, \ldots`, and another random variable we will refer to as the *output*, :math:`Y`. This decomposition seeks to partition the information :math:`\I{X_0,X_1,\ldots : Y}` among the antichains of the inputs.

Background
==========

It is often desirable to determine how a set of inputs influence the behavior of an output. Consider the exclusive or logic gates, for example:

.. ipython::

   In [1]: from dit.pid.distributions import bivariates, trivariates

   In [2]: xor = bivariates['synergy']

   In [3]: print(xor)
   Class:          Distribution
   Alphabet:       ('0', '1') for all rvs
   Base:           linear
   Outcome Class:  str
   Outcome Length: 3
   RV Names:       None

   x     p(x)
   000   1/4
   011   1/4
   101   1/4
   110   1/4

We can see from inspection that either input (the first two indexes) is independent of the output (the final index), yet the two inputs together determine the output. One could call this "synergistic" information. Next, consider the giant bit distribution:

.. ipython::

   In [4]: gb = bivariates['redundant']

   In [5]: print(gb)
   Class:          Distribution
   Alphabet:       ('0', '1') for all rvs
   Base:           linear
   Outcome Class:  str
   Outcome Length: 3
   RV Names:       None

   x     p(x)
   000   1/2
   111   1/2

Here, we see that either input informs us of exactly what the output is. One could call this "redundant" information. Furthermore, consider the :ref:`coinformation` of these distributions:

.. ipython::

   In [6]: from dit.multivariate import coinformation as I

   In [7]: I(xor)
   Out[7]: -1.0

   In [8]: I(gb)
   Out[8]: 1.0

This could lead one to intuit that negative values of the coinformation correspond to synergistic effects in a distribution, while positive values correspond to redundant effects. This intuition, however, is at best misleading: the coinformation of a 4-variable giant bit and 4-variable parity distribution are both positive:

.. ipython::

   In [9]: I(dit.example_dists.giant_bit(4, 2))
   Out[9]: 1.0

   In [10]: I(dit.example_dists.n_mod_m(4, 2))
   Out[10]: 1.0

This, as well as other issues, lead Williams & Beer :cite:`williams2010nonnegative` to propose the *partial information decomposition*.

Framework
=========

The goal of the partial information is to assign to each some non-negative portion of :math:`\I{\{X_i\} : Y}` to each antichain over the inputs. An antichain over the inputs is a set of sets, where each of those sets is not a subset of any of the others. For example, :math:`\left\{ \left\{X_0, X_1\right\}, \left\{X_1, X_2\right\} \right\}` is an antichain, but :math:`\left\{ \left\{X_0, X_1\right\}, \left\{X_0 X_1, X_2\right\} \right\}` is not.

The antichains for a lattice based on this partial order:

.. math::

   \alpha \leq \beta \iff \forall \mathbf{b} \in \beta, \exists \mathbf{a} \in \alpha, \mathbf{a} \subseteq \mathbf{b}

From here, we wish to find a redundancy measure, :math:`\Icap{\bullet}` which would assign a fraction of :math:`\I{\{X_i\} : Y}` to each antichain intuitively quantifying what portion of the information in the output could be learned by observing any of the sets of variables within the antichain. In order to be a viable measure of redundancy, there are several axioms a redundancy measure must satisfy.

Bivariate Lattice
-----------------

Let us consider the special case of two inputs. The lattice consists of four elements: :math:`\left\{\left\{X_0\right\}, \left\{X_1\right\}\right\}`, :math:`\left\{\left\{X_0\right\}\right\}`, :math:`\left\{\left\{X_1\right\}\right\}`, and :math:`\left\{\left\{X_0, X_1\right\}\right\}`. We can interpret these elements as the *redundancy* provided by both inputs, the information *uniquely* provided by :math:`X_0`, the information *uniquely* provided by :math:`X_1`, and the information *synergistically* provided only by both inputs together. Together these for elements decompose the input-output mutual information:

.. math::

   \I{X_0, X_1 : Y} = \Ipart{\left\{X_0\right\}, \left\{X_1\right\} : Y} + \Ipart{\left\{X_0\right\} : Y} + \Ipart{\left\{X_1\right\} : Y} + \Ipart{\left\{X_0, X_1\right\} : Y}

Furthermore, due to the self-redundancy axiom (described ahead), the single-input mutual informations decomposed in the following way:

.. math::

   \I{X_0 : Y} = \Ipart{\left\{X_0\right\}, \left\{X_1\right\} : Y} + \Ipart{\left\{X_0\right\} : Y}

   \I{X_1 : Y} = \Ipart{\left\{X_0\right\}, \left\{X_1\right\} : Y} + \Ipart{\left\{X_1\right\} : Y}

Colloquially, from input :math:`X_0` one can learn what is redundantly provided by either input, plus what is uniquely provided by :math:`X_0`, but not what is uniquely provided by :math:`X_1` or what can only be learned synergistically from both inputs.

Axioms
------

The following three axioms were provided by Williams & Beer.

Symmetry
^^^^^^^^

The redundancy :math:`\Icap{X_{0:n} : Y}` is invariant under reorderings of :math:`X_i`.

Self-Redundancy
^^^^^^^^^^^^^^^

The redundancy of a single input is its mutual information with the output:

.. math::

   \Icap{X_i : Y} = \I{X_i : Y}

Monotonicity
^^^^^^^^^^^^

The redundancy should only decrease with in inclusion of more inputs:

.. math::

   \Icap{\mathcal{A}_1, \ldots, \mathcal{A}_{k-1}, \mathcal{A}_k : Y} \leq \Icap{\mathcal{A}_1, \ldots, \mathcal{A}_{k-1} : Y}

with equality if :math:`\mathcal{A}_{k-1} \subseteq \mathcal{A}_k`.

There have been other axioms proposed following from those of Williams & Beer.

Identity
^^^^^^^^

The identity axiom :cite:`harder2013bivariate` states that if the output is identical to the inputs, then the redundancy is the mutual information between the inputs:

.. math::

   \Icap{X_0, X_1 : \left(X_0, X_1\right)} = \I{X_0 : X_1}

Target (output) Monotonicity
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This axiom states that redundancy can not increase when replacing the output by a function of itself.

.. math::

   \Icap{X_{0:n} : Y} \ge \Icap{X_{0:n} : f(Y)}

It first appeared in :cite:`bertschinger2013shared` and was expanded upon in :cite:`rauh2017extractable`.

Measures
========

We now turn our attention a variety of methods proposed to flesh out this partial information decomposition.

.. ipython::

   In [11]: from dit.pid import *

.. py:module:: dit.pid.imin
:math:`\Imin{\bullet}`
----------------------

:math:`\Imin{\bullet}`:cite:`williams2010nonnegative` was Williams & Beer's initial proposal for a redundancy measure. It is given by:

.. math::

   \Imin{\mathcal{A}_1, \mathcal{A}_2, \ldots : Y} = \sum_{y \in Y} p(y) \min_{\mathcal{A}_i} \I{\mathcal{A}_i : Y=y}

However, this measure has been criticized for acting in an unintuitive manner :cite:`griffith2014quantifying`:

.. ipython::

   In [12]: d = dit.Distribution(['000', '011', '102', '113'], [1/4]*4)

   In [13]: PID_WB(d)
   ╔════════╤════════╤════════╗
   ║ I_min  │  I_r   │   pi   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 2.0000 │ 1.0000 ║
   ║  {0}   │ 1.0000 │ 0.0000 ║
   ║  {1}   │ 1.0000 │ 0.0000 ║
   ║ {0}{1} │ 1.0000 │ 1.0000 ║
   ╚════════╧════════╧════════╝

We have constructed a distribution whose inputs are independent random bits, and whose output is the concatenation of those inputs. Intuitively, the output should then be informed by one bit of unique information from :math:`X_0` and one bit of unique information from :math:`X_1`. However, :math:`\Imin{\bullet}` assesses that there is one bit of redundant information, and one bit of synergistic information. This is because :math:`\Imin{\bullet}` quantifies redundancy as the least amount of information one can learn about an output given any single input. Here, however, the one bit we learn from :math:`X_0` is, in a sense, orthogonal from the one bit we learn from :math:`X_1`. This observation has lead to much of the follow-on work.

.. py:module:: dit.pid.immi
:math:`\Immi{\bullet}`
----------------------

One potential measure of redundancy is the *minimum mutual information* :cite:`bertschinger2013shared`:

.. math::

   \Immi{X_{0:n} : Y} = \min_{i} \I{X_i : Y}

This measure, though crude, is known to be correct for multivariate gaussian variables :cite:`olbrich2015information`.

.. py:module:: dit.pid.iwedge
:math:`\Iwedge{\bullet}`
------------------------

Redundancy seems to intuitively be related to common information :ref:`Common Informations`. This intuition lead to the development of :math:`\Iwedge{\bullet}` :cite:`griffith2014intersection`:

.. math::

   \Iwedge{X_{0:n} : Y} = \I{ \meet X_i : Y}

That is, redundancy is the information the :ref:`Gács-Körner Common Information` of the inputs shares with the output.

.. warning::

   This measure can result in a negative PID.

.. py:module:: dit.pid.iproj
:math:`\Iproj{\bullet}`
-----------------------

Utilizing information geometry, Harder et al :cite:`harder2013bivariate` have developed a strictly bivariate measure of redundancy, :math:`\Iproj{\bullet}`:

.. math::

   \Iproj{\left\{X_0\right\}\left\{X_1\right\} : Y} = \min \{ I^\pi_Y[X_0 \mss X_1], I^\pi_Y[X_1 \mss X_0] \}

where

.. math::

   I^\pi_Y[X_0 \mss X_1] = \sum_{x_0, y} p(x_0, y) \log \frac{p_{(x_0 \mss X_1)}(y)}{p(y)}

   p_{(x_0 \mss X_1)}(Y) = \pi_{C_{cl}(\langle X_1 \rangle_Y)}(p(Y | x_0)

   \pi_B(p) = \arg \min_{r \in B} \DKL{p || r}

   C_{cl}(\langle X_1 \rangle_Y) = C_{cl}(\left\{p(Y | x_1) : x_1 \in X_1 \right\})

where :math:`C_{cl}(\bullet)` denotes closure. Intuitively, this measures seeks to quantify redundancy as the minimum of how much :math:`p(Y | X_0)` can be expressed when :math:`X_0` is projected on to :math:`X_1`, and vice versa.

.. py:module:: dit.pid.ibroja
:math:`\Ibroja{\bullet}`
------------------------

In a very intuitive effort, Bertschinger et al (henceforth BROJA) :cite:`bertschinger2014quantifying,griffith2014quantifying` defined unique information as the minimum conditional mutual informations obtainable while holding the input-output marginals fixed:

.. math::

   \Delta = \{ Q : \forall i : p(x_i, y) = q(x_i, y) \}

   \Ibroja{X_{0:n} : Y} = \min_{Q \in \Delta} \I{X_i : Y | X_\overline{\{i\}}}

.. note::

   In the bivariate case, Griffith independently suggested the same decomposition but from the viewpoint of synergy :cite:`griffith2014quantifying`.

The BROJA measure has recently been criticized for behaving in an unintuitive manner on some examples. Consider the *reduced or* distribution:

.. ipython::

   In [16]: bivariates['reduced or']
   Out[16]:
   Class:          Distribution
   Alphabet:       ('0', '1') for all rvs
   Base:           linear
   Outcome Class:  str
   Outcome Length: 3
   RV Names:       None

   x     p(x)
   000   1/2
   011   1/4
   101   1/4

   In [17]: print(PID_BROJA(bivariates['reduced or']))
   ╔═════════╤════════╤════════╗
   ║ I_broja │  I_r   │   pi   ║
   ╟─────────┼────────┼────────╢
   ║  {0:1}  │ 1.0000 │ 0.6887 ║
   ║   {0}   │ 0.3113 │ 0.0000 ║
   ║   {1}   │ 0.3113 │ 0.0000 ║
   ║  {0}{1} │ 0.3113 │ 0.3113 ║
   ╚═════════╧════════╧════════╝

We see that in this instance BROJA assigns no partial information to either unique information. However, it is not difficult to argue that in the case that either input is a 1, that input then has unique information regarding the output.

:math:`\Iproj{\bullet}` and :math:`\Ibroja{\bullet}` are Distinct
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In the BROJA paper :cite:`bertschinger2014quantifying` the only example given where their decomposition differs from that of Harder et al. is the :py:func:`dit.example_dists.summed_dice`. We can find a simpler example where they differ using hypothesis:

.. ipython::

   In [17]: from hypothesis import find

   In [18]: from dit.utils.testing import distribution_structures

   In [19]: find(distribution_structures(3, 2, True), lambda d: PID_Proj(d) != PID_BROJA(d))
   Out[19]:
   Class:          Distribution
   Alphabet:       (0, 1) for all rvs
   Base:           linear
   Outcome Class:  tuple
   Outcome Length: 3
   RV Names:       None

   x           p(x)
   (0, 0, 0)   0.25
   (0, 0, 1)   0.25
   (0, 1, 1)   0.25
   (1, 0, 0)   0.25

.. py:module:: dit.pid.iccs
:math:`\Iccs{\bullet}`
----------------------

Taking a pointwise point of view, Ince has proposed a measure of redundancy based on the :ref:`coinformation` :cite:`ince2017measuring`:

.. math::

   \Iccs{X_{0:n} : Y} = \sum p(x_0, \ldots, x_n, y) \I{x_0 : \ldots : x_n : y}~~\textrm{if}~~\operatorname{sign}(\I{x_i : y}) = \operatorname{sign}(\I{x_0 : \ldots : x_n : y})

While this measure behaves intuitively in many examples, it also assigns negative values to some partial information atoms in some instances.

This decomposition also displays an interesting phenomena, that of *subadditive redundancy*. The **gband** distribution is an independent mix of a giant bit (redundancy of 1 bit) and the **and** distribution (redundancy of 0.1038 bits), and yet **gband** has 0.8113 bits of redundancy:

.. ipython::

   In [20]: PID_CCS(bivariates['gband'])
   Out[20]:
   ╔════════╤════════╤════════╗
   ║ I_ccs  │  I_r   │   pi   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 1.8113 │ 0.0000 ║
   ║  {0}   │ 1.3113 │ 0.5000 ║
   ║  {1}   │ 1.3113 │ 0.5000 ║
   ║ {0}{1} │ 0.8113 │ 0.8113 ║
   ╚════════╧════════╧════════╝

.. warning::

   This measure can result in a negative PID.

.. py:module:: dit.pid.idep
:math:`\Idep{\bullet}`
----------------------

James et al :cite:`james2017unique` have developed a method of quantifying unique information based on the :ref:`Dependency Decomposition`. Unique information from variable :math:`X_i` is evaluated as the least change in sources-target mutual information when adding the constraint :math:`X_i Y`.

.. ipython::

   In [21]: PID_dep(bivariates['not two'])
   Out[21]:
   ╔════════╤════════╤════════╗
   ║ I_dep  │  I_r   │   pi   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 0.5710 │ 0.5364 ║
   ║  {0}   │ 0.0200 │ 0.0146 ║
   ║  {1}   │ 0.0200 │ 0.0146 ║
   ║ {0}{1} │ 0.0054 │ 0.0054 ║
   ╚════════╧════════╧════════╝

.. py:module:: dit.pid.ipm
:math:`\Ipm{\bullet}`
---------------------

Also taking a pointwise view, Finn & Lizier's :math:`\Ipm{\bullet}` :cite:`finn2017` instead splits the pointwise mutual information into two components:

.. math::

   i(s, t) = h(s) - h(s|t)

They then define two partial information lattices, one quantified locally by :math:`h(s)` and the other by :math:`h(s|t)`. By averaging these local lattices and then recombining them, we arrive at a standard Williams & Beer redundancy lattice.

.. ipython::

   In [22]: PID_PM(bivariates['pnt. unq'])
   Out[22]:
   ╔════════╤════════╤════════╗
   ║ I_pm   │  I_r   │   pi   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 1.0000 │ 0.0000 ║
   ║  {0}   │ 0.5000 │ 0.5000 ║
   ║  {1}   │ 0.5000 │ 0.5000 ║
   ║ {0}{1} │ 0.0000 │ 0.0000 ║
   ╚════════╧════════╧════════╝

.. warning::

   This measure can result in a negative PID.

.. py:module:: dit.pid.irav
:math:`\Irav{\bullet}`
---------------------

Taking a functional perspective as in :math:`\Iwedge`, :math:`\Irav` defines bivariate redundancy as the maximum coinformation between the two sources :math:`X_0, X_1', a target :math:`Y`, and a deterministic function of the inputs :math:`f(X_0,X_1)`.

.. math::

   \Irav{X_{0:2} : Y} = \max_f\left(\I{X_0\!:\!X_1\!:\!Y\!:\!f(X_0,X_1)}

This measure is designed to exploit the conflation of synergy and redundancy in the three variable coinformation: :math:`\I{X_0\!:\!X_1\!:\!Y} = R - S`.

.. ipython::

   In [23]: PID_RAV(bivariates['pnt. unq'])
   Out[23]:
   ╔════════╤════════╤════════╗
   ║ I_pm   │  I_r   │   pi   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 1.0000 │ 0.0000 ║
   ║  {0}   │ 0.5000 │ 0.5000 ║
   ║  {1}   │ 0.5000 │ 0.5000 ║
   ║ {0}{1} │ 0.0000 │ 0.0000 ║
   ╚════════╧════════╧════════╝

.. py:module:: dit.pid.irr
:math:`\Irr{\bullet}`
---------------------

In order to combine :math:`\Immi{\bullet}` with the coinformation, Goodwell and Kumar :cite:`goodwell2017temporal` have introduced their *rescaled redundancy*:

.. math::

   \Irr{X_0 : X_1} = R_{\text{min}} + I_{S} (\Immi{X_{0:2} : Y} - R_{\text{min}}

   R_{\text{min}} = \max\{ 0, \I{X_0 : X_1 : Y} \}

   I_{S} = \frac{\I{X_0 : X_1}}{\min\{ \H{X_0}, \H{X_1} \}}

.. ipython::

   In [24]: PID_RR(bivariates['pnt. unq'])
   Out[24]:
   ╔════════╤════════╤════════╗
   ║ I_rr   │  I_r   │   pi   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 1.0000 │ 0.3333 ║
   ║  {0}   │ 0.5000 │ 0.1667 ║
   ║  {1}   │ 0.5000 │ 0.1667 ║
   ║ {0}{1} │ 0.3333 │ 0.3333 ║
   ╚════════╧════════╧════════╝

.. py:module:: dit.pid.ira
:math:`\Ira{\bullet}`
---------------------

Drawing from the reconstructability analysis work of Zwick :cite:`zwick2004overview`, we can define :math:`Ira{\bullet}` as a restricted form of :math:`\Idep{\bullet}`.

.. warning::

   This measure can result in a negative PID.

.. py:module:: dit.pid.iskar
Secret Key Agreement Rates
--------------------------

One can associate :ref:`Secret Key Agreement` rates with unique informations by considering the rate at which one source and the target can agree upon a secret key while the other source eavesdrops. This results in four possibilities:
- neither source nor target communicate
- only the source communicates
- only the target communicates
- both the source and the target communicate

No Communication
~~~~~~~~~~~~~~~~

.. math::

   \Ipart{X_i \rightarrow Y \setminus X_j} = \operatorname{S}[X_i : Y || X_j]

.. warning::

   This measure can result in an inconsistent PID.

One-Way Communication
~~~~~~~~~~~~~~~~~~~~~

Camel
^^^^^

.. math::

   \Ipart{X_i \rightarrow Y \setminus X_j} = \operatorname{S}[X_i \rightarrow Y || X_j]

Elephant
^^^^^^^^

.. math::

   \Ipart{X_i \rightarrow Y \setminus X_j} = \operatorname{S}[X_i \leftarrow Y || X_j]

.. warning::

   This measure can result in an inconsistent PID.

Two-Way Communication
~~~~~~~~~~~~~~~~~~~~~

.. math::

   \Ipart{X_i \rightarrow Y \setminus X_j} = \operatorname{S}[X_i \leftrightarrow Y || X_j]

.. warning::

   This measure can result in an inconsistent PID.

Partial Entropy Decomposition
=============================

Ince :cite:`ince2017partial` proposed applying the PID framework to decompose multivariate entropy (without considering information about a separate target variable). This *partial entropy decomposition* (PED), seeks to partition a mutlivariate entropy :math:`\H{X_0,X_1,\ldots}` among the antichains of the variables. The PED perspective shows that bivariate mutual information is equal to the difference between redundant entropy and synergistic entropy.

.. math::

   \I{X_0 : X_1} = \Hpart{\left\{X_0\right\}, \left\{X_1\right\}} - \Hpart{\left\{X_0,X_1\right\}}

.. py:module:: dit.pid.hcs
:math:`\Hcs{\bullet}`
----------------------

Taking a pointwise point of view, following :math:`\Iccs{\bullet}`, Ince has proposed a measure of redundant entropy based on the :ref:`coinformation` :cite:`ince2017partial`:

.. math::

   \Hcs{X_{0:n}} = \sum p(x_0, \ldots, x_n) \I{x_0 : \ldots : x_n}~~\textrm{if}~~(\I{x_0 : \ldots : x_n} > 0)

While this measure behaves intuitively in many examples, it also assigns negative values to some partial entropy atoms in some instances. However, Ince :cite:`ince2017partial` argues that concepts such as mechanistic information redundnacy (non-zero information redundancy between independent predictors, c.f. AND) necessitate negative partial entropy terms.

Like :math:`\Iccs{\bullet}`,  :math:`\Hcs{\bullet}` is also subadditive.

.. ipython::

   In [25]: PED_CS(dit.Distribution(['00','01','10','11'],[0.25]*4))
   Out[25]:
   ╔════════╤════════╤════════╗
   ║  H_cs  │  H_r   │  H_d   ║
   ╟────────┼────────┼────────╢
   ║ {0:1}  │ 2.0000 │ 0.0000 ║
   ║  {0}   │ 1.0000 │ 1.0000 ║
   ║  {1}   │ 1.0000 │ 1.0000 ║
   ║ {0}{1} │ 0.0000 │ 0.0000 ║
   ╚════════╧════════╧════════╝


text:
var models = require( "../models" );

var Account = models.Account;

var loginPage = function( req, res )
{
    res.render( "login", { csrfToken: req.csrfToken() } );
};

var signupPage = function( req, res )
{
    res.render( "signup", { csrfToken: req.csrfToken() } );
};

var logout = function( req, res )
{
    req.session.destroy();
    res.redirect( "/" );
};

var login = function( req, res )
{
    var body = req.body;
    if( !body.username || !body.pass )
    {
        return res.status( 400 ).json( { error: "all fields required" } );
    }

    Account.AccountModel.authenticate( body.username, body.pass, function( err, account ) {
        if( err || !account )
        {
            return res.status( 400 ).json( { error: "wrong username or passwaord" } );
        }

        req.session.account = account.toAPI();

        res.json( { redirect: "/maker" } );
    } );
};

var signup = function( req, res )
{
    var body = req.body;
    if( !body.username || !body.pass || !body.pass2 )
    {
        return res.status( 400 ).json( { error: "all fields required" } );
    }

    if( body.pass !== body.pass2 )
    {
        return res.status( 400 ).json( { error: "passwords don't match" } );
    }

    Account.AccountModel.generateHash( body.pass, function( salt, hash) {
        var accountData = {
            username: body.username,
            salt: salt,
            password: hash
        };

        var newAccount = new Account.AccountModel( accountData );

        newAccount.save( function( err ) {
            if( err )
            {
                console.log( err );
                return res.status( 400 ).json( { error: "an error occured" } );
            }

            req.session.account = newAccount.toAPI();

            res.json( { redirect: "/maker" } );
        } );
    } );
};

module.exports.loginPage = loginPage;
module.exports.login = login;
module.exports.logout = logout;
module.exports.signupPage = signupPage;
module.exports.signup = signup;


text:
<?php

namespace GeoIp2\Record;

class Continent extends AbstractPlaceRecord
{

protected $validAttributes = array(
'code',
'geonameId',
'names'
);
}


text:
<?php

class Ess_M2ePro_Model_Resource_Ebay_Template_Return
    extends Ess_M2ePro_Model_Resource_Abstract
{
    //########################################

    public function _construct()
    {
        $this->_init('M2ePro/Ebay_Template_Return', 'id');
    }

    //########################################
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TextualAnnotation.cs" company="OxyPlot">
//   Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
//   Provides an abstract base class for annotations that contains text.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace OxyPlot.Wpf
{
    using System.Windows;
    using System.Windows.Media;

    /// <summary>
    /// Provides an abstract base class for annotations that contains text.
    /// </summary>
    public abstract class TextualAnnotation : Annotation
    {
        /// <summary>
        /// Identifies the <see cref="Text"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
            "Text", typeof(string), typeof(TextualAnnotation), new PropertyMetadata(null, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="TextPosition"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TextPositionProperty =
            DependencyProperty.Register("TextPosition", typeof(DataPoint), typeof(TextualAnnotation), new PropertyMetadata(DataPoint.Undefined, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="TextRotation"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TextRotationProperty = DependencyProperty.Register(
            "TextRotation", typeof(double), typeof(TextualAnnotation), new PropertyMetadata(0.0, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="TextColor"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TextColorProperty = DependencyProperty.Register(
            "TextColor", typeof(Color), typeof(TextualAnnotation), new PropertyMetadata(Colors.Blue, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="TextHorizontalAlignment"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TextHorizontalAlignmentProperty =
            DependencyProperty.Register(
                "TextHorizontalAlignment",
                typeof(HorizontalAlignment),
                typeof(TextualAnnotation),
                new UIPropertyMetadata(HorizontalAlignment.Center, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="TextVerticalAlignment"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TextVerticalAlignmentProperty =
            DependencyProperty.Register(
                "TextVerticalAlignment",
                typeof(VerticalAlignment),
                typeof(TextualAnnotation),
                new UIPropertyMetadata(VerticalAlignment.Center, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="FontFamily"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty FontFamilyProperty =
            DependencyProperty.Register(
                "FontFamily",
                typeof(FontFamily),
                typeof(TextualAnnotation),
                new UIPropertyMetadata(null, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="FontWeight"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty FontWeightProperty =
            DependencyProperty.Register(
                "FontWeight",
                typeof(FontWeight),
                typeof(TextualAnnotation),
                new UIPropertyMetadata(FontWeights.Normal, AppearanceChanged));

        /// <summary>
        /// Identifies the <see cref="FontSize"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty FontSizeProperty =
            DependencyProperty.Register(
                "FontSize",
                typeof(double),
                typeof(TextualAnnotation),
                new UIPropertyMetadata(double.NaN, AppearanceChanged));

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        public string Text
        {
            get
            {
                return (string)this.GetValue(TextProperty);
            }

            set
            {
                this.SetValue(TextProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the color of the text.
        /// </summary>
        public Color TextColor
        {
            get
            {
                return (Color)this.GetValue(TextColorProperty);
            }

            set
            {
                this.SetValue(TextColorProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the text position.
        /// </summary>
        /// <remarks>If the value is <c>DataPoint.Undefined</c>, the centroid of the polygon will be used.</remarks>
        public DataPoint TextPosition
        {
            get { return (DataPoint)this.GetValue(TextPositionProperty); }
            set { this.SetValue(TextPositionProperty, value); }
        }

        /// <summary>
        /// Gets or sets the text horizontal alignment.
        /// </summary>
        /// <value>The text horizontal alignment.</value>
        public HorizontalAlignment TextHorizontalAlignment
        {
            get
            {
                return (HorizontalAlignment)this.GetValue(TextHorizontalAlignmentProperty);
            }

            set
            {
                this.SetValue(TextHorizontalAlignmentProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the vertical alignment of text (above or below the line).
        /// </summary>
        public VerticalAlignment TextVerticalAlignment
        {
            get
            {
                return (VerticalAlignment)this.GetValue(TextVerticalAlignmentProperty);
            }

            set
            {
                this.SetValue(TextVerticalAlignmentProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the rotation angle (degrees).
        /// </summary>
        public double TextRotation
        {
            get
            {
                return (double)this.GetValue(TextRotationProperty);
            }

            set
            {
                this.SetValue(TextRotationProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the font family.
        /// </summary>
        /// <value>
        /// The font family.
        /// </value>
        public FontFamily FontFamily
        {
            get
            {
                return (FontFamily)this.GetValue(FontFamilyProperty);
            }

            set
            {
                this.SetValue(FontFamilyProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the font weight.
        /// </summary>
        /// <value>
        /// The font weight.
        /// </value>
        public FontWeight FontWeight
        {
            get
            {
                return (FontWeight)this.GetValue(FontWeightProperty);
            }

            set
            {
                this.SetValue(FontWeightProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the size of the font.
        /// </summary>
        /// <value>
        /// The size of the font.
        /// </value>
        public double FontSize
        {
            get
            {
                return (double)this.GetValue(FontSizeProperty);
            }

            set
            {
                this.SetValue(FontSizeProperty, value);
            }
        }

        /// <summary>
        /// Synchronizes the properties.
        /// </summary>
        public override void SynchronizeProperties()
        {
            base.SynchronizeProperties();
            var a = (Annotations.TextualAnnotation)this.InternalAnnotation;
            a.TextColor = this.TextColor.ToOxyColor();
            a.Text = this.Text;
            a.TextPosition = this.TextPosition;
            a.TextRotation = this.TextRotation;
            a.TextHorizontalAlignment = this.TextHorizontalAlignment.ToHorizontalAlignment();
            a.TextVerticalAlignment = this.TextVerticalAlignment.ToVerticalAlignment();
            a.Font = this.FontFamily?.Source;
            a.FontSize = this.FontSize;
            a.FontWeight = this.FontWeight.ToOpenTypeWeight();
        }
    }
}


text:
package cd4017be.indlog.render.gui;

import cd4017be.lib.Gui.AdvancedGui;
import cd4017be.lib.Gui.TileContainer;
import cd4017be.lib.Gui.TileContainer.TankSlot;
import cd4017be.lib.Gui.DataContainer.IGuiData;
import cd4017be.indlog.tileentity.Tank;
import cd4017be.indlog.util.AdvancedTank;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;

public class GuiTank extends AdvancedGui {
	private static final long interval = 5000;
	private final Tank tile;
	private static long clickTime = 0;

	public GuiTank(IGuiData tile, EntityPlayer player) {
		super(new TileContainer(tile, player));
		this.tile = (Tank)tile;
		this.MAIN_TEX = new ResourceLocation("indlog:textures/gui/tank.png");
	}

	@Override
	public void initGui() {
		this.xSize = 226;
		this.ySize = 98;
		super.initGui();
		this.titleX = xSize * 3 / 4;
		guiComps.add(new Button(1, 201, 73, 18, 18, 0, ()-> tile.tank.output ? 1:0, (t)-> sendCommand(2)).texture(226, 0).setTooltip("tank.dir#"));
		guiComps.add(new Button(2, 176, 84, 7, 7, 0, ()-> tile.auto ? 1:0, (t)-> sendCommand(3)).texture(249, 28).setTooltip("tank.auto#"));
		addTankButtons(this, 0);
	}

	private static boolean confirm() {
		return System.currentTimeMillis() - clickTime < interval;
	}

	public static void addTankButtons(AdvancedGui gui, int cmd) {
		int i = gui.guiComps.size();
		TileContainer cont = (TileContainer)gui.inventorySlots;
		for (TankSlot tank : cont.tankSlots) {
			gui.guiComps.add(gui.new Button(i++, tank.xPos - 8, tank.yPos, 7, 7, 0, ()-> confirm() ? 1:0, (t)-> {
			if(confirm()) {
				gui.sendCommand(cmd + tank.tankNumber * 2);
				clickTime = 0;
			} else clickTime = System.currentTimeMillis();
		}).texture(249, 14).setTooltip("tank.del#"));
			if (tank.inventory instanceof AdvancedTank) {
				AdvancedTank at = (AdvancedTank)tank.inventory;
				gui.guiComps.add(gui.new Button(i++, tank.xPos - 8, tank.yPos + (tank.size & 0xf) * 18 - 9, 7, 7, 0, ()-> at.lock ? 1:0, (t)-> gui.sendCommand(cmd + tank.tankNumber * 2 + 1)).texture(249, 0).setTooltip("tank.lock#"));
			}
		}
	}

}


text:
import os
import unittest
from flask import request
from beacons import app

if 'DB_NAME' not in os.environ:
    os.environ['DATABASE_URI'] = 'sqlite://'
    os.environ['DB_NAME'] = ':memory:'

class TestViews(unittest.TestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DATABASE_URI'] = \
            os.environ.get('DATABASE_URI') + os.environ.get('DB_NAME')
        self.app = app.test_client()

    def tearDown(self):
        pass

    def test_0000_test_list_beacons(self):
        self.assertEqual(200, 200)

    def test_0010_test_list_beacons(self):
        with app.test_request_context('/', method='GET'):
            # now you can do something with the request until the
            # end of the with block, such as basic assertions:
            assert request.path == '/'
            assert request.method == 'GET'

    def test_0020_test_oauth(self):
        with app.test_request_context('/oauth2callback', method='GET'):
            # now you can do something with the request until the
            # end of the with block, such as basic assertions:
            assert request.path == '/oauth2callback'
            assert request.method == 'GET'

    def test_0030_test_register_beacon(self):
        with app.test_request_context('/register', method='GET'):
            # now you can do something with the request until the
            # end of the with block, such as basic assertions:
            assert request.path == '/register'
            assert request.method == 'GET'

def suite():
    "Test suite"
    test_suite = unittest.TestSuite()
    test_suite.addTests(
        unittest.TestLoader().loadTestsFromTestCase(TestViews)
    )
    return test_suite

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())


text:
package com.github.n_i_e.deepfolderview;

import java.util.Date;

class Debug {

	public static void writelog(final String message) {
		Date now = new Date();
		System.out.print(now);
		System.out.print(" ");
		System.out.println(message);
	}

}


text:
<?php namespace redhotmayo\registration;

use Illuminate\Support\Facades\App;
use redhotmayo\dataaccess\repository\ThrottleRegistrationRepository;
use redhotmayo\dataaccess\repository\UserRepository;
use redhotmayo\mailers\UserMailer;
use redhotmayo\model\User;
use redhotmayo\registration\exceptions\ThrottleException;
use redhotmayo\utility\Arrays;

class Registration {
    /**
     * @var \redhotmayo\dataaccess\repository\UserRepository
     */
    private $userRepository;

    /**
     * @var \redhotmayo\mailers\UserMailer
     */
    private $mailer;

    public function __construct(UserRepository $userRepository, UserMailer $mailer) {
        $this->userRepository = $userRepository;
        $this->mailer = $mailer;
    }

    /**
     * @param array $input
     * @param RegistrationValidator $validator
     * @param \redhotmayo\dataaccess\repository\ThrottleRegistrationRepository $throttle
     * @return bool
     *
     * @throws ThrottleException
     */
    public function register(array $input, RegistrationValidator $validator, ThrottleRegistrationRepository $throttle=null) {
        $registered = false;

        /** @var ThrottleRegistrationRepository $throttle */
        $throttle = $this->getThrottleRepository($throttle);
        $validated = $validator->validate($input, $validator->getCreationRules());

        //save user
        if ($validated) {
            $user = User::FromArray($input);
            $registered = $this->userRepository->save($user);
        }

        //send user an email
        if (App::environment() != 'local' &&
            App::environment() != 'testing' &&
            $registered && isset($user)) {
            $this->mailer->welcome($user);
        }

        if ($registered) {
           $throttle->decrementMax($input);
        }

        return $registered;
    }

    /**
     * @codeCoverageIgnore
     */
    private function getThrottleRepository($throttle) {
        $result = $throttle;

        if (!isset($throttle)) {
            $result = App::make('ThrottleRegistrationRepository');
        }

        return $result;
    }
}


text:
using Autofac;
using Autofac.Integration.WebApi;
using ICS.Core.Data;
using ICS.Domain.Data;
using ICS.Domain.Repository;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace ICS.API.Config
{
    public static class AutofacWebApiConfig
    {
        public static void Initialize(HttpConfiguration config)
        {

            Initialize(config,
                RegisterServices(new ContainerBuilder()));
        }

        public static void Initialize(
            HttpConfiguration config, IContainer container)
        {

            config.DependencyResolver =
                new AutofacWebApiDependencyResolver(container);
        }

        private static IContainer RegisterServices(ContainerBuilder builder)
        {

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            //EF DbContext
            builder.RegisterType<ICSDbContext>().As<DbContext>().InstancePerRequest();
            //Repositories
            builder.RegisterGeneric(typeof(EntityRepository<>)).As(typeof(IEntityRepository<>)).InstancePerRequest();
            //Services

            return builder.Build();
        }
    }
}


text:
namespace lldb_private {

/// ValueObject:
///
/// This abstract class provides an interface to a particular value, be it a register, a local or global variable,
/// that is evaluated in some particular scope.  The ValueObject also has the capibility of being the "child" of
/// some other variable object, and in turn of having children.
/// If a ValueObject is a root variable object - having no parent - then it must be constructed with respect to some
/// particular ExecutionContextScope.  If it is a child, it inherits the ExecutionContextScope from its parent.
/// The ValueObject will update itself if necessary before fetching its value, summary, object description, etc.
/// But it will always update itself in the ExecutionContextScope with which it was originally created.

/// A brief note on life cycle management for ValueObjects.  This is a little tricky because a ValueObject can contain
/// various other ValueObjects - the Dynamic Value, its children, the dereference value, etc.  Any one of these can be
/// handed out as a shared pointer, but for that contained value object to be valid, the root object and potentially other
/// of the value objects need to stay around.
/// We solve this problem by handing out shared pointers to the Value Object and any of its dependents using a shared
/// ClusterManager.  This treats each shared pointer handed out for the entire cluster as a reference to the whole
/// cluster.  The whole cluster will stay around until the last reference is released.
///
/// The ValueObject mostly handle this automatically, if a value object is made with a Parent ValueObject, then it adds
/// itself to the ClusterManager of the parent.

/// It does mean that external to the ValueObjects we should only ever make available ValueObjectSP's, never ValueObjects
/// or pointers to them.  So all the "Root level" ValueObject derived constructors should be private, and
/// should implement a Create function that new's up object and returns a Shared Pointer that it gets from the GetSP() method.
///
/// However, if you are making an derived ValueObject that will be contained in a parent value object, you should just
/// hold onto a pointer to it internally, and by virtue of passing the parent ValueObject into its constructor, it will
/// be added to the ClusterManager for the parent.  Then if you ever hand out a Shared Pointer to the contained ValueObject,
/// just do so by calling GetSP() on the contained object.

class ValueObject : public UserID
{
public:

    enum GetExpressionPathFormat
    {
        eGetExpressionPathFormatDereferencePointers = 1,
        eGetExpressionPathFormatHonorPointers
    };

    enum ValueObjectRepresentationStyle
    {
        eValueObjectRepresentationStyleValue = 1,
        eValueObjectRepresentationStyleSummary,
        eValueObjectRepresentationStyleLanguageSpecific,
        eValueObjectRepresentationStyleLocation,
        eValueObjectRepresentationStyleChildrenCount,
        eValueObjectRepresentationStyleType,
        eValueObjectRepresentationStyleName,
        eValueObjectRepresentationStyleExpressionPath
    };

    enum ExpressionPathScanEndReason
    {
        eExpressionPathScanEndReasonEndOfString = 1,           // out of data to parse
        eExpressionPathScanEndReasonNoSuchChild,               // child element not found
        eExpressionPathScanEndReasonEmptyRangeNotAllowed,      // [] only allowed for arrays
        eExpressionPathScanEndReasonDotInsteadOfArrow,         // . used when -> should be used
        eExpressionPathScanEndReasonArrowInsteadOfDot,         // -> used when . should be used
        eExpressionPathScanEndReasonFragileIVarNotAllowed,     // ObjC ivar expansion not allowed
        eExpressionPathScanEndReasonRangeOperatorNotAllowed,   // [] not allowed by options
        eExpressionPathScanEndReasonRangeOperatorInvalid,      // [] not valid on objects other than scalars, pointers or arrays
        eExpressionPathScanEndReasonArrayRangeOperatorMet,     // [] is good for arrays, but I cannot parse it
        eExpressionPathScanEndReasonBitfieldRangeOperatorMet,  // [] is good for bitfields, but I cannot parse after it
        eExpressionPathScanEndReasonUnexpectedSymbol,          // something is malformed in the expression
        eExpressionPathScanEndReasonTakingAddressFailed,       // impossible to apply & operator
        eExpressionPathScanEndReasonDereferencingFailed,       // impossible to apply * operator
        eExpressionPathScanEndReasonRangeOperatorExpanded,     // [] was expanded into a VOList
        eExpressionPathScanEndReasonSyntheticValueMissing,     // getting the synthetic children failed
        eExpressionPathScanEndReasonUnknown = 0xFFFF
    };

    enum ExpressionPathEndResultType
    {
        eExpressionPathEndResultTypePlain = 1,                 // anything but...
        eExpressionPathEndResultTypeBitfield,                  // a bitfield
        eExpressionPathEndResultTypeBoundedRange,              // a range [low-high]
        eExpressionPathEndResultTypeUnboundedRange,            // a range []
        eExpressionPathEndResultTypeValueObjectList,           // several items in a VOList
        eExpressionPathEndResultTypeInvalid = 0xFFFF
    };

    enum ExpressionPathAftermath
    {
        eExpressionPathAftermathNothing = 1,               // just return it
        eExpressionPathAftermathDereference,               // dereference the target
        eExpressionPathAftermathTakeAddress                // take target's address
    };

    enum ClearUserVisibleDataItems
    {
        eClearUserVisibleDataItemsNothing = 1u << 0,
        eClearUserVisibleDataItemsValue = 1u << 1,
        eClearUserVisibleDataItemsSummary = 1u << 2,
        eClearUserVisibleDataItemsLocation = 1u << 3,
        eClearUserVisibleDataItemsDescription = 1u << 4,
        eClearUserVisibleDataItemsSyntheticChildren = 1u << 5,
        eClearUserVisibleDataItemsAllStrings = eClearUserVisibleDataItemsValue | eClearUserVisibleDataItemsSummary | eClearUserVisibleDataItemsLocation | eClearUserVisibleDataItemsDescription,
        eClearUserVisibleDataItemsAll = 0xFFFF
    };

    struct GetValueForExpressionPathOptions
    {
        bool m_check_dot_vs_arrow_syntax;
        bool m_no_fragile_ivar;
        bool m_allow_bitfields_syntax;
        bool m_no_synthetic_children;

        GetValueForExpressionPathOptions(bool dot = false,
                                         bool no_ivar = false,
                                         bool bitfield = true,
                                         bool no_synth = false) :
            m_check_dot_vs_arrow_syntax(dot),
            m_no_fragile_ivar(no_ivar),
            m_allow_bitfields_syntax(bitfield),
            m_no_synthetic_children(no_synth)
        {
        }

        GetValueForExpressionPathOptions&
        DoCheckDotVsArrowSyntax()
        {
            m_check_dot_vs_arrow_syntax = true;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DontCheckDotVsArrowSyntax()
        {
            m_check_dot_vs_arrow_syntax = false;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DoAllowFragileIVar()
        {
            m_no_fragile_ivar = false;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DontAllowFragileIVar()
        {
            m_no_fragile_ivar = true;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DoAllowBitfieldSyntax()
        {
            m_allow_bitfields_syntax = true;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DontAllowBitfieldSyntax()
        {
            m_allow_bitfields_syntax = false;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DoAllowSyntheticChildren()
        {
            m_no_synthetic_children = false;
            return *this;
        }

        GetValueForExpressionPathOptions&
        DontAllowSyntheticChildren()
        {
            m_no_synthetic_children = true;
            return *this;
        }

        static const GetValueForExpressionPathOptions
        DefaultOptions()
        {
            static GetValueForExpressionPathOptions g_default_options;

            return g_default_options;
        }

    };

    struct DumpValueObjectOptions
    {
        uint32_t m_max_ptr_depth;
        uint32_t m_max_depth;
        bool m_show_types;
        bool m_show_location;
        bool m_use_objc;
        lldb::DynamicValueType m_use_dynamic;
        bool m_use_synthetic;
        bool m_scope_already_checked;
        bool m_flat_output;
        uint32_t m_omit_summary_depth;
        bool m_ignore_cap;
        lldb::Format m_format;
        lldb::TypeSummaryImplSP m_summary_sp;
        std::string m_root_valobj_name;
        bool m_hide_root_type;
        bool m_hide_name;
        bool m_hide_value;

        DumpValueObjectOptions() :
            m_max_ptr_depth(0),
            m_max_depth(UINT32_MAX),
            m_show_types(false),
            m_show_location(false),
            m_use_objc(false),
            m_use_dynamic(lldb::eNoDynamicValues),
            m_use_synthetic(true),
            m_scope_already_checked(false),
            m_flat_output(false),
            m_omit_summary_depth(0),
            m_ignore_cap(false),
            m_format (lldb::eFormatDefault),
            m_summary_sp(),
            m_root_valobj_name(),
            m_hide_root_type(false),  // provide a special compact display for "po"
            m_hide_name(false), // provide a special compact display for "po"
            m_hide_value(false) // provide a special compact display for "po"
        {}

        static const DumpValueObjectOptions
        DefaultOptions()
        {
            static DumpValueObjectOptions g_default_options;

            return g_default_options;
        }

        DumpValueObjectOptions (const DumpValueObjectOptions& rhs) :
            m_max_ptr_depth(rhs.m_max_ptr_depth),
            m_max_depth(rhs.m_max_depth),
            m_show_types(rhs.m_show_types),
            m_show_location(rhs.m_show_location),
            m_use_objc(rhs.m_use_objc),
            m_use_dynamic(rhs.m_use_dynamic),
            m_use_synthetic(rhs.m_use_synthetic),
            m_scope_already_checked(rhs.m_scope_already_checked),
            m_flat_output(rhs.m_flat_output),
            m_omit_summary_depth(rhs.m_omit_summary_depth),
            m_ignore_cap(rhs.m_ignore_cap),
            m_format(rhs.m_format),
            m_summary_sp(rhs.m_summary_sp),
            m_root_valobj_name(rhs.m_root_valobj_name),
            m_hide_root_type(rhs.m_hide_root_type),
            m_hide_name(rhs.m_hide_name),
            m_hide_value(rhs.m_hide_value)
        {}

        DumpValueObjectOptions&
        SetMaximumPointerDepth(uint32_t depth = 0)
        {
            m_max_ptr_depth = depth;
            return *this;
        }

        DumpValueObjectOptions&
        SetMaximumDepth(uint32_t depth = 0)
        {
            m_max_depth = depth;
            return *this;
        }

        DumpValueObjectOptions&
        SetShowTypes(bool show = false)
        {
            m_show_types = show;
            return *this;
        }

        DumpValueObjectOptions&
        SetShowLocation(bool show = false)
        {
            m_show_location = show;
            return *this;
        }

        DumpValueObjectOptions&
        SetUseObjectiveC(bool use = false)
        {
            m_use_objc = use;
            return *this;
        }

        DumpValueObjectOptions&
        SetShowSummary(bool show = true)
        {
            if (show == false)
                SetOmitSummaryDepth(UINT32_MAX);
            else
                SetOmitSummaryDepth(0);
            return *this;
        }

        DumpValueObjectOptions&
        SetUseDynamicType(lldb::DynamicValueType dyn = lldb::eNoDynamicValues)
        {
            m_use_dynamic = dyn;
            return *this;
        }

        DumpValueObjectOptions&
        SetUseSyntheticValue(bool use_synthetic = true)
        {
            m_use_synthetic = use_synthetic;
            return *this;
        }

        DumpValueObjectOptions&
        SetScopeChecked(bool check = true)
        {
            m_scope_already_checked = check;
            return *this;
        }

        DumpValueObjectOptions&
        SetFlatOutput(bool flat = false)
        {
            m_flat_output = flat;
            return *this;
        }

        DumpValueObjectOptions&
        SetOmitSummaryDepth(uint32_t depth = 0)
        {
            m_omit_summary_depth = depth;
            return *this;
        }

        DumpValueObjectOptions&
        SetIgnoreCap(bool ignore = false)
        {
            m_ignore_cap = ignore;
            return *this;
        }

        DumpValueObjectOptions&
        SetRawDisplay(bool raw = false)
        {
            if (raw)
            {
                SetUseSyntheticValue(false);
                SetOmitSummaryDepth(UINT32_MAX);
                SetIgnoreCap(true);
                SetHideName(false);
                SetHideValue(false);
            }
            else
            {
                SetUseSyntheticValue(true);
                SetOmitSummaryDepth(0);
                SetIgnoreCap(false);
                SetHideName(false);
                SetHideValue(false);
            }
            return *this;
        }

        DumpValueObjectOptions&
        SetFormat (lldb::Format format = lldb::eFormatDefault)
        {
            m_format = format;
            return *this;
        }

        DumpValueObjectOptions&
        SetSummary (lldb::TypeSummaryImplSP summary = lldb::TypeSummaryImplSP())
        {
            m_summary_sp = summary;
            return *this;
        }

        DumpValueObjectOptions&
        SetRootValueObjectName (const char* name = NULL)
        {
            if (name)
                m_root_valobj_name.assign(name);
            else
                m_root_valobj_name.clear();
            return *this;
        }

        DumpValueObjectOptions&
        SetHideRootType (bool hide_root_type = false)
        {
            m_hide_root_type = hide_root_type;
            return *this;
        }

        DumpValueObjectOptions&
        SetHideName (bool hide_name = false)
        {
            m_hide_name = hide_name;
            return *this;
        }

        DumpValueObjectOptions&
        SetHideValue (bool hide_value = false)
        {
            m_hide_value = hide_value;
            return *this;
        }
    };

    class EvaluationPoint
    {
    public:

        EvaluationPoint ();

        EvaluationPoint (ExecutionContextScope *exe_scope, bool use_selected = false);

        EvaluationPoint (const EvaluationPoint &rhs);

        ~EvaluationPoint ();

        const ExecutionContextRef &
        GetExecutionContextRef() const
        {
            return m_exe_ctx_ref;
        }

        // Set the EvaluationPoint to the values in exe_scope,
        // Return true if the Evaluation Point changed.
        // Since the ExecutionContextScope is always going to be valid currently,
        // the Updated Context will also always be valid.

//        bool
//        SetContext (ExecutionContextScope *exe_scope);

        void
        SetIsConstant ()
        {
            SetUpdated();
            m_mod_id.SetInvalid();
        }

        bool
        IsConstant () const
        {
            return !m_mod_id.IsValid();
        }

        ProcessModID
        GetModID () const
        {
            return m_mod_id;
        }

        void
        SetUpdateID (ProcessModID new_id)
        {
            m_mod_id = new_id;
        }

        bool
        IsFirstEvaluation () const
        {
            return m_first_update;
        }

        void
        SetNeedsUpdate ()
        {
            m_needs_update = true;
        }

        void
        SetUpdated ();

        bool
        NeedsUpdating()
        {
            SyncWithProcessState();
            return m_needs_update;
        }

        bool
        IsValid ()
        {
            if (!m_mod_id.IsValid())
                return false;
            else if (SyncWithProcessState ())
            {
                if (!m_mod_id.IsValid())
                    return false;
            }
            return true;
        }

        void
        SetInvalid ()
        {
            // Use the stop id to mark us as invalid, leave the thread id and the stack id around for logging and
            // history purposes.
            m_mod_id.SetInvalid();

            // Can't update an invalid state.
            m_needs_update = false;

        }

    private:
        bool
        SyncWithProcessState ();

        ProcessModID m_mod_id; // This is the stop id when this ValueObject was last evaluated.
        ExecutionContextRef m_exe_ctx_ref;
        bool m_needs_update;
        bool m_first_update;
    };

    const EvaluationPoint &
    GetUpdatePoint () const
    {
        return m_update_point;
    }

    EvaluationPoint &
    GetUpdatePoint ()
    {
        return m_update_point;
    }

    const ExecutionContextRef &
    GetExecutionContextRef() const
    {
        return m_update_point.GetExecutionContextRef();
    }

    lldb::TargetSP
    GetTargetSP() const
    {
        return m_update_point.GetExecutionContextRef().GetTargetSP();
    }

    lldb::ProcessSP
    GetProcessSP() const
    {
        return m_update_point.GetExecutionContextRef().GetProcessSP();
    }

    lldb::ThreadSP
    GetThreadSP() const
    {
        return m_update_point.GetExecutionContextRef().GetThreadSP();
    }

    lldb::StackFrameSP
    GetFrameSP() const
    {
        return m_update_point.GetExecutionContextRef().GetFrameSP();
    }

    void
    SetNeedsUpdate ();

    virtual ~ValueObject();

    ClangASTType
    GetClangType ();

    //------------------------------------------------------------------
    // Sublasses must implement the functions below.
    //------------------------------------------------------------------
    virtual uint64_t
    GetByteSize() = 0;

    virtual lldb::ValueType
    GetValueType() const = 0;

    //------------------------------------------------------------------
    // Sublasses can implement the functions below.
    //------------------------------------------------------------------
    virtual ConstString
    GetTypeName();

    virtual ConstString
    GetQualifiedTypeName();

    virtual lldb::LanguageType
    GetObjectRuntimeLanguage();

    virtual uint32_t
    GetTypeInfo (ClangASTType *pointee_or_element_clang_type = NULL);

    virtual bool
    IsPointerType ();

    virtual bool
    IsArrayType ();

    virtual bool
    IsScalarType ();

    virtual bool
    IsPointerOrReferenceType ();

    virtual bool
    IsPossibleDynamicType ();

    virtual bool
    IsObjCNil ();

    virtual bool
    IsBaseClass ()
    {
        return false;
    }

    virtual bool
    IsDereferenceOfParent ()
    {
        return false;
    }

    bool
    IsIntegerType (bool &is_signed);

    virtual bool
    GetBaseClassPath (Stream &s);

    virtual void
    GetExpressionPath (Stream &s, bool qualify_cxx_base_classes, GetExpressionPathFormat = eGetExpressionPathFormatDereferencePointers);

    lldb::ValueObjectSP
    GetValueForExpressionPath(const char* expression,
                              const char** first_unparsed = NULL,
                              ExpressionPathScanEndReason* reason_to_stop = NULL,
                              ExpressionPathEndResultType* final_value_type = NULL,
                              const GetValueForExpressionPathOptions& options = GetValueForExpressionPathOptions::DefaultOptions(),
                              ExpressionPathAftermath* final_task_on_target = NULL);

    int
    GetValuesForExpressionPath(const char* expression,
                               lldb::ValueObjectListSP& list,
                               const char** first_unparsed = NULL,
                               ExpressionPathScanEndReason* reason_to_stop = NULL,
                               ExpressionPathEndResultType* final_value_type = NULL,
                               const GetValueForExpressionPathOptions& options = GetValueForExpressionPathOptions::DefaultOptions(),
                               ExpressionPathAftermath* final_task_on_target = NULL);

    virtual bool
    IsInScope ()
    {
        return true;
    }

    virtual off_t
    GetByteOffset()
    {
        return 0;
    }

    virtual uint32_t
    GetBitfieldBitSize ()
    {
        return 0;
    }

    virtual uint32_t
    GetBitfieldBitOffset ()
    {
        return 0;
    }

    bool
    IsBitfield ()
    {
        return (GetBitfieldBitSize() != 0) || (GetBitfieldBitOffset() != 0);
    }

    virtual bool
    IsArrayItemForPointer()
    {
        return m_is_array_item_for_pointer;
    }

    virtual const char *
    GetValueAsCString ();

    virtual bool
    GetValueAsCString (lldb::Format format,
                       std::string& destination);

    virtual uint64_t
    GetValueAsUnsigned (uint64_t fail_value, bool *success = NULL);

    virtual bool
    SetValueFromCString (const char *value_str, Error& error);

    // Return the module associated with this value object in case the
    // value is from an executable file and might have its data in
    // sections of the file. This can be used for variables.
    virtual lldb::ModuleSP
    GetModule();

    virtual ValueObject*
    GetRoot ();

    virtual bool
    GetDeclaration (Declaration &decl);

    //------------------------------------------------------------------
    // The functions below should NOT be modified by sublasses
    //------------------------------------------------------------------
    const Error &
    GetError();

    const ConstString &
    GetName() const;

    virtual lldb::ValueObjectSP
    GetChildAtIndex (size_t idx, bool can_create);

    // this will always create the children if necessary
    lldb::ValueObjectSP
    GetChildAtIndexPath (const std::initializer_list<size_t> &idxs,
                         size_t* index_of_error = NULL);

    lldb::ValueObjectSP
    GetChildAtIndexPath (const std::vector<size_t> &idxs,
                         size_t* index_of_error = NULL);

    lldb::ValueObjectSP
    GetChildAtIndexPath (const std::initializer_list< std::pair<size_t, bool> > &idxs,
                         size_t* index_of_error = NULL);

    lldb::ValueObjectSP
    GetChildAtIndexPath (const std::vector< std::pair<size_t, bool> > &idxs,
                         size_t* index_of_error = NULL);

    virtual lldb::ValueObjectSP
    GetChildMemberWithName (const ConstString &name, bool can_create);

    virtual size_t
    GetIndexOfChildWithName (const ConstString &name);

    size_t
    GetNumChildren ();

    const Value &
    GetValue() const;

    Value &
    GetValue();

    virtual bool
    ResolveValue (Scalar &scalar);

    virtual const char *
    GetLocationAsCString ();

    const char *
    GetSummaryAsCString ();

    bool
    GetSummaryAsCString (TypeSummaryImpl* summary_ptr,
                         std::string& destination);

    const char *
    GetObjectDescription ();

    bool
    HasSpecialPrintableRepresentation (ValueObjectRepresentationStyle val_obj_display,
                                       lldb::Format custom_format);

    enum PrintableRepresentationSpecialCases
    {
        ePrintableRepresentationSpecialCasesDisable = 0,
        ePrintableRepresentationSpecialCasesAllow = 1,
        ePrintableRepresentationSpecialCasesOnly = 3
    };

    bool
    DumpPrintableRepresentation (Stream& s,
                                 ValueObjectRepresentationStyle val_obj_display = eValueObjectRepresentationStyleSummary,
                                 lldb::Format custom_format = lldb::eFormatInvalid,
                                 PrintableRepresentationSpecialCases special = ePrintableRepresentationSpecialCasesAllow);
    bool
    GetValueIsValid () const;

    bool
    GetValueDidChange ();

    bool
    UpdateValueIfNeeded (bool update_format = true);

    bool
    UpdateFormatsIfNeeded();

    lldb::ValueObjectSP
    GetSP ()
    {
        return m_manager->GetSharedPointer(this);
    }

    void
    SetName (const ConstString &name);

    virtual lldb::addr_t
    GetAddressOf (bool scalar_is_load_address = true,
                  AddressType *address_type = NULL);

    lldb::addr_t
    GetPointerValue (AddressType *address_type = NULL);

    lldb::ValueObjectSP
    GetSyntheticChild (const ConstString &key) const;

    lldb::ValueObjectSP
    GetSyntheticArrayMember (size_t index, bool can_create);

    lldb::ValueObjectSP
    GetSyntheticArrayMemberFromPointer (size_t index, bool can_create);

    lldb::ValueObjectSP
    GetSyntheticArrayMemberFromArray (size_t index, bool can_create);

    lldb::ValueObjectSP
    GetSyntheticBitFieldChild (uint32_t from, uint32_t to, bool can_create);

    lldb::ValueObjectSP
    GetSyntheticExpressionPathChild(const char* expression, bool can_create);

    virtual lldb::ValueObjectSP
    GetSyntheticChildAtOffset(uint32_t offset, const ClangASTType& type, bool can_create);

    virtual lldb::ValueObjectSP
    GetDynamicValue (lldb::DynamicValueType valueType);

    lldb::DynamicValueType
    GetDynamicValueType ();

    virtual lldb::ValueObjectSP
    GetStaticValue ();

    virtual lldb::ValueObjectSP
    GetNonSyntheticValue ();

    lldb::ValueObjectSP
    GetSyntheticValue (bool use_synthetic = true);

    virtual bool
    HasSyntheticValue();

    virtual bool
    IsSynthetic() { return false; }

    virtual lldb::ValueObjectSP
    CreateConstantValue (const ConstString &name);

    virtual lldb::ValueObjectSP
    Dereference (Error &error);

    virtual lldb::ValueObjectSP
    AddressOf (Error &error);

    virtual lldb::addr_t
    GetLiveAddress()
    {
        return LLDB_INVALID_ADDRESS;
    }

    virtual void
    SetLiveAddress(lldb::addr_t addr = LLDB_INVALID_ADDRESS,
                   AddressType address_type = eAddressTypeLoad)
    {
    }

    virtual lldb::ValueObjectSP
    Cast (const ClangASTType &clang_ast_type);

    virtual lldb::ValueObjectSP
    CastPointerType (const char *name,
                     ClangASTType &ast_type);

    virtual lldb::ValueObjectSP
    CastPointerType (const char *name,
                     lldb::TypeSP &type_sp);

    // The backing bits of this value object were updated, clear any
    // descriptive string, so we know we have to refetch them
    virtual void
    ValueUpdated ()
    {
        ClearUserVisibleData(eClearUserVisibleDataItemsValue |
                             eClearUserVisibleDataItemsSummary |
                             eClearUserVisibleDataItemsDescription);
    }

    virtual bool
    IsDynamic ()
    {
        return false;
    }

    virtual SymbolContextScope *
    GetSymbolContextScope();

    static void
    DumpValueObject (Stream &s,
                     ValueObject *valobj);
    static void
    DumpValueObject (Stream &s,
                     ValueObject *valobj,
                     const DumpValueObjectOptions& options);

    static lldb::ValueObjectSP
    CreateValueObjectFromExpression (const char* name,
                                     const char* expression,
                                     const ExecutionContext& exe_ctx);

    static lldb::ValueObjectSP
    CreateValueObjectFromAddress (const char* name,
                                  uint64_t address,
                                  const ExecutionContext& exe_ctx,
                                  ClangASTType type);

    static lldb::ValueObjectSP
    CreateValueObjectFromData (const char* name,
                               DataExtractor& data,
                               const ExecutionContext& exe_ctx,
                               ClangASTType type);

    static void
    LogValueObject (Log *log,
                    ValueObject *valobj);

    static void
    LogValueObject (Log *log,
                    ValueObject *valobj,
                    const DumpValueObjectOptions& options);

    // returns true if this is a char* or a char[]
    // if it is a char* and check_pointer is true,
    // it also checks that the pointer is valid
    bool
    IsCStringContainer (bool check_pointer = false);

    size_t
    ReadPointedString (Stream& s,
                       Error& error,
                       uint32_t max_length = 0,
                       bool honor_array = true,
                       lldb::Format item_format = lldb::eFormatCharArray);

    virtual size_t
    GetPointeeData (DataExtractor& data,
                    uint32_t item_idx = 0,
					uint32_t item_count = 1);

    virtual uint64_t
    GetData (DataExtractor& data);

    virtual bool
    SetData (DataExtractor &data, Error &error);

    bool
    GetIsConstant () const
    {
        return m_update_point.IsConstant();
    }

    void
    SetIsConstant ()
    {
        m_update_point.SetIsConstant();
    }

    lldb::Format
    GetFormat () const;

    void
    SetFormat (lldb::Format format)
    {
        if (format != m_format)
            ClearUserVisibleData(eClearUserVisibleDataItemsValue);
        m_format = format;
    }

    lldb::TypeSummaryImplSP
    GetSummaryFormat()
    {
        UpdateFormatsIfNeeded();
        return m_type_summary_sp;
    }

    void
    SetSummaryFormat(lldb::TypeSummaryImplSP format)
    {
        m_type_summary_sp = format;
        ClearUserVisibleData(eClearUserVisibleDataItemsSummary);
    }

    void
    SetValueFormat(lldb::TypeFormatImplSP format)
    {
        m_type_format_sp = format;
        ClearUserVisibleData(eClearUserVisibleDataItemsValue);
    }

    lldb::TypeFormatImplSP
    GetValueFormat()
    {
        UpdateFormatsIfNeeded();
        return m_type_format_sp;
    }

    void
    SetSyntheticChildren(const lldb::SyntheticChildrenSP &synth_sp)
    {
        if (synth_sp.get() == m_synthetic_children_sp.get())
            return;
        ClearUserVisibleData(eClearUserVisibleDataItemsSyntheticChildren);
        m_synthetic_children_sp = synth_sp;
    }

    lldb::SyntheticChildrenSP
    GetSyntheticChildren()
    {
        UpdateFormatsIfNeeded();
        return m_synthetic_children_sp;
    }

    // Use GetParent for display purposes, but if you want to tell the parent to update itself
    // then use m_parent.  The ValueObjectDynamicValue's parent is not the correct parent for
    // displaying, they are really siblings, so for display it needs to route through to its grandparent.
    virtual ValueObject *
    GetParent()
    {
        return m_parent;
    }

    virtual const ValueObject *
    GetParent() const
    {
        return m_parent;
    }

    ValueObject *
    GetNonBaseClassParent();

    void
    SetAddressTypeOfChildren(AddressType at)
    {
        m_address_type_of_ptr_or_ref_children = at;
    }

    AddressType
    GetAddressTypeOfChildren();

    void
    SetHasCompleteType()
    {
        m_did_calculate_complete_objc_class_type = true;
    }

    //------------------------------------------------------------------
    /// Find out if a ValueObject might have children.
    ///
    /// This call is much more efficient than CalculateNumChildren() as
    /// it doesn't need to complete the underlying type. This is designed
    /// to be used in a UI environment in order to detect if the
    /// disclosure triangle should be displayed or not.
    ///
    /// This function returns true for class, union, structure,
    /// pointers, references, arrays and more. Again, it does so without
    /// doing any expensive type completion.
    ///
    /// @return
    ///     Returns \b true if the ValueObject might have children, or \b
    ///     false otherwise.
    //------------------------------------------------------------------
    virtual bool
    MightHaveChildren();

protected:
    typedef ClusterManager<ValueObject> ValueObjectManager;

    class ChildrenManager
    {
    public:
        ChildrenManager() :
            m_mutex(Mutex::eMutexTypeRecursive),
            m_children(),
            m_children_count(0)
        {}

        bool
        HasChildAtIndex (size_t idx)
        {
            Mutex::Locker locker(m_mutex);
            ChildrenIterator iter = m_children.find(idx);
            ChildrenIterator end = m_children.end();
            return (iter != end);
        }

        ValueObject*
        GetChildAtIndex (size_t idx)
        {
            Mutex::Locker locker(m_mutex);
            ChildrenIterator iter = m_children.find(idx);
            ChildrenIterator end = m_children.end();
            if (iter == end)
                return NULL;
            else
                return iter->second;
        }

        void
        SetChildAtIndex (size_t idx, ValueObject* valobj)
        {
            ChildrenPair pair(idx,valobj); // we do not need to be mutex-protected to make a pair
            Mutex::Locker locker(m_mutex);
            m_children.insert(pair);
        }

        void
        SetChildrenCount (size_t count)
        {
            m_children_count = count;
        }

        size_t
        GetChildrenCount ()
        {
            return m_children_count;
        }

        void
        Clear()
        {
            m_children_count = 0;
            Mutex::Locker locker(m_mutex);
            m_children.clear();
        }

    private:
        typedef std::map<size_t, ValueObject*> ChildrenMap;
        typedef ChildrenMap::iterator ChildrenIterator;
        typedef ChildrenMap::value_type ChildrenPair;
        Mutex m_mutex;
        ChildrenMap m_children;
        size_t m_children_count;
    };

    //------------------------------------------------------------------
    // Classes that inherit from ValueObject can see and modify these
    //------------------------------------------------------------------
    ValueObject  *      m_parent;       // The parent value object, or NULL if this has no parent
    ValueObject  *      m_root;         // The root of the hierarchy for this ValueObject (or NULL if never calculated)
    EvaluationPoint     m_update_point; // Stores both the stop id and the full context at which this value was last
                                        // updated.  When we are asked to update the value object, we check whether
                                        // the context & stop id are the same before updating.
    ConstString         m_name;         // The name of this object
    DataExtractor       m_data;         // A data extractor that can be used to extract the value.
    Value               m_value;
    Error               m_error;        // An error object that can describe any errors that occur when updating values.
    std::string         m_value_str;    // Cached value string that will get cleared if/when the value is updated.
    std::string         m_old_value_str;// Cached old value string from the last time the value was gotten
    std::string         m_location_str; // Cached location string that will get cleared if/when the value is updated.
    std::string         m_summary_str;  // Cached summary string that will get cleared if/when the value is updated.
    std::string         m_object_desc_str; // Cached result of the "object printer".  This differs from the summary
                                              // in that the summary is consed up by us, the object_desc_string is builtin.

    ClangASTType        m_override_type;// If the type of the value object should be overridden, the type to impose.

    ValueObjectManager *m_manager;      // This object is managed by the root object (any ValueObject that gets created
                                        // without a parent.)  The manager gets passed through all the generations of
                                        // dependent objects, and will keep the whole cluster of objects alive as long
                                        // as a shared pointer to any of them has been handed out.  Shared pointers to
                                        // value objects must always be made with the GetSP method.

    ChildrenManager                      m_children;
    std::map<ConstString, ValueObject *> m_synthetic_children;

    ValueObject*                         m_dynamic_value;
    ValueObject*                         m_synthetic_value;
    ValueObject*                         m_deref_valobj;

    lldb::ValueObjectSP m_addr_of_valobj_sp; // We have to hold onto a shared pointer to this one because it is created
                                             // as an independent ValueObjectConstResult, which isn't managed by us.

    lldb::Format                m_format;
    lldb::Format                m_last_format;
    uint32_t                    m_last_format_mgr_revision;
    lldb::TypeSummaryImplSP     m_type_summary_sp;
    lldb::TypeFormatImplSP      m_type_format_sp;
    lldb::SyntheticChildrenSP   m_synthetic_children_sp;
    ProcessModID                m_user_id_of_forced_summary;
    AddressType                 m_address_type_of_ptr_or_ref_children;

    bool                m_value_is_valid:1,
                        m_value_did_change:1,
                        m_children_count_valid:1,
                        m_old_value_valid:1,
                        m_is_deref_of_parent:1,
                        m_is_array_item_for_pointer:1,
                        m_is_bitfield_for_scalar:1,
                        m_is_child_at_offset:1,
                        m_is_getting_summary:1,
                        m_did_calculate_complete_objc_class_type:1;

    friend class ClangExpressionDeclMap;  // For GetValue
    friend class ClangExpressionVariable; // For SetName
    friend class Target;                  // For SetName
    friend class ValueObjectConstResultImpl;

    //------------------------------------------------------------------
    // Constructors and Destructors
    //------------------------------------------------------------------

    // Use the no-argument constructor to make a constant variable object (with no ExecutionContextScope.)

    ValueObject();

    // Use this constructor to create a "root variable object".  The ValueObject will be locked to this context
    // through-out its lifespan.

    ValueObject (ExecutionContextScope *exe_scope,
                 AddressType child_ptr_or_ref_addr_type = eAddressTypeLoad);

    // Use this constructor to create a ValueObject owned by another ValueObject.  It will inherit the ExecutionContext
    // of its parent.

    ValueObject (ValueObject &parent);

    ValueObjectManager *
    GetManager()
    {
        return m_manager;
    }

    virtual bool
    UpdateValue () = 0;

    virtual void
    CalculateDynamicValue (lldb::DynamicValueType use_dynamic);

    virtual lldb::DynamicValueType
    GetDynamicValueTypeImpl ()
    {
        return lldb::eNoDynamicValues;
    }

    virtual bool
    HasDynamicValueTypeInfo ()
    {
        return false;
    }

    virtual void
    CalculateSyntheticValue (bool use_synthetic = true);

    // Should only be called by ValueObject::GetChildAtIndex()
    // Returns a ValueObject managed by this ValueObject's manager.
    virtual ValueObject *
    CreateChildAtIndex (size_t idx, bool synthetic_array_member, int32_t synthetic_index);

    // Should only be called by ValueObject::GetNumChildren()
    virtual size_t
    CalculateNumChildren() = 0;

    void
    SetNumChildren (size_t num_children);

    void
    SetValueDidChange (bool value_changed);

    void
    SetValueIsValid (bool valid);

    void
    ClearUserVisibleData(uint32_t items = ValueObject::eClearUserVisibleDataItemsAllStrings);

    void
    AddSyntheticChild (const ConstString &key,
                       ValueObject *valobj);

    DataExtractor &
    GetDataExtractor ();

    void
    ClearDynamicTypeInformation ();

    //------------------------------------------------------------------
    // Sublasses must implement the functions below.
    //------------------------------------------------------------------

    virtual ClangASTType
    GetClangTypeImpl () = 0;

    const char *
    GetLocationAsCStringImpl (const Value& value,
                              const DataExtractor& data);

private:
    //------------------------------------------------------------------
    // For ValueObject only
    //------------------------------------------------------------------

    virtual ClangASTType
    MaybeCalculateCompleteType ();

    lldb::ValueObjectSP
    GetValueForExpressionPath_Impl(const char* expression_cstr,
                                   const char** first_unparsed,
                                   ExpressionPathScanEndReason* reason_to_stop,
                                   ExpressionPathEndResultType* final_value_type,
                                   const GetValueForExpressionPathOptions& options,
                                   ExpressionPathAftermath* final_task_on_target);

    // this method will ONLY expand [] expressions into a VOList and return
    // the number of elements it added to the VOList
    // it will NOT loop through expanding the follow-up of the expression_cstr
    // for all objects in the list
    int
    ExpandArraySliceExpression(const char* expression_cstr,
                               const char** first_unparsed,
                               lldb::ValueObjectSP root,
                               lldb::ValueObjectListSP& list,
                               ExpressionPathScanEndReason* reason_to_stop,
                               ExpressionPathEndResultType* final_value_type,
                               const GetValueForExpressionPathOptions& options,
                               ExpressionPathAftermath* final_task_on_target);

    DISALLOW_COPY_AND_ASSIGN (ValueObject);

};

} // namespace lldb_private

#endif  // liblldb_ValueObject_h_