text:
.. _api:

Swee'pea's API
==============

.. py:class:: TableFunction()

    Implements a table-valued function (eponymous-only virtual table) in
    SQLite. In English, a table-valued function is a user-defined function that
    can return 0 or more rows of data. Normal user-defined functions must
    return a scalar value, and aggregate functions can accept multiple inputs
    but are still restricted to a single scalar output. These restrictions are
    lifted from table-valued functions. They are called table-valued because
    their output can be thought of as a table.

    Subclasses must define the ``columns`` (return values) and ``params``
    (input values) to their function. These are declared as class attributes.

    Subclasses must also implement two methods:

    * ``initialize(**query)``
    * ``iterate(idx)``

    .. code-block:: python

        # Example table-valued function that returns a range of integers.
        class Series(TableFunction):
            columns = ['value']
            params = ['start', 'stop', 'step']
            name = 'series'

            def initialize(self, start=0, stop=None, step=1):
                self.start = self.current = start
                self.stop = stop or float('inf')
                self.step = step

            def iterate(self, idx):
                if self.current > self.stop:
                    raise StopIteration

                return_val = self.current
                self.current += self.step
                return (return_val,)

        # Must register with a connection in order to use.
        conn = sqlite3.connect(':memory:')
        Series.register(conn)

        # Now we can call it.
        for num, in conn.execute('select * from series(0, 10, 2)'):
            print num

        # Prints 0, 2, 4, 6, 8, 10.

    .. py:attribute:: columns

        A list or tuple describing the rows returned by this function.

    .. py:attribute:: params

        A list or tuple describing the parameters this function accepts.

    .. py:attribute:: name

        The name of the table-valued function. If not provided, name will be
        inferred from the class name.

    .. py:method:: initialize(**query)

        This method is called once for each set of values the table-valued
        function is called with.

        :param query: The parameters the function was called with.
        :returns: return value is discarded.

    .. py:method:: iterate(idx)

        This method is called repeatedly until it raises ``StopIteration``. The
        return value should be a row-tuple matching the format described by the
        ``columns`` attribute.

        :param int idx: The row index being requested.
        :raises: StopIteration
        :returns: A row tuple

    .. py:method:: register(connection)

        Register the table-valued function with a SQLite database connection.
        You must register a table-valued function in order to use it.

        :param connection: a ``sqlite3.Connection`` instance.

.. py:class:: CursorWrapper(cursor)

    Wraps a SQLite3 cursor, providing additional functionality. This object
    should not be instantiated directly, but instead is returned when executing
    ``SELECT`` queries.

    When iterated over, the cursor wrapper will yield result rows as tuples.

    .. py:method:: iterator()

        Provides an iterator over the result-set that does not cache the result
        rows. Use this for iterating over large result sets, or result sets
        that only need to be iterated over once.

        Example:

        .. code-block:: python

            # Query will return a large number of rows.
            query = PageView.select(PageView.url, PageView.timestamp)
            for row in query.execute(db).iterator():
                report.write((row.url, row.timestamp))

    .. py:method:: first()

        Return the first row or ``None`` if no rows were returned.

    .. py:method:: get()

        Return the first row or raise a ``DoesNotExist`` exception if no rows
        were returned.

        :raises: DoesNotExist

    .. py:method:: scalar()

        Returns the first column of the first row, or raise a ``DoesNotExist``
        if no rows were returned. Useful for retrieving the value of a query
        that performed an aggregation, like a ``COUNT()`` or ``SUM()``.

.. py:class:: DictCursorWrapper

    A subclass of :py:class:`CursorWrapper` that yields result rows as
    dictionaries.

.. py:class:: NamedTupleCursorWrapper

    A subclass of :py:class:`CursorWrapper` that yields result rows as
    named tuples.

.. py:class:: ObjectCursorWrapper(cursor, constructor)

    A subclass of :py:class:`CursorWrapper` that accepts a constructor and for
    each result tuple, will call the constructor with the row and yield the
    return value.

    :param constructor: A callable which accepts a row of data and returns an
        arbitrary object.

Database
--------

.. py:class:: Database(database[, pragmas=None[, journal_mode=None[, rank_functions=False[, regex_function=True[, hash_functions=False[, **kwargs]]]]]])

    Wrapper for managing SQLite database connections. Handles connections in a
    thread-safe manner and provides Pythonic APIs for managing transactions,
    executing queries, and introspecting database internals.

    :param database: The filename of the SQLite database, or the string
        ``':memory:'`` for an in-memory database. To defer the initialization
        of the database, you can also specify ``None``.
    :param pragmas: A list of 2-tuples describing the pragma key and value to
        be applied when a connection is opened.
    :param journal_mode: Journaling mode to use with SQLite database.
    :param bool rank_functions: Whether to register user-defined functions for
        scoring search results. For use with full-text-search extension.
    :param bool regex_function: Whether to register a user-defined function to
        provide support for the ``REGEXP`` operator.
    :param bool hash_functions: Whether to register cryptographic hash
        functions.
    :param kwargs: Arbitrary keyword arguments passed to the ``sqlite3``
        connection constructor.

    .. py:method:: init(database, **connect_kwargs)

        This method is used to initialize a deferred database. A database is
        said to be deferred when it is instantiated with the database file as
        ``None``. Reasons you might do this are to declare the database in one
        place, and actually assign it to a given file elsewhere in the code
        (e.g. for running tests).

        :param database: The filename of the SQLite database, or the string
            ``':memory:'`` for an in-memory database.
        :param connect_kwargs: Arbitrary keyword arguments passed to the
            ``sqlite3`` connection constructor.

    .. py:method:: connect([reuse_if_open=False])

        Open a connection to the SQLite database. If a connection already
        exists for the current thread, an ``OperationalError`` will be raised.
        Alternatively, you can specify ``reuse_if_open`` to suppress the error
        in the event a connection is already open.

        :param bool reuse_if_open: If a connection already exists, re-use it
            rather than raising an exception.
        :raises OperationalError:
        :rtype bool:
        :returns: Boolean value indicating whether a connection was opened.
            Will always be ``True`` unless ``reuse_if_open`` was specified and
            a connection already existed.

    .. py:method:: close()

        Close the current thread's connection. If no connection is currently
        open, no exception will be raised.

        :rtype bool:
        :returns: Boolean indicating whether a connection was closed.

    .. py:method:: aggregate([name=None])

        Decorator for declaring and registering a user-defined aggregate
        function.

        Example:

        .. code-block:: python

            @db.aggregate('avg')
            class Average(object):
                def __init__(self):
                    self.vals = []

                def step(self, value):
                    self.vals.append(value)

                def finalize(self):
                    return sum(self.vals) / len(self.vals)

    .. py: method:: collation([name=None])

        Decorator for declaring and registering a user-defined collation.
        Collations define the ordering for a set of values.

        Example:

        .. code-block:: python

            @db.collation('numeric')
            def numeric(lhs, rhs):
                # Sort strings with numbers in them.
                l1 = [int(t) if t.isdigit() else t
                      for t in re.split('(\d+)', lhs)]
                l2 = [int(t) if t.isdigit() else t
                      for t in re.split('(\d+)', lhs)]
                return cmp(l1, l2)

    .. py:method:: func([name=None[, n=-1[, deterministic=True]]])

        Decorator for declaring and registering a user-defined function.
        User-defined functions accept up to ``n`` parameters and return a
        scalar value. If ``n`` is not fixed, you may specify ``-1``.

        :param str name: Name of the function.
        :param int n: Number of parameters function accepts, or ``-1``.
        :param bool deterministic: Function is deterministic.

        Example:

        .. code-block:: python

            @db.func('md5')
            def md5(s):
                return hashlib.md5(s).hexdigest()

    .. py:method:: table_function([name=None])

        Decorator for declaring and registering a table-valued function with
        the database. Table-valued functions are described in the section on
        :py:class:`TableFunction`, but briefly, a table-valued function accepts
        any number of parameters, and instead of returning a scalar value,
        returns any number of rows of tabular data.

        Example:

        .. code-block:: python

            @db.table_function('series')
            class Series(TableFunction):
                columns = ['value']
                params = ['start', 'stop']

                def initialize(self, start=0, stop=None):
                    self.start, self.stop = start, (stop or float('Inf'))
                    self.current = self.start

                def iterate(self, idx):
                    if self.current > self.stop:
                        raise StopIteration
                    ret = self.current
                    self.current += 1
                    return (ret,)

    .. py:method:: on_commit(func)

        Decorator for declaring and registering a post-commit hook. The
        handler's return value is ignored, but if a ``ValueError`` is raised,
        then the transaction will be rolled-back.

        The decorated function should not accept any parameters.

        Example:

        .. code-block:: python

            @db.on_commit
            def commit_handler():
                if datetime.date.today().weekday() == 6:
                    raise ValueError('no commits on sunday!')

    .. py:method:: on_rollback(func)

        Decorator for registering a rollback handler. The return value is
        ignored.

        The decorated function should not accept any parameters.

        Example:

        .. code-block:: python

            @db.on_rollback
            def rollback_handler():
                logger.info('rollback was issued.')

    .. py:method:: on_update(func)

        Decorator for registering an update hook. The decorated function is
        executed for each row that is inserted, updated or deleted. The return
        value is ignored.

        User-defined callback must accept the following parameters:

        * query type (INSERT, UPDATE or DELETE)
        * database name (typically 'main')
        * table name
        * rowid of affected row

        Example:

        .. code-block:: python

            @db.on_update
            def change_logger(query_type, db, table, rowid):
                logger.debug('%s query on %s.%s row %s', query_type, db,
                             table, rowid)

    .. py:method:: is_closed()

        Return a boolean indicating whether the database is closed.

    .. py:method:: connection()

        Get the currently open connection. If the database is closed, then a
        new connection will be opened and returned.

    .. py:method:: execute_sql(sql[, params=None[, commit=True]])

        Execute the given SQL query and returns the cursor. If no connection is
        currently open, one will be opened automatically.

        :param sql: SQL query
        :param params: A list or tuple of parameters for the query.
        :param bool commit: Whether a ``commit`` should be invoked after the
            query is executed.
        :returns: A ``sqlite3.Cursor`` instance.

    .. py:method:: execute(query)

        Execute the SQL query represented by the :py:class:`Query` object. The
        query will be parsed into a parameterized SQL query automatically.

        :param Query query: The :py:class:`Query` instance to execute.
        :returns: A ``sqlite3.Cursor`` instance.

    .. py:method:: pragma(key[, value=SENTINEL])

        Issue a PRAGMA query on the current connection. To query the status of
        a specific PRAGMA, typically only the ``key`` will be specified.

        For more information, see the `SQLite PRAGMA docs <http://sqlite.org/pragma.html>`_.

        .. note::
            Many ``PRAGMA`` settings are exposed as properties on the
            :py:class:`Database` object.

    .. py:method:: add_pragma(key, value)

        Apply the specified pragma query each time a new connection is opened.
        If a connection is currently open, the pragma will be executed.

    .. py:method:: remove_pragma(key)

        Remove the pragma operation specified by the given key from the list of
        pragma queries executed on each new connection.

    .. py:method:: begin([lock_type=None])

        Start a transaction using the specified lock type. If the lock type is
        unspecified, then a bare ``BEGIN`` statement is issued.

        Because swee'pea runs ``sqlite3`` in autocommit mode, it is necessary
        to explicitly begin transactions using this method.

        For an alternative API, see the :py:meth:`~Database.atomic` helper.

    .. py:method:: commit()

        Call ``commit()`` on the currently-open ``sqlite3.Connection`` object.

    .. py:method:: rollback()

        Call ``rollback()`` on the currently-open ``sqlite3.Connection`` object.

    .. py:method:: __getitem__(name)

        Factory method for creating :py:class:`BoundTable` instances.

        Example:

        .. code-block:: python

            UserTbl = db['users']
            query = UserTbl.select(UserTbl.c.username)
            for username, in query.execute():
                print username

    .. py:method:: __enter__()

        Use the database as a context-manager. When the context manager is
        entered, a connection is opened (if one is not already open) and a
        transaction begins. When the context manager exits, the transaction is
        either committed or rolled-back (depending on whether the context
        manager exits with an exception). Finally, the connection is closed.

        Example:

        .. code-block:: python

            with database:
                database.execute_sql('CREATE TABLE foo (data TEXT)')
                FooTbl = database['foo']
                for i in range(10):
                    FooTbl.insert({FooTbl.c.data: str(i)}).execute()

    .. py:method:: last_insert_rowid()

        Return the ``rowid`` of the most-recently-inserted row on the currently
        active connection.

    .. py:method:: changes()

        Return the number of rows changed by the most recent query.

    .. py:attribute:: autocommit

        A property which indicates whether the connection is in autocommit mode
        or not.

    .. py:method:: set_busy_handler([timeout=5000])

        Replace the default SQLite busy handler with one that introduces some
        *jitter* into the amount of time delayed between checks. This addresses
        an issue that frequently occurs when multiple threads are attempting to
        modify data at nearly the same time.

        :param timeout: Max number of milliseconds to attempt to execute query.

    .. py:method:: atomic()

        Context manager or decorator that executes the wrapped statements in
        either a transaction or a savepoint. The outer-most call to ``atomic``
        will use a transaction, and any subsequent nested calls will use
        savepoints.

        .. note::
            For most use-cases, it makes the most sense to always use
            ``atomic`` when you wish to execute queries in a transaction.
            The benefit of using ``atomic`` is that you do not need to
            manually keep track of the transaction stack depth, as this will
            be managed for you.

    .. py:method:: transaction()

        Execute statements in a transaction using either a context manager or
        decorator. If an error is raised inside the wrapped block, the
        transaction will be rolled back, otherwise statements are committed
        when exiting. Transactions can also be explicitly rolled back or
        committed within the transaction block by calling
        :py:meth:`~transaction.rollback` or :py:meth:`~transaction.commit`.
        If you manually commit or roll back, a new transaction will be started
        automatically.

        Nested blocks can be wrapped with ``transaction`` - the database
        will keep a stack and only commit when it reaches the end of the outermost
        function / block.

    .. py:method:: savepoint()

        Execute statements in a savepoint using either a context manager or
        decorator. If an error is raised inside the wrapped block, the
        savepoint will be rolled back, otherwise statements are committed when
        exiting. Like :py:meth:`~Database.transaction`, a savepoint can also
        be explicitly rolled-back or committed by calling
        :py:meth:`~savepoint.rollback` or :py:meth:`~savepoint.commit`. If you
        manually commit or roll back, a new savepoint **will not** be created.

        Savepoints can be thought of as nested transactions.

        :param str sid: An optional string identifier for the savepoint.

    .. py:method:: get_tables()

        Return a sorted list of the tables in the database.

    .. py:method:: get_indexes(table)

        Returns a list of index metadata for the given table. The index
        metadata is returned as a 4-tuple consisting of:

        * Index name.
        * SQL used to create the index.
        * Names of columns being indexed.
        * Whether the index is unique.

    .. py:method:: get_columns(table)

        Returns a list of column metadata for the given table. Column
        metadata is returned as a 4-tuple consisting of:

        * Column name.
        * Data-type column was declared with.
        * Whether the column can be NULL.
        * Whether the column is the primary key.

    .. py:method:: get_primary_keys(table)

        Returns a list of column(s) that comprise the table's primary key.

    .. py:method:: get_foreign_keys(table)

        Returns a list of foreign key metadata for the given table. Foreign
        key metadata is returned as a 3-tuple consisting of:

        * Source column name, i.e. the column on the given table.
        * Destination table.
        * Destination column.

    .. py:method:: backup(dest_db)

        Backup the current database to the given destination
        :py:class:`Database` instance.

        :param Database dest_db: database to hold backup.

    .. py:method:: backup_to_file(filename)

        Backup the current database to the given filename.

    .. py:attribute:: cache_size

        Property that exposes ``PRAGMA cache_size``.

    .. py:attribute:: foreign_keys

        Property that exposes ``PRAGMA foreign_keys``.

    .. py:attribute:: journal_mode

        Property that exposes ``PRAGMA journal_mode``.

    .. py:attribute:: journal_size_limit

        Property that exposes ``PRAGMA journal_size_limit``.

    .. py:attribute:: mmap_size

        Property that exposes ``PRAGMA mmap_size``.

    .. py:attribute:: page_size

        Property that exposes ``PRAGMA page_size``

    .. py:attribute:: read_uncommited

        Property that exposes ``PRAGMA read_uncommited``

    .. py:attribute:: synchronous

        Property that exposes ``PRAGMA synchronous``

    .. py:attribute:: wal_autocheckpoint

        Property that exposes ``PRAGMA wal_autocheckpoint``

SQL Builder
-----------

.. py:class:: Table(name[, columns=None[, schema=None[, alias=None]]])

    Represents a table in a SQL query. Tables can be initialized with a static
    list of columns, or columns can be referenced dynamically using the ``c``
    attribute.

    Example:

    .. code-block:: python

        # Example using a static list of columns:
        UserTbl = Table('users', ('id', 'username'))
        query = (UserTbl
                 .select()  # "id" and "username" automatically selected.
                 .order_by(UserTbl.username))

        # Using dynamic columns:
        TweetTbl = Table('tweets')
        query = (TweetTbl
                 .select(TweetTbl.c.content, TweetTbl.c.timestamp)
                 .join(UserTbl, on=(TweetTbl.c.user_id == UserTbl.id))
                 .where(UserTbl.username == 'charlie')
                 .order_by(TweetTbl.c.timestamp.desc()))

    .. py:method:: bind(database)

        Create a table reference that is bound to the given database. Returns
        a :py:class:`BoundTable` instance.

    .. py:method:: select(*selection)

        Create a :py:class:`Select` query from the given table. If the
        ``selection`` is not provided, and the table defines a static list of
        columns, then the selection will default to all defined columns.

        :param selection: values to select.
        :returns: a :py:class:`Select` query instance.

    .. py:method:: insert([data=None[, columns=None[, on_conflict=None[, **kwargs]]]])

        Create a :py:class:`Insert` query into the given table. Data to be
        inserted can be provided in a number of different formats:

        * a dictionary of table columns to values
        * keyword arguments of column names to values
        * a list/tuple/iterable of dictionaries
        * a :py:class:`Select` query instance.

        .. note::
            When providing a :py:class:`Select` query, it is necessary to also
            provide a list of columns.

            It is also advisable to provide a list of columns when supplying a
            list or iterable of rows to insert.

        Simple insert example:

        .. code-block:: python

            User = Table('users', ('id', 'username', 'is_admin'))

            # Simple inserts.
            query = User.insert({User.username: 'huey', User.is_admin: False})

            # Equivalent to above.
            query = User.insert(username='huey', is_admin=False)

        Inserting multiple rows:

        .. code-block:: python

            # Inserting multiple rows of data.
            data = (
                {User.username: 'huey', User.is_admin: False},
                {User.username: 'mickey', User.is_admin: True})
            query = User.insert(data)

            # Equivalent to above
            query = User.insert(data, columns=(User.username, User.is_admin))

        Inserting using a SELECT query:

        .. code-block:: python

            Person = Table('person', ('id', 'name'))

            query = User.insert(
                Person.select(Person.name, False),
                columns=(User.username, User.is_admin))

            # Results in:
            # INSERT INTO "users" ("username", "is_admin")
            # SELECT "person"."name", false FROM "person";

    .. py:method:: update([data=None[, on_conflict=None[, **kwargs]]])

        Create a :py:class:`Update` query for the given table. Update can be
        provided as a dictionary keyed by column, or using keyword arguments.

        Examples:

        .. code-block:: python

            User = Table('users', ('id', 'username', 'is_admin'))

            query = (User
                     .update({User.is_admin: False})
                     .where(User.username == 'huey'))

            # Equivalent to above:
            query = User.update(is_admin=False).where(User.username == 'huey')

        Example of an atomic update:

        .. code-block:: python

            PageView = Table('pageviews', ('url', 'view_count'))

            query = (PageView
                     .update({PageView.view_count: PageView.view_count + 1})
                     .where(PageView.url == some_url))

    .. py:method:: delete()

        Create a :py:class:`Delete` query for the given table.

        Example:

        .. code-block:: python

            query = User.delete().where(User.c.account_expired == True)

    .. py:method:: filter(**kwargs)

        Perform a :py:class:`Select` query, filtering the result set using
        keyword arguments to represent filter expressions. All expressions are
        combined using ``AND``.

        This method is provided as a convenience API.

        Example:

        .. code-block:: python

            Person = Table('person', ('id', 'name', 'dob'))

            today = datetime.date.today()
            eighteen_years_ago = today - datetime.timedelta(years=18)
            adults = Person.filter(dob__gte=eighteen_years_ago)

    .. py:method:: rank()

        Convenience method for representing an expression which calculates the
        rank of search results.

        Example:

        .. code-block:: python

            NoteIdx = Table('note_idx', ('docid', 'content'))
            rank = NoteIdx.rank()
            query = (NoteIdx
                     .select(NoteIdx.docid, NoteIdx.content, rank.alias('score'))
                     .where(NoteIdx.match('search query'))
                     .order_by(rank)
                     .namedtuples())

            for search_result in query.execute(database):
                print search_result.score, search_result.content

    .. py:method:: bm25()

        Convenience method for representing an expression which calculates the
        rank of search results using the BM25 algorithm. Usage is identical to
        :py:meth:`~Table.rank`.

    .. py:method:: match(search_term)

        Convenience method for generating an expression that corresponds to a
        search on a full-text search virtual table. For an example of usage,
        see :py:meth:`~Table.rank`.

.. py:class:: BoundTable(database, name[, columns=None[, schema=None[, alias=None]]])

    Identical to :py:class:`Table` with the exception that any queries on the
    table will automatically be bound to the provided database.

    With an ordinary :py:class:`Table` object, you would write the following:

    .. code-block:: python

        User = Table('users', ('id', 'username'))
        query = User.select().namedtuples()
        for user in query.execute(database):
            print user.username

    With a bound table, you can instead write:

    .. code-block:: python

        BoundUser = User.bind(database)
        query = User.select().namedtuples()
        for user in query.execute():
            print user.username

        # Or, even simpler, since bound select queries implement __iter__:
        for user in query:
            print user.username


text:
#include "native_client/src/trusted/nonnacl_util/sel_ldr_launcher.h"

#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"

namespace nacl {

SelLdrLauncherBase::SelLdrLauncherBase()
  : channel_(NACL_INVALID_HANDLE),
    bootstrap_socket_(NULL),
    secure_socket_addr_(NULL),
    socket_addr_(NULL) {
}

SelLdrLauncherBase::~SelLdrLauncherBase() {
  if (NACL_INVALID_HANDLE != channel_) {
    NaClClose(channel_);
  }
}

bool SelLdrLauncherBase::ConnectBootstrapSocket() {
  CHECK(factory_ == NULL);
  factory_.reset(new DescWrapperFactory);
  CHECK(channel_ != NACL_INVALID_HANDLE);
  bootstrap_socket_.reset(factory_->MakeImcSock(channel_));
  if (bootstrap_socket_ == NULL) {
    return false;
  }
  // bootstrap_socket_ now has ownership of channel_, so we get rid of
  // our "reference" to it.
  channel_ = NACL_INVALID_HANDLE;

  return true;
}

bool SelLdrLauncherBase::RetrieveSockAddr() {
  DescWrapper::MsgHeader   header;
  DescWrapper::MsgIoVec    iovec[1];
  DescWrapper*             descs[NACL_ABI_IMC_USER_DESC_MAX];
  scoped_array<unsigned char> bytes(
      new unsigned char[NACL_ABI_IMC_USER_BYTES_MAX]);
  if (bytes.get() == NULL) {
    return false;
  }

  // Set up to receive a message.
  iovec[0].base = bytes.get();
  iovec[0].length = NACL_ABI_IMC_USER_BYTES_MAX;
  header.iov = iovec;
  header.iov_length = NACL_ARRAY_SIZE(iovec);
  header.ndescv = descs;
  header.ndescv_length = NACL_ARRAY_SIZE(descs);
  header.flags = 0;
  // Receive the message.
  ssize_t received = bootstrap_socket_->RecvMsg(&header, 0, NULL);
  if (0 != received) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::RetrieveSockAddr: "
            "RecvMsg() returned %d\n", static_cast<int>(received));
    return false;
  }
  // Check that there were exactly two descriptors passed.
  if (2 != header.ndescv_length) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::RetrieveSockAddr: "
            "got desc count %d, expected 2\n",
            static_cast<int>(header.ndescv_length));
    return false;
  }
  secure_socket_addr_.reset(descs[0]);
  socket_addr_.reset(descs[1]);

  return true;
}

bool SelLdrLauncherBase::SetupCommand(NaClSrpcChannel* command) {
  // Get the bootstrap socket.
  if (!ConnectBootstrapSocket()) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::SetupCommand: "
            "getting bootstrap socket failed\n");
    return false;
  }
  // Get the socket address from the descriptor.
  if (!RetrieveSockAddr()) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::SetupCommand: "
            "getting sel_ldr socket address failed\n");
    return false;
  }
  // Connect to the trusted command channel.
  scoped_ptr<DescWrapper> command_desc(secure_socket_addr_->Connect());
  if (command_desc == NULL) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::SetupCommand: Connect() failed\n");
    return false;
  }
  // Start the SRPC client to communicate with the trusted command channel.
  // SRPC client takes an additional reference to command_desc.
  if (!NaClSrpcClientCtor(command, command_desc->desc())) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::SetupCommand: "
            "NaClSrpcClientCtor failed\n");
    return false;
  }
  return true;
}

bool SelLdrLauncherBase::LoadModule(NaClSrpcChannel* command,
                                    DescWrapper* nexe) {
  // TODO(sehr): This argument to load_module is unused.  Remove it.
  static const char kLoadModulePlaceHolderString[] = "place holder";

  CHECK(nexe != NULL);
  // Load module over command channel.
  NaClSrpcResultCodes rpc_result =
      NaClSrpcInvokeBySignature(command,
                                "load_module:hs:",
                                nexe->desc(),
                                kLoadModulePlaceHolderString);
  if (NACL_SRPC_RESULT_OK != rpc_result) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::LoadModule: "
            "rpc_result=%d is not successful\n",
            static_cast<int>(rpc_result));
    NaClSrpcDtor(command);
    return false;
  }
  return true;
}

bool SelLdrLauncherBase::SetupCommandAndLoad(NaClSrpcChannel* command,
                                             DescWrapper* nexe) {
  if (!SetupCommand(command)) {
    return false;
  }
  if (nexe != NULL) {
    if (!LoadModule(command, nexe)) {
      return false;
    }
  }
  return true;
}

bool SelLdrLauncherBase::StartModule(NaClSrpcChannel* command) {
  // Start untrusted code module.
  int start_result;
  NaClSrpcResultCodes rpc_result = NaClSrpcInvokeBySignature(command,
                                                             "start_module::i",
                                                             &start_result);
  NaClLog(4, "SelLdrLauncher::StartModule rpc result %d\n",
          static_cast<int>(rpc_result));
  if (NACL_SRPC_RESULT_OK != rpc_result || LOAD_OK != start_result) {
    NaClSrpcDtor(command);
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::StartModule: "
            "start_module failed: rpc_result=%d, start_result=%d (%s)\n",
            static_cast<int>(rpc_result), start_result,
            NaClErrorString(static_cast<NaClErrorCode>(start_result)));
    return false;
  }
  return true;
}

bool SelLdrLauncherBase::SetupAppChannel(NaClSrpcChannel* out_app_chan) {
  // Connect to the untrusted service itself.
  scoped_ptr<DescWrapper> untrusted_desc(socket_addr_->Connect());
  if (untrusted_desc == NULL) {
    NaClLog(LOG_ERROR, "SelLdrLauncher::StartModuleAndSetupAppChannel: "
            "Connect failed\n");
    return false;
  }
  // Start the SRPC client to communicate with the untrusted service
  // SRPC client takes an additional reference to untrusted_desc.
  if (!NaClSrpcClientCtor(out_app_chan, untrusted_desc->desc())) {
    NaClLog(LOG_ERROR, "SelLdrLauncherBase::SetupAppChannel: "
            "NaClSrpcClientCtor failed\n");
    return false;
  }
  return true;
}

// Sends the SRPC to start the nexe over |command| and sets up the application
// SRPC chanel |out_app_chan|.
bool SelLdrLauncherBase::StartModuleAndSetupAppChannel(
    NaClSrpcChannel* command,
    NaClSrpcChannel* out_app_chan) {
  if (!StartModule(command)) {
    return false;
  }
  if (!SetupAppChannel(out_app_chan)) {
    return false;
  }
  return true;
}

DescWrapper* SelLdrLauncherBase::Wrap(NaClDesc* raw_desc) {
  CHECK(factory_ != NULL);
  return factory_->MakeGeneric(raw_desc);
}

DescWrapper* SelLdrLauncherBase::WrapCleanup(NaClDesc* raw_desc) {
  CHECK(factory_ != NULL);
  return factory_->MakeGenericCleanup(raw_desc);
}

nacl::string SelLdrLauncherBase::GetCrashLogOutput() {
  DescWrapper::MsgHeader hdr;
  DescWrapper::MsgIoVec iov;
  char msg_buf[1024];
  ssize_t nbytes = 0;

  iov.base = msg_buf;
  iov.length = sizeof msg_buf;
  hdr.iov = &iov;
  hdr.iov_length = 1;
  hdr.ndescv = NULL;
  hdr.ndescv_length = 0;
  hdr.flags = 0;
  if (NULL != bootstrap_socket_.get()) {
    nbytes = bootstrap_socket_->RecvMsg(&hdr, 0, NULL);
  }
  if (nbytes > 0) {
    return nacl::string(msg_buf, nbytes);
  }
  return "";
}

}  // namespace nacl

redpajama_set_name: RedPajamaGithub


text:
import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
import getType from "jest-get-type";

export const toBeType = (received, expected) => {
	const type = getType(received);
	const pass = type === expected;
	const message = pass
		? () =>
			matcherHint('.not.toBeType', 'value', 'type') +
			'\n\n' +
			`Expected value to be of type:\n` +
			`  ${printExpected(expected)}\n` +
			`Received:\n` +
			`  ${printReceived(received)}\n`
		: () =>
			matcherHint('.toBeType', 'value', 'type') +
			'\n\n' +
			`Expected value to be of type:\n` +
			`  ${printExpected(expected)}\n` +
			`Received:\n` +
			`  ${printReceived(received)}\n` +
			`type:\n` +
			`  ${printReceived(type)}`;

	return { pass, message }
};

const wrapped = {
	toBeType
};

export const extend = (expect) => {
	expect.extend(wrapped);
};

export default wrapped;


text:
#ifndef _TETMESHEMBEDING_H_
#define _TETMESHEMBEDING_H_

#include <TetMesh.h>
#include <Objmesh.h>

namespace UTILITY{

  class TetMeshEmbeding{

  public:
	TetMeshEmbeding();
	TetMeshEmbeding(pTetMesh tetMesh,pObjmesh objMesh);
	void setTetMesh(pTetMesh tetMesh);
	void setObjmesh(pObjmesh objMesh);

	pTetMesh getTetMesh();
	pObjmesh getObjMesh();
	pTetMesh_const getTetMesh()const;
	pObjmesh_const getObjMesh()const;

	void buildInterpWeights();
	void interpolate(const VectorXd& u);

	bool loadObjMesh(const string filename);
	bool loadTetMesh(const string filename);

	bool loadWeights(const string fname);
	bool writeWeights(const string fname)const;

	void getBBox(double min[3],double max[3])const;
	double getMaxRadius()const;

	const vector<int> &getInterpNodes()const;
	const VectorXd &getInterpWeights()const;

  private:
	pTetMesh _tetMesh;
	pObjmesh _objMesh;
	VectorXd _objRestVerts;

	vector<int> _nodes;
	VectorXd _weights;

	VectorXd _uTarget;
  };

  typedef boost::shared_ptr<TetMeshEmbeding> pTetMeshEmbeding;
  typedef boost::shared_ptr<const TetMeshEmbeding> pTetMeshEmbeding_const;

}//end of namespace

#endif /* _TETMESHEMBEDING_H_ */


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.sling.ide</groupId>
    <artifactId>reactor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>org.apache.sling.ide.api-test</artifactId>
  <name>Sling IDE Tools: API Tests</name>
  <dependencies>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>org.apache.sling.ide</groupId>
          <artifactId>org.apache.sling.ide.api</artifactId>
          <version>${project.version}</version>
          <type>eclipse-plugin</type>
      </dependency>
  </dependencies>
</project>


text:
Word patterns are enclosed in single quotes (') and are represented using a regex. Non-capitalized words are variables. Constants are still capitalized.

### `!`
- dstack: `( w addr -- )`
- Writes `w` to the address `addr`.

### `'`
- dstack: `( -- xt )`
- pattern: `'^ ([^ ]*)(?: |$)'`
- Places the execution token of the word found on the stack, if not found returns `0`.
  - An execution token will never be `0`.
- Also sets the carry bit to `1` if the instruction is immediate.

### `(compile)`
- pattern: `'^ ([^ ]*)(?: |$)'`
- Consumes a word and compiles it into the current definition.
- Skips the word currently being written when searching for words so the word can reference previous definitions.

### `(run)`
- pattern: `'^ ([^ ]*)(?: |$)'`
- Consumes a word and immediately executes it.

### `*`
- dstack: `( a b -- a*b )`

### `*/`
- dstack: `( a b c -- a*b/c )`

### `*/MOD`
- dstack: `( a b c -- a*b%c a*b/c )`

### `+`
- dstack: `( a b -- a+b )`

### `+!`
- dstack: `( a addr -- )`
- Adds `a` to word at address `addr`.

### `,`
- dstack: `( w -- )`
- Writes and allocates a single processor word to the data space of the most recently created word.

### `-`
- dstack: `( a b -- a-b )`

### `.`
- dstack: `( w -- )`
- Print a signed number `w` using the base specified in `BASE`.

### `."`
- Compile:
  - Pattern: `'^ ([^ ]*)"'`
  - Appends the run semantics to the current word.
- Run:
  - Prints out the string pattern.

### `/`
- dstack: `( a b -- a/b )`

### `/MOD`
- dstack: `( a b -- a%b a/b )`

### `0<`
- dstack: `( a -- bool )`
- Puts a `1` on the stack if `a < 0` (signed comparison), `0` otherwise.

### `0=`
- dstack: `( a -- bool )`
- Puts a `1` on the stack if `a == 0`, `0` otherwise.

### `1+`
- dstack: `( a -- a+1 )`

### `1-`
- dstack: `( a -- a-1 )`

### `2*`
- dstack: `( a -- a*2 )`

### `2/`
- dstack: `( a -- a/2 )`

### `:`
- Compile-time pattern: `'^ ([^ ]*)(?: |$)'`
- Creates a new unfinished word entry in the dictionary with the name matched by the capture group in the pattern.
- Enters compilation mode.

### `;`
- Finish the definition of this word and insert an `EXIT`.

### `<`
- dstack: `( a b -- bool )`
- Puts a `1` on the stack if `a` is less than `b`, `0` otherwise.

### `<=`
- dstack: `( a b -- bool )`
- Puts a `1` on the stack if `a` is less than or equal to `b`, `0` otherwise.

### `=`
- dstack: `( a b -- bool )`
- Puts a `1` on the stack if `a` and `b` are equal, `0` otherwise.

### `>`
- dstack: `( a b -- bool )`
- Puts a `1` on the stack if `a` is greater than `b`, `0` otherwise.

### `>`
- dstack: `( a b -- bool )`
- Puts a `1` on the stack if `a` is greater than or equal to `b`, `0` otherwise.

### `@`
- dstack: `( addr -- w )`
- Reads `w` from the address `addr`.

### `ABORT`
- dstack: `( -- )`
- Has the same functionality as `QUIT` in UFORTH.

### `ABORT"`
- pattern: `'^ ([^ ]*)"'`
- Compiles the specified message into the current word and prints it along with executing `QUIT`.

### `ABS`
- dstack: `( a -- abs(a) )`
- Computes the absolute value of `a`.

### `ACCEPT`
- dstack: `( n addr1 -- addr2 )`
- Writes characters from the input up to `n` characters at address `addr1`, `addr2` is the address following the last character written.

### `ALLOT`
- dstack: `( w -- )`
- Allocates, but does not initialize, `w` total processor words to the data space of the most recently created word.

### `AND`
- dstack: `( a b -- a&b )`

### `base`
- dstack: `( -- addr )`
- Retrieves the address to the base that numbers should be interpreted with using `NUMBER`.

### `BL`
- dstack: `( -- ' ' )`
- Adds the character for space/blank to the stack.

### `BODY`
- dstack: `( -- addr )`
- Retrieves the address of the data space of the most recently completed word.

### `BS`
- dstack: `( -- '\b' )`
- Adds the character for backspace to the stack.

### `COMPILE,`
- dstack: `( xt -- )`
- Adds a call to the execution token `xt` directly into the current word.

### `CONSTATNT`
- Compile:
  - dstack: `( n -- )`
  - pattern: `'^ ([^ ]*)(?: |$)'`
    - The matched pattern becomes the name of the word.
- Run:
  - dstack: `( -- n )`

### `CONTINUE`
- Continues a loop on the next iteration from the beginning.

### `COPY:`
- dstack: `( w .. - w .. w )`
- Aquires the next number using `NUMBER` and compiles an immediate stack copy to the top from a specific depth.

### `COUNT`
- dstack: `( addr1 - addr2 n )`
- Retrieves the character count from the string in memory at `addr1`, placing the character pointer `addr2` and the number of characters `n` on the stack.

### `CR`
- dstack: `( -- )`
- Sends a newline to the terminal.

### `CREATE`
- pattern: `'^ ([^ ]*)(?: |$)'`
- Creates a new word entry with the name given by the pattern.
- The only thing this changes internally is that the dictionary entry values are set.

### `DECIMAL`
- dstack: `( -- )`
- Sets `base` to `10`.

### `DEFERO`
- dstack: `( o -- )`
- Adds an octet `o` to the word currently being built.

### `DEFERS`
- dstack: `( s -- )`
- Adds a short (two octets) `s` to the word currently being built.

### `DEFERW`
- dstack: `( w -- )`
- Adds a processor word `w` to the word currently being built.

### `DIGIT`
- dstack: `( w -- )`
- Takes a processor word `w` and emits the character for a single digit based on the base.

### `DO`
- Compile:
  - dstack: `( -- paddr )`
  - Places the program address `paddr` onto the stack to place `pc - paddr - 3` at `LOOP`.
- Run:
  - dstack: `( n -- )`
  - Begins a loop which will execute `n` times.

### `DOES`
- Compile:
  - Ends compilation of this word, but begins compilation of a program to override the most recent word with.
- Run:
  - Sets the word currently being built to have the program specified after `DOES`.
- Execution:
  - dstack: `( -- )`

### `DOES>`
- Compile:
  - Same functionality as `DOES`.
- Run:
  - Same functionality as `DOES`.
- Execution:
  - dstack: `( -- addr )`
  - Same as `DOES`, but also places the data space address `addr` of the word on the stack.

### `DROP`
- dstack: `( w -- )`

### `DUP`
- dstack: `( w -- w w )`

### `DWORD`
- dstack: `( addr c - n )`
- Counts the amount of characters until the delimiter `c` is found at `addr` and adds it to the stack.

### `ELSE`
- Compile:
  - dstack: `( paddr1 -- paddr2 )`
  - Writes `pc - paddr1` to `paddr1` and creates a new `paddr2` for the invocation of `THEN` to write to.
- Run:
  - Specifies the location to go to in an `IF` statement if the condition is false.

### `EMIT`
- dstack: `( c -- )`
- Print the character c on the terminal.
  - This can control the terminal using the backspace and newline characters.

### `EXECUTE`
- dstack: `( .. xt -- .. )`
- Executes an execution token.

### `EXIT`
- Returns from the current word.

### `FALSE`
- dstack: `( -- false )`
- Places a `0` on the stack.

### `FILL`
- dstack: `( u w addr -- )`
- Fill the location at address `addr` with `u` number of the processor word `w`.

### `FIND`
- dstack: `( addr n -- xt )`
- Find the WORD with the string at `addr` with length `n` and place its execution token, or `0` if not found, on the stack.
  - An execution token will never be `0`.
- Also sets the carry bit to `1` if the instruction is immediate.

### `FORGET`
- pattern: `'^ ([^ ]*)(?: |$)'`
- Forgets everything defined after and including the specified word.

### `HERE`
- dstack: `( -- addr )`
- Places the data space pointer `addr` on the stack.

### `hered`
- dstack: `( -- addr )`
- Provides the address of the data space post-increment stack pointer.

### `herep`
- dstack: `( -- addr )`
- Provides the address of the program memory post-increment stack pointer.

### `hereb`
- dstack: `( -- addr )`
- Provides the address of the dictionary head/beginning pointer (the most recent word that is complete).

### `HEX`
- dstack: `( -- )`
- Sets `base` to `16`.

### `I`
- dstack: `( -- i )`
- Gets inner loop iterator.

### `IDO`
- Run:
  - dstack: `( -- )`
  - Begins an infinite loop which can only be broken out of using `LEAVE`.
- Compile:
  - dstack: `( -- paddr )`
  - Places the program address `paddr` onto the stack to place `pc - paddr - 3` at `LOOP`.

### `IF`
- Same as `IFZ!`.

### `IF=`
- Run:
  - dstack: `( a b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for equal.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IF!=`
- Run:
  - dstack: `( a b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for not equal.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IF>`
- Run:
  - dstack: `( a b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for greater than.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IF>=`
- Run:
  - dstack: `( a b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for greater than or equal to.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IF>U`
- Run:
  - dstack: `( a b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for greater than unsigned.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IF>=U`
- Run:
  - dstack: `( a b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for greater than or equal to unsigned.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFC`
- Run:
  - dstack: `( -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for carry bit set.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFC!`
- Run:
  - dstack: `( -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for not carry bit set.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFO`
- Run:
  - dstack: `( -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for overflow bit set.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFO!`
- Run:
  - dstack: `( -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for not overflow bit set.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFI`
- Run:
  - dstack: `( -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for interrupt bit set.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFI!`
- Run:
  - dstack: `( -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for not interrupt bit set.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFZ`
- Run:
  - dstack: `( a -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for zero.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFZ!`
- Run:
  - dstack: `( a -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for not zero.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFA`
- Run:
  - dstack: `( b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for available interrupt on bus `b`.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IFA!`
- Run:
  - dstack: `( b -- )`
  - Goes to `ELSE` or `THEN` if the condition is not met.
  - Checks for no available interrupt on bus `b`.
- Compile:
  - dstack: `( -- paddr )`
  - Adds the program address to write the relative address `pc - paddr` to for jumping to the else.

### `IMMEDIATE`
- Makes the most recent word an immediate word, meaning that it is executed even in compile mode.

### `INTERPRET`
- Interprets whatever is at the TIB, processing each word using `shell_xt` until all words are consumed.

### `J`
- dstack: `( -- j )`
- Gets second most inner loop iterator.

### `K`
- dstack: `( -- k )`
- Gets third most inner loop iterator.

### `KEY`
- dstack: `( -- c )`
- Retrieves a key character `c` in ASCII from the input device.

### `KEY?`
- dstack: `( -- bool )`
- If a key is ready to be received by `KEY`, returns `1`, otherwise `0`.

### `L`
- dstack: `( -- l )`
- Gets fourth most inner loop iterator.

### `LEAVE`
- Compile:
  - dstack: `( -- )`
- Run:
  - Breaks out of a loop.

### `LITERAL`
- dstack: `( -- w )`
- Compile-time dstack: `( w -- )`

### `LOOP`
- Compile:
  - dstack: `( addr -- )`
  - Consumes the loop address and terminates the loop definition.
- Run:
  - Repeats the condition of the loop and checks it again.

### `LSHIFT`
- dstack: `( a s -- a<<s )`

### `MAX`
- dstack: `( a b -- c )`
- `c` is the max of `a` or `b`.

### `MIN`
- dstack: `( a b -- c )`
- `c` is the min of `a` or `b`.

### `MOD`
- dstack: `( a b -- a%b )`

### `MOVE`
- dstack: `( n addr1 addr2 -- )`
- Moves `n` processor words from `addr1` to `addr2`.

### `NEGATE`
- dstack: `( a -- -a )`

### `NIP`
- dstack: `( a b -- b )`

### `NL`
- dstack: `( -- '\n' )`
- Adds the character for newline to the stack.

### `NUMBER`
- dstack: `( -- w )`
- Reads a number from the `pp` with the base from `base` or aborts on failure.

### `OR`
- dstack: `( a b -- a|b )`

### `OVER`
- dstack: `( a b -- a b a )`

### `pa`
- dstack: `( -- addr )`
- Places the address `addr` of the input processing address (which is also an address) on the stack.
  - This address points to the beginning of where the input buffer begins.

### `POSTPONE`
- Compile-time pattern: `'^ ([^ ]*)(?: |$)'`
- Append the compilation semantics of the word to the current word's defintion.
- If the word is not found it will abort.

### `pp`
- dstack: `( -- addr )`
- Places the address `addr` of the input processing position (which is also an address) on the stack.

### `QUIT`
- This is called at the beginning of the program and when any fault occurs.
- This soft-resets everything in the processor and returns control to the shell.

### `RECURSE`
- Recursively calls the word currently being built. Must follow a `:` or `CREATE`.

### `REVEAL`
- Reveals and finishes the most recent word, moving `hereb` to its location.

### `ROT`
- dstack: `( a b c - b c a )`

### `ROT:`
- dstack: `( w .. - .. w )`
- Aquires the next number using `NUMBER` and compiles an immediate stack rotate to the top from a specific depth.

### `RSHIFT`
- dstack: `( a b - a>>b )`

### `S"`
- Compile:
  - pattern: `'^ ([^ ]*)"'`
- Run:
  - dstack: `( -- str )`
  - Puts the string address `str` of the string specified at compile-time onto the stack.

### `SCAN`
- dstack: `( c n -- addr )`
- Scans from `pp` out until the character `c` is found, checking up to `n` characters, then returning the address of `c`.
  - If nothing is found returns `0`

### `shell_xt`
- Contains the xt which is used by `INTERPRET` for determining what to do with words.
  - This can be `(compile)` or `(run)`.
    - If it is not either of these, words executed which have different run-time and compile-time operation will choose the run-time option instead.
      - This is a convention that new words that have such behavior should also follow, though it is not necessary for the system to operate correctly.

### `SPACE`
- dstack: `( -- )`
- Displays a space character.

### `SPACES`
- dstack: `( n -- )`
- Displays `n` space characters.

### `STATE`
- dstack: `( -- bool )`
- Places a `1` on the stack if the system is in `(compile)` mode, `0` otherwise.

### `STREQ`
- dstack: `( addr1 n1 addr2 n2 -- bool )`
- Checks if `n1 == n2` and returns `0` if they arent equal, otherwise returns `1` if the strings are equal, `0` otherwise.
- Note: The most efficient way to implement this is with dstack: `( n1 addr1 addr2 n2 -- bool )`
  - This would only save one instruction and, since this is a FORTH kernel, readability is more important.

### `THEN`
- Compile:
  - dstack: `( paddr -- )`
- Run:
  - Signifies the location which an if statement ends at.

### `TRUE`
- dstack: `( -- true )`
- Places a `1` on the stack.

### `TUCK`
- dstack: `( a b -- b a b )`

### `TYPE`
- dstack: `( addr n -- )`
- Types `n` characters from `addr` to the terminal.
  - Control characters may interface with the terminal.

### `U.`
- dstack: `( w -- )`
- Print an unsigned number `w` using the base specified in `BASE`.

### `U<`
- dstack: `( a b -- bool )`
- If the unsigned compaison of `a < b` is true, add a `1` to the stack, `0` otherwise.

### `U*`
- dstack: `( a b -- a*b )`
- Unsigned multiplication of `a` and `b`.

### `UNLOOP`
- dstack: `( -- )`
- Discards the innermost loop parameters to return, jump, or branch out of the loop.

### `VARIABLE`
- Run:
  - dstack: `( -- )`
  - pattern: `'^ ([^ ]*)(?: |$)'`
  - Creates a new word with the pattern.
- Execution:
  - dstack: `( -- addr )`
  - Places the unique address `addr` of the variable on the stack.

### `WORD`
- dstack: `( c -- str )`
- pattern: `'^ ([^ ]*)(?: |$)'`
- Takes a character delimiter and places a string from `pp` in the data space at hered, then returns it.

### `WORDS`
- dstack: `( -- )`
- Prints all available words in the dictionary.

### `XOR`
- dstack: `( a b -- a^b )`

### `XT>NAME`
- dstack: `( xt -- str )`
- Consumes an execution token and produces the address to the name of the xt.

### `[`
- Enter into run mode.

### `]`
- Enter into compilation mode.


text:
<?php

namespace Babble\Models;

use ArrayAccess;
use Babble\Content\ContentLoader;
use JsonSerializable;

class TemplateRecord implements ArrayAccess, JsonSerializable
{
    private $record;

    public function __construct(Record $record)
    {
        $this->record = $record;
    }

    public function __toString()
    {
        return json_encode($this->record);
    }

    public function getType()
    {
        return $this->record->getType();
    }

    public function children()
    {
        $model = $this->record->getModel();
        if (!$model->isHierarchical()) return [];

        $loader = new ContentLoader($model);
        return $loader->childrenOf($this->record->getValue('id'));
    }

    private function renderProperty(string $property)
    {
        return $this->record->getModel()->getProperty($property, ['this' => $this]);
    }

    public function field($name): TemplateField
    {
        $field = $this->record->getModel()->getField($name);
        return new TemplateField($field);
    }

    public function offsetExists($offset): bool
    {
        return !!$this->record->getView($offset) || $this->record->getModel()->hasProperty($offset);
    }

    public function offsetGet($offset)
    {
        $result = $this->record->getView($offset);
        if(!$result) $result = $this->renderProperty($offset);

        return $result;
    }

    public function offsetSet($offset, $value)
    {
    }

    public function offsetUnset($offset)
    {
    }

    function jsonSerialize()
    {
        return $this->record;
    }

    public function getAbsoluteURL(): string
    {
        return $this->record->getAbsoluteURL();
    }
}


text:
    val = (zval*)ecalloc(1, sizeof(zval));\
    ZVAL_NULL(val)

#define MAKE_STD_ZVAL(val) \
    if(val != NULL) efree(val); \
    MAKE_PERSISTENT_ZVAL(val)

#define ZVAL_STRING_EX(val, string) \
    ZVAL_STRING(val, string)

#define ZEND_HASH_HAS_MORE_ELEMENTS(ht) \
    zend_hash_has_more_elements(ht)

#define ZEND_HASH_GET_CURRENT_DATA(ht) \
    zend_hash_get_current_data(ht)

#define ZEND_HASH_ADD(ht, key, val) \
    zend_hash_update(ht, zend_string_init(key, sizeof(key) - 1, 0), *val)

#define ZEND_HASH_ADD_U(ht, key, val) \
    { \
        zval *tmp; \
        MAKE_STD_ZVAL(tmp); \
        tmp = val; \
        ZEND_HASH_ADD(ht, key, &tmp); \
    }

#define ZEND_HASH_UPDATE_INDEX(ht, idx, val) \
    zend_hash_index_update(ht, idx, val)

#define INIT_ZOBJECT(class_entry, val) \
     if(val == NULL) { \
        MAKE_STD_ZVAL(val); \
        object_init_ex(val, class_entry); \
     }

#define ZEND_DECLARE_PROPERTY_NULL(class_entry, property, access) \
    zend_declare_property_null(class_entry, property, sizeof(property) - 1, access)

#define ZEND_DECLARE_PROPERTY_DOUBLE(class_entry, property, value, access) \
    zend_declare_property_double(class_entry, property, sizeof(property) - 1, value, access)

#define ZEND_READ_PROPERTY(class_entry, object, property) \
     zend_read_property(class_entry, object, property, sizeof(property) - 1, 1, (zval*)ecalloc(1, sizeof(zval)))

#define ZEND_UPDATE_PROPERTY(class_entry, object, property, value) \
    zend_update_property(class_entry, object, property, sizeof(property) - 1, value);

#define ZEND_UPDATE_PROPERTY_NULL(class_entry, object, property) \
    zend_update_property_null(class_entry, object, property, sizeof(property) - 1);

#define ZEND_UPDATE_PROPERTY_DOUBLE(class_entry, object, property, value) \
    zend_update_property_double(class_entry, object, property, sizeof(property) - 1, value);

#define FLUSH_OBJECT_PROPERTY_ARRAY(class_entry, object, property, buff) \
    INIT_ZOBJECT(class_entry, object); \
    MAKE_PERSISTENT_ZVAL(buff); \
    array_init(buff); \
    zend_update_property(class_entry, object, property, sizeof(property) - 1, buff)

#define FLUSH_OBJECT_PROPERTY_NULL(class_entry, object, property) \
    zend_update_property_null(class_entry, object, property, sizeof(property) - 1); \
    { \
        zval *zProp; \
        MAKE_STD_ZVAL(zProp); \
        ZVAL_STRING(zProp, property); \
        Z_OBJ_HANDLER_P(object, unset_property)(object, zProp, NULL); \
    }

#define FN_OBJECT_CREATE_HANDLER(name) \
     zend_object* name##_create_handler(zend_class_entry *type)

#define MEMSET_OBJECT(name, var_name, type) \
    name ## _object *var_name = (name ## _object *) ecalloc(1, OBJECT_SIZE(name ## _object, type)); \
    memset(var_name, 0, sizeof(name ## _object))

#define OBJECT_SIZE(object_type, class_entry) \
     sizeof(object_type) + zend_object_properties_size(class_entry)

#define INIT_OBJECT_CREATE_HANDLER(obj, class_entry, dtor, storage, clone, handlers_p, retval) \
    { \
        zend_object_std_init(&obj->std, class_entry); \
        object_properties_init(&obj->std, class_entry); \
        obj->std.handlers = &handlers_p; \
    }

#define OBJECT_CREATE_HANDLER_RETURN_TYPE() \
    zend_object

#define F_NAME(name, fn) \
     name ## fn

#define INIT_NS_CLASS(name, namespace, class_name) \
     zend_class_entry F_NAME(name, ce); \
     INIT_NS_CLASS_ENTRY(F_NAME(name, ce), namespace, class_name, F_NAME(name, _methods)); \
     F_NAME(name, _ce) = zend_register_internal_class(&F_NAME(name, ce)); \
     (*F_NAME(name, _ce)).create_object = F_NAME(name, _create_handler);\
     memcpy(&F_NAME(name, _object_handlers), zend_get_std_object_handlers(), sizeof(zend_object_handlers))

#define INIT_OBJECT_CREATE_HANDLER_RETURN(obj, retval) \
     &obj->std

#define UNSET_PROPERTY(object, property) \
     { \
        zval *prop; \
        MAKE_STD_ZVAL(prop); \
        ZVAL_STRING(prop, property); \
        Z_OBJ_HT_P(object)->unset_property(object, prop, NULL); \
     }

#define ZEND_THROW_EXCEPTION(message) \
     zend_throw_exception(zend_exception_get_default(), message, 0)

#define DECLARE_OBJECT_STRUCT(name, class_name) \
     struct name ## _object { \
        class_name *name; \
        zend_object std; \
     }

#endif

#endif


text:
Get-Module -Name Barracuda.WAF | Remove-Module -Force
Import-Module $(Join-Path -Path $PSScriptRoot -ChildPath '../Barracuda.WAF/Barracuda.WAF.psd1') -Force

InModuleScope Barracuda.WAF {
    Describe "Get-BarracudaWAFSecurityPolicyCloaking" {

        It "should retrieve information of security policy cloaking" {
            Mock Invoke-Api {}

            Get-BarracudaWAFSecurityPolicyCloaking -PolicyName 'default'

            Assert-MockCalled Invoke-Api -ParameterFilter { $Path -eq "/restapi/v3/security-policies/default/cloaking" } -Scope It
        }

        It "should accept pipeline input" {

            'default', 'owa' | Get-BarracudaWAFSecurityPolicyCloaking

            Assert-MockCalled Invoke-Api -Times 2 -Scope It

        }

        It "should support parameters query string parameter" {

            Mock Invoke-Api {}

            $params = @('filter-response-header', 'headers-to-filter', 'return-codes-to-exempt', 'suppress-return-code')

            Get-BarracudaWAFSecurityPolicyCloaking -PolicyName 'default' -Parameters $params

            Assert-MockCalled Invoke-Api -ParameterFilter { $Path -eq "/restapi/v3/security-policies/default/cloaking" -and $Parameters.parameters -eq ($params -join ',') } -Scope It
        }
    }
}


text:
/**
 * @file
 * @date      2014-2017
 * @copyright Max Planck Society
 *
 * @author    Edgar D. Klenske <edgar.klenske@tuebingen.mpg.de>
 * @author    Stephan Wenninger <stephan.wenninger@tuebingen.mpg.de>
 * @author    Raffi Enficiaud <raffi.enficiaud@tuebingen.mpg.de>
 *
 * @brief     The GP class implements the Gaussian Process functionality.
 */

#ifndef GAUSSIAN_PROCESS_H
#define GAUSSIAN_PROCESS_H

#include <Eigen/Dense>
#include <vector>
#include <list>
#include <memory>
#include <utility>
#include <cstdint>
#include <cmath>
#include "covariance_functions.h"

// Constants

// Jitter is the minimal "noise" on the otherwise noiseless kernel matrices to
// make the Cholesky decomposition stable.
#define JITTER 1e-6

class GP
{
private:
    covariance_functions::CovFunc* covFunc_;
    covariance_functions::CovFunc* covFuncProj_;
    Eigen::VectorXd data_loc_;
    Eigen::VectorXd data_out_;
    Eigen::VectorXd data_var_;
    Eigen::MatrixXd gram_matrix_;
    Eigen::VectorXd alpha_;
    Eigen::LDLT<Eigen::MatrixXd> chol_gram_matrix_;
    double log_noise_sd_;
    bool use_explicit_trend_;
    Eigen::MatrixXd feature_vectors_;
    Eigen::MatrixXd feature_matrix_;
    Eigen::LDLT<Eigen::MatrixXd> chol_feature_matrix_;
    Eigen::VectorXd beta_;

public:
    typedef std::pair<Eigen::VectorXd, Eigen::MatrixXd> VectorMatrixPair;

    GP(); // allowing the standard constructor makes the use so much easier!
    GP(const covariance_functions::CovFunc& covFunc);
    GP(const double noise_variance,
       const covariance_functions::CovFunc& covFunc);
    ~GP(); // Need to tidy up

    GP(const GP& that);
    GP& operator=(const GP& that);

    /*! Sets the covariance function
     *
     * This operation is possible only if there is not inference going on in the
     * current instance. This is useful after initialisation.
     */
    bool setCovarianceFunction(const covariance_functions::CovFunc& covFunc);

    /*!
     * Sets the output projection covariance function.
     */
    void enableOutputProjection(const covariance_functions::CovFunc& covFunc);

    /*!
     * Removes the output projection covariance function.
     */
    void disableOutputProjection();

    /*!
     * Returns a GP sample for the given locations.
     *
     * Returns a sample of the prior if the Gram matrix is empty.
     */
    Eigen::VectorXd drawSample(const Eigen::VectorXd& locations) const;

    /*!
     * Returns a sample of the GP based on a given vector of random numbers.
     */
    Eigen::VectorXd drawSample(const Eigen::VectorXd& locations,
                               const Eigen::VectorXd& random_vector) const;

    /*!
     * Builds an inverts the Gram matrix for a given set of datapoints.
     *
     * This function works on the already stored data and doesn't return
     * anything. The work is done here, I/O somewhere else.
     */
    void infer();

    /*!
     * Stores the given datapoints in the form of data location \a data_loc,
     * the output values \a data_out and noise vector \a data_sig.
     * Calls infer() everytime so that the Gram matrix is rebuild and the
     * Cholesky decomposition is computed.
     */
    void infer(const Eigen::VectorXd& data_loc,
               const Eigen::VectorXd& data_out,
               const Eigen::VectorXd& data_var = Eigen::VectorXd());

    /*!
     * Calculates the GP based on a subset of data (SD) approximation. The data
     * vector for the GP consists of a subset of n most important data points,
     * where the importance is defined as covariance to the prediction point. If
     * no prediction point is given, the last data point is used (extrapolation
     * mode).
     */
    void inferSD(const Eigen::VectorXd& data_loc,
                 const Eigen::VectorXd& data_out,
                 const int n,
                 const Eigen::VectorXd& data_var = Eigen::VectorXd(),
                 const double prediction_point = std::numeric_limits<double>::quiet_NaN());

    /*!
     * Sets the GP back to the prior:
     * Removes datapoints, empties the Gram matrix.
     */
    void clearData();

    /*!
     * Predicts the mean and covariance for a vector of locations.
     *
     * This function just builds the prior and mixed covariance matrices and
     * calls the other predict afterwards.
     */
    Eigen::VectorXd predict(const Eigen::VectorXd& locations, Eigen::VectorXd* variances = nullptr) const;

    /*!
     * Predicts the mean and covariance for a vector of locations based on
     * the output projection.
     *
     * This function just builds the prior and mixed covariance matrices and
     * calls the other predict afterwards.
     */
    Eigen::VectorXd predictProjected(const Eigen::VectorXd& locations, Eigen::VectorXd* variances = nullptr) const;

    /*!
     * Does the real work for predict. Solves the Cholesky decomposition for the
     * given matrices. The Gram matrix and measurements need to be cached
     * already.
     */
    Eigen::VectorXd predict(const Eigen::MatrixXd& prior_cov, const Eigen::MatrixXd& mixed_cov,
                             const Eigen::MatrixXd& phi = Eigen::MatrixXd() , Eigen::VectorXd* variances = nullptr) const;

    /*!
     * Sets the hyperparameters to the given vector.
     */
    void setHyperParameters(const Eigen::VectorXd& hyperParameters);

    /*!
     * Returns the hyperparameters to the given vector.
     */
    Eigen::VectorXd getHyperParameters() const;

    /*!
     * Enables the use of a explicit linear basis function.
     */
    void enableExplicitTrend();

    /*!
     * Disables the use of a explicit linear basis function.
     */
    void disableExplicitTrend();

};

#endif  // ifndef GAUSSIAN_PROCESS_H


text:
import functools

from wallace.config import App
import wallace.config.cache

_cache = []
_solo = []

def get_running():
    if _solo:
        return _solo
    return _cache

def register(f):
    @functools.wraps(f)
    def wrapper():
        _refresh()
        return f()
    _cache.append(wrapper)
    return wrapper

def _refresh():
    App._inst = None
    wallace.config.cache._connection_cache = {}

def get_all_tests():
    return _cache

def solo(f):
    _solo.append(f)
    return f


text:
<?php

namespace Ouzo\Utilities;

use DateTime;

class TimeAgo
{
    private string $key;
    private array $params = [];

    public function __construct(private ?string $date)
    {
        $this->prepare();
    }

    private function prepare(): void
    {
        $date = new DateTime($this->date);
        if ($this->showJustNow()) {
            $this->key = 'timeAgo.justNow';
            return;
        }
        if ($minutesAgo = $this->showMinutesAgo()) {
            $this->key = 'timeAgo.minAgo';
            $this->params = ['label' => $minutesAgo];
            return;
        }
        if ($this->showTodayAt()) {
            $this->key = 'timeAgo.todayAt';
            $this->params = ['label' => $date->format('H:i')];
            return;
        }
        if ($this->showYesterdayAt()) {
            $this->key = 'timeAgo.yesterdayAt';
            $this->params = ['label' => $date->format('H:i')];
            return;
        }
        if ($this->showThisYear()) {
            $this->key = 'timeAgo.thisYear';
            $this->params = ['day' => $date->format('j'), 'month' => 'timeAgo.month.' . $date->format('n')];
            return;
        }
        $this->key = $date->format('Y-m-d');
    }

    private function showJustNow(): bool
    {
        return $this->getDateDiff() <= 60;
    }

    private function showMinutesAgo(): ?int
    {
        $difference = $this->getDateDiff();
        return ($difference > 60 && $difference < 3600) ? floor($difference / 60) : null;
    }

    private function showTodayAt(): bool
    {
        $difference = $this->getDateDiff();
        return $this->isSameDay() && $difference >= 3600 && $difference < 86400;
    }

    private function getDateDiff(): int
    {
        return $this->nowAsTimestamp() - $this->dateAsTimestamp();
    }

    private function nowAsTimestamp(): int
    {
        return Clock::now()->getTimestamp();
    }

    private function dateAsTimestamp(): int
    {
        return strtotime($this->date);
    }

    private function isSameDay(): bool
    {
        $now = $this->nowAsTimestamp();
        $date = $this->dateAsTimestamp();
        return date('Y-m-d', $now) == date('Y-m-d', $date);
    }

    private function showYesterdayAt(): bool
    {
        $now = $this->nowAsTimestamp();
        $date = $this->dateAsTimestamp();
        if (date('Y-m', $now) == date('Y-m', $date)) {
            return date('d', $now) - date('d', $date) == 1;
        }
        return false;
    }

    private function showThisYear(): bool
    {
        $now = $this->nowAsTimestamp();
        $date = $this->dateAsTimestamp();
        return date('Y', $now) == date('Y', $date);
    }

    public static function create(string $date): TimeAgo
    {
        return new self($date);
    }

    public function getKey(): string
    {
        return $this->key;
    }

    public function getParams(): array
    {
        return $this->params;
    }
}


text:
/*
 *  Arctic-snowstorm
 *  (c) 2014-2015, Teempla Inc.
 *
 *  MIT License
 */
"use strict";

define([
    'class',
    'lodash',
    'q',
    'path'
], function(Class, _, Q, path) {

    /**
     *  Wrapper for manage AbstractConnectors.
     *  Call method connect and disconnect for all enabled connectors
     *
     * @class ConnectorsManager
     * @name ConnectorsManager
     */
    return Class.extend({

        /**
         * Connectors names list
         *
         * @property {String[]}
         * @private
         */
        connectorsNames: null,

        /**
         * List of all connected connectors
         *
         * @property {AbstractConnector[]}
         * @private
         */
        connectors: null,

        /**
         * ProcessRunner constructor
         *
         * @param {String[]} connectorsNames - List of connectors names
         * @extends {Class}
         * @public
         *
         * @constructor
         */
        constructor: function (connectorsNames) {

            var self = this;

            // Init worker
            self.connectorsNames = connectorsNames || [];
        },

        /**
         * Connect all enabled connectors
         *
         * @public
         *
         * @return {Promise} - Return empty promise
         */
        connect: function(){

            var self = this;

            // Fix connectors path
            var connectorsPaths = _.map(this.connectorsNames, function(name){ return path.join('connectors', name); });

            // Load and save connector to connectors property
            return self.loadConnectors(connectorsPaths)
                .then(function(connectors){

                    var promisesArray = [];
                    self.connectors = connectors;

                    _.each(connectors, function(connector){
                        // Call abstract static connector method for init connection
                        promisesArray.push(connector.connect());
                    });

                    return Q.all(promisesArray);
                });
        },

        /**
         * Disconnect all enabled connectors
         *
         * @public
         *
         * @return {Promise} - Return empty promise
         */
        disconnect: function(){

            var promisesArray = [];

            _.each(this.connectors, function(connector){
                promisesArray.push(connector.disconnect());
            });

            return Q.all(promisesArray);
        },

        /**
         * Sync disconnect all enabled connectors
         *
         * @public
         */
        syncDisconnect: function(){

            _.each(this.connectors, function(connector){
                connector.syncDisconnect();
            });
        },

        /**
         * Dynamically load connectors by path
         *
         * @private
         * @return {Promise|AbstractConnector} - return promise with AbstractConnectors collection
         */
        loadConnectors: function(connectorsPaths){

            var deferred = Q.defer();
            var connectors = [];

            requirejs(connectorsPaths, function(){

                _.each(arguments, function(connector){
                    connectors.push(connector);
                });

                deferred.resolve(connectors);
            });

            return deferred.promise;
        }

    });
});


text:
package org.apache.hadoop.yarn.factory.providers;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.YarnException;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.factories.YarnRemoteExceptionFactory;
import org.apache.hadoop.yarn.factories.impl.pb.YarnRemoteExceptionFactoryPBImpl;

public class YarnRemoteExceptionFactoryProvider {

  private YarnRemoteExceptionFactoryProvider() {
  }

  public static YarnRemoteExceptionFactory getYarnRemoteExceptionFactory(Configuration conf) {
    if (conf == null) {
      conf = new Configuration();
    }
    String recordFactoryClassName = conf.get(YarnConfiguration.IPC_EXCEPTION_FACTORY);
    if (recordFactoryClassName == null) {
      String serializer = conf.get(YarnConfiguration.IPC_SERIALIZER_TYPE, YarnConfiguration.DEFAULT_IPC_SERIALIZER_TYPE);
      if (serializer.equals(YarnConfiguration.DEFAULT_IPC_SERIALIZER_TYPE)) {
        return YarnRemoteExceptionFactoryPBImpl.get();
      } else {
        throw new YarnException("Unknown serializer: [" + conf.get(YarnConfiguration.IPC_SERIALIZER_TYPE) + "]. Use keys: [" + YarnConfiguration.IPC_EXCEPTION_FACTORY + "] to specify Exception factory");
      }
    } else {
      return (YarnRemoteExceptionFactory) getFactoryClassInstance(recordFactoryClassName);
    }
  }

  private static Object getFactoryClassInstance(String factoryClassName) {
    try {
      Class<?> clazz = Class.forName(factoryClassName);
      Method method = clazz.getMethod("get", null);
      method.setAccessible(true);
      return method.invoke(null, null);
    } catch (ClassNotFoundException e) {
      throw new YarnException(e);
    } catch (NoSuchMethodException e) {
      throw new YarnException(e);
    } catch (InvocationTargetException e) {
      throw new YarnException(e);
    } catch (IllegalAccessException e) {
      throw new YarnException(e);
    }
  }
}


text:
Gauteng Lesson Logbook
======================

This is a log of the dojo sessions we've run in the Gauteng office.


text:
using System;

namespace Training_Lab
{
    class Program
    {
        static void Main(string[] args)
        {

            var width = double.Parse(Console.ReadLine());
            var length = double.Parse(Console.ReadLine());

            var corridor = 1;
            var tableWidth = 1.2;
            var tableLength = 0.7;

            var lengthWithoutCorridor = length - corridor;
            var numberOfTablesInRow = Math.Floor(lengthWithoutCorridor / tableLength);

            var numberOfRows = Math.Floor(width / tableWidth);

            Console.WriteLine(numberOfTablesInRow*numberOfRows-3);

        }
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var intersection = function intersection() {};

exports.intersection = intersection;


text:
dockitech-api-client-admin
=========

Jar con parti amministrative


text:
namespace java.util
{
    public partial class InvalidPropertiesFormatException : global::java.io.IOException
    {
        public InvalidPropertiesFormatException(global::java.lang.Throwable prm1){}
        public InvalidPropertiesFormatException(global::java.lang.String prm1){}
    }
}


text:
<?php

namespace Orkestro\Bundle\CoreBundle\Kernel;

use Symfony;
use Doctrine;
use Sensio;
use Orkestro;
use Knp;
use FOS;
use HWI;
use A2lix;
use Prezent;
use Stof;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

abstract class Kernel extends BaseKernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new Prezent\Doctrine\TranslatableBundle\PrezentDoctrineTranslatableBundle(),
            new A2lix\TranslationFormBundle\A2lixTranslationFormBundle(),
            new Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),

            new Orkestro\Bundle\CoreBundle\OrkestroCoreBundle(),
            new Orkestro\Bundle\AddressingBundle\OrkestroAddressingBundle(),
            new Orkestro\Bundle\ApiBundle\OrkestroApiBundle(),
            new Orkestro\Bundle\CartBundle\OrkestroCartBundle(),
            new Orkestro\Bundle\CategoryBundle\OrkestroCategoryBundle(),
            new Orkestro\Bundle\ConfigBundle\OrkestroConfigBundle(),
            new Orkestro\Bundle\CountryBundle\OrkestroCountryBundle(),
            new Orkestro\Bundle\DeliveryBundle\OrkestroDeliveryBundle(),
            new Orkestro\Bundle\GeneratorBundle\OrkestroGeneratorBundle(),
            new Orkestro\Bundle\LocaleBundle\OrkestroLocaleBundle(),
            new Orkestro\Bundle\ManufacturerBundle\OrkestroManufacturerBundle(),
            new Orkestro\Bundle\OrderBundle\OrkestroOrderBundle(),
            new Orkestro\Bundle\ProductBundle\OrkestroProductBundle(),
            new Orkestro\Bundle\UserBundle\OrkestroUserBundle(),
            new Orkestro\Bundle\WebBundle\OrkestroWebBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $rootDir = $this->getRootDir();

        $loader->load($rootDir.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


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

namespace Lite.ExcelLibrary.BinaryDrawingFormat
{
	public partial class MsofbtBlip : EscherRecord
	{
		public MsofbtBlip() { }

		public MsofbtBlip(EscherRecord record) : base(record) { }

		public Guid UID;

		public Byte Marker;

		public Byte[] ImageData;

	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Theme Library Configuration
 *
 * This files holds theme settings
 *
 * @package 	CodeIgniter
 * @category 	Configuration
 * @author 	Kader Bouyakoub <bkader@mail.com>
 * @link 	https://github.com/bkader
 * @link 	https://twitter.com/KaderBouyakoub
 */

/*
| -------------------------------------------------------------------
| Theme Settings
| -------------------------------------------------------------------
|
|  'theme.theme' 			the activated site theme.
|  'theme.master' 			theme default master view file.
|  'theme.layout' 			theme default layout file.
|  'theme.title_sep' 		string to be used as title separator.
|  'theme.compress' 		whether to compress HTML output to not.
|  'theme.cache_lifetime' 	whether to cache output or not.
|
| CDN settings:
|	'theme.cdn_enabled'		If TRUE, the 2nd param of css(), js() is used.
|	'theme.cdn_server'		If your host your assets on a CDN, privide URL.
*/

// Site default theme
$config['theme.theme'] = 'default';

// Site default master view file.
$config['theme.master'] = 'template';

// Site default layout file
$config['theme.layout'] = 'default';

// Site title separator
$config['theme.title_sep'] = '–';

// Minify HTML Output
$config['theme.compress'] = (defined('ENVIRONMENT') && ENVIRONMENT == 'production');

// Cache life time
$config['theme.cache_lifetime'] = 0;

// Enable CDN (to use 2nd argument of css() & js() functions)
$config['theme.cdn_enabled'] = (defined('ENVIRONMENT') && ENVIRONMENT == 'production');

// The CDN URL if you host your files there
$config['theme.cdn_server'] = ''; // i.e: 'http://static.myhost.com/';

// ------------------------------------------------------------------------
// Backup plan :D for site name, desription & keywords
// ------------------------------------------------------------------------

// Default site title, description and keywords.
$config['theme.site_title']       = 'CI-Theme';
$config['theme.site_description'] = 'CodeIgniter Themes Library';
$config['theme.site_keywords']    = 'codeigniter, themes, libraries, bkader';
$config['theme.assets_ver'] = '20170805';

/* End of file theme.php */
/* Location: ./application/config/theme.php */


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var bind = function bind() {};

exports.bind = bind;


text:
package net.sf.jabref.gui.bibtexkeypattern;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JCheckBox;

import net.sf.jabref.Globals;
import net.sf.jabref.gui.BasePanel;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.gui.undo.UndoableKeyChange;
import net.sf.jabref.gui.worker.AbstractWorker;
import net.sf.jabref.logic.bibtexkeypattern.BibtexKeyPatternUtil;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.database.BibDatabase;
import net.sf.jabref.model.entry.BibEntry;

/**
 * Function for resolving duplicate BibTeX keys.
 */
public class SearchFixDuplicateLabels extends AbstractWorker {

    private final BasePanel panel;
    private Map<String, List<BibEntry>> dupes;

    public SearchFixDuplicateLabels(BasePanel panel) {

        this.panel = panel;
    }

    @Override
    public void run() {
        // Find all multiple occurrences of BibTeX keys.
        dupes = new HashMap<>();

        Map<String, BibEntry> foundKeys = new HashMap<>();
        BibDatabase db = panel.getDatabase();
        for (BibEntry entry : db.getEntries()) {
            entry.getCiteKeyOptional().filter(key -> !key.isEmpty()).ifPresent(key -> {
                // See whether this entry's key is already known:
                if (foundKeys.containsKey(key)) {
                    // Already known, so we have found a dupe. See if it was already found as a dupe:
                    if (dupes.containsKey(key)) {
                        // Already in the dupe map. Add this entry as well:
                        dupes.get(key).add(entry);
                    } else {
                        // Construct a list of entries for this key:
                        List<BibEntry> al = new ArrayList<>();
                        // Add both the first one we found, and the one we found just now:
                        al.add(foundKeys.get(key));
                        al.add(entry);
                        // Add the list to the dupe map:
                        dupes.put(key, al);
                    }
                } else {
                    // Not already known. Add key and entry to map:
                    foundKeys.put(key, entry);
                }
            });
        }
    }

    @Override
    public void init() throws Throwable {
        panel.output(Localization.lang("Resolving duplicate BibTeX keys..."));

    }

    @Override
    public void update() {
        List<BibEntry> toGenerateFor = new ArrayList<>();
        for (Map.Entry<String, List<BibEntry>> dupeEntry : dupes.entrySet()) {
            ResolveDuplicateLabelDialog rdld = new ResolveDuplicateLabelDialog(panel, dupeEntry.getKey(), dupeEntry.getValue());
            rdld.show();
            if (rdld.isOkPressed()) {
                List<JCheckBox> cbs = rdld.getCheckBoxes();
                for (int i = 0; i < cbs.size(); i++) {
                    if (cbs.get(i).isSelected()) {
                        // The checkbox for entry i has been selected, so we should generate a new key for it:
                        toGenerateFor.add(dupeEntry.getValue().get(i));
                    }
                }
            } else if (rdld.isCancelPressed()) {
                break;
            }
        }

        // Do the actual generation:
        if (!toGenerateFor.isEmpty()) {
            NamedCompound ce = new NamedCompound(Localization.lang("Resolve duplicate BibTeX keys"));
            for (BibEntry entry : toGenerateFor) {
                String oldKey = entry.getCiteKeyOptional().orElse(null);
                BibtexKeyPatternUtil.makeLabel(panel.getBibDatabaseContext().getMetaData()
                        .getCiteKeyPattern(Globals.prefs.getBibtexKeyPatternPreferences().getKeyPattern()),
                        panel.getDatabase(), entry,
                        Globals.prefs.getBibtexKeyPatternPreferences());
                ce.addEdit(new UndoableKeyChange(entry, oldKey, entry.getCiteKeyOptional().get()));
            }
            ce.end();
            panel.getUndoManager().addEdit(ce);
            panel.markBaseChanged();
        }
        panel.output(Localization.lang("Finished resolving duplicate BibTeX keys. %0 entries modified.",
                String.valueOf(toGenerateFor.size())));
    }
}


text:
class RecreateGutsPermissionsAndAuthorizations < ActiveRecord::Migration[5.0]
  def change
    drop_table :guts_permissions
    drop_table :guts_authorizations

    create_table :guts_permissions do |t|
      t.string :resource
      t.string :grant
      t.references(
        :permissionable,
        polymorphic: true,
        index: { name: 'index_permissions_on_permissionable_type_and_permissionable' }
      )
      t.timestamps null: false
    end
  end
end


text:
package io.questions.testdata.samples.samplequestionnaire

import cats.syntax.show._
import io.questions.testdata.ExampleComponents
import io.questions.model.questionnaire.FieldName.FieldNameStringSyntax
import io.questions.model.questionnaire.QuestionText.QuestionTextSyntax
import io.questions.model.questionnaire.integrity.IntegrityError
import io.questions.model.questionnaire.nodekey.NodeKey
import io.questions.model.questionnaire.{ Element, QuestionnaireId, QuestionnaireNode }
import io.questions.testdata.samples.enumerations._
import io.questions.testdata.ExampleComponents

object SampleQuestionnaire {
  val id: QuestionnaireId = QuestionnaireId.random

  val questionnaire: QuestionnaireNode = ExampleComponents.standard(
    NodeKey.random,
    "applicant".fieldName,
    "Applicant".text,
    Element.NonRepeatingParent(
      SampleQuestionsSection.section,
      DependentQuestionsSection.section,
      OtherElementsSection.section
    ),
    enums = Map(
      Country.name            → Country.values,
      Gender.name             → Gender.values,
      RelationshipStatus.name → RelationshipStatus.values,
      Title.name              → Title.values,
      YesNo.name              → YesNo.values,
      Currencies.name         → Currencies.values
    ),
    questionnaireId = id
  )

  private val integrity: Set[IntegrityError] = questionnaire.checkIntegrity
  if (integrity.nonEmpty) println(s"Integrity errors found in the SampleQuestionnaire:\n${integrity.map(_.show).mkString("\n")}") //scalastyle:ignore
}