text:
from __future__ import absolute_import, division, print_function

from io import TextIOWrapper
from collections import deque, namedtuple
from splunklib import six
try:
    from collections import OrderedDict  # must be python 2.7
except ImportError:
    from ..ordereddict import OrderedDict
from splunklib.six.moves import StringIO
from itertools import chain
from splunklib.six.moves import map as imap
from json import JSONDecoder, JSONEncoder
from json.encoder import encode_basestring_ascii as json_encode_string
from splunklib.six.moves import urllib

import csv
import gzip
import os
import re
import sys
import warnings

from . import environment

csv.field_size_limit(10485760)  # The default value is 128KB; upping to 10MB. See SPL-12117 for background on this issue

def set_binary_mode(fh):
    """ Helper method to set up binary mode for file handles.
    Emphasis being sys.stdin, sys.stdout, sys.stderr.
    For python3, we want to return .buffer
    For python2+windows we want to set os.O_BINARY
    """
    typefile = TextIOWrapper if sys.version_info >= (3, 0) else file
    # check for file handle
    if not isinstance(fh, typefile):
        return fh

    # check for python3 and buffer
    if sys.version_info >= (3, 0) and hasattr(fh, 'buffer'):
        return fh.buffer
    # check for python3
    elif sys.version_info >= (3, 0):
        pass
    # check for windows python2. SPL-175233 -- python3 stdout is already binary
    elif sys.platform == 'win32':
        # Work around the fact that on Windows '\n' is mapped to '\r\n'. The typical solution is to simply open files in
        # binary mode, but stdout is already open, thus this hack. 'CPython' and 'PyPy' work differently. We assume that
        # all other Python implementations are compatible with 'CPython'. This might or might not be a valid assumption.
        from platform import python_implementation
        implementation = python_implementation()
        if implementation == 'PyPy':
            return os.fdopen(fh.fileno(), 'wb', 0)
        else:
            import msvcrt
            msvcrt.setmode(fh.fileno(), os.O_BINARY)
    return fh

class CommandLineParser(object):
    r""" Parses the arguments to a search command.

    A search command line is described by the following syntax.

    **Syntax**::

       command       = command-name *[wsp option] *[wsp [dquote] field-name [dquote]]
       command-name  = alpha *( alpha / digit )
       option        = option-name [wsp] "=" [wsp] option-value
       option-name   = alpha *( alpha / digit / "_" )
       option-value  = word / quoted-string
       word          = 1*( %01-%08 / %0B / %0C / %0E-1F / %21 / %23-%FF ) ; Any character but DQUOTE and WSP
       quoted-string = dquote *( word / wsp / "\" dquote / dquote dquote ) dquote
       field-name    = ( "_" / alpha ) *( alpha / digit / "_" / "." / "-" )

    **Note:**

    This syntax is constrained to an 8-bit character set.

    **Note:**

    This syntax does not show that `field-name` values may be comma-separated when in fact they can be. This is
    because Splunk strips commas from the command line. A custom search command will never see them.

    **Example:**

    countmatches fieldname = word_count pattern = \w+ some_text_field

    Option names are mapped to properties in the targeted ``SearchCommand``. It is the responsibility of the property
    setters to validate the values they receive. Property setters may also produce side effects. For example,
    setting the built-in `log_level` immediately changes the `log_level`.

    """
    @classmethod
    def parse(cls, command, argv):
        """ Splits an argument list into an options dictionary and a fieldname
        list.

        The argument list, `argv`, must be of the form::

            *[option]... *[<field-name>]

        Options are validated and assigned to items in `command.options`. Field names are validated and stored in the
        list of `command.fieldnames`.

        #Arguments:

        :param command: Search command instance.
        :type command: ``SearchCommand``
        :param argv: List of search command arguments.
        :type argv: ``list``
        :return: ``None``

        #Exceptions:

        ``SyntaxError``: Argument list is incorrectly formed.
        ``ValueError``: Unrecognized option/field name, or an illegal field value.

        """
        debug = environment.splunklib_logger.debug
        command_class = type(command).__name__

        # Prepare

        debug('Parsing %s command line: %r', command_class, argv)
        command.fieldnames = None
        command.options.reset()
        argv = ' '.join(argv)

        command_args = cls._arguments_re.match(argv)

        if command_args is None:
            raise SyntaxError('Syntax error: {}'.format(argv))

        # Parse options

        for option in cls._options_re.finditer(command_args.group('options')):
            name, value = option.group('name'), option.group('value')
            if name not in command.options:
                raise ValueError(
                    'Unrecognized {} command option: {}={}'.format(command.name, name, json_encode_string(value)))
            command.options[name].value = cls.unquote(value)

        missing = command.options.get_missing()

        if missing is not None:
            if len(missing) > 1:
                raise ValueError(
                    'Values for these {} command options are required: {}'.format(command.name, ', '.join(missing)))
            raise ValueError('A value for {} command option {} is required'.format(command.name, missing[0]))

        # Parse field names

        fieldnames = command_args.group('fieldnames')

        if fieldnames is None:
            command.fieldnames = []
        else:
            command.fieldnames = [cls.unquote(value.group(0)) for value in cls._fieldnames_re.finditer(fieldnames)]

        debug('  %s: %s', command_class, command)

    @classmethod
    def unquote(cls, string):
        """ Removes quotes from a quoted string.

        Splunk search command quote rules are applied. The enclosing double-quotes, if present, are removed. Escaped
        double-quotes ('\"' or '""') are replaced by a single double-quote ('"').

        **NOTE**

        We are not using a json.JSONDecoder because Splunk quote rules are different than JSON quote rules. A
        json.JSONDecoder does not recognize a pair of double-quotes ('""') as an escaped quote ('"') and will
        decode single-quoted strings ("'") in addition to double-quoted ('"') strings.

        """
        if len(string) == 0:
            return ''

        if string[0] == '"':
            if len(string) == 1 or string[-1] != '"':
                raise SyntaxError('Poorly formed string literal: ' + string)
            string = string[1:-1]

        if len(string) == 0:
            return ''

        def replace(match):
            value = match.group(0)
            if value == '""':
                return '"'
            if len(value) < 2:
                raise SyntaxError('Poorly formed string literal: ' + string)
            return value[1]

        result = re.sub(cls._escaped_character_re, replace, string)
        return result

    # region Class variables

    _arguments_re = re.compile(r"""
        ^\s*
        (?P<options>     # Match a leading set of name/value pairs
            (?:
                (?:(?=\w)[^\d]\w*)                         # name
                \s*=\s*                                    # =
                (?:"(?:\\.|""|[^"])*"|(?:\\.|[^\s"])+)\s*  # value
            )*
        )\s*
        (?P<fieldnames>  # Match a trailing set of field names
            (?:
                (?:"(?:\\.|""|[^"])*"|(?:\\.|[^\s"])+)\s*
            )*
        )\s*$
        """, re.VERBOSE | re.UNICODE)

    _escaped_character_re = re.compile(r'(\\.|""|[\\"])')

    _fieldnames_re = re.compile(r"""("(?:\\.|""|[^"])+"|(?:\\.|[^\s"])+)""")

    _options_re = re.compile(r"""
        # Captures a set of name/value pairs when used with re.finditer
        (?P<name>(?:(?=\w)[^\d]\w*))                   # name
        \s*=\s*                                        # =
        (?P<value>"(?:\\.|""|[^"])*"|(?:\\.|[^\s"])+)  # value
        """, re.VERBOSE | re.UNICODE)

    # endregion

class ConfigurationSettingsType(type):
    """ Metaclass for constructing ConfigurationSettings classes.

    Instances of :class:`ConfigurationSettingsType` construct :class:`ConfigurationSettings` classes from classes from
    a base :class:`ConfigurationSettings` class and a dictionary of configuration settings. The settings in the
    dictionary are validated against the settings in the base class. You cannot add settings, you can only change their
    backing-field values and you cannot modify settings without backing-field values. These are considered fixed
    configuration setting values.

    This is an internal class used in two places:

    + :meth:`decorators.Configuration.__call__`

      Adds a ConfigurationSettings attribute to a :class:`SearchCommand` class.

    + :meth:`reporting_command.ReportingCommand.fix_up`

      Adds a ConfigurationSettings attribute to a :meth:`ReportingCommand.map` method, if there is one.

    """
    def __new__(mcs, module, name, bases):
        mcs = super(ConfigurationSettingsType, mcs).__new__(mcs, str(name), bases, {})
        return mcs

    def __init__(cls, module, name, bases):

        super(ConfigurationSettingsType, cls).__init__(name, bases, None)
        cls.__module__ = module

    @staticmethod
    def validate_configuration_setting(specification, name, value):
        if not isinstance(value, specification.type):
            if isinstance(specification.type, type):
                type_names = specification.type.__name__
            else:
                type_names = ', '.join(imap(lambda t: t.__name__, specification.type))
            raise ValueError('Expected {} value, not {}={}'.format(type_names, name, repr(value)))
        if specification.constraint and not specification.constraint(value):
            raise ValueError('Illegal value: {}={}'.format(name, repr(value)))
        return value

    specification = namedtuple(
        'ConfigurationSettingSpecification', (
            'type',
            'constraint',
            'supporting_protocols'))

    # P1 [ ] TODO: Review ConfigurationSettingsType.specification_matrix for completeness and correctness

    specification_matrix = {
        'clear_required_fields': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'distributed': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[2]),
        'generates_timeorder': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'generating': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1, 2]),
        'local': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'maxinputs': specification(
            type=int,
            constraint=lambda value: 0 <= value <= six.MAXSIZE,
            supporting_protocols=[2]),
        'overrides_timeorder': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'required_fields': specification(
            type=(list, set, tuple),
            constraint=None,
            supporting_protocols=[1, 2]),
        'requires_preop': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'retainsevents': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'run_in_preview': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[2]),
        'streaming': specification(
            type=bool,
            constraint=None,
            supporting_protocols=[1]),
        'streaming_preop': specification(
            type=(bytes, six.text_type),
            constraint=None,
            supporting_protocols=[1, 2]),
        'type': specification(
            type=(bytes, six.text_type),
            constraint=lambda value: value in ('events', 'reporting', 'streaming'),
            supporting_protocols=[2])}

class CsvDialect(csv.Dialect):
    """ Describes the properties of Splunk CSV streams """
    delimiter = ','
    quotechar = '"'
    doublequote = True
    skipinitialspace = False
    lineterminator = '\r\n'
    if sys.version_info >= (3, 0) and sys.platform == 'win32':
        lineterminator = '\n'
    quoting = csv.QUOTE_MINIMAL

class InputHeader(dict):
    """ Represents a Splunk input header as a collection of name/value pairs.

    """

    def __str__(self):
        return '\n'.join([name + ':' + value for name, value in six.iteritems(self)])

    def read(self, ifile):
        """ Reads an input header from an input file.

        The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the
        input header is signalled by an empty line or an end-of-file.

        :param ifile: File-like object that supports iteration over lines.

        """
        name, value = None, None

        for line in ifile:
            if line == '\n':
                break
            item = line.split(':', 1)
            if len(item) == 2:
                # start of a new item
                if name is not None:
                    self[name] = value[:-1]  # value sans trailing newline
                name, value = item[0], urllib.parse.unquote(item[1])
            elif name is not None:
                # continuation of the current item
                value += urllib.parse.unquote(line)

        if name is not None:
            self[name] = value[:-1] if value[-1] == '\n' else value

Message = namedtuple('Message', ('type', 'text'))

class MetadataDecoder(JSONDecoder):

    def __init__(self):
        JSONDecoder.__init__(self, object_hook=self._object_hook)

    @staticmethod
    def _object_hook(dictionary):

        object_view = ObjectView(dictionary)
        stack = deque()
        stack.append((None, None, dictionary))

        while len(stack):
            instance, member_name, dictionary = stack.popleft()

            for name, value in six.iteritems(dictionary):
                if isinstance(value, dict):
                    stack.append((dictionary, name, value))

            if instance is not None:
                instance[member_name] = ObjectView(dictionary)

        return object_view

class MetadataEncoder(JSONEncoder):

    def __init__(self):
        JSONEncoder.__init__(self, separators=MetadataEncoder._separators)

    def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o)

    _separators = (',', ':')

class ObjectView(object):

    def __init__(self, dictionary):
        self.__dict__ = dictionary

    def __repr__(self):
        return repr(self.__dict__)

    def __str__(self):
        return str(self.__dict__)

class Recorder(object):

    def __init__(self, path, f):
        self._recording = gzip.open(path + '.gz', 'wb')
        self._file = f

    def __getattr__(self, name):
        return getattr(self._file, name)

    def __iter__(self):
        for line in self._file:
            self._recording.write(line)
            self._recording.flush()
            yield line

    def read(self, size=None):
        value = self._file.read() if size is None else self._file.read(size)
        self._recording.write(value)
        self._recording.flush()
        return value

    def readline(self, size=None):
        value = self._file.readline() if size is None else self._file.readline(size)
        if len(value) > 0:
            self._recording.write(value)
            self._recording.flush()
        return value

    def record(self, *args):
        for arg in args:
            self._recording.write(arg)

    def write(self, text):
        self._recording.write(text)
        self._file.write(text)
        self._recording.flush()

class RecordWriter(object):

    def __init__(self, ofile, maxresultrows=None):
        self._maxresultrows = 50000 if maxresultrows is None else maxresultrows

        self._ofile = set_binary_mode(ofile)
        self._fieldnames = None
        self._buffer = StringIO()

        self._writer = csv.writer(self._buffer, dialect=CsvDialect)
        self._writerow = self._writer.writerow
        self._finished = False
        self._flushed = False

        self._inspector = OrderedDict()
        self._chunk_count = 0
        self._pending_record_count = 0
        self._committed_record_count = 0

    @property
    def is_flushed(self):
        return self._flushed

    @is_flushed.setter
    def is_flushed(self, value):
        self._flushed = True if value else False

    @property
    def ofile(self):
        return self._ofile

    @ofile.setter
    def ofile(self, value):
        self._ofile = set_binary_mode(value)

    @property
    def pending_record_count(self):
        return self._pending_record_count

    @property
    def _record_count(self):
        warnings.warn(
            "_record_count will be deprecated soon. Use pending_record_count instead.",
             PendingDeprecationWarning
        )
        return self.pending_record_count

    @property
    def committed_record_count(self):
        return self._committed_record_count

    @property
    def _total_record_count(self):
        warnings.warn(
            "_total_record_count will be deprecated soon. Use committed_record_count instead.",
             PendingDeprecationWarning
        )
        return self.committed_record_count

    def write(self, data):
        bytes_type = bytes if sys.version_info >= (3, 0) else str
        if not isinstance(data, bytes_type):
            data = data.encode('utf-8')
        self.ofile.write(data)

    def flush(self, finished=None, partial=None):
        assert finished is None or isinstance(finished, bool)
        assert partial is None or isinstance(partial, bool)
        assert not (finished is None and partial is None)
        assert finished is None or partial is None
        self._ensure_validity()

    def write_message(self, message_type, message_text, *args, **kwargs):
        self._ensure_validity()
        self._inspector.setdefault('messages', []).append((message_type, message_text.format(*args, **kwargs)))

    def write_record(self, record):
        self._ensure_validity()
        self._write_record(record)

    def write_records(self, records):
        self._ensure_validity()
        write_record = self._write_record
        for record in records:
            write_record(record)

    def _clear(self):
        self._buffer.seek(0)
        self._buffer.truncate()
        self._inspector.clear()
        self._pending_record_count = 0

    def _ensure_validity(self):
        if self._finished is True:
            assert self._record_count == 0 and len(self._inspector) == 0
            raise RuntimeError('I/O operation on closed record writer')

    def _write_record(self, record):

        fieldnames = self._fieldnames

        if fieldnames is None:
            self._fieldnames = fieldnames = list(record.keys())
            value_list = imap(lambda fn: (str(fn), str('__mv_') + str(fn)), fieldnames)
            self._writerow(list(chain.from_iterable(value_list)))

        get_value = record.get
        values = []

        for fieldname in fieldnames:
            value = get_value(fieldname, None)

            if value is None:
                values += (None, None)
                continue

            value_t = type(value)

            if issubclass(value_t, (list, tuple)):

                if len(value) == 0:
                    values += (None, None)
                    continue

                if len(value) > 1:
                    value_list = value
                    sv = ''
                    mv = '$'

                    for value in value_list:

                        if value is None:
                            sv += '\n'
                            mv += '$;$'
                            continue

                        value_t = type(value)

                        if value_t is not bytes:

                            if value_t is bool:
                                value = str(value.real)
                            elif value_t is six.text_type:
                                value = value
                            elif isinstance(value, six.integer_types) or value_t is float or value_t is complex:
                                value = str(value)
                            elif issubclass(value_t, (dict, list, tuple)):
                                value = str(''.join(RecordWriter._iterencode_json(value, 0)))
                            else:
                                value = repr(value).encode('utf-8', errors='backslashreplace')

                        sv += value + '\n'
                        mv += value.replace('$', '$$') + '$;$'

                    values += (sv[:-1], mv[:-2])
                    continue

                value = value[0]
                value_t = type(value)

            if value_t is bool:
                values += (str(value.real), None)
                continue

            if value_t is bytes:
                values += (value, None)
                continue

            if value_t is six.text_type:
                if six.PY2:
                    value = value.encode('utf-8')
                values += (value, None)
                continue

            if isinstance(value, six.integer_types) or value_t is float or value_t is complex:
                values += (str(value), None)
                continue

            if issubclass(value_t, dict):
                values += (str(''.join(RecordWriter._iterencode_json(value, 0))), None)
                continue

            values += (repr(value), None)

        self._writerow(values)
        self._pending_record_count += 1

        if self.pending_record_count >= self._maxresultrows:
            self.flush(partial=True)

    try:
        # noinspection PyUnresolvedReferences
        from _json import make_encoder
    except ImportError:
        # We may be running under PyPy 2.5 which does not include the _json module
        _iterencode_json = JSONEncoder(separators=(',', ':')).iterencode
    else:
        # Creating _iterencode_json this way yields a two-fold performance improvement on Python 2.7.9 and 2.7.10
        from json.encoder import encode_basestring_ascii

        @staticmethod
        def _default(o):
            raise TypeError(repr(o) + ' is not JSON serializable')

        _iterencode_json = make_encoder(
            {},                       # markers (for detecting circular references)
            _default,                 # object_encoder
            encode_basestring_ascii,  # string_encoder
            None,                     # indent
            ':', ',',                 # separators
            False,                    # sort_keys
            False,                    # skip_keys
            True                      # allow_nan
        )

        del make_encoder

class RecordWriterV1(RecordWriter):

    def flush(self, finished=None, partial=None):

        RecordWriter.flush(self, finished, partial)  # validates arguments and the state of this instance

        if self.pending_record_count > 0 or (self._chunk_count == 0 and 'messages' in self._inspector):

            messages = self._inspector.get('messages')

            if self._chunk_count == 0:

                # Messages are written to the messages header when we write the first chunk of data
                # Guarantee: These messages are displayed by splunkweb and the job inspector

                if messages is not None:

                    message_level = RecordWriterV1._message_level.get

                    for level, text in messages:
                        self.write(message_level(level, level))
                        self.write('=')
                        self.write(text)
                        self.write('\r\n')

                self.write('\r\n')

            elif messages is not None:

                # Messages are written to the messages header when we write subsequent chunks of data
                # Guarantee: These messages are displayed by splunkweb and the job inspector, if and only if the
                # command is configured with
                #
                #       stderr_dest = message
                #
                # stderr_dest is a static configuration setting. This means that it can only be set in commands.conf.
                # It cannot be set in code.

                stderr = sys.stderr

                for level, text in messages:
                    print(level, text, file=stderr)

            self.write(self._buffer.getvalue())
            self._chunk_count += 1
            self._committed_record_count += self.pending_record_count
            self._clear()

        self._finished = finished is True

    _message_level = {
        'DEBUG': 'debug_message',
        'ERROR': 'error_message',
        'FATAL': 'error_message',
        'INFO': 'info_message',
        'WARN': 'warn_message'
    }

class RecordWriterV2(RecordWriter):

    def flush(self, finished=None, partial=None):

        RecordWriter.flush(self, finished, partial)  # validates arguments and the state of this instance

        if partial or not finished:
            # Don't flush partial chunks, since the SCP v2 protocol does not
            # provide a way to send partial chunks yet.
            return

        if not self.is_flushed:
            self.write_chunk(finished=True)

    def write_chunk(self, finished=None):
        inspector = self._inspector
        self._committed_record_count += self.pending_record_count
        self._chunk_count += 1

        # TODO: DVPL-6448: splunklib.searchcommands | Add support for partial: true when it is implemented in
        # ChunkedExternProcessor (See SPL-103525)
        #
        # We will need to replace the following block of code with this block:
        #
        # metadata = [item for item in (('inspector', inspector), ('finished', finished), ('partial', partial))]
        #
        # if partial is True:
        #     finished = False

        if len(inspector) == 0:
            inspector = None

        metadata = [item for item in (('inspector', inspector), ('finished', finished))]
        self._write_chunk(metadata, self._buffer.getvalue())
        self._clear()

    def write_metadata(self, configuration):
        self._ensure_validity()

        metadata = chain(six.iteritems(configuration), (('inspector', self._inspector if self._inspector else None),))
        self._write_chunk(metadata, '')
        self.write('\n')
        self._clear()

    def write_metric(self, name, value):
        self._ensure_validity()
        self._inspector['metric.' + name] = value

    def _clear(self):
        super(RecordWriterV2, self)._clear()
        self._fieldnames = None

    def _write_chunk(self, metadata, body):

        if metadata:
            metadata = str(''.join(self._iterencode_json(dict([(n, v) for n, v in metadata if v is not None]), 0)))
            if sys.version_info >= (3, 0):
                metadata = metadata.encode('utf-8')
            metadata_length = len(metadata)
        else:
            metadata_length = 0

        if sys.version_info >= (3, 0):
            body = body.encode('utf-8')
        body_length = len(body)

        if not (metadata_length > 0 or body_length > 0):
            return

        start_line = 'chunked 1.0,%s,%s\n' % (metadata_length, body_length)
        self.write(start_line)
        self.write(metadata)
        self.write(body)
        self._ofile.flush()
        self._flushed = True


text:
import React from 'react'
import { renderWithTheme } from '@looker/components-test-utils'
import type { IAPIMethods } from '@looker/sdk-rtl'
import { fireEvent, screen } from '@testing-library/react'
import { DashboardFilter } from './DashboardFilter'

jest.mock('@looker/sdk', () => ({
  ...jest.requireActual('@looker/sdk'),
  model_fieldname_suggestions: jest.fn((sdk: { get: () => any }) => sdk.get()),
}))

// eslint-disable-next-line import/first
import { model_fieldname_suggestions } from '@looker/sdk'

describe('DashboardFilter', () => {
  it('renders label', () => {
    const onChangeMock = jest.fn()
    renderWithTheme(
      <DashboardFilter
        filter={{ name: 'Status', field: {} }}
        onChange={onChangeMock}
      />
    )
    expect(screen.getByText('Status')).toBeVisible()
  })

  it('renders validation message', () => {
    const onChangeMock = jest.fn()
    renderWithTheme(
      <DashboardFilter
        filter={{ name: 'Status', field: {}, required: true }}
        onChange={onChangeMock}
      />
    )
    expect(screen.getByText('Value required')).toBeVisible()
  })

  it('calls onChange', () => {
    const onChangeMock = jest.fn()
    renderWithTheme(
      <DashboardFilter
        filter={{
          name: 'Status',
          field: { suggestions: ['complete', 'pending', 'cancelled'] },
          ui_config: { type: 'button_group' },
        }}
        onChange={onChangeMock}
      />
    )
    const cancelled = screen.getByText('cancelled')
    fireEvent.click(cancelled)
    expect(onChangeMock.mock.calls).toMatchInlineSnapshot(`
      Array [
        Array [
          "cancelled",
        ],
      ]
    `)
  })

  it('handles undefined field (LookML filter)', () => {
    const onChangeMock = jest.fn()
    renderWithTheme(
      <DashboardFilter
        filter={{
          name: 'date',
          type: 'date_filter',
          default_value: '30 days',
        }}
        onChange={onChangeMock}
      />
    )
    expect(screen.getByText('is in the last')).toBeVisible()
    expect(screen.getByText('30')).toBeVisible()
    expect(screen.getByText('days')).toBeVisible()
  })

  describe('value', () => {
    it('uses default_value', () => {
      const onChangeMock = jest.fn()
      renderWithTheme(
        <DashboardFilter
          filter={{
            name: 'Status',
            field: {},
            default_value: 'complete',
            allow_multiple_values: true,
          }}
          onChange={onChangeMock}
        />
      )
      expect(screen.getByRole('option')).toHaveTextContent('complete')
    })

    it('uses expression if available', () => {
      const onChangeMock = jest.fn()
      renderWithTheme(
        <DashboardFilter
          filter={{
            name: 'Status',
            field: {},
            default_value: 'complete',
            allow_multiple_values: true,
          }}
          expression="complete,pending"
          onChange={onChangeMock}
        />
      )
      const values = screen.getAllByRole('option')
      expect(values[0]).toHaveTextContent('complete')
      expect(values[1]).toHaveTextContent('pending')
    })
  })

  describe('options', () => {
    it('uses field suggestions if available', () => {
      const onChangeMock = jest.fn()
      renderWithTheme(
        <DashboardFilter
          filter={{
            name: 'Status',
            field: { suggestions: ['complete', 'pending', 'cancelled'] },
            default_value: 'complete',
            ui_config: { type: 'button_group' },
          }}
          expression="complete,pending"
          onChange={onChangeMock}
        />
      )
      const values = screen.getAllByRole('button')

      expect(values[0]).toHaveTextContent('complete')
      expect(values[0]).toHaveAttribute('aria-pressed', 'true')

      expect(values[1]).toHaveTextContent('pending')
      expect(values[1]).toHaveAttribute('aria-pressed', 'true')

      expect(values[2]).toHaveTextContent('cancelled')
      expect(values[2]).toHaveAttribute('aria-pressed', 'false')
    })

    it('uses field enumerations if available', () => {
      const onChangeMock = jest.fn()
      renderWithTheme(
        <DashboardFilter
          filter={{
            name: 'Status',
            field: {
              enumerations: [
                { label: 'complete', value: 'complete' },
                { label: 'pending', value: 'pending' },
                { label: 'cancelled', value: 'cancelled' },
              ],
            },
            default_value: 'complete',
            ui_config: { type: 'button_group' },
          }}
          expression="complete,pending"
          onChange={onChangeMock}
        />
      )
      const values = screen.getAllByRole('button')

      expect(values[0]).toHaveTextContent('complete')
      expect(values[0]).toHaveAttribute('aria-pressed', 'true')

      expect(values[1]).toHaveTextContent('pending')
      expect(values[1]).toHaveAttribute('aria-pressed', 'true')

      expect(values[2]).toHaveTextContent('cancelled')
      expect(values[2]).toHaveAttribute('aria-pressed', 'false')
    })

    it('fetches suggestions', async () => {
      const onChangeMock = jest.fn()
      const sdkOkMock = jest.fn((value) => Promise.resolve(value))

      const sdkGetMock = jest.fn(() => ({
        suggestions: ['complete', 'pending', 'cancelled'],
      }))

      const sdkMock = ({
        ok: sdkOkMock,
        get: sdkGetMock,
      } as unknown) as IAPIMethods

      renderWithTheme(
        <DashboardFilter
          filter={{
            name: 'Status',
            field: {
              name: 'orders.status',
              suggestable: true,
              project_name: 'bar',
              suggest_dimension: 'orders.status',
              view: 'orders',
            },
            default_value: 'complete',
            model: 'foo',
            ui_config: { type: 'button_group' },
          }}
          sdk={sdkMock}
          expression="complete,pending"
          onChange={onChangeMock}
        />
      )
      const values = await screen.findAllByRole('button')

      expect(values[0]).toHaveTextContent('complete')
      expect(values[0]).toHaveAttribute('aria-pressed', 'true')

      expect(values[1]).toHaveTextContent('pending')
      expect(values[1]).toHaveAttribute('aria-pressed', 'true')

      expect(values[2]).toHaveTextContent('cancelled')
      expect(values[2]).toHaveAttribute('aria-pressed', 'false')

      expect(model_fieldname_suggestions).toHaveBeenCalledWith(
        { ok: sdkOkMock, get: sdkGetMock },
        {
          field_name: 'orders.status',
          model_name: 'foo',
          term: '',
          view_name: 'orders',
        }
      )
    })

    it('shows fetch error message', async () => {
      const onChangeMock = jest.fn()
      const sdkMock = ({
        ok: jest.fn((value) => value),
        get: jest.fn(() => {
          throw new Error()
        }),
      } as unknown) as IAPIMethods
      renderWithTheme(
        <DashboardFilter
          filter={{
            name: 'Status',
            field: {
              suggestable: true,
            },
            default_value: 'complete',
            ui_config: { type: 'button_group' },
          }}
          sdk={sdkMock}
          expression="complete,pending"
          onChange={onChangeMock}
        />
      )
      expect(await screen.findByTestId('error-icon')).toBeVisible()
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
namespace PouchDBCoreTests {
    function isString(someString: string) {
    }
    function isNumber(someNumber: number) {
    }

    function testAllDocs() {
        const db = new PouchDB<{ foo: number }>();

        db.allDocs().then(({ offset, total_rows, rows }) => {
            isNumber(offset);
            isNumber(total_rows);

            rows.forEach(({ id, key, value, doc }) => {
                isString(id);
                isString(key);
                isString(value.rev);

                // check document property
                isNumber(doc.foo);
            })
        });

        db.allDocs({ startkey: "a", endkey: "b" });
        db.allDocs({ startkey: "a", endkey: "b", inclusive_end: true });
        db.allDocs({ keys: ["a", "b", "c" ]});
        db.allDocs({ key: "a" });
        db.allDocs({
            attachments: true,
            binary: true,
            conflicts: true,
            descending: true,
            include_docs: true,
            limit: 5,
            skip: 1
        });
    }

    function testCompact() {
      const db = new PouchDB<{}>();
      // Promise version
      db.compact().then( (res: PouchDB.Core.Response) => {});
      // Promise version with optional options
      db.compact({interval: 300}).then( (res: PouchDB.Core.Response) => {});
      // Options with a callback
      db.compact({interval: 300},  (res: PouchDB.Core.Response) => {});
    }

    function testDestroy() {
        const db = new PouchDB<{}>();

        db.destroy({}, (error) => {
        });
        db.destroy().then(() => {
                }).catch((error) => {
                });
    }

    function testBasics() {
        type MyModel = { property: 'someProperty '};
        let model: PouchDB.Core.Document<MyModel>;
        const id = 'model';

        const db = new PouchDB<MyModel>();

        db.post(model).then((result) => {
            isString(result.id);
        });
        db.post(model, null, (error, response) => {
        });

        db.get(id).then((result) => model = result);
        db.get(id, null, (error, result) => {
        });

        db.put(model).then((error) => {
        });
        db.put(model, null, null, null, (error) => {
        });

        db.info().then((info) => {
        });
        db.info({ ajax: { cache: true }}, (error, result) => {
        });
    }

    function testRemove() {
      type MyModel = { rev: 'rev', property: 'someProperty '};
      let model: PouchDB.Core.Document<MyModel>;
      const id = 'model';
      const rev = 'rev';

      const db = new PouchDB<MyModel>();

      // Promise version with doc
      db.remove(model).then( (res: PouchDB.Core.Response) => {});

      // Promise version with doc and options
      db.remove(model, {}).then( (res: PouchDB.Core.Response) => {});

      // Promise version with docId and rev
      db.remove(id, rev).then( (res: PouchDB.Core.Response) => {});

      // Promise version with docId and rev and options
      db.remove(id, rev, {}).then( (res: PouchDB.Core.Response) => {});

      // Callback version with doc
      db.remove(model, {}, (res: PouchDB.Core.Response) => {});

      // Callback version with docId and rev
      db.remove(id, rev, {}, (res: PouchDB.Core.Response) => {});
    }
}


text:
Printer API Server
==================

Command Summary
---------------

See [`https://forest-api.herokuapp.com/`](https://forest-api.herokuapp.com) for a list of available commands.

Database Structure
------------------

See [this file](https://github.com/printerSystemCSI210/api-server/blob/master/initializers/_project.js) for the current database structure


text:
require_relative 'spec_helper'
require 'ostruct'

# platform helper
def jruby?
  RUBY_ENGINE == 'jruby'
end

module StarWars
  names = [
    'X-Wing',
    'Y-Wing',
    'A-Wing',
    'Millenium Falcon',
    'Home One',
    'TIE Fighter',
    'TIE Interceptor',
    'Executor',
  ]

  `rm -f ./_test_.db`
  # Set up "Bases" in ActiveRecord

  if jruby?
    ActiveRecord::Base.establish_connection(adapter: "jdbcsqlite3", database: "./_test_.db")
    DB = Sequel.connect('jdbc:sqlite:./_test_.db')
  elsif ENV['DATABASE'] == 'POSTGRESQL'
    ActiveRecord::Base.establish_connection(
      adapter: "postgresql",
      username: "postgres",
      database: "graphql_ruby_test"
    )
    DB = Sequel.connect('postgres://postgres:@localhost:5432/graphql_ruby_test')
  else
    ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "./_test_.db")
    DB = Sequel.sqlite("./_test_.db")
  end

  ActiveRecord::Schema.define do
    self.verbose = false
    create_table :bases, force: true do |t|
      t.column :name, :string
      t.column :planet, :string
      t.column :faction_id, :integer
    end
  end

  class Base < ActiveRecord::Base
  end

  Base.create!(name: "Yavin", planet: "Yavin 4", faction_id: 1)
  Base.create!(name: "Echo Base", planet: "Hoth", faction_id: 1)
  Base.create!(name: "Secret Hideout", planet: "Dantooine", faction_id: 1)
  Base.create!(name: "Death Star", planet: nil, faction_id: 2)
  Base.create!(name: "Shield Generator", planet: "Endor", faction_id: 2)
  Base.create!(name: "Headquarters", planet: "Coruscant", faction_id: 2)

  class SequelBase < Sequel::Model(:bases)
  end

  class FactionRecord
    attr_reader :id, :name, :ships, :bases, :bases_clone
    def initialize(id:, name:, ships:, bases:, bases_clone:)
      @id = id
      @name = name
      @ships = ships
      @bases = bases
      @bases_clone = bases_clone
    end
  end

  rebels  = FactionRecord.new({
    id: '1',
    name: 'Alliance to Restore the Republic',
    ships:  ['1', '2', '3', '4', '5'],
    bases: Base.where(faction_id: 1),
    bases_clone: Base.where(faction_id: 1),
  })

  empire = FactionRecord.new({
    id: '2',
    name: 'Galactic Empire',
    ships: ['6', '7', '8'],
    bases: Base.where(faction_id: 2),
    bases_clone: Base.where(faction_id: 2),
  })

  DATA = {
    "Faction" => {
      "1" => rebels,
      "2" => empire,
    },
    "Ship" => names.each_with_index.reduce({}) do |memo, (name, idx)|
      id = (idx + 1).to_s
      memo[id] = OpenStruct.new(name: name, id: id)
      memo
    end,
    "Base" => Hash.new { |h, k| h[k] = Base.find(k) }
  }

  def DATA.create_ship(name, faction_id)
    new_id = (self["Ship"].keys.map(&:to_i).max + 1).to_s
    new_ship = OpenStruct.new(id: new_id, name: name)
    self["Ship"][new_id] = new_ship
    self["Faction"][faction_id].ships << new_id
    new_ship
  end
end


text:
function configureGrunt(grunt) {
  grunt.initConfig({
    jasmine_node: {
      remote: ['spec/remote_server']
    }
  });

  grunt.loadNpmTasks('grunt-jasmine-node');
  grunt.registerTask('remote', 'Run tests on a remote web service', ['jasmine_node:remote']);
}

module.exports = configureGrunt;


text:
[ -z $PROCESSING_BASE ] && export PROCESSING_BASE="$1"

export TICKET_HOLDER="paus"
export TIER2_USER="paus"

if [ -d  "$PROCESSING_BASE/bin" ]
then
  export MIT_PROD_DIR="$PROCESSING_BASE"
  export PATH="$HOME/bin:$PROCESSING_BASE/bin:${PATH}"
  export PYTHONPATH="$PROCESSING_BASE/python:${PYTHONPATH}"
  pVersion=`python --version 2>&1`
  pLocalVersion=`/usr/bin/python --version 2>&1`
  if [ "$pVersion" == "$pLocalVersion" ]
  then
    addedPath=`echo /usr/lib64/python*/site-packages`
    export PYTHONPATH="${PYTHONPATH}:$addedPath"
  else
    echo " Local python version not compatible with CMSSW release."
    echo " This might cause issues."
  fi
else
  echo ""
  echo " Setting up MitProd Processing failed! (\$PROCESSING_BASE = is empty)."
  echo ""
fi


text:
import Ember from 'ember';
import Locale from '../locale';
var AbstractAdapterMixin = Ember.Mixin.create({
	lookupLocale() {
		Ember.assert('furnace-i18n: adapter method lookupLocale not implemented!');
	},

	lookupLibrary() {
		Ember.assert('furnace-i18n: adapter method lookupLibrary not implemented!');
	}

});

var LocalAdapterMixin = Ember.Mixin.create(AbstractAdapterMixin,{
	singletons: true,

	lookupLocale(localeKey) {
		return Ember.getOwner(this).lookup('locale:' + localeKey,{singleton: this.singletons});
	},

	lookupLibrary(locale,path) {
		return Ember.getOwner(this).lookup('locale:' + locale.get('text.key')+'.'+path,{singleton: this.singletons}) || null;
	}
})

var AjaxAdapterMixin = Ember.Mixin.create(AbstractAdapterMixin,{
	ajax : Ember.inject.service(),

	locales: 'adhoc',

	libraries: 'adhoc',

	_cache : null,

	_queues : null,

	_promise : null,

	init() {
		this._super(...arguments);
		this._cache={};
		this._queues=Ember.A();
	},

	lookupLocale(localeKey) {
		var adapter=this;
		var service=this.get('service');
		var locale= Ember.getOwner(this).lookup('locale:' + localeKey);
		if(locale && this.locales==='adhoc') {
			return locale;
		}
		if(!locale && this.locales==='never') {
			throw new Error('No locale for '+localeKey);
		}

		var promise = this.get('ajax').request('locales/'+localeKey).then(function(data){
			if(data.locale) {
				if(data.locale.libraries) {
					adapter._cache[localeKey]=data.locale.libraries;
					delete data.locale.libraries;
				}
			}
			if(!locale) {
				locale=Locale.create(Ember.getOwner(adapter).ownerInjection(),{
					key:localeKey
				});
				Ember.merge(locale,data.locale);
				return locale;
			} else {
				Ember.merge(locale,data.locale);
				locale._libraries={};
				service._didUpdateLocale(locale);
			}
		});

		if(!locale) {
			return promise;
		}
		return locale;
	},

	lookupLibrary(locale,path) {
		var local=Ember.getOwner(this).lookup('locale:' + locale.get('text.key')+'.'+path);

		var key=locale.get('key');
		var cache=this._cache;
		if(!cache[key]) {
			cache[key]={};
		}
		if(!cache[key][path]) {
			if((this.libraries==='adhoc' && !local) || this.libraries==='always') {
				var queue = this._appendToQueue(key,path);
				return queue.promise.then(function() {
					Ember.merge(local,cache[key][path]);
					return local;
				});
			} else{
				cache[key][path]={};
			}
		}
		if(!local) {
			local={};
		}
		Ember.merge(local,cache[key][path]);
		return local;
	},

	_createQueue(localeKey,path) {
		var adapter=this;
		var queue={
			processed: false,
			paths: Ember.A(),
			localeKey: localeKey
		};
		queue.paths.push(path);
		this._queues.push(queue);
		queue.promise = new Ember.RSVP.Promise(function(resolve,reject) {
			Ember.run.schedule('actions',adapter,adapter._processQueue,queue,resolve,reject);
		});
		return queue;
	},

	_appendToQueue(localeKey,path) {
		var queue=this._queues.find(function(queue) {
			return (queue.localeKey===localeKey && queue.paths.includes(path));
		});
		if(queue) {
			return queue;
		} else {
			queue=this._queues.find(function(queue) {
				return (queue.localeKey===localeKey && queue.processed===false);
			});
			if(queue) {
				queue.paths.push(path);
				return queue;
			}
		}
		return this._createQueue(localeKey,path);
	},

	_processQueue(queue,resolve,reject) {
		var adapter=this;
		queue.processed=true;
		this.get('ajax').request('locales/'+queue.localeKey+'?paths[]='+queue.paths.join('&paths[]=')).then(function(data){
			adapter.handleLibraryResponse(queue,data);
			resolve();
		}).catch(function(e) {
			reject(e);
		}).finally(function() {
			adapter._queues.removeObject(queue);
		});
	},

	handleLibraryResponse(queue,payload) {
		if(!payload.locale) {
			throw new Error('Invalid response, missing locale information');
		}
		if(payload.locale.key && payload.locale.key!==queue.localeKey) {
			throw new Error('Invalid response, got key "'+payload.locale.key+'" for key "'+queue.localeKey+'"');
		}
		for(var key in payload.locale.libraries) {
			this._cache[queue.localeKey][key]=payload.locale.libraries[key];
		}
	}
});

export {AbstractAdapterMixin,LocalAdapterMixin,AjaxAdapterMixin}


text:
"""
The DoInterestManager keeps track of which parent/zones that we currently
have interest in.  When you want to "look" into a zone you add an interest
to that zone.  When you want to get rid of, or ignore, the objects in that
zone, remove interest in that zone.

p.s. A great deal of this code is just code moved from ClientRepository.py.
"""

from pandac.PandaModules import *
from MsgTypes import *
from direct.showbase.PythonUtil import *
from direct.showbase import DirectObject
from PyDatagram import PyDatagram
from direct.directnotify.DirectNotifyGlobal import directNotify
import types
from direct.showbase.PythonUtil import report

class InterestState:
    StateActive = 'Active'
    StatePendingDel = 'PendingDel'
    def __init__(self, desc, state, context, event, parentId, zoneIdList,
                 eventCounter, auto=False):
        self.desc = desc
        self.state = state
        self.context = context
        # We must be ready to keep track of multiple events. If somebody
        # requested an interest to be removed and we get a second request
        # for removal of the same interest before we get a response for the
        # first interest removal, we now have two parts of the codebase
        # waiting for a response on the removal of a single interest.
        self.events = []
        self.eventCounter = eventCounter
        if event:
            self.addEvent(event)
        self.parentId = parentId
        self.zoneIdList = zoneIdList
        self.auto = auto
    def addEvent(self, event):
        self.events.append(event)
        self.eventCounter.num += 1
    def getEvents(self):
        return list(self.events)
    def clearEvents(self):
        self.eventCounter.num -= len(self.events)
        assert self.eventCounter.num >= 0
        self.events = []
    def sendEvents(self):
        for event in self.events:
            messenger.send(event)
        self.clearEvents()
    def setDesc(self, desc):
        self.desc = desc
    def isPendingDelete(self):
        return self.state == InterestState.StatePendingDel
    def __repr__(self):
        return 'InterestState(desc=%s, state=%s, context=%s, event=%s, parentId=%s, zoneIdList=%s)' % (
            self.desc, self.state, self.context, self.events, self.parentId, self.zoneIdList)

class InterestHandle:
    """This class helps to ensure that valid handles get passed in to DoInterestManager funcs"""
    def __init__(self, id):
        self._id = id
    def asInt(self):
        return self._id
    def __eq__(self, other):
        if type(self) == type(other):
            return self._id == other._id
        return self._id == other
    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, self._id)

# context value for interest changes that have no complete event
NO_CONTEXT = 0

class DoInterestManager(DirectObject.DirectObject):
    """
    Top level Interest Manager
    """
    notify = directNotify.newCategory("DoInterestManager")
    InterestDebug = ConfigVariableBool('interest-debug', False)

    # 'handle' is a number that represents a single interest set that the
    # client has requested; the interest set may be modified
    _HandleSerialNum = 0
    # high bit is reserved for server interests
    _HandleMask = 0x7FFF

    # 'context' refers to a single request to change an interest set
    _ContextIdSerialNum = 100
    _ContextIdMask = 0x3FFFFFFF # avoid making Python create a long

    _interests = {}
    if __debug__:
        _debug_interestHistory = []
        _debug_maxDescriptionLen = 40

    _SerialGen = SerialNumGen()
    _SerialNum = serialNum()

    def __init__(self):
        assert DoInterestManager.notify.debugCall()
        DirectObject.DirectObject.__init__(self)
        self._addInterestEvent = uniqueName('DoInterestManager-Add')
        self._removeInterestEvent = uniqueName('DoInterestManager-Remove')
        self._noNewInterests = False
        self._completeDelayedCallback = None
        # keep track of request contexts that have not completed
        self._completeEventCount = ScratchPad(num=0)
        self._allInterestsCompleteCallbacks = []

    def __verbose(self):
        return self.InterestDebug or self.getVerbose()

    def _getAnonymousEvent(self, desc):
        return 'anonymous-%s-%s' % (desc, DoInterestManager._SerialGen.next())

    def setNoNewInterests(self, flag):
        self._noNewInterests = flag

    def noNewInterests(self):
        return self._noNewInterests

    def setAllInterestsCompleteCallback(self, callback):
        if ((self._completeEventCount.num == 0) and
            (self._completeDelayedCallback is None)):
            callback()
        else:
            self._allInterestsCompleteCallbacks.append(callback)

    def getAllInterestsCompleteEvent(self):
        return 'allInterestsComplete-%s' % DoInterestManager._SerialNum

    def resetInterestStateForConnectionLoss(self):
        DoInterestManager._interests.clear()
        self._completeEventCount = ScratchPad(num=0)
        if __debug__:
            self._addDebugInterestHistory("RESET", "", 0, 0, 0, [])

    def isValidInterestHandle(self, handle):
        # pass in a handle (or anything else) and this will return true if it is
        # still a valid interest handle
        if not isinstance(handle, InterestHandle):
            return False
        return handle.asInt() in DoInterestManager._interests

    def updateInterestDescription(self, handle, desc):
        iState = DoInterestManager._interests.get(handle.asInt())
        if iState:
            iState.setDesc(desc)

    def addInterest(self, parentId, zoneIdList, description, event=None):
        """
        Look into a (set of) zone(s).
        """
        assert DoInterestManager.notify.debugCall()
        handle = self._getNextHandle()
        # print 'base.cr.addInterest(',description,',',handle,'):',globalClock.getFrameCount()
        if self._noNewInterests:
            DoInterestManager.notify.warning(
                "addInterest: addingInterests on delete: %s" % (handle))
            return

        # make sure we've got parenting rules set in the DC
        if parentId not in (self.getGameDoId(),):
            parent = self.getDo(parentId)
            if not parent:
                DoInterestManager.notify.error(
                    'addInterest: attempting to add interest under unknown object %s' % parentId)
            else:
                if not parent.hasParentingRules():
                    DoInterestManager.notify.error(
                        'addInterest: no setParentingRules defined in the DC for object %s (%s)'
                        '' % (parentId, parent.__class__.__name__))

        if event:
            contextId = self._getNextContextId()
        else:
            contextId = 0
            # event = self._getAnonymousEvent('addInterest')

        DoInterestManager._interests[handle] = InterestState(
            description, InterestState.StateActive, contextId, event, parentId, zoneIdList, self._completeEventCount)
        if self.__verbose():
            print 'CR::INTEREST.addInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s, event=%s)' % (
                handle, parentId, zoneIdList, description, event)
        self._sendAddInterest(handle, contextId, parentId, zoneIdList, description)
        if event:
            messenger.send(self._getAddInterestEvent(), [event])
        assert self.printInterestsIfDebug()
        return InterestHandle(handle)

    def addAutoInterest(self, parentId, zoneIdList, description):
        """
        Look into a (set of) zone(s).
        """
        assert DoInterestManager.notify.debugCall()
        handle = self._getNextHandle()
        if self._noNewInterests:
            DoInterestManager.notify.warning(
                "addInterest: addingInterests on delete: %s" % (handle))
            return

        # make sure we've got parenting rules set in the DC
        if parentId not in (self.getGameDoId(),):
            parent = self.getDo(parentId)
            if not parent:
                DoInterestManager.notify.error(
                    'addInterest: attempting to add interest under unknown object %s' % parentId)
            else:
                if not parent.hasParentingRules():
                    DoInterestManager.notify.error(
                        'addInterest: no setParentingRules defined in the DC for object %s (%s)'
                        '' % (parentId, parent.__class__.__name__))

        DoInterestManager._interests[handle] = InterestState(
            description, InterestState.StateActive, 0, None, parentId, zoneIdList, self._completeEventCount, True)
        if self.__verbose():
            print 'CR::INTEREST.addInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s)' % (
                handle, parentId, zoneIdList, description)
        assert self.printInterestsIfDebug()
        return InterestHandle(handle)

    def removeInterest(self, handle, event = None):
        """
        Stop looking in a (set of) zone(s)
        """
        # print 'base.cr.removeInterest(',handle,'):',globalClock.getFrameCount()

        assert DoInterestManager.notify.debugCall()
        assert isinstance(handle, InterestHandle)
        existed = False
        if not event:
            event = self._getAnonymousEvent('removeInterest')
        handle = handle.asInt()
        if handle in DoInterestManager._interests:
            existed = True
            intState = DoInterestManager._interests[handle]
            if event:
                messenger.send(self._getRemoveInterestEvent(),
                               [event, intState.parentId, intState.zoneIdList])
            if intState.isPendingDelete():
                self.notify.warning(
                    'removeInterest: interest %s already pending removal' %
                    handle)
                # this interest is already pending delete, so let's just tack this
                # callback onto the list
                if event is not None:
                    intState.addEvent(event)
            else:
                if len(intState.events) > 0:
                    # we're not pending a removal, but we have outstanding events?
                    # probably we are waiting for an add/alter complete.
                    # should we send those events now?
                    assert self.notify.warning('removeInterest: abandoning events: %s' %
                                               intState.events)
                    intState.clearEvents()
                intState.state = InterestState.StatePendingDel
                contextId = self._getNextContextId()
                intState.context = contextId
                if event:
                    intState.addEvent(event)
                self._sendRemoveInterest(handle, contextId)
                if not event:
                    self._considerRemoveInterest(handle)
                if self.__verbose():
                    print 'CR::INTEREST.removeInterest(handle=%s, event=%s)' % (
                        handle, event)
        else:
            DoInterestManager.notify.warning(
                "removeInterest: handle not found: %s" % (handle))
        assert self.printInterestsIfDebug()
        return existed

    def removeAutoInterest(self, handle):
        """
        Stop looking in a (set of) zone(s)
        """
        assert DoInterestManager.notify.debugCall()
        assert isinstance(handle, InterestHandle)
        existed = False
        handle = handle.asInt()
        if handle in DoInterestManager._interests:
            existed = True
            intState = DoInterestManager._interests[handle]
            if intState.isPendingDelete():
                self.notify.warning(
                    'removeInterest: interest %s already pending removal' %
                    handle)
                # this interest is already pending delete, so let's just tack this
                # callback onto the list
            else:
                if len(intState.events) > 0:
                    # we're not pending a removal, but we have outstanding events?
                    # probably we are waiting for an add/alter complete.
                    # should we send those events now?
                    self.notify.warning('removeInterest: abandoning events: %s' %
                                        intState.events)
                    intState.clearEvents()
                intState.state = InterestState.StatePendingDel
                self._considerRemoveInterest(handle)
                if self.__verbose():
                    print 'CR::INTEREST.removeAutoInterest(handle=%s)' % (handle)
        else:
            DoInterestManager.notify.warning(
                "removeInterest: handle not found: %s" % (handle))
        assert self.printInterestsIfDebug()
        return existed

    @report(types = ['args'], dConfigParam = 'guildmgr')
    def removeAIInterest(self, handle):
        """
        handle is NOT an InterestHandle.  It's just a bare integer representing an
        AI opened interest. We're making the client close down this interest since
        the AI has trouble removing interests(that its opened) when the avatar goes
        offline.  See GuildManager(UD) for how it's being used.
        """
        self._sendRemoveAIInterest(handle)

    def alterInterest(self, handle, parentId, zoneIdList, description=None,
                      event=None):
        """
        Removes old interests and adds new interests.

        Note that when an interest is changed, only the most recent
        change's event will be triggered. Previous events are abandoned.
        If this is a problem, consider opening multiple interests.
        """
        assert DoInterestManager.notify.debugCall()
        assert isinstance(handle, InterestHandle)
        #assert not self._noNewInterests
        handle = handle.asInt()
        if self._noNewInterests:
            DoInterestManager.notify.warning(
                "alterInterest: addingInterests on delete: %s" % (handle))
            return

        exists = False
        if event is None:
            event = self._getAnonymousEvent('alterInterest')
        if handle in DoInterestManager._interests:
            if description is not None:
                DoInterestManager._interests[handle].desc = description
            else:
                description = DoInterestManager._interests[handle].desc

            # are we overriding an existing change?
            if DoInterestManager._interests[handle].context != NO_CONTEXT:
                DoInterestManager._interests[handle].clearEvents()

            contextId = self._getNextContextId()
            DoInterestManager._interests[handle].context = contextId
            DoInterestManager._interests[handle].parentId = parentId
            DoInterestManager._interests[handle].zoneIdList = zoneIdList
            DoInterestManager._interests[handle].addEvent(event)

            if self.__verbose():
                print 'CR::INTEREST.alterInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s, event=%s)' % (
                    handle, parentId, zoneIdList, description, event)
            self._sendAddInterest(handle, contextId, parentId, zoneIdList, description, action='modify')
            exists = True
            assert self.printInterestsIfDebug()
        else:
            DoInterestManager.notify.warning(
                "alterInterest: handle not found: %s" % (handle))
        return exists

    def openAutoInterests(self, obj):
        if hasattr(obj, '_autoInterestHandle'):
            # must be multiple inheritance
            self.notify.debug('openAutoInterests(%s): interests already open' % obj.__class__.__name__)
            return
        autoInterests = obj.getAutoInterests()
        obj._autoInterestHandle = None
        if not len(autoInterests):
            return
        obj._autoInterestHandle = self.addAutoInterest(obj.doId, autoInterests, '%s-autoInterest' % obj.__class__.__name__)
    def closeAutoInterests(self, obj):
        if not hasattr(obj, '_autoInterestHandle'):
            # must be multiple inheritance
            self.notify.debug('closeAutoInterests(%s): interests already closed' % obj)
            return
        if obj._autoInterestHandle is not None:
            self.removeAutoInterest(obj._autoInterestHandle)
        del obj._autoInterestHandle

    # events for InterestWatcher
    def _getAddInterestEvent(self):
        return self._addInterestEvent
    def _getRemoveInterestEvent(self):
        return self._removeInterestEvent

    def _getInterestState(self, handle):
        return DoInterestManager._interests[handle]

    def _getNextHandle(self):
        handle = DoInterestManager._HandleSerialNum
        while True:
            handle = (handle + 1) & DoInterestManager._HandleMask
            # skip handles that are already in use
            if handle not in DoInterestManager._interests:
                break
            DoInterestManager.notify.warning(
                'interest %s already in use' % handle)
        DoInterestManager._HandleSerialNum = handle
        return DoInterestManager._HandleSerialNum
    def _getNextContextId(self):
        contextId = DoInterestManager._ContextIdSerialNum
        while True:
            contextId = (contextId + 1) & DoInterestManager._ContextIdMask
            # skip over the 'no context' id
            if contextId != NO_CONTEXT:
                break
        DoInterestManager._ContextIdSerialNum = contextId
        return DoInterestManager._ContextIdSerialNum

    def _considerRemoveInterest(self, handle):
        """
        Consider whether we should cull the interest set.
        """
        assert DoInterestManager.notify.debugCall()

        if handle in DoInterestManager._interests:
            if DoInterestManager._interests[handle].isPendingDelete():
                # make sure there is no pending event for this interest
                if DoInterestManager._interests[handle].context == NO_CONTEXT:
                    assert len(DoInterestManager._interests[handle].events) == 0
                    del DoInterestManager._interests[handle]

    if __debug__:
        def printInterestsIfDebug(self):
            if DoInterestManager.notify.getDebug():
                self.printInterests()
            return 1 # for assert

        def _addDebugInterestHistory(self, action, description, handle,
                                     contextId, parentId, zoneIdList):
            if description is None:
                description = ''
            DoInterestManager._debug_interestHistory.append(
                (action, description, handle, contextId, parentId, zoneIdList))
            DoInterestManager._debug_maxDescriptionLen = max(
                DoInterestManager._debug_maxDescriptionLen, len(description))

        def printInterestHistory(self):
            print "***************** Interest History *************"
            format = '%9s %' + str(DoInterestManager._debug_maxDescriptionLen) + 's %6s %6s %9s %s'
            print format % (
                "Action", "Description", "Handle", "Context", "ParentId",
                "ZoneIdList")
            for i in DoInterestManager._debug_interestHistory:
                print format % tuple(i)
            print "Note: interests with a Context of 0 do not get" \
                " done/finished notices."

        def printInterestSets(self):
            print "******************* Interest Sets **************"
            format = '%6s %' + str(DoInterestManager._debug_maxDescriptionLen) + 's %11s %11s %8s %8s %8s'
            print format % (
                "Handle", "Description",
                "ParentId", "ZoneIdList",
                "State", "Context",
                "Event")
            for id, state in DoInterestManager._interests.items():
                if len(state.events) == 0:
                    event = ''
                elif len(state.events) == 1:
                    event = state.events[0]
                else:
                    event = state.events
                print format % (id, state.desc,
                                state.parentId, state.zoneIdList,
                                state.state, state.context,
                                event)
            print "************************************************"

        def printInterests(self):
            self.printInterestHistory()
            self.printInterestSets()

    def _sendAddInterest(self, handle, contextId, parentId, zoneIdList, description,
                         action=None):
        """
        Part of the new otp-server code.

        handle is a client-side created number that refers to
                a set of interests.  The same handle number doesn't
                necessarily have any relationship to the same handle
                on another client.
        """
        assert DoInterestManager.notify.debugCall()
        if __debug__:
            if isinstance(zoneIdList, types.ListType):
                zoneIdList.sort()
            if action is None:
                action = 'add'
            self._addDebugInterestHistory(
                action, description, handle, contextId, parentId, zoneIdList)
        if parentId == 0:
            DoInterestManager.notify.error(
                'trying to set interest to invalid parent: %s' % parentId)
        datagram = PyDatagram()
        # Add message type
        datagram.addUint16(CLIENT_ADD_INTEREST)
        datagram.addUint16(handle)
        datagram.addUint32(contextId)
        datagram.addUint32(parentId)
        if isinstance(zoneIdList, types.ListType):
            vzl = list(zoneIdList)
            vzl.sort()
            uniqueElements(vzl)
            for zone in vzl:
                datagram.addUint32(zone)
        else:
           datagram.addUint32(zoneIdList)
        self.send(datagram)

    def _sendRemoveInterest(self, handle, contextId):
        """
        handle is a client-side created number that refers to
                a set of interests.  The same handle number doesn't
                necessarily have any relationship to the same handle
                on another client.
        """
        assert DoInterestManager.notify.debugCall()
        assert handle in DoInterestManager._interests
        datagram = PyDatagram()
        # Add message type
        datagram.addUint16(CLIENT_REMOVE_INTEREST)
        datagram.addUint16(handle)
        if contextId != 0:
            datagram.addUint32(contextId)
        self.send(datagram)
        if __debug__:
            state = DoInterestManager._interests[handle]
            self._addDebugInterestHistory(
                "remove", state.desc, handle, contextId,
                state.parentId, state.zoneIdList)

    def _sendRemoveAIInterest(self, handle):
        """
        handle is a bare int, NOT an InterestHandle.  Use this to
        close an AI opened interest.
        """
        datagram = PyDatagram()
        # Add message type
        datagram.addUint16(CLIENT_REMOVE_INTEREST)
        datagram.addUint16((1<<15) + handle)
        self.send(datagram)

    def cleanupWaitAllInterestsComplete(self):
        if self._completeDelayedCallback is not None:
            self._completeDelayedCallback.destroy()
            self._completeDelayedCallback = None

    def queueAllInterestsCompleteEvent(self, frames=5):
        # wait for N frames, if no new interests, send out all-done event
        # calling this is OK even if there are no pending interest completes
        def checkMoreInterests():
            # if there are new interests, cancel this delayed callback, another
            # will automatically be scheduled when all interests complete
            # print 'checkMoreInterests(',self._completeEventCount.num,'):',globalClock.getFrameCount()
            return self._completeEventCount.num > 0
        def sendEvent():
            messenger.send(self.getAllInterestsCompleteEvent())
            for callback in self._allInterestsCompleteCallbacks:
                callback()
            self._allInterestsCompleteCallbacks = []
        self.cleanupWaitAllInterestsComplete()
        self._completeDelayedCallback = FrameDelayedCall(
            'waitForAllInterestCompletes',
            callback=sendEvent,
            frames=frames,
            cancelFunc=checkMoreInterests)
        checkMoreInterests = None
        sendEvent = None

    def handleInterestDoneMessage(self, di):
        """
        This handles the interest done messages and may dispatch an event
        """
        assert DoInterestManager.notify.debugCall()
        handle = di.getUint16()
        contextId = di.getUint32()
        if self.__verbose():
            print 'CR::INTEREST.interestDone(handle=%s)' % handle
        DoInterestManager.notify.debug(
            "handleInterestDoneMessage--> Received handle %s, context %s" % (
            handle, contextId))
        if handle in DoInterestManager._interests:
            eventsToSend = []
            # if the context matches, send out the event
            if contextId == DoInterestManager._interests[handle].context:
                DoInterestManager._interests[handle].context = NO_CONTEXT
                # the event handlers may call back into the interest manager. Send out
                # the events after we're once again in a stable state.
                #DoInterestManager._interests[handle].sendEvents()
                eventsToSend = list(DoInterestManager._interests[handle].getEvents())
                DoInterestManager._interests[handle].clearEvents()
            else:
                DoInterestManager.notify.debug(
                    "handleInterestDoneMessage--> handle: %s: Expecting context %s, got %s" % (
                    handle, DoInterestManager._interests[handle].context, contextId))
            if __debug__:
                state = DoInterestManager._interests[handle]
                self._addDebugInterestHistory(
                    "finished", state.desc, handle, contextId, state.parentId,
                    state.zoneIdList)
            self._considerRemoveInterest(handle)
            for event in eventsToSend:
                messenger.send(event)
        else:
            DoInterestManager.notify.warning(
                "handleInterestDoneMessage: handle not found: %s" % (handle))
        # if there are no more outstanding interest-completes, send out global all-done event
        if self._completeEventCount.num == 0:
            self.queueAllInterestsCompleteEvent()
        assert self.printInterestsIfDebug()

if __debug__:
    import unittest

    class AsyncTestCase(unittest.TestCase):
        def setCompleted(self):
            self._async_completed = True
        def isCompleted(self):
            return getattr(self, '_async_completed', False)

    class AsyncTestSuite(unittest.TestSuite):
        pass

    class AsyncTestLoader(unittest.TestLoader):
        suiteClass = AsyncTestSuite

    class AsyncTextTestRunner(unittest.TextTestRunner):
        def run(self, testCase):
            result = self._makeResult()
            startTime = time.time()
            test(result)
            stopTime = time.time()
            timeTaken = stopTime - startTime
            result.printErrors()
            self.stream.writeln(result.separator2)
            run = result.testsRun
            self.stream.writeln("Ran %d test%s in %.3fs" %
                                (run, run != 1 and "s" or "", timeTaken))
            self.stream.writeln()
            if not result.wasSuccessful():
                self.stream.write("FAILED (")
                failed, errored = map(len, (result.failures, result.errors))
                if failed:
                    self.stream.write("failures=%d" % failed)
                if errored:
                    if failed: self.stream.write(", ")
                    self.stream.write("errors=%d" % errored)
                self.stream.writeln(")")
            else:
                self.stream.writeln("OK")
            return result

    class TestInterestAddRemove(AsyncTestCase, DirectObject.DirectObject):
        def testInterestAdd(self):
            event = uniqueName('InterestAdd')
            self.acceptOnce(event, self.gotInterestAddResponse)
            self.handle = base.cr.addInterest(base.cr.GameGlobalsId, 100, 'TestInterest', event=event)
        def gotInterestAddResponse(self):
            event = uniqueName('InterestRemove')
            self.acceptOnce(event, self.gotInterestRemoveResponse)
            base.cr.removeInterest(self.handle, event=event)
        def gotInterestRemoveResponse(self):
            self.setCompleted()

    def runTests():
        suite = unittest.makeSuite(TestInterestAddRemove)
        unittest.AsyncTextTestRunner(verbosity=2).run(suite)


text:
<?php
include "conf.php";

if ($argc != 2) {
	error_log("Usage:\n  ".$argv[0]." delivery-id");
	exit(1);
}
$delivery_id = $argv[1];

$ch = curl_init("https://api.bluehouselab.com/smscenter/v1.0/result/".$delivery_id);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, "$APPID:$APIKEY");

$response = curl_exec($ch);
$response_header = curl_getinfo($ch);
echo $response_header["http_code"]."\n";
print_r(json_decode($response, true));
curl_close($ch);
?>


text:
package strategy;

public interface InstrumentBehavior
{
	public void instrument();
}


text:
layout: post
title: Tweets
date: 2022-01-01
summary: These are the tweets for January 1, 2022.
categories:
---


text:
package com.currencycloud.client;

import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import com.currencycloud.client.model.Transfer;
import com.currencycloud.client.model.Transfers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class TransfersTest extends BetamaxTestSupport {

    private CurrencyCloudClient client;

    @Before
    public void prepareClient() {
        client = prepareTestClient(null, null, "334cbfdb9ba9bfb6ffd499b0c6af6b12");
    }

    @Before
    @After
    public void methodName() {
        log.debug("------------------------- " + name.getMethodName() + " -------------------------");
    }

    @Test
    @Betamax(tape = "can_create", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
    public void testCanCreateTransfer()  {
        Transfer transfer = Transfer.create("a7117404-e150-11e6-a5af-080027a79e8f", "946f2d58-e150-11e6-a5af-080027a79e8f", "GBP", new BigDecimal("1250.0"));
        transfer.setReason("Client funding");
        transfer = client.createTransfer(transfer);

        assertThat(transfer.getId(), equalTo("993d63bd-e151-11e6-a5af-080027a79e8f"));
        assertThat(transfer.getShortReference(), equalTo("BT-20180101-JGCWQH"));
        assertThat(transfer.getSourceAccountId(), equalTo("a7117404-e150-11e6-a5af-080027a79e8f"));
        assertThat(transfer.getDestinationAccountId(), equalTo("946f2d58-e150-11e6-a5af-080027a79e8f"));
        assertThat(transfer.getCurrency(), equalTo("GBP"));
        assertThat(transfer.getAmount(), equalTo(new BigDecimal("1250.0")));
        assertThat(transfer.getStatus(), equalTo("completed"));
        assertThat(transfer.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getCompletedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getCreatorAccountId(), equalTo("262e3d2a-e152-11e6-a5af-080027a79e8f"));
        assertThat(transfer.getCreatorContactId(), equalTo("30cb8632-e152-11e6-a5af-080027a79e8f"));
        assertThat(transfer.getReason(), equalTo("Client funding"));
    }

    @Test
    @Betamax(tape = "can_retrieve", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
    public void testCanRetrieveTransfer()  {
        Transfer transfer = client.retrieveTransfer("b0c2df71-28db-42ef-b6b7-5710f22d2115");

        assertThat(transfer.getId(), equalTo("b0c2df71-28db-42ef-b6b7-5710f22d2115"));
        assertThat(transfer.getShortReference(), equalTo("BT-20180101-YRSYGK"));
        assertThat(transfer.getSourceAccountId(), equalTo("1bd29e41-f019-0133-ed7e-0022194273c7"));
        assertThat(transfer.getDestinationAccountId(), equalTo("d9c34271-b7a6-0133-9fe2-0022194273c7"));
        assertThat(transfer.getCurrency(), equalTo("EUR"));
        assertThat(transfer.getAmount(), equalTo(new BigDecimal("123.45")));
        assertThat(transfer.getStatus(), equalTo("completed"));
        assertThat(transfer.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getCompletedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getCreatorAccountId(), equalTo("2090939e-b2f7-3f2b-1363-4d235b3f58af"));
        assertThat(transfer.getCreatorContactId(), equalTo("8a98ebac-6f88-e205-a685-4d235b1b088b"));
        assertThat(transfer.getReason(), equalTo("Test"));

    }

    @Test
    @Betamax(tape = "can_find", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
    public void testCanFindTransfer()  {
        Transfers transferData = client.findTransfers(null, null);
        List<Transfer> transfers = transferData.getTransfers();

        assertThat(transfers, not(nullValue()));
        assertThat(transfers.size(), is(2));
        assertThat(transfers.get(0).getId(), equalTo("993d63bd-e151-11e6-a5af-080027a79e8f"));
        assertThat(transfers.get(0).getShortReference(), equalTo("BT-20180101-JGCWQH"));
        assertThat(transfers.get(0).getSourceAccountId(), equalTo("a7117404-e150-11e6-a5af-080027a79e8f"));
        assertThat(transfers.get(0).getDestinationAccountId(), equalTo("946f2d58-e150-11e6-a5af-080027a79e8f"));
        assertThat(transfers.get(0).getCurrency(), equalTo("GBP"));
        assertThat(transfers.get(0).getAmount(), equalTo(new BigDecimal("1250.00")));
        assertThat(transfers.get(0).getStatus(), equalTo("completed"));
    }

    @Test
    @Betamax(tape = "can_cancel", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
    public void testCanCancelTransfer()  {
        Transfer transfer = client.cancelTransfer("b0c2df71-28db-42ef-b6b7-5710f22d2115");

        assertThat(transfer.getId(), equalTo("b0c2df71-28db-42ef-b6b7-5710f22d2115"));
        assertThat(transfer.getShortReference(), equalTo("BT-20180101-YRSYGK"));
        assertThat(transfer.getSourceAccountId(), equalTo("1bd29e41-f019-0133-ed7e-0022194273c7"));
        assertThat(transfer.getDestinationAccountId(), equalTo("d9c34271-b7a6-0133-9fe2-0022194273c7"));
        assertThat(transfer.getCurrency(), equalTo("EUR"));
        assertThat(transfer.getAmount(), equalTo(new BigDecimal("123.45")));
        assertThat(transfer.getStatus(), equalTo("completed"));
        assertThat(transfer.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getCompletedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
        assertThat(transfer.getCreatorAccountId(), equalTo("2090939e-b2f7-3f2b-1363-4d235b3f58af"));
        assertThat(transfer.getCreatorContactId(), equalTo("8a98ebac-6f88-e205-a685-4d235b1b088b"));
        assertThat(transfer.getReason(), equalTo("Test"));
    }

    @Test
    @Betamax(tape = "can_create_with_unique_request_id", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
    public void testCanCreateTransferWithUniqueRequestId()  {
        final Transfer transferIn = Transfer.create("1034561f-aa8c-4bbe-a2c5-22fe45fbb76f",
                "e22d8fde-9c0c-4eb0-a67e-234cf123458f",
                "GBP", new BigDecimal("8500.0"));
        transferIn.setReason("Unit Test");
        transferIn.setUniqueRequestId("zWE9S4ff4ptXR7bp9DBazRk4");
        final Transfer transfer = client.createTransfer(transferIn);

        assertThat(transfer.getId(), equalTo("bb3de44e-1212-4c50-8765-e5c06622aeac"));
        assertThat(transfer.getShortReference(), equalTo("BT-20211110-AABBCC"));
        assertThat(transfer.getSourceAccountId(), equalTo("1034561f-aa8c-4bbe-a2c5-22fe45fbb76f"));
        assertThat(transfer.getDestinationAccountId(), equalTo("e22d8fde-9c0c-4eb0-a67e-234cf123458f"));
        assertThat(transfer.getCurrency(), equalTo("GBP"));
        assertThat(transfer.getAmount(), equalTo(new BigDecimal("8500.00")));
        assertThat(transfer.getStatus(), equalTo("pending"));
        assertThat(transfer.getCreatedAt(), equalTo(parseDateTime("2021-11-10T14:06:04+00:00")));
        assertThat(transfer.getUpdatedAt(), equalTo(parseDateTime("2021-11-10T14:06:04+00:00")));
        assertThat(transfer.getCompletedAt(), is(nullValue()));
        assertThat(transfer.getCreatorAccountId(), equalTo("765934d-2942-4d85-bf18-ed803b5491c9"));
        assertThat(transfer.getCreatorContactId(), equalTo("6f3c7502-d332-4e12-b841-743fb0666b9f"));
        assertThat(transfer.getReason(), equalTo("Unit Test"));
        assertThat(transfer.getUniqueRequestId(), equalTo("zWE9S4ff4ptXR7bp9DBazRk4"));
    }

    @Test
    @Betamax(tape = "can_find_with_uniques_request_id", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
    public void testCanFindTransferWithUniqueRequestId() {
        final Transfer transferIn = Transfer.create();
        transferIn.setUniqueRequestId("zWE9S4ff4ptXR7bp9DBazRk4");
        final Transfers transferData = client.findTransfers(transferIn, null);
        final List<Transfer> transfers = transferData.getTransfers();

        assertThat(transfers, not(nullValue()));
        assertThat(transfers.size(), is(1));
        final Transfer transfer = transfers.get(0);
        assertThat(transfer.getId(), equalTo("bb3de44e-1212-4c50-8765-e5c06622aeac"));
        assertThat(transfer.getShortReference(), equalTo("BT-20211110-AABBCC"));
        assertThat(transfer.getSourceAccountId(), equalTo("1034561f-aa8c-4bbe-a2c5-22fe45fbb76f"));
        assertThat(transfer.getDestinationAccountId(), equalTo("e22d8fde-9c0c-4eb0-a67e-234cf123458f"));
        assertThat(transfer.getCurrency(), equalTo("GBP"));
        assertThat(transfer.getAmount(), equalTo(new BigDecimal("8500.00")));
        assertThat(transfer.getStatus(), equalTo("pending"));
        assertThat(transfer.getCreatedAt(), equalTo(parseDateTime("2021-11-10T14:06:04+00:00")));
        assertThat(transfer.getUpdatedAt(), equalTo(parseDateTime("2021-11-10T14:06:04+00:00")));
        assertThat(transfer.getCompletedAt(), is(nullValue()));
        assertThat(transfer.getCreatorAccountId(), equalTo("765934d-2942-4d85-bf18-ed803b5491c9"));
        assertThat(transfer.getCreatorContactId(), equalTo("6f3c7502-d332-4e12-b841-743fb0666b9f"));
        assertThat(transfer.getReason(), equalTo("Unit Test"));
        assertThat(transfer.getUniqueRequestId(), equalTo("zWE9S4ff4ptXR7bp9DBazRk4"));
    }
}


text:
describe :argf_each_byte, shared: true do
  before :each do
    @file1_name = fixture __FILE__, "file1.txt"
    @file2_name = fixture __FILE__, "file2.txt"

    @bytes = []
    File.read(@file1_name).each_byte { |b| @bytes << b }
    File.read(@file2_name).each_byte { |b| @bytes << b }
  end

  it "yields each byte of all streams to the passed block" do
    argf [@file1_name, @file2_name] do
      bytes = []
      @argf.send(@method) { |b| bytes << b }
      bytes.should == @bytes
    end
  end

  it "returns self when passed a block" do
    argf [@file1_name, @file2_name] do
      @argf.send(@method) {}.should equal(@argf)
    end
  end

  it "returns an Enumerator when passed no block" do
    argf [@file1_name, @file2_name] do
      enum = @argf.send(@method)
      enum.should be_an_instance_of(Enumerator)

      bytes = []
      enum.each { |b| bytes << b }
      bytes.should == @bytes
    end
  end

  describe "when no block is given" do
    it "returns an Enumerator" do
      argf [@file1_name, @file2_name] do
        enum = @argf.send(@method)
        enum.should be_an_instance_of(Enumerator)

        bytes = []
        enum.each { |b| bytes << b }
        bytes.should == @bytes
      end
    end

    describe "returned Enumerator" do
      describe "size" do
        it "should return nil" do
          argf [@file1_name, @file2_name] do
            @argf.send(@method).size.should == nil
          end
        end
      end
    end
  end
end


text:
package ipv6addr

import (
	"context"

	"github.com/sacloud/libsacloud/v2/helper/service"
	"github.com/sacloud/libsacloud/v2/sacloud"
)

func (s *Service) Delete(req *DeleteRequest) error {
	return s.DeleteWithContext(context.Background(), req)
}

func (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error {
	if err := req.Validate(); err != nil {
		return err
	}

	client := sacloud.NewIPv6AddrOp(s.caller)
	if err := client.Delete(ctx, req.Zone, req.IPv6Addr); err != nil {
		return service.HandleNotFoundError(err, !req.FailIfNotFound)
	}
	return nil
}


text:
package org.overlord.commons.dev.server.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.IOUtils;

/**
 * Some general porpoise utils for working with archives.
 *
 * @author eric.wittmann@redhat.com
 */
public class ArchiveUtils {

	/**
	 * Unpacks the given archive file into the output directory.
	 * @param archiveFile an archive file
	 * @param toDir where to unpack the archive to
	 * @throws IOException
	 */
	public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException {
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(archiveFile);
            Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
			while (zipEntries.hasMoreElements()) {
				ZipArchiveEntry entry = zipEntries.nextElement();
				String entryName = entry.getName();
				File outFile = new File(toDir, entryName);
				if (!outFile.getParentFile().exists()) {
					if (!outFile.getParentFile().mkdirs()) {
						throw new IOException("Failed to create parent directory: " + outFile.getParentFile().getCanonicalPath()); //$NON-NLS-1$
					}
				}

				if (entry.isDirectory()) {
					if (!outFile.exists() && !outFile.mkdir()) {
						throw new IOException("Failed to create directory: " + outFile.getCanonicalPath()); //$NON-NLS-1$
					} else if (outFile.exists() && !outFile.isDirectory()) {
						throw new IOException("Failed to create directory (already exists but is a file): " + outFile.getCanonicalPath()); //$NON-NLS-1$
					}
				} else {
					InputStream zipStream = null;
					OutputStream outFileStream = null;

					zipStream = zipFile.getInputStream(entry);
					outFileStream = new FileOutputStream(outFile);
					try {
						IOUtils.copy(zipStream, outFileStream);
					} finally {
						IOUtils.closeQuietly(zipStream);
						IOUtils.closeQuietly(outFileStream);
					}
				}
			}
		} finally {
			ZipFile.closeQuietly(zipFile);
		}
	}

}


text:
using std::string;

// Desired number of training batches.
const int kNumBatches = 500000;

namespace {

// Train on a random image.
void train_image(const LoaderImagenetDet& image_loader,
           const std::vector<std::vector<Annotation> >& images,
           TrackerTrainer* tracker_trainer) {
  // Get a random image.
  const int image_num = rand() % images.size();
  const std::vector<Annotation>& annotations = images[image_num];

  // Choose a random annotation.
  const int annotation_num = rand() % annotations.size();

  // Load the image with its ground-truth bounding box.
  cv::Mat image;
  BoundingBox bbox;
  image_loader.LoadAnnotation(image_num, annotation_num, &image, &bbox);

  // Train on this example
  tracker_trainer->Train(image, image, bbox, bbox);
}

// Train on all annotated frames in the set of videos.
void train_video(const std::vector<Video>& videos, TrackerTrainer* tracker_trainer) {
  // Get a random video.
  const int video_num = rand() % videos.size();
  const Video& video = videos[video_num];

  // Get the video's annotations.
  const std::vector<Frame>& annotations = video.annotations;

  // We need at least 2 annotations in this video for this to be useful.
  if (annotations.size() < 2) {
    printf("Error - video %s has only %zu annotations\n", video.path.c_str(),
           annotations.size());
    return;
  }

  // Choose a random annotation.
  const int annotation_index = rand() % (annotations.size() - 1);

  // Load the frame's annotation.
  int frame_num_prev;
  cv::Mat image_prev;
  BoundingBox bbox_prev;
  video.LoadAnnotation(annotation_index, &frame_num_prev, &image_prev, &bbox_prev);

  // Load the next frame's annotation.
  int frame_num_curr;
  cv::Mat image_curr;
  BoundingBox bbox_curr;
  video.LoadAnnotation(annotation_index + 1, &frame_num_curr, &image_curr, &bbox_curr);

  // Train on this example
  tracker_trainer->Train(image_prev, image_curr, bbox_prev, bbox_curr);

  // Save
  frame_num_prev = frame_num_curr;
  image_prev = image_curr;
  bbox_prev = bbox_curr;
}

} // namespace

int main (int argc, char *argv[]) {
  if (argc < 14) {
    std::cerr << "Usage: " << argv[0]
              << " videos_folder_imagenet annotations_folder_imagenet"
              << " alov_videos_folder alov_annotations_folder"
              << " network.caffemodel train.prototxt val.prototxt"
              << " solver_file"
              << " lambda_shift lambda_scale min_scale max_scale"
              << " gpu_id"
              << std::endl;
    return 1;
  }

  FLAGS_alsologtostderr = 1;

  ::google::InitGoogleLogging(argv[0]);

  int arg_index = 1;
  const string& videos_folder_imagenet      = argv[arg_index++];
  const string& annotations_folder_imagenet = argv[arg_index++];
  const string& alov_videos_folder      = argv[arg_index++];
  const string& alov_annotations_folder = argv[arg_index++];
  const string& caffe_model   = argv[arg_index++];
  const string& train_proto   = argv[arg_index++];
  const string& solver_file  = argv[arg_index++];
  const double lambda_shift        = atof(argv[arg_index++]);
  const double lambda_scale        = atof(argv[arg_index++]);
  const double min_scale           = atof(argv[arg_index++]);
  const double max_scale           = atof(argv[arg_index++]);
  const int gpu_id          = atoi(argv[arg_index++]);
  const int random_seed          = atoi(argv[arg_index++]);

  caffe::Caffe::set_random_seed(random_seed);
  printf("Using random seed: %d\n", random_seed);

#ifdef CPU_ONLY
  printf("Setting up Caffe in CPU mode\n");
  caffe::Caffe::set_mode(caffe::Caffe::CPU);
#else
  printf("Setting up Caffe in GPU mode with ID: %d\n", gpu_id);
  caffe::Caffe::set_mode(caffe::Caffe::GPU);
  caffe::Caffe::SetDevice(gpu_id);
#endif

  // Load the image data.
  LoaderImagenetDet image_loader(videos_folder_imagenet, annotations_folder_imagenet);
  const std::vector<std::vector<Annotation> >& train_images = image_loader.get_images();
  printf("Total training images: %zu\n", train_images.size());

  // Load the video data.
  LoaderAlov alov_video_loader(alov_videos_folder, alov_annotations_folder);
  const bool get_train = true;
  std::vector<Video> train_videos;
  alov_video_loader.get_videos(get_train, &train_videos);
  printf("Total training videos: %zu\n", train_videos.size());

  // Create an ExampleGenerator to generate training examples.
  ExampleGenerator example_generator(lambda_shift, lambda_scale,
                                     min_scale, max_scale);

  // Set up network.
  RegressorTrain regressor_train(train_proto, caffe_model,
                                 gpu_id, solver_file);

  // Set up trainer.
  TrackerTrainer tracker_trainer(&example_generator, &regressor_train);

  // Train tracker.
  while (tracker_trainer.get_num_batches() < kNumBatches) {
    // Train on an image example.
    train_image(image_loader, train_images, &tracker_trainer);

    // Train on a video example.
    train_video(train_videos, &tracker_trainer);
  }

  return 0;
}


text:
package de.passau.uni.sec.compose.id.rest.functional.util;

import java.net.URI;

import org.apache.http.HttpHost;
import org.apache.http.client.AuthCache;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

@SuppressWarnings("deprecation")
public class DigestHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {

    public DigestHttpComponentsClientHttpRequestFactory(DefaultHttpClient client){
        super(client);
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        return createHttpContext(uri);
    }

    private HttpContext createHttpContext(URI uri){
        AuthCache authCache = new BasicAuthCache();
        DigestScheme digestScheme = new DigestScheme();
        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
        authCache.put(targetHost, digestScheme);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }
}


text:
lua-snapshot
============

Make a snapshot for lua state to detect memory leaks.

See dump.lua for example.

Build
=====

make linux

or

make mingw (in windows)

or

make macosx


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mwiti.collins.inspector">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@drawable/eagleeye"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".WrapperActivity" />
        <activity android:name=".CreateAccount" />
        <activity android:name=".MainActivity" />
        <activity android:name=".WelcomeActivity" />
        <activity android:name=".LoginActivity"></activity>
    </application>

</manifest>


text:
pub struct Struct(pub u32);

impl Drop for Struct {
    fn drop(&mut self) {}
}