text:
"""
Custom luigi parameters.
"""

__all__ = [
    "NO_STR", "NO_INT", "NO_FLOAT", "is_no_param", "get_param", "TaskInstanceParameter",
    "DurationParameter", "BytesParameter", "CSVParameter", "MultiCSVParameter", "RangeParameter",
    "MultiRangeParameter", "NotifyParameter", "NotifyMultiParameter", "NotifyMailParameter",
]

import csv

import luigi
import six

from law.notification import notify_mail
from law.util import (
    human_duration, parse_duration, time_units, time_unit_aliases, human_bytes, parse_bytes,
    byte_units, is_lazy_iterable, make_tuple, make_unique, brace_expand, try_int,
)
from law.logger import get_logger

logger = get_logger(__name__)

# make luigi's BoolParameter parsing explicit globally, https://github.com/spotify/luigi/pull/2427
luigi.BoolParameter.parsing = getattr(luigi.BoolParameter, "EXPLICIT_PARSING", "explicit")

# also update existing BoolParameter instances in luigi's config classes to have explicit parsing
for cls in luigi.task.Config.__subclasses__():
    for attr in dir(cls):
        member = getattr(cls, attr)
        if isinstance(member, luigi.BoolParameter):
            member.parsing = luigi.BoolParameter.parsing

#: String value denoting an empty parameter.
NO_STR = "NO_STR"

#: Integer value denoting an empty parameter.
NO_INT = -1

#: Float value denoting an empty parameter.
NO_FLOAT = -1.0

def is_no_param(value):
    """
    Checks whether a parameter *value* denotes an empty parameter, i.e., if the value is either
    :py:attr:`NO_STR`, :py:attr:`NO_INT`, or :py:attr:`NO_FLOAT`.
    """
    return value in (NO_STR, NO_INT, NO_FLOAT)

def get_param(value, default=None):
    """
    Returns the passed *value* when it does not refer to an empty parameter value, checked with
    :py:func:`is_no_param`. Otherwise, *default* is returned, which defaults to *None*.
    """
    return default if is_no_param(value) else value

class TaskInstanceParameter(luigi.Parameter):
    """
    Parameter that can be used to pass the instance of a task. This class does not implement
    parameter value parsing.
    """

    def serialize(self, x):
        """"""
        if isinstance(x, Task):
            return getattr(x, "live_task_id", x.task_id)
        return str(x)

class DurationParameter(luigi.Parameter):
    """ __init__(unit="s", *args, **kwargs)
    Parameter that interprets a string (or float) value as a duration, represented by a float
    number with a configurable unit. *unit* is forwarded as both the *unit* and *input_unit*
    argument of :py:func:`law.util.parse_duration` which is used for the conversion. For optimal
    precision, value serialization uses :py:func:`law.util.human_duration` with *colon_format*.
    Example:

    .. code-block:: python

        p = DurationParameter(unit="s")
        p.parse("5")                      # -> 5.0 (using the unit implicitly)
        p.parse("5s")                     # -> 5.0
        p.parse("5m")                     # -> 300.0
        p.parse("05:10")                  # -> 310.0
        p.parse("5 minutes, 15 seconds")  # -> 310.0
        p.serialize(310)                  # -> "05:15"

        p = DurationParameter(unit="m")
        p.parse("5")                      # -> 5.0 (using the unit implicitly)
        p.parse("5s")                     # -> 0.083
        p.parse("5m")                     # -> 5.0
        p.parse("05:10")                  # -> 5.167
        p.parse("5 minutes, 15 seconds")  # -> 5.25
        p.serialize(310)                  # -> "05:15:00"

    For more info, see :py:func:`law.util.parse_duration` and :py:func:`law.util.human_duration`.
    """

    def __init__(self, *args, **kwargs):
        # validate and set the unit
        self._unit = None
        self.unit = kwargs.pop("unit", "s")

        super(DurationParameter, self).__init__(*args, **kwargs)

    @property
    def unit(self):
        return self._unit

    @unit.setter
    def unit(self, unit):
        unit = time_unit_aliases.get(unit, unit)
        if unit not in time_units:
            raise ValueError("unknown unit '{}', valid values are {}".format(
                unit, time_units.keys()))

        self._unit = unit

    def parse(self, inp):
        """"""
        if not inp or inp == NO_STR:
            inp = "0"

        return parse_duration(inp, input_unit=self.unit, unit=self.unit)

    def serialize(self, value):
        """"""
        if not value:
            value = 0

        value_seconds = parse_duration(value, input_unit=self.unit, unit="s")
        return human_duration(seconds=value_seconds, colon_format=True)

class BytesParameter(luigi.Parameter):
    """ __init__(unit="MB", *args, **kwargs)
    Parameter that interprets a string (or float) value as a number of bytes, represented by a float
    number with a configurable unit. *unit* is forwarded as both the *unit* and *input_unit*
    argument of :py:func:`law.util.parse_bytes` which is used for the conversion.
    Example:

    .. code-block:: python

        p = BytesParameter(unit="MB")
        p.parse("5")                      # -> 5.0 (using the unit implicitly)
        p.parse("5 MB")                   # -> 5.0
        p.parse(5)                        # -> 5.0
        p.parse("1 GB")                   # -> 1024.0
        p.serialize(310)                  # -> "310MB"

        p = BytesParameter(unit="GB")
        p.parse("5")                      # -> 5.0 (using the unit implicitly)
        p.parse("1024 MB")                # -> 1.0
        p.serialize("2048 MB")            # -> "2GB"

    For more info, see :py:func:`law.util.parse_bytes` and :py:func:`law.util.human_bytes`.
    """

    def __init__(self, *args, **kwargs):
        # validate and set the unit
        self._unit = None
        self.unit = kwargs.pop("unit", "MB")

        super(BytesParameter, self).__init__(*args, **kwargs)

    @property
    def unit(self):
        return self._unit

    @unit.setter
    def unit(self, unit):
        if unit not in byte_units:
            raise ValueError("unknown unit '{}', valid values are {}".format(unit, byte_units))

        self._unit = unit

    def parse(self, inp):
        """"""
        if not inp or inp == NO_STR:
            inp = "0"

        return parse_bytes(inp, input_unit=self.unit, unit=self.unit)

    def serialize(self, value):
        """"""
        if not value:
            value = 0

        value_bytes = parse_bytes(value, input_unit=self.unit, unit="bytes")
        v, u = human_bytes(value_bytes, unit=self.unit)

        return "{}{}".format(try_int(v), u)

class CSVParameter(luigi.Parameter):
    r""" __init__(*args, cls=luigi.Parameter, unique=False, sort=False, min_len=None, \
        max_len=None, choices=None, brace_expand=False, escape_sep=True, **kwargs)
    Parameter that parses a comma-separated value (CSV) and produces a tuple. *cls* can refer to an
    other parameter class that will be used to parse and serialize the particular items.

    When *unique* is *True*, both parsing and serialization methods make sure that values are
    unique. *sort* can be a boolean or a function for sorting parameter values.

    When *min_len* (*max_len*) is set to an integer, an error is raised in case the number of
    elements to serialize or parse (evaluated after potentially ensuring uniqueness) deceeds
    (exceeds) that value. Just like in luigi's *ChoiceParamater*, *choices* can be a sequence of
    accepted values.

    When *brace_expand* is *True*, brace expansion is applied, potentially extending the list of
    values. However, note that in this case commas that are not meant to act as a delimiter cannot
    be quoted in csv-style with double quotes, but they should rather be backslash-escaped instead.
    Unless *escape_sep* is *False*, escaped separators (comma) are not split when parsing
    strings and, likewise, separators contained in values to serialze are escaped.

    Example:

    .. code-block:: python

        p = CSVParameter(cls=luigi.IntParameter)
        p.parse("4,5,6,6")
        # => (4, 5, 6, 6)
        p.serialize((7, 8, 9))
        # => "7,8,9"

        # "," that should not be used as delimiter
        p = CSVParameter()
        p.parse("a,b,\"c,d\"")
        # -> ("a", "b", "c,d")
        # same as
        p.parse("a,b,c\,d")
        # -> ("a", "b", "c,d")

        # uniqueness check
        p = CSVParameter(cls=luigi.IntParameter, unique=True)
        p.parse("4,5,6,6")
        # => (4, 5, 6)

        # length check
        p = CSVParameter(cls=luigi.IntParameter, max_len=2)
        p.parse("4,5,6")
        # => ValueError

        # choices
        p = CSVParameter(cls=luigi.IntParameter, choices=(1, 2))
        p.parse("2,3")
        # => ValueError

        # brace expansion
        p = CSVParameter(cls=luigi.IntParameter, brace_expand=True)
        # (note that with brace_expand enabled, the quoting if "," only works with back slashes)
        p.parse("1{2,3,4}9")
        # => (129, 139, 149)

    .. note::

        Due to the way `instance caching
        <https://luigi.readthedocs.io/en/stable/parameters.html#parameter-instance-caching>`__
        is implemented in luigi, parameters should always have hashable, immutable values.
        Therefore, this parameter produces a tuple and, in particular, not a list. To avoid
        undesired side effects, the *default* value given to the constructor is also converted to a
        tuple.

    .. py:attribute:: _inst
       type: cls

        Instance of the luigi parameter class *cls* that is used internally for parameter parsing
        and serialization.
    """

    def __init__(self, *args, **kwargs):
        self._cls = kwargs.pop("cls", luigi.Parameter)
        self._unique = kwargs.pop("unique", False)
        self._sort = kwargs.pop("sort", False)
        self._min_len = kwargs.pop("min_len", None)
        self._max_len = kwargs.pop("max_len", None)
        self._choices = kwargs.pop("choices", None)
        self._brace_expand = kwargs.pop("brace_expand", False)
        self._escape_sep = kwargs.pop("escape_sep", True)

        # ensure that the default value is a tuple
        if "default" in kwargs:
            kwargs["default"] = make_tuple(kwargs["default"])

        super(CSVParameter, self).__init__(*args, **kwargs)

        self._inst = self._cls()

    def _check_unique(self, value):
        if not self._unique:
            return value

        return make_unique(value)

    def _check_sort(self, value):
        if not self._sort:
            return value

        key = self._sort if callable(self._sort) else None
        value = sorted(value, key=key)

        return tuple(value)

    def _check_len(self, value):
        str_repr = lambda: ",".join(str(v) for v in value)

        if self._min_len is not None and len(value) < self._min_len:
            raise ValueError("'{}' contains {} value(s), a minimum of {} is required".format(
                str_repr(), len(value), self._min_len))

        # check max_len
        if self._max_len is not None and len(value) > self._max_len:
            raise ValueError("'{}' contains {} value(s), a maximum of {} is required".format(
                str_repr(), len(value), self._max_len))

    def _check_choices(self, value):
        if not self._choices:
            return

        unknown = []
        for v in value:
            if v not in self._choices:
                unknown.append(v)

        if unknown:
            str_repr = lambda value: ",".join(str(v) for v in value)
            raise ValueError("invalid parameter value(s) '{}', valid choices are '{}'".format(
                str_repr(make_unique(unknown)), str_repr(self._choices)))

    def parse(self, inp):
        """"""
        if not inp or inp == NO_STR:
            value = tuple()
        elif isinstance(inp, (tuple, list)) or is_lazy_iterable(inp):
            value = make_tuple(inp)
        elif isinstance(inp, six.string_types):
            if self._brace_expand:
                elems = brace_expand(inp, split_csv=True, escape_csv_sep=self._escape_sep)
            else:
                # replace escaped separators
                if self._escape_sep:
                    escaped_sep = "__law_escaped_csv_sep__"
                    inp = inp.replace("\\,", escaped_sep)
                # proper csv split
                elems = list(csv.reader([inp]))[0]
                # add back escaped separators per element
                if self._escape_sep:
                    elems = [elem.replace(escaped_sep, ",") for elem in elems]
            value = tuple(map(self._inst.parse, elems))
        else:
            value = (inp,)

        # apply uniqueness, sort, length and choices checks
        value = self._check_unique(value)
        value = self._check_sort(value)
        self._check_len(value)
        self._check_choices(value)

        return value

    def serialize(self, value):
        """"""
        if not value:
            value = tuple()

        value = make_tuple(value)

        # apply uniqueness, sort, length and choices checks
        value = self._check_unique(value)
        value = self._check_sort(value)
        self._check_len(value)
        self._check_choices(value)

        return ",".join(str(self._inst.serialize(elem)) for elem in value)

class MultiCSVParameter(CSVParameter):
    r""" __init__(*args, cls=luigi.Parameter, unique=False, sort=False, min_len=None, \
        max_len=None, choices=None, brace_expand=False, escape_sep=True, **kwargs)
    Parameter that parses several comma-separated values (CSV), separated by colons, and produces a
    nested tuple. *cls* can refer to an other parameter class that will be used to parse and
    serialize the particular items.

    Except for the additional support for multiple CSV sequences, the parsing and serialization
    implementation is based on :py:class:`CSVParameter`, which also handles the features controlled
    by *unique*, *sort*, *max_len*, *min_len*, *choices*, *brace_expand* and *escape_sep* per
    sequence of values.

    However, note that in this case colon characters that are not meant to act as a delimiter cannot
    be quoted in csv-style with double quotes, but they should rather be backslash-escaped instead.
    Unless *escape_sep* is *False*, escaped separators (colon) are not split when parsing strings
    and, likewise, separators contained in values to serialze are escaped.

    Example:

    .. code-block:: python

        p = MultiCSVParameter(cls=luigi.IntParameter)
        p.parse("4,5:6,6")
        # => ((4, 5), (6, 6))
        p.serialize((7, 8, (9,)))
        # => "7,8:9"

        # ":" that should not be used as delimiter
        p = MultiCSVParameter()
        p.parse("a,b:\"c:d\"")
        # -> (("a", "b"), ("c:d",))
        # same as
        p.parse("a,b:c\:d")
        # -> (("a", "b"), ("c:d",))

        # uniqueness check
        p = MultiCSVParameter(cls=luigi.IntParameter, unique=True)
        p.parse("4,5:6,6")
        # => ((4, 5), (6,))

        # length check
        p = MultiCSVParameter(cls=luigi.IntParameter, max_len=2)
        p.parse("4,5:6,7,8")
        # => ValueError

        # choices
        p = MultiCSVParameter(cls=luigi.IntParameter, choices=(1, 2))
        p.parse("1,2:2,3")
        # => ValueError

        # brace expansion
        # (note that with brace_expand enabled, the quoting if ":" only works with back slashes)
        p = MultiCSVParameter(cls=luigi.IntParameter, brace_expand=True)
        p.parse("4,5:6,7,8{8,9}")
        # => ((4, 5), (6, 7, 88, 89))

    .. note::

        Due to the way `instance caching
        <https://luigi.readthedocs.io/en/stable/parameters.html#parameter-instance-caching>`__
        is implemented in luigi, parameters should always have hashable values. Therefore, this
        parameter produces a (nested) tuple and, in particular, not a list. To avoid undesired side
        effects, the *default* value given to the constructor is also converted to a tuple.

    .. py:attribute:: _inst
       type: cls

        Instance of the luigi parameter class *cls* that is used internally for parameter parsing
        and serialization.
    """

    # custom csv dialect for splitting by ":" for automatic quoting
    class _Dialect(csv.excel):
        delimiter = ":"

    _dialect = _Dialect()

    def parse(self, inp):
        """"""
        if not inp or inp == NO_STR:
            value = tuple()
        elif isinstance(inp, (tuple, list)) or is_lazy_iterable(inp):
            value = tuple(super(MultiCSVParameter, self).parse(v) for v in inp)
        elif isinstance(inp, six.string_types):
            # replace escaped separators
            if self._escape_sep:
                escaped_sep = "__law_escaped_multi_csv_sep__"
                inp = inp.replace("\\" + ":", escaped_sep)
            # split
            elems = list(csv.reader([inp], dialect=self._dialect))[0]
            # add back escaped separators per element
            if self._escape_sep:
                elems = [elem.replace(escaped_sep, ":") for elem in elems]
            value = tuple(super(MultiCSVParameter, self).parse(e) for e in elems)
        else:
            value = (super(MultiCSVParameter, self).parse(inp),)

        return value

    def serialize(self, value):
        """"""
        if not value:
            return ""

        # ensure that value is a nested tuple
        value = tuple(map(make_tuple, make_tuple(value)))

        return ":".join(super(MultiCSVParameter, self).serialize(v) for v in value)

class RangeParameter(luigi.Parameter):
    """ __init__(*args, require_start=True, require_end=True, single_value=False, **kwargs)
    Parameter that parses a range in the format ``start:stop`` and returns a tuple with two integer
    elements.

    When *require_start* or *require_stop* are *False*, the formats ``:stop`` and ``start:``,
    respectively, are accepted as well. In these cases, the tuple will contain an attribute
    :py:attr:`OPEN` do denote that either side is unconstrained.

    When *single_value* is *True*, single integer values are accepted and lead to a tuple with one
    element.

    .. code-block:: python

        p = RangeParameter()
        p.parse("4:8")
        # => (4, 8)
        p.serialize((5, 9))
        # => "5:9"
        p.parse("4:")
        # => ValueError
        p.parse("4")
        # => ValueError

        p = RangeParameter(require_start=False, require_stop=False)
        p.parse("4:5")
        # => (4, 5)
        p.parse("4:")
        # => (4, OPEN)
        p.parse(":5")
        # => (OPEN, 5)
        p.parse(":")
        # => (OPEN, OPEN)
        p.serialize((OPEN, 8))
        # => ":8"

        p = RangeParameter(single_value=True)
        p.parse("4")
        # => (4,)
        p.serialize((5,))
        # => "4"

    .. py:classattribute:: RANGE_SEP
       type: string

        Character used as a separator between range edges when parsing strings and serializing
        values. Defaults to ``":"``.

    .. py:classattribute:: OPEN
       type: None

        Value denoting open edges in parsed ranges.
    """

    RANGE_SEP = ":"
    OPEN = None

    def __init__(self, *args, **kwargs):
        self._require_start = kwargs.pop("require_start", True)
        self._require_end = kwargs.pop("require_end", True)
        self._single_value = kwargs.pop("single_value", False)

        # ensure that the default value is a tuple
        if "default" in kwargs:
            kwargs["default"] = make_tuple(kwargs["default"])

        super(RangeParameter, self).__init__(*args, **kwargs)

    def _check(self, value):
        if not isinstance(value, tuple):
            raise TypeError("invalid type of range {}, must be a tuple".format(value))

        elif len(value) == 1 and self._single_value:
            if not isinstance(value[0], six.integer_types):
                raise TypeError("invalid type of single value in range {}".format(value))

        elif len(value) == 2:
            start, end = value
            if start == self.OPEN:
                if self._require_start:
                    raise ValueError("range {} lacks start value which is required".format(value))
            elif not isinstance(start, six.integer_types):
                raise TypeError("invalid type of start value in range {}".format(value))
            if end == self.OPEN:
                if self._require_end:
                    raise ValueError("range {} lacks end value which is required".format(value))
            elif not isinstance(end, six.integer_types):
                raise TypeError("invalid type of end value in range {}".format(value))

        elif value:
            raise ValueError("cannot interpret {} with {} elements as {}".format(
                value, len(value), self.__class__.__name__))

    def parse(self, inp):
        """"""
        if not inp or inp == NO_STR:
            value = tuple()
        elif isinstance(inp, (tuple, list)) or is_lazy_iterable(inp):
            value = make_tuple(inp)
        elif isinstance(inp, six.integer_types):
            value = (inp,)
        elif isinstance(inp, six.string_types):
            parts = inp.split(self.RANGE_SEP)
            # convert integers
            try:
                value = tuple((int(p) if p else self.OPEN) for p in parts)
            except ValueError:
                raise ValueError("range '{}' contains non-integer elements".format(inp))
        else:
            value = (inp,)

        self._check(value)

        return value

    def serialize(self, value):
        """"""
        if not value:
            value = tuple()

        self._check(value)

        value = [("" if v == self.OPEN else str(v)) for v in value]
        return self.RANGE_SEP.join(value)

class MultiRangeParameter(RangeParameter):
    """ __init__(*args, require_start=True, require_end=True, single_value=False, **kwargs)
    Parameter that parses several integer ranges (each in the format ``start-end``), separated by
    comma, and produces a nested tuple.

    Except for the additional support for multiple ranges, the parsing and serialization
    implementation is based on :py:class:`RangeParameter`, which also handles the control of open
    edges with *require_start* and *require_end*, and the acceptance of single integer values with
    *single_value*. Example:

    .. code-block:: python

        p = MultiRangeParameter()
        p.parse("4:8,12:14")
        # => ((4, 8), (12, 14))
        p.serialize(((5, 9), (13, 15)))
        # => ""5:9,13:15""

    .. py:classattribute:: MULTI_RANGE_SEP
       type: string

        Character used as a separator between ranges when parsing strings and serializing
        values. Defaults to ``","``.
    """

    MULTI_RANGE_SEP = ","

    def parse(self, inp):
        """"""
        if not inp or inp == NO_STR:
            value = tuple()
        elif isinstance(inp, (tuple, list)) or is_lazy_iterable(inp):
            value = tuple(super(MultiRangeParameter, self).parse(v) for v in inp)
        elif isinstance(inp, six.string_types):
            elems = inp.split(self.MULTI_RANGE_SEP)
            value = tuple(super(MultiRangeParameter, self).parse(e) for e in elems)
        else:
            value = (super(MultiRangeParameter, self).parse(inp),)

        return value

    def serialize(self, value):
        """"""
        if not value:
            return ""

        # ensure that value is a nested tuple
        value = tuple(map(make_tuple, make_tuple(value)))

        return self.MULTI_RANGE_SEP.join(
            super(MultiRangeParameter, self).serialize(v) for v in value)

class NotifyParameter(luigi.BoolParameter):
    """
    Base class for notification parameters. A notification parameter must provide a notification
    transport in :py:meth:`get_transport`, e.g.

    .. code-block:: python

        def get_transport(self):
            return {
                "func": notification_func,
                "raw": True,  # or False
            }

    When a task has a specific notification parameter set to *True* and its run method is decorated
    with the :py:func:`law.notify` function, *notification_func* is called with at least three
    arguments: *success*, *title* and *message*. *success* is a boolean which is *True* when the
    decorated function did not raise an exception. *title* is always a string. When *raw* is *False*
    (the default), *message* is also a string. Otherwise, it is an ordered dictionary containing key
    value pairs describing the message content. All options passed to
    :py:func:`law.decorator.notify` are forwarded to *notification_func* as optional arguments.
    """

    def get_transport(self):
        """
        Method to configure the transport that is toggled by this parameter. Should return a
        dictionary with ``"func"`` and ``"raw"`` (optional) fields.
        """
        return None

class NotifyMultiParameter(NotifyParameter):
    """ __init__(parameters=[], *args, **kwargs)
    Parameter that takes multiple other :py:class:`NotifyParameter`'s to join their notification
    functionality in a single parameter. Example:

    .. code-block:: python

        class MyTask(law.Task):

            notify = law.NotifyMultiParameter(parameters=[
                law.NotifyMailParameter(significant=False),
                ...  # further NotifyParameters
            ])
    """

    def __init__(self, *args, **kwargs):
        self.parameters = kwargs.pop("parameters", [])

        super(NotifyMultiParameter, self).__init__(*args, **kwargs)

    def get_transport(self):
        """"""
        return [param.get_transport() for param in self.parameters]

class NotifyMailParameter(NotifyParameter):
    """
    Notification parameter defining a basic email transport. Uses
    :py:meth:`law.notification.notify_mail` internally.
    """

    def __init__(self, *args, **kwargs):
        super(NotifyMailParameter, self).__init__(*args, **kwargs)

        if not self.description:
            self.description = "when true, and the task's run method is decorated with " \
                "law.decorator.notify, an email notification is sent once the task finishes"

    @classmethod
    def notify(success, *args, **kwargs):
        """"""
        return notify_mail(*args, **kwargs)

    def get_transport(self):
        """"""
        return {
            "func": self.notify,
            "raw": False,
            "colored": False,
        }

# trailing imports
from law.task.base import Task


text:
function cvx_save_prefs( varargin )

%CVX_SAVE_PREFS   Saves current CVX settings for future MATLAB sessions.
%   CVX_SAVE_PREFS saves the the current global CVX settings to a special
%   prefences file (stored in the "prefdir" directory). This enables CVX to
%   remember your preferred settings (solver, precision, etc.) between
%   MATLAB sessions.

global cvx___
if ~isfield( cvx___, 'pfile' ),
    error( 'CVX:BadPrefsSave', 'CVX is not currently loaded; there are no preferences to save.' );
elseif nargin == 0,
    fprintf( 'Saving prefs...' );
end
outp.expert = cvx___.expert;
outp.precision = cvx___.precision;
outp.precflag = cvx___.precflag;
outp.rat_growth = cvx___.rat_growth;
outp.path = cvx___.path;
outp.solvers = cvx___.solvers;
outp.license = cvx___.license;
outp.solvers.map.default = cvx___.solvers.selected;
[ outp.solvers.list.check, outp.solvers.list.solve, outp.solvers.list.eargs ] = deal( {} );
outp.solvers.active = 0;
save(cvx___.pfile,'-struct','outp');
if nargin == 0,
    fprintf( 'done.\n' );
end

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">

  <head>
    <!-- General meta -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {% if page.indexing == false %}
      <meta name="robots" content="noindex">
    {% endif %}

    {% if page.collectionpage %}
      {% seo title=false %}

      {% assign collectiondata = site.collections | where: "label", page.collectionpage | first %}
      <title>{{ collectiondata.title }} - {{ site.title }}</title>
      <meta property="og:title" content="{{ collectiondata.title }}">
      <meta name="description" content="{{ collectiondata.description }}">
      <meta property="og:description" content="{{ collectiondata.description }}">
    {% else %}
      {% seo %}
    {% endif %}
    {% if site.fonts.preconnect_urls %}
      {% for url in site.fonts.preconnect_urls %}
        <link rel="preconnect" href="{{ url }}" crossorigin />
      {% endfor %}
    {% endif %}

    <link rel="manifest" href="{{ "/manifest.json" | relative_url }}">
    <meta name="theme-color" content="{{ site.manifest.theme_color | default: '#242e2b' }}"/>

    {% if site.css_inline == true %}
      {% include site-styles.html %}
    {% else %}
      <link rel="stylesheet" href="{{ "/assets/styles.css" | relative_url }}">
    {% endif %}

    {% if site.favicons or site.avatarurl %}{% include site-favicons.html %}{% endif %}

    {% if site.google_analytics %}{% include site-analytics.html %}{% endif %}

    {% include site-fonts.html %}

    {% include site-before-start.html %}
  </head>

  <body class="layout-{{ page.layout }}{% if page.title %}  {{ page.title | slugify }}{% endif %}">
    {% include site-icons.svg %}

    {{ content }}

    {% if site.service_worker != false %}{% include site-sw.html %}{% endif %}

    {% include site-before-end.html %}
  </body>

</html>


text:
/**
 * @generated
 * @providesModule Metadata
 */
module.exports = {
  "files": [
    {
      "id": "api-reference-relay-container",
      "title": "RelayContainer",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-container.html",
      "next": "api-reference-relay-route",
      "source": "APIReference-Container.md"
    },
    {
      "id": "api-reference-relay-graphql-mutation",
      "title": "Relay.GraphQLMutation",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-graphql-mutation.html",
      "next": "api-reference-relay-proptypes",
      "source": "APIReference-GraphQLMutation.md"
    },
    {
      "id": "api-reference-relay-mutation",
      "title": "Relay.Mutation",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-mutation.html",
      "next": "api-reference-relay-graphql-mutation",
      "source": "APIReference-Mutation.md"
    },
    {
      "id": "api-reference-relay-proptypes",
      "title": "Relay.PropTypes",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-proptypes.html",
      "next": "api-reference-relay-store",
      "source": "APIReference-PropTypes.md"
    },
    {
      "id": "api-reference-relay-ql",
      "title": "Relay.QL",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-ql.html",
      "next": "api-reference-relay-mutation",
      "source": "APIReference-QL.md"
    },
    {
      "id": "api-reference-relay",
      "title": "Relay",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay.html",
      "next": "api-reference-relay-container",
      "source": "APIReference-Relay.md"
    },
    {
      "id": "api-reference-relay-renderer",
      "title": "Relay.Renderer",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-renderer.html",
      "next": "api-reference-relay-root-container",
      "source": "APIReference-Renderer.md"
    },
    {
      "id": "api-reference-relay-root-container",
      "title": "Relay.RootContainer",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-root-container.html",
      "next": "api-reference-relay-ql",
      "source": "APIReference-RootContainer.md"
    },
    {
      "id": "api-reference-relay-route",
      "title": "Relay.Route",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-route.html",
      "next": "api-reference-relay-renderer",
      "source": "APIReference-Route.md"
    },
    {
      "id": "api-reference-relay-store",
      "title": "Relay.Store",
      "layout": "docs",
      "category": "Relay Classic API",
      "permalink": "docs/api-reference-relay-store.html",
      "next": "interfaces-relay-network-layer",
      "source": "APIReference-Store.md"
    },
    {
      "id": "graphql-connections",
      "title": "Connection",
      "layout": "docs",
      "category": "GraphQL",
      "permalink": "docs/graphql-connections.html",
      "next": "graphql-mutations",
      "source": "GraphQL-Connections.md"
    },
    {
      "id": "graphql-further-reading",
      "title": "Further Reading",
      "layout": "docs",
      "category": "GraphQL",
      "permalink": "docs/graphql-further-reading.html",
      "next": "api-reference-relay",
      "source": "GraphQL-FurtherReading.md"
    },
    {
      "id": "graphql-mutations",
      "title": "Mutations",
      "layout": "docs",
      "category": "GraphQL",
      "permalink": "docs/graphql-mutations.html",
      "next": "graphql-further-reading",
      "source": "GraphQL-Mutations.md"
    },
    {
      "id": "graphql-object-identification",
      "title": "Object Identification",
      "layout": "docs",
      "category": "GraphQL",
      "permalink": "docs/graphql-object-identification.html",
      "next": "graphql-connections",
      "source": "GraphQL-ObjectIdentification.md"
    },
    {
      "id": "graphql-relay-specification",
      "title": "GraphQL Relay Specification",
      "layout": "docs",
      "category": "GraphQL",
      "permalink": "docs/graphql-relay-specification.html",
      "next": "graphql-object-identification",
      "source": "GraphQL-RelaySpecification.md"
    },
    {
      "id": "guides-babel-plugin",
      "title": "Babel Relay Plugin",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-babel-plugin.html",
      "next": "graphql-relay-specification",
      "source": "Guides-BabelPlugin.md"
    },
    {
      "id": "guides-containers",
      "title": "Containers",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-containers.html",
      "next": "guides-routes",
      "source": "Guides-Containers.md"
    },
    {
      "id": "guides-mutations",
      "title": "Mutations",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-mutations.html",
      "next": "guides-network-layer",
      "source": "Guides-Mutations.md"
    },
    {
      "id": "guides-network-layer",
      "title": "Network Layer",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-network-layer.html",
      "next": "guides-babel-plugin",
      "source": "Guides-NetworkLayer.md"
    },
    {
      "id": "guides-ready-state",
      "title": "Ready State",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-ready-state.html",
      "next": "guides-mutations",
      "source": "Guides-ReadyState.md"
    },
    {
      "id": "guides-root-container",
      "title": "Root Container",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-root-container.html",
      "next": "guides-ready-state",
      "source": "Guides-RootContainer.md"
    },
    {
      "id": "guides-routes",
      "title": "Routes",
      "layout": "docs",
      "category": "Relay Classic Guides",
      "permalink": "docs/guides-routes.html",
      "next": "guides-root-container",
      "source": "Guides-Routes.md"
    },
    {
      "id": "interfaces-relay-mutation-request",
      "title": "RelayMutationRequest",
      "layout": "docs",
      "category": "Relay Classic Interfaces",
      "permalink": "docs/interfaces-relay-mutation-request.html",
      "next": "interfaces-relay-query-request",
      "source": "Interfaces-MutationRequest.md"
    },
    {
      "id": "interfaces-relay-network-layer",
      "title": "RelayNetworkLayer",
      "layout": "docs",
      "category": "Relay Classic Interfaces",
      "permalink": "docs/interfaces-relay-network-layer.html",
      "next": "interfaces-relay-mutation-request",
      "source": "Interfaces-NetworkLayer.md"
    },
    {
      "id": "interfaces-relay-query-request",
      "title": "RelayQueryRequest",
      "layout": "docs",
      "category": "Relay Classic Interfaces",
      "permalink": "docs/interfaces-relay-query-request.html",
      "source": "Interfaces-QueryRequest.md"
    },
    {
      "id": "api-cheatsheet",
      "title": "API Cheatsheet",
      "layout": "docs",
      "category": "Relay Compat",
      "permalink": "docs/api-cheatsheet.html",
      "next": "guides-containers",
      "source": "APICheatsheet.md"
    },
    {
      "id": "babel-plugin-relay",
      "title": "babel-plugin-relay",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/babel-plugin-relay.html",
      "next": "relay-compiler",
      "source": "BabelPluginRelay.md"
    },
    {
      "id": "compatibility-cheatsheet",
      "title": "Compatibility Cheatsheet",
      "layout": "docs",
      "category": "Relay Compat",
      "permalink": "docs/compatibility-cheatsheet.html",
      "next": "api-cheatsheet",
      "source": "CompatibilityCheatsheet.md"
    },
    {
      "id": "conversion-playbook",
      "title": "Conversion Playbook",
      "layout": "docs",
      "category": "Relay Compat",
      "permalink": "docs/conversion-playbook.html",
      "next": "conversion-scripts",
      "source": "ConversionPlaybook.md"
    },
    {
      "id": "conversion-scripts",
      "title": "Conversion Scripts",
      "layout": "docs",
      "category": "Relay Compat",
      "permalink": "docs/conversion-scripts.html",
      "next": "upgrading-setvariables",
      "source": "ConversionScripts.md"
    },
    {
      "id": "relay-debugging",
      "title": "Debugging",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/relay-debugging.html",
      "next": "relay-compat",
      "source": "Debugging.md"
    },
    {
      "id": "relay-directives",
      "title": "Directives",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/relay-directives.html",
      "next": "babel-plugin-relay",
      "source": "Directives.md"
    },
    {
      "id": "relay-environment",
      "title": "The Relay \"Environment\"",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/relay-environment.html",
      "next": "network-layer",
      "source": "Environment.md"
    },
    {
      "id": "fragment-container",
      "title": "FragmentContainer",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/fragment-container.html",
      "next": "refetch-container",
      "source": "FragmentContainer.md"
    },
    {
      "id": "relay-modern",
      "title": "Introduction to Relay Modern",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/relay-modern.html",
      "next": "new-in-relay-modern",
      "source": "Introduction.md"
    },
    {
      "id": "mutations",
      "title": "Mutations",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/mutations.html",
      "next": "subscriptions",
      "source": "Mutations.md"
    },
    {
      "id": "network-layer",
      "title": "The Relay Network Layer",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/network-layer.html",
      "next": "query-renderer",
      "source": "NetworkLayer.md"
    },
    {
      "id": "new-in-relay-modern",
      "title": "New in Relay Modern",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/new-in-relay-modern.html",
      "next": "relay-environment",
      "source": "NewInRelayModern.md"
    },
    {
      "id": "pagination-container",
      "title": "PaginationContainer",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/pagination-container.html",
      "next": "routing",
      "source": "PaginationContainer.md"
    },
    {
      "id": "query-renderer",
      "title": "QueryRenderer",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/query-renderer.html",
      "next": "fragment-container",
      "source": "QueryRenderer.md"
    },
    {
      "id": "refetch-container",
      "title": "RefetchContainer",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/refetch-container.html",
      "next": "pagination-container",
      "source": "RefetchContainer.md"
    },
    {
      "id": "relay-compat",
      "title": "Compatibility Mode",
      "layout": "docs",
      "category": "Relay Compat",
      "permalink": "docs/relay-compat.html",
      "next": "conversion-playbook",
      "source": "RelayCompat.md"
    },
    {
      "id": "relay-compiler",
      "title": "Relay Compiler",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/relay-compiler.html",
      "next": "relay-debugging",
      "source": "RelayCompiler.md"
    },
    {
      "id": "routing",
      "title": "Routing",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/routing.html",
      "next": "mutations",
      "source": "Routing.md"
    },
    {
      "id": "subscriptions",
      "title": "Subscriptions",
      "layout": "docs",
      "category": "Relay Modern",
      "permalink": "docs/subscriptions.html",
      "next": "relay-directives",
      "source": "Subscriptions.md"
    },
    {
      "id": "upgrading-setvariables",
      "title": "Upgrading setVariables",
      "layout": "docs",
      "category": "Relay Compat",
      "permalink": "docs/upgrading-setvariables.html",
      "next": "compatibility-cheatsheet",
      "source": "UpgradingSetVariables.md"
    },
    {
      "id": "getting-started",
      "title": "Getting Started",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/getting-started.html",
      "next": "tutorial",
      "source": "QuickStart-GettingStarted.md"
    },
    {
      "id": "getting-started",
      "title": "Começando",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/getting-started.pt-br.html",
      "next": "tutorial",
      "source": "QuickStart-GettingStarted.pt-br.md"
    },
    {
      "id": "getting-started",
      "title": "准备",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/getting-started.zh-CN.html",
      "next": "tutorial",
      "source": "QuickStart-GettingStarted.zh-CN.md"
    },
    {
      "id": "thinking-in-graphql",
      "title": "Thinking in GraphQL",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/thinking-in-graphql.html",
      "next": "thinking-in-relay",
      "source": "QuickStart-ThinkingInGraphQL.md"
    },
    {
      "id": "thinking-in-graphql",
      "title": "深入理解 GraphQL",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/thinking-in-graphql.zh-CN.html",
      "next": "thinking-in-relay",
      "source": "QuickStart-ThinkingInGraphQL.zh-CN.md"
    },
    {
      "id": "thinking-in-relay",
      "title": "Thinking In Relay",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/thinking-in-relay.html",
      "next": "videos",
      "source": "QuickStart-ThinkingInRelay.md"
    },
    {
      "id": "tutorial",
      "title": "Tutorial",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/tutorial.html",
      "next": "thinking-in-graphql",
      "source": "QuickStart-Tutorial.md"
    },
    {
      "id": "tutorial",
      "title": "教程",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/tutorial.zh-CN.html",
      "next": "thinking-in-graphql",
      "source": "QuickStart-Tutorial.zh-CN.md"
    },
    {
      "id": "videos",
      "title": "Videos",
      "layout": "docs",
      "category": "Quick Start",
      "permalink": "docs/videos.html",
      "next": "relay-modern",
      "source": "QuickStart-Videos.md"
    }
  ]
};


text:
    <link rel="stylesheet" type="text/css" media="all" href="../../css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="all" href="../../css/frame.css" />
    <title>iHeart</title>

        <button id="closeATT" type="button" class="close close-md" data-dismiss="modal" aria-hidden="true">×</button>

Add to Trello

                    <select class="form-control"  id="board-list" placeholder="Enter board">
                      <option value="1">1</option>
                      <option value="2">2</option>
                      <option value="3">3</option>
                      <option value="4">4</option>
                      <option value="5">5</option>
                    </select>

                    <select class="form-control"  id="list-list" placeholder="Enter list">
                      <option>1</option>
                      <option>2</option>
                      <option>3</option>
                      <option>4</option>
                      <option>5</option>
                    </select>

                <input type="email" class="form-control" id="card-title" placeholder="Card title">

                <textarea id="card-description" class="form-control" rows="3" placeholder="Card description"></textarea>

        <button type="button" data-dismiss="modal" class="btn close-md">Close</button>
        <button id="addTrello" type="button" class="btn btn-primary">Save changes</button>


text:
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicBoolean;

import sun.misc.Unsafe;

/**
 * Checker test on the 1.8 unsafe operations. Note, this is by no means an
 * exhaustive unit test for these CAS (compare-and-swap) and fence operations.
 * Instead, this test ensures the methods are recognized as intrinsic and behave
 * as expected.
 */
public class Main {

  private static final Unsafe unsafe = getUnsafe();

  private static Thread[] sThreads = new Thread[10];

  //
  // Fields accessed by setters and adders, and by memory fence tests.
  //

  public int i = 0;
  public long l = 0;
  public Object o = null;

  public int x_value;
  public int y_value;
  public volatile boolean running;

  //
  // Setters.
  //

  /// CHECK-START: int Main.set32(java.lang.Object, long, int) intrinsics_recognition (after)
  /// CHECK-DAG: <<Result:i\d+>> InvokeVirtual intrinsic:UnsafeGetAndSetInt
  /// CHECK-DAG:                 Return [<<Result>>]
  private static int set32(Object o, long offset, int newValue) {
    return unsafe.getAndSetInt(o, offset, newValue);
  }

  /// CHECK-START: long Main.set64(java.lang.Object, long, long) intrinsics_recognition (after)
  /// CHECK-DAG: <<Result:j\d+>> InvokeVirtual intrinsic:UnsafeGetAndSetLong
  /// CHECK-DAG:                 Return [<<Result>>]
  private static long set64(Object o, long offset, long newValue) {
    return unsafe.getAndSetLong(o, offset, newValue);
  }

  /// CHECK-START: java.lang.Object Main.setObj(java.lang.Object, long, java.lang.Object) intrinsics_recognition (after)
  /// CHECK-DAG: <<Result:l\d+>> InvokeVirtual intrinsic:UnsafeGetAndSetObject
  /// CHECK-DAG:                 Return [<<Result>>]
  private static Object setObj(Object o, long offset, Object newValue) {
    return unsafe.getAndSetObject(o, offset, newValue);
  }

  //
  // Adders.
  //

  /// CHECK-START: int Main.add32(java.lang.Object, long, int) intrinsics_recognition (after)
  /// CHECK-DAG: <<Result:i\d+>> InvokeVirtual intrinsic:UnsafeGetAndAddInt
  /// CHECK-DAG:                 Return [<<Result>>]
  private static int add32(Object o, long offset, int delta) {
    return unsafe.getAndAddInt(o, offset, delta);
  }

  /// CHECK-START: long Main.add64(java.lang.Object, long, long) intrinsics_recognition (after)
  /// CHECK-DAG: <<Result:j\d+>> InvokeVirtual intrinsic:UnsafeGetAndAddLong
  /// CHECK-DAG:                 Return [<<Result>>]
  private static long add64(Object o, long offset, long delta) {
    return unsafe.getAndAddLong(o, offset, delta);
  }

  //
  // Fences (native).
  //

  /// CHECK-START: void Main.load() intrinsics_recognition (after)
  /// CHECK-DAG: InvokeVirtual intrinsic:UnsafeLoadFence
  //
  /// CHECK-START: void Main.load() instruction_simplifier (after)
  /// CHECK-NOT: InvokeVirtual intrinsic:UnsafeLoadFence
  //
  /// CHECK-START: void Main.load() instruction_simplifier (after)
  /// CHECK-DAG: MemoryBarrier kind:LoadAny
  private static void load() {
    unsafe.loadFence();
  }

  /// CHECK-START: void Main.store() intrinsics_recognition (after)
  /// CHECK-DAG: InvokeVirtual intrinsic:UnsafeStoreFence
  //
  /// CHECK-START: void Main.store() instruction_simplifier (after)
  /// CHECK-NOT: InvokeVirtual intrinsic:UnsafeStoreFence
  //
  /// CHECK-START: void Main.store() instruction_simplifier (after)
  /// CHECK-DAG: MemoryBarrier kind:AnyStore
  private static void store() {
    unsafe.storeFence();
  }

  /// CHECK-START: void Main.full() intrinsics_recognition (after)
  /// CHECK-DAG: InvokeVirtual intrinsic:UnsafeFullFence
  //
  /// CHECK-START: void Main.full() instruction_simplifier (after)
  /// CHECK-NOT: InvokeVirtual intrinsic:UnsafeFullFence
  //
  /// CHECK-START: void Main.full() instruction_simplifier (after)
  /// CHECK-DAG: MemoryBarrier kind:AnyAny
  private static void full() {
    unsafe.fullFence();
  }

  //
  // Thread fork/join.
  //

  private static void fork(Runnable r) {
    for (int i = 0; i < 10; i++) {
      sThreads[i] = new Thread(r);
    }
    // Start the threads only after the full array has been written with new threads,
    // because one test relies on the contents of this array to be consistent.
    for (int i = 0; i < 10; i++) {
      sThreads[i].start();
    }
  }

  private static void join() {
    try {
      for (int i = 0; i < 10; i++) {
        sThreads[i].join();
      }
    } catch (InterruptedException e) {
      throw new Error("Failed join: " + e);
    }
  }

  //
  // Driver.
  //

  public static void main(String[] args) {
    System.out.println("starting");

    final Main m = new Main();

    // Get the offsets.

    final long intOffset, longOffset, objOffset;
    try {
      Field intField = Main.class.getDeclaredField("i");
      Field longField = Main.class.getDeclaredField("l");
      Field objField = Main.class.getDeclaredField("o");

      intOffset = unsafe.objectFieldOffset(intField);
      longOffset = unsafe.objectFieldOffset(longField);
      objOffset = unsafe.objectFieldOffset(objField);

    } catch (NoSuchFieldException e) {
      throw new Error("No offset: " + e);
    }

    // Some sanity on setters and adders within same thread.

    set32(m, intOffset, 3);
    expectEqual32(3, m.i);

    set64(m, longOffset, 7L);
    expectEqual64(7L, m.l);

    setObj(m, objOffset, m);
    expectEqualObj(m, m.o);

    add32(m, intOffset, 11);
    expectEqual32(14, m.i);

    add64(m, longOffset, 13L);
    expectEqual64(20L, m.l);

    // Some sanity on setters within different threads.

    fork(new Runnable() {
      public void run() {
        for (int i = 0; i < 10; i++)
          set32(m, intOffset, i);
      }
    });
    join();
    expectEqual32(9, m.i);  // one thread's last value wins

    fork(new Runnable() {
      public void run() {
        for (int i = 0; i < 10; i++)
          set64(m, longOffset, (long) (100 + i));
      }
    });
    join();
    expectEqual64(109L, m.l);  // one thread's last value wins

    fork(new Runnable() {
      public void run() {
        for (int i = 0; i < 10; i++)
          setObj(m, objOffset, sThreads[i]);
      }
    });
    join();
    expectEqualObj(sThreads[9], m.o);  // one thread's last value wins

    // Some sanity on adders within different threads.

    fork(new Runnable() {
      public void run() {
        for (int i = 0; i < 10; i++)
          add32(m, intOffset, i + 1);
      }
    });
    join();
    expectEqual32(559, m.i);  // all values accounted for

    fork(new Runnable() {
      public void run() {
        for (int i = 0; i < 10; i++)
          add64(m, longOffset, (long) (i + 1));
      }
    });
    join();
    expectEqual64(659L, m.l);  // all values accounted for

    // Some sanity on fences within same thread. Note that memory fences within one
    // thread make little sense, but the sanity check ensures nothing bad happens.

    m.i = -1;
    m.l = -2L;
    m.o = null;

    load();
    store();
    full();

    expectEqual32(-1, m.i);
    expectEqual64(-2L, m.l);
    expectEqualObj(null, m.o);

    // Some sanity on full fence within different threads. We write the non-volatile m.l after
    // the fork(), which means there is no happens-before relation in the Java memory model
    // with respect to the read in the threads. This relation is enforced by the memory fences
    // and the weak-set() -> get() guard. Note that the guard semantics used here are actually
    // too strong and already enforce total memory visibility, but this test illustrates what
    // should still happen if Java had a true relaxed memory guard.

    final AtomicBoolean guard1 = new AtomicBoolean();
    m.l = 0L;

    fork(new Runnable() {
      public void run() {
        while (!guard1.get());  // busy-waiting
        full();
        expectEqual64(-123456789L, m.l);
      }
    });

    m.l = -123456789L;
    full();
    while (!guard1.weakCompareAndSet(false, true));  // relaxed memory order
    join();

    // Some sanity on release/acquire fences within different threads. We write the non-volatile
    // m.l after the fork(), which means there is no happens-before relation in the Java memory
    // model with respect to the read in the threads. This relation is enforced by the memory fences
    // and the weak-set() -> get() guard. Note that the guard semantics used here are actually
    // too strong and already enforce total memory visibility, but this test illustrates what
    // should still happen if Java had a true relaxed memory guard.

    final AtomicBoolean guard2 = new AtomicBoolean();
    m.l = 0L;

    fork(new Runnable() {
      public void run() {
        while (!guard2.get());  // busy-waiting
        load();
        expectEqual64(-987654321L, m.l);
      }
    });

    m.l = -987654321L;
    store();
    while (!guard2.weakCompareAndSet(false, true));  // relaxed memory order
    join();

    // Some sanity on release/acquire fences within different threads using a test suggested by
    // Hans Boehm. Even this test remains with the realm of sanity only, since having the threads
    // read the same value consistently would be a valid outcome.

    m.x_value = -1;
    m.y_value = -1;
    m.running = true;

    fork(new Runnable() {
      public void run() {
        while (m.running) {
          for (int few_times = 0; few_times < 1000; few_times++) {
            // Read y first, then load fence, then read x.
            // They should appear in order, if seen at all.
            int local_y = m.y_value;
            load();
            int local_x = m.x_value;
            expectLessThanOrEqual32(local_y, local_x);
          }
        }
      }
    });

    for (int many_times = 0; many_times < 100000; many_times++) {
      m.x_value = many_times;
      store();
      m.y_value = many_times;
    }
    m.running = false;
    join();

    // All done!

    System.out.println("passed");
  }

  // Use reflection to implement "Unsafe.getUnsafe()";
  private static Unsafe getUnsafe() {
    try {
      Class<?> unsafeClass = Unsafe.class;
      Field f = unsafeClass.getDeclaredField("theUnsafe");
      f.setAccessible(true);
      return (Unsafe) f.get(null);
    } catch (Exception e) {
      throw new Error("Cannot get Unsafe instance");
    }
  }

  private static void expectEqual32(int expected, int result) {
    if (expected != result) {
      throw new Error("Expected: " + expected + ", found: " + result);
    }
  }

  private static void expectLessThanOrEqual32(int val1, int val2) {
    if (val1 > val2) {
      throw new Error("Expected: " + val1 + " <= " + val2);
    }
  }

  private static void expectEqual64(long expected, long result) {
    if (expected != result) {
      throw new Error("Expected: " + expected + ", found: " + result);
    }
  }

  private static void expectEqualObj(Object expected, Object result) {
    if (expected != result) {
      throw new Error("Expected: " + expected + ", found: " + result);
    }
  }
}


text:
#import "ZXBinarizer.h"
#import "ZXBinaryBitmap.h"
#import "ZXBitArray.h"
#import "ZXBitMatrix.h"

@interface ZXBinaryBitmap ()

@property (nonatomic, strong, readonly) ZXBinarizer *binarizer;
@property (nonatomic, strong) ZXBitMatrix *matrix;

@end

@implementation ZXBinaryBitmap

- (id)initWithBinarizer:(ZXBinarizer *)binarizer {
  if (self = [super init]) {
    if (binarizer == nil) {
      [NSException raise:NSInvalidArgumentException format:@"Binarizer must be non-null."];
    }

    _binarizer = binarizer;
  }

  return self;
}

+ (id)binaryBitmapWithBinarizer:(ZXBinarizer *)binarizer {
  return [[self alloc] initWithBinarizer:binarizer];
}

- (int)width {
  return self.binarizer.width;
}

- (int)height {
  return self.binarizer.height;
}

- (ZXBitArray *)blackRow:(int)y row:(ZXBitArray *)row error:(NSError **)error {
  return [self.binarizer blackRow:y row:row error:error];
}

- (ZXBitMatrix *)blackMatrixWithError:(NSError **)error {
  if (self.matrix == nil) {
    self.matrix = [self.binarizer blackMatrixWithError:error];
  }
  return self.matrix;
}

- (BOOL)cropSupported {
  return [self.binarizer luminanceSource].cropSupported;
}

- (ZXBinaryBitmap *)crop:(int)left top:(int)top width:(int)aWidth height:(int)aHeight {
  ZXLuminanceSource *newSource = [[self.binarizer luminanceSource] crop:left top:top width:aWidth height:aHeight];
  return [[ZXBinaryBitmap alloc] initWithBinarizer:[self.binarizer createBinarizer:newSource]];
}

- (BOOL)rotateSupported {
  return [self.binarizer luminanceSource].rotateSupported;
}

- (ZXBinaryBitmap *)rotateCounterClockwise {
  ZXLuminanceSource *newSource = [[self.binarizer luminanceSource] rotateCounterClockwise];
  return [[ZXBinaryBitmap alloc] initWithBinarizer:[self.binarizer createBinarizer:newSource]];
}

- (ZXBinaryBitmap *)rotateCounterClockwise45 {
  ZXLuminanceSource *newSource = [[self.binarizer luminanceSource] rotateCounterClockwise45];
  return [[ZXBinaryBitmap alloc] initWithBinarizer:[self.binarizer createBinarizer:newSource]];
}

- (NSString *)description {
  ZXBitMatrix *matrix = [self blackMatrixWithError:nil];
  if (matrix) {
    return [matrix description];
  } else {
    return @"";
  }
}

@end


text:
<?php

namespace MongoDB\Model;

use ArrayAccess;
use MongoDB\Exception\BadMethodCallException;
use ReturnTypeWillChange;

use function array_key_exists;

/**
 * Collection information model class.
 *
 * This class models the collection information returned by the listCollections
 * command or, for legacy servers, queries on the "system.namespaces"
 * collection. It provides methods to access options for the collection.
 *
 * @api
 * @see \MongoDB\Database::listCollections()
 * @see https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst
 */
class CollectionInfo implements ArrayAccess
{
    /** @var array */
    private $info;

    /**
     * @param array $info Collection info
     */
    public function __construct(array $info)
    {
        $this->info = $info;
    }

    /**
     * Return the collection info as an array.
     *
     * @see https://php.net/oop5.magic#language.oop5.magic.debuginfo
     * @return array
     */
    public function __debugInfo()
    {
        return $this->info;
    }

    /**
     * Return the maximum number of documents to keep in the capped collection.
     *
     * @deprecated 1.0 Deprecated in favor of using getOptions
     *
     * @return integer|null
     */
    public function getCappedMax()
    {
        /* The MongoDB server might return this number as an integer or float */
        return isset($this->info['options']['max']) ? (integer) $this->info['options']['max'] : null;
    }

    /**
     * Return the maximum size (in bytes) of the capped collection.
     *
     * @deprecated 1.0 Deprecated in favor of using getOptions
     *
     * @return integer|null
     */
    public function getCappedSize()
    {
        /* The MongoDB server might return this number as an integer or float */
        return isset($this->info['options']['size']) ? (integer) $this->info['options']['size'] : null;
    }

    /**
     * Return information about the _id index for the collection.
     *
     * @return array
     */
    public function getIdIndex(): array
    {
        return (array) ($this->info['idIndex'] ?? []);
    }

    /**
     * Return the "info" property of the server response.
     *
     * @see https://mongodb.com/docs/manual/reference/command/listCollections/#output
     * @return array
     */
    public function getInfo(): array
    {
        return (array) ($this->info['info'] ?? []);
    }

    /**
     * Return the collection name.
     *
     * @see https://mongodb.com/docs/manual/reference/command/listCollections/#output
     * @return string
     */
    public function getName()
    {
        return (string) $this->info['name'];
    }

    /**
     * Return the collection options.
     *
     * @see https://mongodb.com/docs/manual/reference/command/listCollections/#output
     * @return array
     */
    public function getOptions()
    {
        return (array) ($this->info['options'] ?? []);
    }

    /**
     * Return the collection type.
     *
     * @see https://mongodb.com/docs/manual/reference/command/listCollections/#output
     * @return string
     */
    public function getType(): string
    {
        return (string) $this->info['type'];
    }

    /**
     * Return whether the collection is a capped collection.
     *
     * @deprecated 1.0 Deprecated in favor of using getOptions
     *
     * @return boolean
     */
    public function isCapped()
    {
        return ! empty($this->info['options']['capped']);
    }

    /**
     * Check whether a field exists in the collection information.
     *
     * @see https://php.net/arrayaccess.offsetexists
     * @param mixed $key
     * @return boolean
     */
    #[ReturnTypeWillChange]
    public function offsetExists($key)
    {
        return array_key_exists($key, $this->info);
    }

    /**
     * Return the field's value from the collection information.
     *
     * @see https://php.net/arrayaccess.offsetget
     * @param mixed $key
     * @return mixed
     */
    #[ReturnTypeWillChange]
    public function offsetGet($key)
    {
        return $this->info[$key];
    }

    /**
     * Not supported.
     *
     * @see https://php.net/arrayaccess.offsetset
     * @param mixed $key
     * @param mixed $value
     * @throws BadMethodCallException
     * @return void
     */
    #[ReturnTypeWillChange]
    public function offsetSet($key, $value)
    {
        throw BadMethodCallException::classIsImmutable(self::class);
    }

    /**
     * Not supported.
     *
     * @see https://php.net/arrayaccess.offsetunset
     * @param mixed $key
     * @throws BadMethodCallException
     * @return void
     */
    #[ReturnTypeWillChange]
    public function offsetUnset($key)
    {
        throw BadMethodCallException::classIsImmutable(self::class);
    }
}


text:
<?php
class NHP_Options_text extends NHP_Options{

	/**
	 * Field Constructor.
	 *
	 * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function
	 *
	 * @since NHP_Options 1.0
	*/
	function __construct($field = array(), $value ='', $parent){

		parent::__construct($parent->sections, $parent->args, $parent->extra_tabs);
		$this->field = $field;
		$this->value = $value;
		//$this->render();

	}//function

	/**
	 * Field Render Function.
	 *
	 * Takes the vars and outputs the HTML for the field in the settings
	 *
	 * @since NHP_Options 1.0
	*/
	function render(){
		$class = (isset($this->field['class']))?$this->field['class']:'regular-text';
        // $args['type'] for HTML5 field types 'number', 'tel', 'email', etc.
		$type = (isset($this->field['args']['type']) ? $this->field['args']['type'] : 'text');

		echo '<input type="'.$type.'" id="'.$this->field['id'].'" name="'.$this->args['opt_name'].'['.$this->field['id'].']" value="'.esc_attr($this->value).'" class="'.$class.'" data-std="'.(isset($this->field['std']) ? $this->field['std'] : '').'" />';

		echo (isset($this->field['desc']) && !empty($this->field['desc']))?' '.$this->field['desc'].'':'';
	}//function

}//class
?>


text:
namespace chromeos {

namespace {
const char kFreezerPath[] = "/sys/fs/cgroup/freezer/chrome_renderers";
const char kToBeFrozen[] = "to_be_frozen";
const char kFreezerState[] = "freezer.state";
const char kCgroupProcs[] = "cgroup.procs";

const char kFreezeCommand[] = "FROZEN";
const char kThawCommand[] = "THAWED";

}  // namespace

class FreezerCgroupProcessManager::FileWorker {
 public:
  // Called on UI thread.
  explicit FileWorker(scoped_refptr<base::SequencedTaskRunner> file_thread)
      : ui_thread_(
            base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})),
        file_thread_(file_thread),
        enabled_(false),
        froze_successfully_(false) {
    DCHECK(ui_thread_->RunsTasksInCurrentSequence());
  }

  // Called on FILE thread.
  virtual ~FileWorker() { DCHECK(file_thread_->RunsTasksInCurrentSequence()); }

  void Start() {
    DCHECK(file_thread_->RunsTasksInCurrentSequence());

    default_control_path_ = base::FilePath(kFreezerPath).Append(kCgroupProcs);
    to_be_frozen_control_path_ = base::FilePath(kFreezerPath)
                                     .AppendASCII(kToBeFrozen)
                                     .AppendASCII(kCgroupProcs);
    to_be_frozen_state_path_ = base::FilePath(kFreezerPath)
                                   .AppendASCII(kToBeFrozen)
                                   .AppendASCII(kFreezerState);
    enabled_ = base::PathIsWritable(default_control_path_) &&
               base::PathIsWritable(to_be_frozen_control_path_) &&
               base::PathIsWritable(to_be_frozen_state_path_);

    if (!enabled_) {
      LOG_IF(WARNING, base::SysInfo::IsRunningOnChromeOS())
          << "Cgroup freezer does not exist or is not writable. "
          << "Unable to freeze renderer processes.";
      return;
    }

    // Thaw renderers on startup. This helps robustness for the case where we
    // start up with renderers in frozen state, for example after the previous
    // Chrome process crashed at a point in time after suspend where it still
    // hadn't thawed renderers yet.
    ThawRenderers(base::DoNothing());
  }

  void SetShouldFreezeRenderer(base::ProcessHandle handle, bool frozen) {
    DCHECK(file_thread_->RunsTasksInCurrentSequence());

    WriteCommandToFile(
        base::NumberToString(handle),
        frozen ? to_be_frozen_control_path_ : default_control_path_);
  }

  void FreezeRenderers() {
    DCHECK(file_thread_->RunsTasksInCurrentSequence());

    if (!enabled_) {
      LOG(ERROR) << "Attempting to freeze renderers when the freezer cgroup is "
                 << "not available.";
      return;
    }

    froze_successfully_ =
        WriteCommandToFile(kFreezeCommand, to_be_frozen_state_path_);
  }

  void ThawRenderers(ResultCallback callback) {
    DCHECK(file_thread_->RunsTasksInCurrentSequence());

    if (!enabled_) {
      LOG(ERROR) << "Attempting to thaw renderers when the freezer cgroup is "
                 << "not available.";
      return;
    }

    bool result = WriteCommandToFile(kThawCommand, to_be_frozen_state_path_);

    // TODO(derat): For now, lie and report success if thawing failed but
    // freezing also failed previously. Remove after weird EBADF and ENOENT
    // problems tracked at http://crbug.com/661310 are fixed.
    if (!result && !froze_successfully_)
      result = true;

    ui_thread_->PostTask(FROM_HERE, base::BindOnce(callback, result));
  }

  void CheckCanFreezeRenderers(ResultCallback callback) {
    DCHECK(file_thread_->RunsTasksInCurrentSequence());

    ui_thread_->PostTask(FROM_HERE, base::BindOnce(callback, enabled_));
  }

 private:
  bool WriteCommandToFile(const std::string& command,
                          const base::FilePath& file) {
    int bytes = base::WriteFile(file, command.c_str(), command.size());
    if (bytes == -1) {
      PLOG(ERROR) << "Writing " << command << " to " << file.value()
                  << " failed";
      return false;
    } else if (bytes != static_cast<int>(command.size())) {
      LOG(ERROR) << "Only wrote " << bytes << " byte(s) when writing "
                 << command << " to " << file.value();
      return false;
    }
    return true;
  }

  scoped_refptr<base::SequencedTaskRunner> ui_thread_;
  scoped_refptr<base::SequencedTaskRunner> file_thread_;

  // Control path for the cgroup that is not frozen.
  base::FilePath default_control_path_;

  // Control and state paths for the cgroup whose processes will be frozen.
  base::FilePath to_be_frozen_control_path_;
  base::FilePath to_be_frozen_state_path_;

  bool enabled_;

  // True iff FreezeRenderers() wrote its command successfully the last time it
  // was called.
  bool froze_successfully_;

  DISALLOW_COPY_AND_ASSIGN(FileWorker);
};

FreezerCgroupProcessManager::FreezerCgroupProcessManager()
    : file_thread_(base::ThreadPool::CreateSequencedTaskRunner(
          {base::TaskPriority::BEST_EFFORT, base::MayBlock()})),
      file_worker_(new FileWorker(file_thread_)) {
  file_thread_->PostTask(
      FROM_HERE,
      base::BindOnce(&FileWorker::Start, base::Unretained(file_worker_.get())));
}

FreezerCgroupProcessManager::~FreezerCgroupProcessManager() {
  file_thread_->DeleteSoon(FROM_HERE, file_worker_.release());
}

void FreezerCgroupProcessManager::SetShouldFreezeRenderer(
    base::ProcessHandle handle,
    bool frozen) {
  file_thread_->PostTask(
      FROM_HERE,
      base::BindOnce(&FileWorker::SetShouldFreezeRenderer,
                     base::Unretained(file_worker_.get()), handle, frozen));
}

void FreezerCgroupProcessManager::FreezeRenderers() {
  file_thread_->PostTask(FROM_HERE,
                         base::BindOnce(&FileWorker::FreezeRenderers,
                                        base::Unretained(file_worker_.get())));
}

void FreezerCgroupProcessManager::ThawRenderers(ResultCallback callback) {
  file_thread_->PostTask(
      FROM_HERE,
      base::BindOnce(&FileWorker::ThawRenderers,
                     base::Unretained(file_worker_.get()), callback));
}

void FreezerCgroupProcessManager::CheckCanFreezeRenderers(
    ResultCallback callback) {
  file_thread_->PostTask(
      FROM_HERE,
      base::BindOnce(&FileWorker::CheckCanFreezeRenderers,
                     base::Unretained(file_worker_.get()), callback));
}

}  // namespace chromeos


text:
package invtweaks;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import org.lwjgl.input.Mouse;

import net.minecraft.client.Minecraft;
import net.minecraft.src.Container;
import net.minecraft.src.GuiContainer;
import net.minecraft.src.GuiScreen;
import net.minecraft.src.InvTweaksObfuscation;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Slot;

/**
 * Allows to perform various operations on the inventory
 * and/or containers. Works in both single and multiplayer.
 *
 * @author Jimeo Wan
 *
 */
public class InvTweaksContainerManager extends InvTweaksObfuscation {

    // TODO: Throw errors when the container isn't available anymore

    public static final int DROP_SLOT = -999;
    public static final int INVENTORY_SIZE = 36;
    public static final int HOTBAR_SIZE = 9;
    public static final int ACTION_TIMEOUT = 500;
    public static final int POLLING_DELAY = 3;

    private GuiContainer guiContainer;
    private Container container;
    private Map<InvTweaksContainerSection, List<Slot>> slotRefs
            = new HashMap<InvTweaksContainerSection, List<Slot>>();
    private int clickDelay = 0;

    /**
     * Creates an container manager linked to the currently available container:
     * - If a container GUI is open, the manager gives access to this container contents.
     * - If no GUI is open, the manager works as if the player's inventory was open.
     * @param mc Minecraft
     */
    @SuppressWarnings({"unchecked"})
    public InvTweaksContainerManager(Minecraft mc) {
        super(mc);

        GuiScreen currentScreen = getCurrentScreen();
        if (isGuiContainer(currentScreen)) {
        	this.guiContainer = asGuiContainer(currentScreen);
            this.container = getContainer(this.guiContainer);
        }
        else {
            this.container = getPlayerContainer();
        }

        List<Slot> slots = (List<Slot>) getSlots(container);
        int size = slots.size();
        boolean guiWithInventory = true;

        // Inventory: 4 crafting slots, then 4 armor slots, then inventory
        if (isContainerPlayer(container)) {
            slotRefs.put(InvTweaksContainerSection.CRAFTING_OUT, slots.subList(0, 1));
            slotRefs.put(InvTweaksContainerSection.CRAFTING_IN, slots.subList(1, 5));
            slotRefs.put(InvTweaksContainerSection.ARMOR, slots.subList(5, 9));
        }

        // Creative mode inventory: 4 armor slots, then inventory
        else if (isContainerCreative(container)) {
            slotRefs.put(InvTweaksContainerSection.ARMOR, slots.subList(5, 9));
            size--; // Last slot is something else than the inventory (maybe the trash)
        }

        // Chest/Dispenser
        else if (isContainerChest(container)
                || isContainerDispenser(container)) {
            slotRefs.put(InvTweaksContainerSection.CHEST, slots.subList(0, size-INVENTORY_SIZE));
        }

        // Furnace
        else if (isContainerFurnace(container)) {
            slotRefs.put(InvTweaksContainerSection.FURNACE_IN, slots.subList(0, 1));
            slotRefs.put(InvTweaksContainerSection.FURNACE_FUEL, slots.subList(1, 2));
            slotRefs.put(InvTweaksContainerSection.FURNACE_OUT, slots.subList(2, 3));
        }

        // Workbench
        else if (isContainerWorkbench(container)) {
            slotRefs.put(InvTweaksContainerSection.CRAFTING_OUT, slots.subList(0, 1));
            slotRefs.put(InvTweaksContainerSection.CRAFTING_IN, slots.subList(1, 10));
        }

        // Enchantment table
        else if (isContainerEnchantmentTable(container)) {
            slotRefs.put(InvTweaksContainerSection.ENCHANTMENT, slots.subList(0, 1));
        }

        // Brewing stand
        else if (isContainerBrewingStand(container)) {
            slotRefs.put(InvTweaksContainerSection.BREWING_BOTTLES, slots.subList(0, 3));
            slotRefs.put(InvTweaksContainerSection.BREWING_INGREDIENT, slots.subList(3, 4));
        }

        // Unknown = chest
        else {

        	// Load mod's slots
        	slotRefs = mods.getSpecialContainerSlots(currentScreen, container);

        	// Else, guess slots
        	if (slotRefs.isEmpty()) {
	            if (size >= INVENTORY_SIZE) {
	                // Assuming the container ends with the inventory, just like all vanilla containers.
	                slotRefs.put(InvTweaksContainerSection.CHEST, slots.subList(0, size-INVENTORY_SIZE));
	            }
	            else {
	                guiWithInventory = false;
	                slotRefs.put(InvTweaksContainerSection.CHEST, slots.subList(0, size));
	            }
        	}
        }

        if (guiWithInventory && !slotRefs.containsKey(InvTweaksContainerSection.INVENTORY)) {
            slotRefs.put(InvTweaksContainerSection.INVENTORY, slots.subList(size-INVENTORY_SIZE, size));
            slotRefs.put(InvTweaksContainerSection.INVENTORY_NOT_HOTBAR, slots.subList(size-INVENTORY_SIZE, size-HOTBAR_SIZE));
            slotRefs.put(InvTweaksContainerSection.INVENTORY_HOTBAR, slots.subList(size-HOTBAR_SIZE, size));
        }

    }

    /**
     * Moves a stack from source to destination, adapting the behavior
     * according to the context:
     * - If destination is empty, the source stack is moved.
     * - If the items can be merged, as much items are possible are put
     *   in the destination, and the eventual remains go back to the source.
     * - If the items cannot be merged, they are swapped.
     * @param srcSection The source section
     * @param srcIndex The source slot
     * @param destSection The destination section
     * @param destIndex The destination slot
     * @return false if the source slot is empty or the player is
     * holding an item that couln't be put down.
     * @throws TimeoutException
     */
	public boolean move(InvTweaksContainerSection srcSection, int srcIndex,
            InvTweaksContainerSection destSection, int destIndex) {
	    //System.out.println(srcSection + ":" + srcIndex + " to " + destSection + ":" + destIndex);
	    ItemStack srcStack = getItemStack(srcSection, srcIndex);
	    ItemStack destStack = getItemStack(destSection, destIndex);

        if (srcStack == null && destIndex != DROP_SLOT) {
            return false;
        }
        else if (srcSection == destSection && srcIndex == destIndex) {
            return true;
        }

        // Put hold item down
        if (getHeldStack() != null) {
            int firstEmptyIndex = getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
            if (firstEmptyIndex != -1) {
                leftClick(InvTweaksContainerSection.INVENTORY, firstEmptyIndex);
            }
            else {
                return false;
            }
        }

        // Use intermediate slot if we have to swap tools, maps, etc.
        if (destStack != null
                && getItemID(srcStack) == getItemID(destStack)
                && (getMaxStackSize(srcStack) == 1 ||
                    hasDataTags(srcStack) || hasDataTags(destStack)
                )) {
            int intermediateSlot = getFirstEmptyUsableSlotNumber();
            InvTweaksContainerSection intermediateSection = getSlotSection(intermediateSlot);
            int intermediateIndex = getSlotIndex(intermediateSlot);
            if (intermediateIndex != -1) {
                // Step 1/3: Dest > Int
                leftClick(destSection, destIndex);
                leftClick(intermediateSection, intermediateIndex);
                // Step 2/3: Src > Dest
                leftClick(srcSection, srcIndex);
                leftClick(destSection, destIndex);
                // Step 3/3: Int > Src
                leftClick(intermediateSection, intermediateIndex);
                leftClick(srcSection, srcIndex);
            }
            else {
                return false;
            }
        }

        // Normal move
        else {
            leftClick(srcSection, srcIndex);
            leftClick(destSection, destIndex);
            if (getHeldStack() != null) {
                // FIXME What if we can't put the item back in the source? (for example crafting/furnace output)
                leftClick(srcSection, srcIndex);
            }
        }

        return true;
    }

	/**
     * Moves some items from source to destination.
	 * @param srcSection The source section
	 * @param srcIndex The source slot
     * @param destSection The destination section
     * @param destIndex The destination slot
	 * @param amount The amount of items to move. If <= 0, does nothing.
	 * If > to the source stack size, moves as much as possible from the stack size.
	 * If not all can be moved to the destination, only moves as much as possible.
	 * @return false if the destination slot is already occupied
	 * by a different item (meaning items cannot be moved to destination).
	 * @throws TimeoutException
	 */
	public boolean moveSome(InvTweaksContainerSection srcSection, int srcIndex,
	        InvTweaksContainerSection destSection, int destIndex,
	        int amount) {

	    ItemStack source = getItemStack(srcSection, srcIndex);
	    if (source == null || srcSection == destSection && srcIndex == destIndex) {
            return true;
        }

	    ItemStack destination = getItemStack(srcSection, srcIndex);
        int sourceSize = getStackSize(source);
        int movedAmount = Math.min(amount, sourceSize);

	    if (source != null && (destination == null
	            || areItemStacksEqual(source, destination))) {

	        leftClick(srcSection, srcIndex);
	        for (int i = 0; i < movedAmount; i++) {
	            rightClick(destSection, destIndex);
	        }
	        if (movedAmount < sourceSize) {
	            leftClick(srcSection, srcIndex);
	        }
	        return true;
	    }
	    else {
	        return false;
	    }

	}

    public boolean drop(InvTweaksContainerSection srcSection, int srcIndex) {
        return move(srcSection, srcIndex, null, DROP_SLOT);
    }

    public boolean dropSome(InvTweaksContainerSection srcSection, int srcIndex, int amount) {
        return moveSome(srcSection, srcIndex, null, DROP_SLOT, amount);
    }

    /**
     * If an item is in hand (= attached to the cursor), puts it down.
     *
     * @return true unless the item could not be put down
     * @throws Exception
     */
    public boolean putHoldItemDown(InvTweaksContainerSection destSection, int destIndex) {
        ItemStack heldStack = getHeldStack();
        if (heldStack != null) {
        	if (getItemStack(destSection, destIndex) == null) {
        		click(destSection, destIndex, false);
                return true;
        	}
        	return false;
        }
        return true;
    }

	public void leftClick(InvTweaksContainerSection section, int index) {
        click(section, index, false);
    }

    public void rightClick(InvTweaksContainerSection section, int index) {
        click(section, index, true);
    }

    public void click(InvTweaksContainerSection section, int index, boolean rightClick) {
        //System.out.println("Click " + section + ":" + index);
        // Click! (we finally call the Minecraft code)
        int slot = indexToSlot(section, index);
        if (slot != -1) {
            clickInventory(getPlayerController(),
                    getWindowId(container), // Select container
                    slot, // Targeted slot
                    (rightClick) ? 1 : 0, // Click #
                    false, // Shift not held
                    getThePlayer());
        }

        if (clickDelay > 0) {
            try {
                Thread.sleep(clickDelay);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public Slot getSlotAtMousePosition() {
	    // Copied from GuiContainer
    	if (guiContainer != null) {
	        int x = getMouseX();
	        int y = getMouseY();
		    for (int k = 0; k < getSlots(getContainer(guiContainer)).size(); k++) {
		    	Slot slot = (Slot) getSlots(getContainer(guiContainer)).get(k);
		        if (getIsMouseOverSlot(slot, x, y)) {
		            return slot;
		        }
		    }
		    return null;
    	}
    	else {
    		return null;
    	}
	}

	public boolean getIsMouseOverSlot(Slot slot) {
		return getIsMouseOverSlot(slot, getMouseX(), getMouseY());
	}

	private boolean getIsMouseOverSlot(Slot slot, int x, int y) {
        // Copied from GuiContainer
		if (guiContainer != null) {
	        int i = (guiContainer.width - getGuiWidth(guiContainer)) / 2;
	        int j = (guiContainer.height - getGuiHeight(guiContainer)) / 2;
	        x -= i;
	        y -= j;
	        return x >= getXDisplayPosition(slot) - 1
	                && x < getXDisplayPosition(slot) + 16 + 1
	                && y >= getYDisplayPosition(slot) - 1
	                && y < getYDisplayPosition(slot) + 16 + 1;
	    }
		else {
			return false;
		}
	}

    private int getMouseX() {
        return (Mouse.getEventX() * getWindowWidth(guiContainer)) / getDisplayWidth();
    }

    private int getMouseY() {
        return getWindowHeight(guiContainer) - (Mouse.getEventY() * getWindowHeight(guiContainer)) / getDisplayHeight() - 1;
    }

	public boolean hasSection(InvTweaksContainerSection section) {
        return slotRefs.containsKey(section);
    }

    public List<Slot> getSlots(InvTweaksContainerSection section) {
        return slotRefs.get(section);
    }

    /**
     * @return The size of the whole container
     */
    public int getSize() {
        int result = 0;
        for (List<Slot> slots : slotRefs.values()) {
            result += slots.size();
        }
        return result;
    }

    /**
     * Returns the size of a section of the container.
     * @param slot
     * @return The size, or 0 if there is no such section.
     */
    public int getSize(InvTweaksContainerSection section) {
        if (hasSection(section)) {
            return slotRefs.get(section).size();
        }
        else {
            return 0;
        }
    }

    /**
     *
     * @param section
     * @return -1 if no slot is free
     */
    public int getFirstEmptyIndex(InvTweaksContainerSection section) {
        int i = 0;
        for (Slot slot : slotRefs.get(section)) {
            if (!hasStack(slot)) {
                return i;
            }
            i++;
        }
        return -1;
    }

    /**
     * @param slot
     * @return true if the specified slot exists and is empty, false otherwise.
     */
    public boolean isSlotEmpty(InvTweaksContainerSection section, int slot) {
        if (hasSection(section)) {
            return getItemStack(section, slot) == null;
        }
        else {
            return false;
        }
    }

    public Slot getSlot(InvTweaksContainerSection section, int index) {
        List<Slot> slots = slotRefs.get(section);
        if (slots != null) {
            return slots.get(index);
        } else {
            return null;
        }
    }

    /**
     *
     * @param slotNumber
     * @return -1 if not found
     */
    public int getSlotIndex(int slotNumber) {
        return getSlotIndex(slotNumber, false);
    }

    /**
     *
     * @param slotNumber
     * @param preferInventory Set to true if you prefer to have the index according
     * to the whole inventory, instead of a more specific section (hotbar/not hotbar)
     * @return
     */
    public int getSlotIndex(int slotNumber, boolean preferInventory) {
        // TODO Caching with getSlotSection
        for (InvTweaksContainerSection section : slotRefs.keySet()) {
            if (!preferInventory && section != InvTweaksContainerSection.INVENTORY
                    || (preferInventory && section != InvTweaksContainerSection.INVENTORY_NOT_HOTBAR
                            && section != InvTweaksContainerSection.INVENTORY_HOTBAR)) {
                int i = 0;
                for (Slot slot : slotRefs.get(section)) {
                    if (getSlotNumber(slot) == slotNumber) {
                        return i;
                    }
                    i++;
                }
            }
        }
        return -1;
    }

    /**
     * Note: Prefers INVENTORY_HOTBAR/NOT_HOTBAR instead of INVENTORY.
     * @param slotNumber
     * @return null if the slot number is invalid.
     */
    public InvTweaksContainerSection getSlotSection(int slotNumber) {
        // TODO Caching with getSlotIndex
        for (InvTweaksContainerSection section : slotRefs.keySet()) {
            if (section != InvTweaksContainerSection.INVENTORY) {
                for (Slot slot : slotRefs.get(section)) {
                    if (getSlotNumber(slot) == slotNumber) {
                        return section;
                    }
                }
            }
        }
        return null;
    }

    /**
     * Returns an ItemStack from the wanted section and slot.
     * @param section
     * @param slot
     * @return An ItemStack or null.
     */
    public ItemStack getItemStack(InvTweaksContainerSection section, int index)
            throws NullPointerException, IndexOutOfBoundsException {
        int slot = indexToSlot(section, index);
        if (slot >= 0 && slot < getSlots(container).size()) {
            return getSlotStack(container, slot);
        } else {
            return null;
        }
    }

    public Container getContainer() {
        return container;
    }

    private int getFirstEmptyUsableSlotNumber() {
        for (InvTweaksContainerSection section : slotRefs.keySet()) {
            for (Slot slot : slotRefs.get(section)) {
                // Use only standard slot (to make sure
                // we can freely put and remove items there)
                if (isBasicSlot(slot) && !hasStack(slot)) {
                    return getSlotNumber(slot);
                }
            }
        }
        return -1;
    }

    /**
     * Converts section/index values to slot ID.
     * @param section
     * @param index
     * @return -1 if not found
     */
    private int indexToSlot(InvTweaksContainerSection section, int index) {
        if (index == DROP_SLOT) {
            return DROP_SLOT;
        }
        if (hasSection(section)) {
            Slot slot = slotRefs.get(section).get(index);
            if (slot != null) {
                return getSlotNumber(slot);
            }
            else {
                return -1;
            }
        }
        else {
            return -1;
        }
    }

    public void setClickDelay(int delay) {
        this.clickDelay = delay;
    }

}


text:
package my.apache.ignite.examples.cache;

import javax.cache.Cache;

import my.apache.ignite.examples.NodeStartup;

import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.lang.IgnitePredicate;

/**
 * Start two or more nodes using {@link NodeStartup}
 * with / without attribute as 'workerGroup - sample'.
 * Then see, the data is collocated only between
 * the nodes which have same attributes.
 *
 * @author kamal
 *
 */
public class CacheWithNodeFilter {

	public CacheWithNodeFilter() {
	}

	public static void main(String[] args) {

		try (Ignite ignite = Ignition.start("examples/config/example-cache.xml")) {

			IgniteCache<String, String> fmevents = ignite.getOrCreateCache("alarmcache");

			for (Character c='a'; c<='z'; c++) {
				String ch = c.toString();
				fmevents.put(ch, ch);
			}

			int i=1;
			for (Cache.Entry<String, String> entry : fmevents.localEntries(CachePeekMode.PRIMARY)) {
				System.out.println("i : " + i++ + ", key : " + entry.getKey() + ", val : " + entry.getValue());
			}
		}
	}

	public static class NodePredicate implements IgnitePredicate<ClusterNode> {

		private static final long serialVersionUID = 1L;

		@Override
		public boolean apply(ClusterNode node) {
			System.out.println("ClusterNode : " + node + ", attributes : " + node.attributes());
			return node.attribute("workerGroup").equals("sample");
		}
	}

}

/**
 * $Log$
 *
 */


text:
package algolia.objects

case class QueryRules(
    query: String,
    anchoring: Option[String] = None,
    context: Option[String] = None,
    page: Option[Int] = None,
    hitsPerPage: Option[Int] = None,
    nbPages: Option[Int] = None
)