text:
001
017    package org.apache.commons.math3.genetics;
018
019    import org.apache.commons.math3.exception.NumberIsTooLargeException;
020
021
022    /**
023     * A collection of chromosomes that facilitates generational evolution.
024     *
025     * @since 2.0
026     * @version $Id: Population.java 1416643 2012-12-03 19:37:14Z tn $
027     */
028    public interface Population extends Iterable<Chromosome> {
029        /**
030         * Access the current population size.
031         * @return the current population size.
032         */
033        int getPopulationSize();
034
035        /**
036         * Access the maximum population size.
037         * @return the maximum population size.
038         */
039        int getPopulationLimit();
040
041        /**
042         * Start the population for the next generation.
043         * @return the beginnings of the next generation.
044         */
045        Population nextGeneration();
046
047        /**
048         * Add the given chromosome to the population.
049         * @param chromosome the chromosome to add.
050         * @throws NumberIsTooLargeException if the population would exceed the population limit when adding
051         *   this chromosome
052         */
053        void addChromosome(Chromosome chromosome) throws NumberIsTooLargeException;
054
055        /**
056         * Access the fittest chromosome in this population.
057         * @return the fittest chromosome.
058         */
059        Chromosome getFittestChromosome();
060    }


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CONTENT_PUBLIC_BROWSER_PUSH_MESSAGING_SERVICE_H_
#define CONTENT_PUBLIC_BROWSER_PUSH_MESSAGING_SERVICE_H_

#include <string>

#include "base/callback_forward.h"
#include "content/common/content_export.h"
#include "content/public/common/push_messaging_status.h"
#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushPermissionStatus.h"
#include "url/gurl.h"

namespace content {

class BrowserContext;
class ServiceWorkerContext;

// A push service-agnostic interface that the Push API uses for talking to
// push messaging services like GCM. Must only be used on the UI thread.
class CONTENT_EXPORT PushMessagingService {
 public:
  using RegisterCallback =
      base::Callback<void(const std::string& /* registration_id */,
                          PushRegistrationStatus /* status */)>;
  using UnregisterCallback = base::Callback<void(PushUnregistrationStatus)>;

  using StringCallback = base::Callback<void(const std::string& data,
                                             bool success,
                                             bool not_found)>;

  using ResultCallback = base::Callback<void(bool success)>;

  virtual ~PushMessagingService() {}

  // Returns the absolute URL exposed by the push server where the webapp server
  // can send push messages. This is currently assumed to be the same for all
  // origins and push registrations.
  virtual GURL GetPushEndpoint() = 0;

  // Register the given |sender_id| with the push messaging service in a
  // document context. The frame is known and a permission UI may be displayed
  // to the user.
  virtual void RegisterFromDocument(const GURL& requesting_origin,
                                    int64 service_worker_registration_id,
                                    const std::string& sender_id,
                                    int renderer_id,
                                    int render_frame_id,
                                    bool user_visible_only,
                                    const RegisterCallback& callback) = 0;

  // Register the given |sender_id| with the push messaging service. The frame
  // is not known so if permission was not previously granted by the user this
  // request should fail.
  virtual void RegisterFromWorker(const GURL& requesting_origin,
                                  int64 service_worker_registration_id,
                                  const std::string& sender_id,
                                  const RegisterCallback& callback) = 0;

  // Unregister the given |sender_id| from the push messaging service. The
  // registration will be synchronously deactivated locally, and asynchronously
  // sent to the push service, with automatic retry.
  virtual void Unregister(const GURL& requesting_origin,
                          int64 service_worker_registration_id,
                          const std::string& sender_id,
                          const UnregisterCallback& callback) = 0;

  // Checks the permission status for the requesting origin. Permission is only
  // ever granted when the requesting origin matches the top level embedding
  // origin.
  virtual blink::WebPushPermissionStatus GetPermissionStatus(
      const GURL& requesting_origin,
      const GURL& embedding_origin) = 0;

 protected:
  // Provide a storage mechanism to read/write an opaque
  // "notifications_shown_by_last_few_pushes" string associated with a Service
  // Worker registration. Stored data is deleted when the associated
  // registration is deleted.
  static void GetNotificationsShownByLastFewPushes(
      ServiceWorkerContext* service_worker_context,
      int64 service_worker_registration_id,
      const StringCallback& callback);
  static void SetNotificationsShownByLastFewPushes(
      ServiceWorkerContext* service_worker_context,
      int64 service_worker_registration_id,
      const GURL& origin,
      const std::string& notifications_shown,
      const ResultCallback& callback);

  static void GetSenderId(BrowserContext* browser_context,
                          const GURL& origin,
                          int64 service_worker_registration_id,
                          const StringCallback& callback);

  // Clear the push registration id stored in the service worker with the given
  // |service_worker_registration_id| for the given |origin|.
  static void ClearPushRegistrationID(BrowserContext* browser_context,
                                      const GURL& origin,
                                      int64 service_worker_registration_id,
                                      const base::Closure& callback);
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_PUSH_MESSAGING_SERVICE_H_

redpajama_set_name: RedPajamaGithub


text:
// gulp data_structure:binary_search_tree:traverseBSTbyLevel

/**
 * Should do this
 * @param {*} arr
 */

function traverseBSTbyLevel() {

}

// ========= TEST ========
const should = require('should');
traverseBSTbyLevel().should.eql();
traverseBSTbyLevel().should.eql();
traverseBSTbyLevel().should.eql();
traverseBSTbyLevel().should.eql();
traverseBSTbyLevel().should.eql();
traverseBSTbyLevel().should.eql();

module.exports = traverseBSTbyLevel;


text:
'use strict';

/**
 * Returns the item at the specified index
 * @param {Number} index The index of the Touch object to return
 * @return {Touch}
 */
function item(index) {
    return this._items[index];
}

/**
 * Feedthrough function to the _items array
 * @return {Array} The spliced array
 */
function splice() {
    return Array.prototype.splice.apply(this._items, arguments);
}

/**
 * Gets the number of Touch objects in the list
 * @return {Number} The length of the list
 */
function getLength() {
    return this._items.length;
}

/*****************
 *  Constructor  *
 *****************/

/**
 * Constructs a TouchList object
 * @param {Array} touches An array of touch objects
 */
function TouchList(touches) {

    Object.defineProperties(this, {
        _items : {
            value        : touches || [],
            writable     : true,
            configurable : false,
            enumerable   : false
        },
        length : {
            get          : getLength,
            configurable : false,
            enumerable   : true
        }
    });
}

/***************
 *  Prototype  *
 ***************/

TouchList.prototype = {
    item   : item,
    splice : splice
};

/*************
 *  Exports  *
 *************/

module.exports = TouchList;


text:
<?php

namespace Magento\Catalog\Helper\Product;

use Magento\Catalog\Helper\Product\Configuration\ConfigurationInterface;
use Magento\Framework\App\Helper\AbstractHelper;

/**
 * Helper for fetching properties by product configurational item
 *
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Configuration extends AbstractHelper implements ConfigurationInterface
{
    /**
     * Filter manager
     *
     * @var \Magento\Framework\Filter\FilterManager
     */
    protected $filter;

    /**
     * Product option factory
     *
     * @var \Magento\Catalog\Model\Product\OptionFactory
     */
    protected $_productOptionFactory;

    /**
     * Magento string lib
     *
     * @var \Magento\Framework\Stdlib\StringUtils
     */
    protected $string;

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory
     * @param \Magento\Framework\Filter\FilterManager $filter
     * @param \Magento\Framework\Stdlib\StringUtils $string
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory,
        \Magento\Framework\Filter\FilterManager $filter,
        \Magento\Framework\Stdlib\StringUtils $string
    ) {
        $this->_productOptionFactory = $productOptionFactory;
        $this->filter = $filter;
        $this->string = $string;
        parent::__construct($context);
    }

    /**
     * Retrieves product configuration options
     *
     * @param \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item
     * @return array
     */
    public function getCustomOptions(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item)
    {
        $product = $item->getProduct();
        $options = [];
        $optionIds = $item->getOptionByCode('option_ids');
        if ($optionIds) {
            $options = [];
            foreach (explode(',', $optionIds->getValue()) as $optionId) {
                $option = $product->getOptionById($optionId);
                if ($option) {
                    $itemOption = $item->getOptionByCode('option_' . $option->getId());
                    /** @var $group \Magento\Catalog\Model\Product\Option\Type\DefaultType */
                    $group = $option->groupFactory($option->getType())
                        ->setOption($option)
                        ->setConfigurationItem($item)
                        ->setConfigurationItemOption($itemOption);

                    if ('file' == $option->getType()) {
                        $downloadParams = $item->getFileDownloadParams();
                        if ($downloadParams) {
                            $url = $downloadParams->getUrl();
                            if ($url) {
                                $group->setCustomOptionDownloadUrl($url);
                            }
                            $urlParams = $downloadParams->getUrlParams();
                            if ($urlParams) {
                                $group->setCustomOptionUrlParams($urlParams);
                            }
                        }
                    }

                    $options[] = [
                        'label' => $option->getTitle(),
                        'value' => $group->getFormattedOptionValue($itemOption->getValue()),
                        'print_value' => $group->getPrintableOptionValue($itemOption->getValue()),
                        'option_id' => $option->getId(),
                        'option_type' => $option->getType(),
                        'custom_view' => $group->isCustomizedView(),
                    ];
                }
            }
        }

        $addOptions = $item->getOptionByCode('additional_options');
        if ($addOptions) {
            $options = array_merge($options, unserialize($addOptions->getValue()));
        }

        return $options;
    }

    /**
     * Retrieves product options list
     *
     * @param \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item
     * @return array
     */
    public function getOptions(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item)
    {
        return $this->getCustomOptions($item);
    }

    /**
     * Accept option value and return its formatted view
     *
     * @param string|array $optionValue
     * Method works well with these $optionValue format:
     *      1. String
     *      2. Indexed array e.g. array(val1, val2, ...)
     *      3. Associative array, containing additional option info, including option value, e.g.
     *          array
     *          (
     *              [label] => ...,
     *              [value] => ...,
     *              [print_value] => ...,
     *              [option_id] => ...,
     *              [option_type] => ...,
     *              [custom_view] =>...,
     *          )
     * @param array $params
     * All keys are options. Following supported:
     *  - 'maxLength': truncate option value if needed, default: do not truncate
     *  - 'cutReplacer': replacer for cut off value part when option value exceeds maxLength
     *
     * @return array
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function getFormattedOptionValue($optionValue, $params = null)
    {
        // Init params
        if (!$params) {
            $params = [];
        }
        $maxLength = isset($params['max_length']) ? $params['max_length'] : null;
        $cutReplacer = isset($params['cut_replacer']) ? $params['cut_replacer'] : '...';

        // Proceed with option
        $optionInfo = [];

        // Define input data format
        if (is_array($optionValue)) {
            if (isset($optionValue['option_id'])) {
                $optionInfo = $optionValue;
                if (isset($optionInfo['value'])) {
                    $optionValue = $optionInfo['value'];
                }
            } elseif (isset($optionValue['value'])) {
                $optionValue = $optionValue['value'];
            }
        }

        // Render customized option view
        if (isset($optionInfo['custom_view']) && $optionInfo['custom_view']) {
            $_default = ['value' => $optionValue];
            if (isset($optionInfo['option_type'])) {
                try {
                    $group = $this->_productOptionFactory->create()->groupFactory($optionInfo['option_type']);
                    return ['value' => $group->getCustomizedView($optionInfo)];
                } catch (\Exception $e) {
                    return $_default;
                }
            }
            return $_default;
        }

        // Truncate standard view
        if (is_array($optionValue)) {
            $truncatedValue = implode("\n", $optionValue);
            $truncatedValue = nl2br($truncatedValue);
            return ['value' => $truncatedValue];
        } else {
            if ($maxLength) {
                $truncatedValue = $this->filter->truncate($optionValue, ['length' => $maxLength, 'etc' => '']);
            } else {
                $truncatedValue = $optionValue;
            }
            $truncatedValue = nl2br($truncatedValue);
        }

        $result = ['value' => $truncatedValue];

        if ($maxLength && $this->string->strlen($optionValue) > $maxLength) {
            $result['value'] = $result['value'] . $cutReplacer;
            $optionValue = nl2br($optionValue);
            $result['full_view'] = $optionValue;
        }

        return $result;
    }
}


text:
This is a pre-release version of Nucleus for Sponge API version {{sponge}}

**THIS IS A PRE-RELEASE VERSION AND MAY NOT BE STABLE**

This was built from Nucleus commit: {{hash}}

## Release Notes

If you're having trouble, visit our Discord channel: https://discord.gg/A9QHG5H

{{info}}

## Known Issues

* Some plugins and mods are known to be incompatible with Nucleus. See https://nucleuspowered.org/docs/compatibility.html for more information.


text:
{% extends "_layouts/layout.html" %}

{% block header_class %}{% endblock %}

{% block page_title %}
  GOV.UK product page prototypes
{% endblock %}

{% block content %}

        GOV.UK Service Toolkit

GOV.UK Service Toolkit – "live" version

GOV.UK Service Toolkit – Expose Service Manual Headings

{% endblock %}


text:
"""
This module contains helpers/fixtures to assist in testing Fabric-driven code.

It is not intended for production use, and pulls in some test-oriented
dependencies such as `mock <https://pypi.org/project/mock/>`_. You can install
an 'extra' variant of Fabric to get these dependencies if you aren't already
using them for your own testing purposes: ``pip install fabric[testing]``.

.. note::
    If you're using pytest for your test suite, you may be interested in
    grabbing ``fabric[pytest]`` instead, which encompasses the dependencies of
    both this module and the `fabric.testing.fixtures` module, which contains
    pytest fixtures.

.. versionadded:: 2.1
"""

from itertools import chain, repeat
from io import BytesIO
import os

try:
    from mock import Mock, PropertyMock, call, patch, ANY
except ImportError:
    import warnings

    warning = (
        "You appear to be missing some optional test-related dependencies;"
        "please 'pip install fabric[testing]'."
    )
    warnings.warn(warning, ImportWarning)
    raise

class Command(object):
    """
    Data record specifying params of a command execution to mock/expect.

    :param str cmd:
        Command string to expect. If not given, no expectations about the
        command executed will be set up. Default: ``None``.

    :param bytes out: Data yielded as remote stdout. Default: ``b""``.

    :param bytes err: Data yielded as remote stderr. Default: ``b""``.

    :param int exit: Remote exit code. Default: ``0``.

    :param int waits:
        Number of calls to the channel's ``exit_status_ready`` that should
        return ``False`` before it then returns ``True``. Default: ``0``
        (``exit_status_ready`` will return ``True`` immediately).

    .. versionadded:: 2.1
    """

    def __init__(self, cmd=None, out=b"", err=b"", in_=None, exit=0, waits=0):
        self.cmd = cmd
        self.out = out
        self.err = err
        self.in_ = in_
        self.exit = exit
        self.waits = waits

    def __repr__(self):
        # TODO: just leverage attrs, maybe vendored into Invoke so we don't
        # grow more dependencies? Ehhh
        return "<{} cmd={!r}>".format(self.__class__.__name__, self.cmd)

    def expect_execution(self, channel):
        """
        Assert that the ``channel`` was used to run this command.

        .. versionadded:: 2.7
        """
        channel.exec_command.assert_called_with(self.cmd or ANY)

class ShellCommand(Command):
    """
    A pseudo-command that expects an interactive shell to be executed.

    .. versionadded:: 2.7
    """

    def expect_execution(self, channel):
        channel.invoke_shell.assert_called_once_with()

class MockChannel(Mock):
    """
    Mock subclass that tracks state for its ``recv(_stderr)?`` methods.

    Turns out abusing function closures inside MockRemote to track this state
    only worked for 1 command per session!

    .. versionadded:: 2.1
    """

    def __init__(self, *args, **kwargs):
        # TODO: worth accepting strings and doing the BytesIO setup ourselves?
        # Stored privately to avoid any possible collisions ever. shrug.
        object.__setattr__(self, "__stdout", kwargs.pop("stdout"))
        object.__setattr__(self, "__stderr", kwargs.pop("stderr"))
        # Stdin less private so it can be asserted about
        object.__setattr__(self, "_stdin", BytesIO())
        super(MockChannel, self).__init__(*args, **kwargs)

    def _get_child_mock(self, **kwargs):
        # Don't return our own class on sub-mocks.
        return Mock(**kwargs)

    def recv(self, count):
        return object.__getattribute__(self, "__stdout").read(count)

    def recv_stderr(self, count):
        return object.__getattribute__(self, "__stderr").read(count)

    def sendall(self, data):
        return object.__getattribute__(self, "_stdin").write(data)

class Session(object):
    """
    A mock remote session of a single connection and 1 or more command execs.

    Allows quick configuration of expected remote state, and also helps
    generate the necessary test mocks used by `MockRemote` itself. Only useful
    when handed into `MockRemote`.

    The parameters ``cmd``, ``out``, ``err``, ``exit`` and ``waits`` are all
    shorthand for the same constructor arguments for a single anonymous
    `.Command`; see `.Command` for details.

    To give fully explicit `.Command` objects, use the ``commands`` parameter.

    :param str user:
    :param str host:
    :param int port:
        Sets up expectations that a connection will be generated to the given
        user, host and/or port. If ``None`` (default), no expectations are
        generated / any value is accepted.

    :param commands:
        Iterable of `.Command` objects, used when mocking nontrivial sessions
        involving >1 command execution per host. Default: ``None``.

        .. note::
            Giving ``cmd``, ``out`` etc alongside explicit ``commands`` is not
            allowed and will result in an error.

    .. versionadded:: 2.1
    """

    def __init__(
        self,
        host=None,
        user=None,
        port=None,
        commands=None,
        cmd=None,
        out=None,
        in_=None,
        err=None,
        exit=None,
        waits=None,
    ):
        # Sanity check
        params = cmd or out or err or exit or waits
        if commands and params:
            raise ValueError(
                "You can't give both 'commands' and individual "
                "Command parameters!"
            )  # noqa
        # Fill in values
        self.host = host
        self.user = user
        self.port = port
        self.commands = commands
        if params:
            # Honestly dunno which is dumber, this or duplicating Command's
            # default kwarg values in this method's signature...sigh
            kwargs = {}
            if cmd is not None:
                kwargs["cmd"] = cmd
            if out is not None:
                kwargs["out"] = out
            if err is not None:
                kwargs["err"] = err
            if in_ is not None:
                kwargs["in_"] = in_
            if exit is not None:
                kwargs["exit"] = exit
            if waits is not None:
                kwargs["waits"] = waits
            self.commands = [Command(**kwargs)]
        if not self.commands:
            self.commands = [Command()]

    def generate_mocks(self):
        """
        Mocks `~paramiko.client.SSHClient` and `~paramiko.channel.Channel`.

        Specifically, the client will expect itself to be connected to
        ``self.host`` (if given), the channels will be associated with the
        client's `~paramiko.transport.Transport`, and the channels will
        expect/provide command-execution behavior as specified on the
        `.Command` objects supplied to this `.Session`.

        The client is then attached as ``self.client`` and the channels as
        ``self.channels``.

        :returns:
            ``None`` - this is mostly a "deferred setup" method and callers
            will just reference the above attributes (and call more methods) as
            needed.

        .. versionadded:: 2.1
        """
        client = Mock()
        transport = client.get_transport.return_value  # another Mock

        # NOTE: this originally did chain([False], repeat(True)) so that
        # get_transport().active was False initially, then True. However,
        # because we also have to consider when get_transport() comes back None
        # (which it does initially), the case where we get back a non-None
        # transport _and_ it's not active yet, isn't useful to test, and
        # complicates text expectations. So we don't, for now.
        actives = repeat(True)
        # NOTE: setting PropertyMocks on a mock's type() is apparently
        # How It Must Be Done, otherwise it sets the real attr value.
        type(transport).active = PropertyMock(side_effect=actives)

        channels = []
        for command in self.commands:
            # Mock of a Channel instance, not e.g. Channel-the-class.
            # Specifically, one that can track individual state for recv*().
            channel = MockChannel(
                stdout=BytesIO(command.out), stderr=BytesIO(command.err)
            )
            channel.recv_exit_status.return_value = command.exit

            # If requested, make exit_status_ready return False the first N
            # times it is called in the wait() loop.
            readies = chain(repeat(False, command.waits), repeat(True))
            channel.exit_status_ready.side_effect = readies

            channels.append(channel)

        # Have our transport yield those channel mocks in order when
        # open_session() is called.
        transport.open_session.side_effect = channels

        self.client = client
        self.channels = channels

    def sanity_check(self):
        # Per-session we expect a single transport get
        transport = self.client.get_transport
        transport.assert_called_once_with()
        # And a single connect to our target host.
        self.client.connect.assert_called_once_with(
            username=self.user or ANY,
            hostname=self.host or ANY,
            port=self.port or ANY,
        )

        # Calls to open_session will be 1-per-command but are on transport, not
        # channel, so we can only really inspect how many happened in
        # aggregate. Save a list for later comparison to call_args.
        session_opens = []

        for channel, command in zip(self.channels, self.commands):
            # Expect an open_session for each command exec
            session_opens.append(call())
            # Expect that the channel gets an exec_command or etc
            command.expect_execution(channel=channel)
            # Expect written stdin, if given
            if command.in_:
                assert channel._stdin.getvalue() == command.in_

        # Make sure open_session was called expected number of times.
        calls = transport.return_value.open_session.call_args_list
        assert calls == session_opens

class MockRemote(object):
    """
    Class representing mocked remote state.

    By default this class is set up for start/stop style patching as opposed to
    the more common context-manager or decorator approach; this is so it can be
    used in situations requiring setup/teardown semantics.

    Defaults to setting up a single anonymous `Session`, so it can be used as a
    "request & forget" pytest fixture. Users requiring detailed remote session
    expectations can call methods like `expect`, which wipe that anonymous
    Session & set up a new one instead.

    .. versionadded:: 2.1
    """

    def __init__(self):
        self.expect_sessions(Session())

    # TODO: make it easier to assume single session w/ >1 command?

    def expect(self, *args, **kwargs):
        """
        Convenience method for creating & 'expect'ing a single `Session`.

        Returns the single `MockChannel` yielded by that Session.

        .. versionadded:: 2.1
        """
        return self.expect_sessions(Session(*args, **kwargs))[0]

    def expect_sessions(self, *sessions):
        """
        Sets the mocked remote environment to expect the given ``sessions``.

        Returns a list of `MockChannel` objects, one per input `Session`.

        .. versionadded:: 2.1
        """
        # First, stop the default session to clean up its state, if it seems to
        # be running.
        self.stop()
        # Update sessions list with new session(s)
        self.sessions = sessions
        # And start patching again, returning mocked channels
        return self.start()

    def start(self):
        """
        Start patching SSHClient with the stored sessions, returning channels.

        .. versionadded:: 2.1
        """
        # Patch SSHClient so the sessions' generated mocks can be set as its
        # return values
        self.patcher = patcher = patch("fabric.connection.SSHClient")
        SSHClient = patcher.start()
        # Mock clients, to be inspected afterwards during sanity-checks
        clients = []
        for session in self.sessions:
            session.generate_mocks()
            clients.append(session.client)
        # Each time the mocked SSHClient class is instantiated, it will
        # yield one of our mocked clients (w/ mocked transport & channel)
        # generated above.
        SSHClient.side_effect = clients
        return list(chain.from_iterable(x.channels for x in self.sessions))

    def stop(self):
        """
        Stop patching SSHClient.

        .. versionadded:: 2.1
        """
        # Short circuit if we don't seem to have start()ed yet.
        if not hasattr(self, "patcher"):
            return
        # Stop patching SSHClient
        self.patcher.stop()

    def sanity(self):
        """
        Run post-execution sanity checks (usually 'was X called' tests.)

        .. versionadded:: 2.1
        """
        for session in self.sessions:
            # Basic sanity tests about transport, channel etc
            session.sanity_check()

# TODO: unify with the stuff in paramiko itself (now in its tests/conftest.py),
# they're quite distinct and really shouldn't be.
class MockSFTP(object):
    """
    Class managing mocked SFTP remote state.

    Used in start/stop fashion in eg doctests; wrapped in the SFTP fixtures in
    conftest.py for main use.

    .. versionadded:: 2.1
    """

    def __init__(self, autostart=True):
        if autostart:
            self.start()

    def start(self):
        # Set up mocks
        self.os_patcher = patch("fabric.transfer.os")
        self.client_patcher = patch("fabric.connection.SSHClient")
        self.path_patcher = patch("fabric.transfer.Path")
        mock_os = self.os_patcher.start()
        Client = self.client_patcher.start()
        self.path_patcher.start()
        sftp = Client.return_value.open_sftp.return_value

        # Handle common filepath massage actions; tests will assume these.
        def fake_abspath(path):
            # Run normpath to avoid tests not seeing abspath wrinkles (like
            # trailing slash chomping)
            return "/local/{}".format(os.path.normpath(path))

        mock_os.path.abspath.side_effect = fake_abspath
        sftp.getcwd.return_value = "/remote"
        # Ensure stat st_mode is a real number; Python 2 stat.S_IMODE doesn't
        # appear to care if it's handed a MagicMock, but Python 3's does (?!)
        fake_mode = 0o644  # arbitrary real-ish mode
        sftp.stat.return_value.st_mode = fake_mode
        mock_os.stat.return_value.st_mode = fake_mode
        # Not super clear to me why the 'wraps' functionality in mock isn't
        # working for this :( reinstate a bunch of os(.path) so it still works
        mock_os.sep = os.sep
        for name in ("basename", "split", "join", "normpath"):
            getattr(mock_os.path, name).side_effect = getattr(os.path, name)
        # Return the sftp and OS mocks for use by decorator use case.
        return sftp, mock_os

    def stop(self):
        self.os_patcher.stop()
        self.client_patcher.stop()
        self.path_patcher.stop()


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>
  <string name="app_description">Hatékony feljegyzés készítő Jehova Tanúi számára. Vezetheted az elterjesztett kiadványokat és a szolgálatban töltött időt, jegyzeteket készíthetsz a területedről, illetve az érdeklődőkről.

Jellemzők:
* Könnyedén rögzítheted az adatokat a szolgálatban.
* Többféle megjelenítés; kertes házas, és társasházas területekhez is megfelelő.
* Megtekinthető a területek listája, a területen lévő háztartások listája, az érdeklődők, illetve az egyes látogatások egy-egy személynél.
* Minden látogatásnál rögzíti a dátumot és az időt.
* A  szolgálatban eltöltött idő mérése stopperrel (számláló).
* Háztartások rendszerezése színekkel, automatikusan vagy manuálisan.
* Összeadja az elterjesztett irodalmat, az újra látogatásokat, és a Bibliatanulmányozásokat.
* A havi jelentések részletes rögzítése és megőrzése.
* Összeállítja a hó végi szántóföldi jelentést, és ezt egy gombnyomással el lehet küldeni e-mailben vagy sms-ben.
* Kézi, vagy automatikus biztonsági mentések.
* Adatok mentése a Dropbox-ba, és onnan szinkronizálás az eszközre.
* Teljesen ingyenes alkalmazás, nincsenek hirdetések. Ha akarsz, az alkalmazáson belül tudsz adni adományt, hogy támogasd a fejlesztést.

Adj visszajelzést, vagy tegyél fel kérdést a Google+ Community-n:
https://plus.google.com/communities/112371364498094492171

Nyílt forráskódú (open source) projekt: https://github.com/jwdroid/jwdroid

Címkék: JW, Jehova Tanúi, prédikálás, prédikál, szolgálat, jegyzetelő, feljegyzések

</string>
  <string name="lbl_territory_name">Terület név:</string>
  <string name="title_territory_add">Terület hozzáadása</string>
  <string name="lbl_territory_desc">Rövid leírás:</string>
  <string name="err_empty_name">Nem írtál be semmit!</string>
  <string name="msg_territory_added">Terület hozzáadva</string>
  <string name="msg_territory_deleted">Terület törölve</string>
  <string name="territory_list_empty">Még nincsenek területek. A fenti gomb segítségével tudsz új területet létrehozni.</string>
  <string name="dlg_territory_delete_msg">A terület törlését nem lehet majd visszavonni. Biztosan törölni akarod?</string>
  <string name="dlg_territory_delete_title">Terület törlése</string>
  <string name="dlg_territory_add_label">A terület neve:</string>
  <string name="dlg_territory_add_note">Például az utca neve</string>
  <string name="btn_add">Hozzáadás</string>
  <string name="btn_ok">OK</string>
  <string name="btn_yes">Igen</string>
  <string name="btn_no">Nem</string>
  <string name="btn_cancel">Vissza</string>
  <string name="lbl_magazines">Folyóiratok:</string>
  <string name="lbl_brochures">Tájékoztatólapok:</string>
  <string name="lbl_books">Könyvek:</string>
  <string name="lbl_returns">Újralátogatások:</string>
  <string name="lbl_hours">Órák:</string>
  <string name="lbl_studies">Tanulmányozás:</string>
  <string name="title_chrono">Számláló</string>
  <string name="lbl_chrono_started_time">Szolgálat kezdete: %s</string>
  <string name="lbl_chrono_stopped">A számláló áll</string>
  <string name="btn_chrono_pause">Szünet</string>
  <string name="btn_chrono_resume">Folytatás</string>
  <string name="btn_chrono_finish">Befejezés</string>
  <string name="btn_chrono_start">Indítás</string>
  <string name="msg_chrono_finish">Befejezed a szolgálatot?</string>
  <string name="msg_chrono_start">Elkezded a szolgálatot?</string>
  <string name="msg_chrono_service_started">A szolgálati idő mérése elkezdődött</string>
  <string name="lbl_chrono_current_time">Szolgálatban töltött idő:</string>
  <string name="lbl_chrono_service_note">A számláló azonnali megnyitása</string>
  <string name="action_add_single_object">Egy hozzáadása</string>
  <string name="action_add_many_objects">Több hozzáadása</string>
  <string name="dlg_add_single_object_note">Például a házszámot vagy a lakás számát írd ide</string>
  <string name="msg_object_name">Megnevezés:</string>
  <string name="lbl_set_row">Sorok:</string>
  <string name="lbl_set_col">Oszlopok:</string>
  <string name="lbl_numbers_from">Számok  -tól:</string>
  <string name="lbl_numbers_to">-ig:</string>
  <string name="msg_arrange_after_add">Háztartások hozzáadva. Hogy jobban átlásd, átrendezheted a sorokat és az oszlopokat (például a kaputelefon elrendezése, vagy az emeletenkénti lakások száma szerint), az " Átrendezés " menüpontnál. Átrendezed azonnal?</string>
  <string name="msg_error">Hiba!</string>
  <string name="msg_object_deleted">Háztartás törölve</string>
  <string name="err_invalid_input">Hibás érték!</string>
  <string name="err_no_cols_value">Add meg az oszlopok számát!</string>
  <string name="action_object_change_name">Megnevezés</string>
  <string name="action_object_change_color">Színek</string>
  <string name="action_object_move_up">Fel</string>
  <string name="action_object_move_down">Le</string>
  <string name="action_object_delete">Törlés</string>
  <string name="action_object_move">Mozgatás</string>
  <string name="lbl_from">Ettől:</string>
  <string name="lbl_to">Eddig:</string>
  <string name="lbl_rows">Sorok:</string>
  <string name="lbl_cols">Oszlopok:</string>
  <string name="li_top_down">Fentről lefelé</string>
  <string name="li_bottom_up">Alulról felfelé</string>
  <string name="li_left_right">Balról jobbra</string>
  <string name="li_right_left">Jobbról balra</string>
  <string name="lbl_one_color">  Egyszínű</string>
  <string name="lbl_two_colors">  Két színű</string>
  <string name="lbl_door_empty">Házigazda létrehozása.\n\n Új házigazda hozzáadása a fenti gombbal.</string>
  <string name="lbl_group_empty">Ez a terület még üres. \n\nÚj háztartást a fenti gombbal tudsz hozzáadni.</string>
  <string name="title_help">Súgó</string>
  <string name="title_territory_list">Területek</string>
  <string name="title_people">Érdeklődők</string>
  <string name="title_reports">Jelentések</string>
  <string name="lbl_people_list_empty">Még nincsenek érdeklődők. \nA fenti gombbal tudsz új érdeklődőt felvenni, vagy a "Területek" résznél.</string>
  <string name="lbl_person_add_from_people">Ne felejtsd, hogy ezt a személyt úgy vetted fel, hogy nincs hozzákapcsolva egyik területhez sem.</string>
  <string name="title_report">%s jelentése</string>
  <string name="action_calc_type_sessions">By service list</string>
  <string name="action_calc_type_visits">By visits</string>
  <string name="lbl_report_no_data">Nincs adat</string>
  <string name="msg_delete_session">Biztosan törölni akarod ezt a szolgálatot?</string>
  <string name="msg_session_deleted">Szolgálat törölve</string>
  <string name="action_session_delete">Törlés</string>
  <string name="title_session">Service %s</string>
  <string name="lbl_report_list_empty">Még nincsenek jelentések</string>
  <string name="lbl_report_summary">Összesen</string>
  <string name="lbl_report_empty">Üres jelentés.</string>
  <string name="lbl_session_desc">Megjegyzés a szolgálathoz:</string>
  <string name="lbl_territory_notes">Megjegyzések</string>
  <string name="lbl_territory_got">Területet felvetted:</string>
  <string name="lbl_territory_finished">Területet bemunkáltad:</string>
  <string name="lbl_territory_last_visit">Utolsó látogatás:</string>
  <string name="action_territory_change_name">Név</string>
  <string name="action_territory_info">További részletek</string>
  <string name="action_territory_delete">Törlés</string>
  <string name="lbl_visit_type">Látogatás:</string>
  <string-array name="visit_types">
    <item>NO</item>
    <item>Tanúskodás</item>
    <item>Újralátogatás</item>
    <item>Bibliatanulmányozás</item>
  </string-array>
  <string name="lbl_visit_date">Dátum:</string>
  <string name="chk_visit_calc_auto">Take from text</string>
  <string name="msg_choose_color">Válassz színt:</string>
  <string name="msg_person_desc">Írd be a személy nevét:</string>
  <string name="msg_delete_visit">Biztosan törölni akarod ezt a látogatást?</string>
  <string name="msg_delete_person">Biztosan törölni akarod ezt a személyt, és minden hozzá kapcsolódó látogatást?</string>
  <string name="msg_person_deleted">Személy törölve</string>
  <string name="msg_visit_deleted">Látogatás törölve</string>
  <string name="title_visit">Látogatás</string>
  <string name="action_person_change">Módosít</string>
  <string name="action_person_delete">Törlés</string>
  <string name="action_person_reject">Nem érdekli</string>
  <string name="action_person_nreject">Mégis érdekli</string>
  <string name="action_visit_delete">Törlés</string>
  <string name="menu_preferences">Beállítások</string>
  <string name="menu_feedback">Visszajelzés küldése</string>
  <string name="menu_help">Súgó</string>
  <string name="menu_session_date">Date and time</string>
  <string name="menu_change_session_date">Change date</string>
  <string name="menu_change_session_time">Change time</string>
  <string name="menu_set_position">Set position</string>
  <string name="menu_move_up">Mozgatás felfelé</string>
  <string name="menu_move_down">Mozgatás lefelé</string>
  <string name="menu_move_left">Mozgatás balra</string>
  <string name="menu_move_right">Mozgatás jobbra</string>
  <string name="menu_territory_info">Info</string>
  <string name="menu_territory_layout">Elrendezés</string>
  <string name="menu_territory_arrange">Kézi beállítás</string>
  <string name="menu_territory_shift_up">Mindet felfelé</string>
  <string name="menu_territory_shift_down">Mindet lefelé</string>
  <string name="menu_territory_shift_left">Mindet balra</string>
  <string name="menu_territory_shift_right">Mindet jobbra</string>
  <string name="title_preferences">Beállítások</string>
  <string name="pref_title_appearance">Megjelenítés</string>
  <string name="pref_list_text_rows">Sorok száma</string>
  <string name="pref_list_text_rows_note">Hány sor látszódjon a háztartásoknál (lista nézetben) az utolsó látogatás jegyzeteiből</string>
  <string name="pref_table_button_size">Négyzetek mérete</string>
  <string name="pref_table_button_size_note">A háztartásokat jelölő négyzetek mérete (táblázatos nézetben)</string>
  <string-array name="entries_table_button_size_preference">
    <item>Kicsi</item>
    <item>Közepes</item>
    <item>Nagy</item>
  </string-array>
  <string name="pref_title_colors">Színek</string>
  <string name="pref_autocolor">Automatikus színbeállítás</string>
  <string name="pref_autocolor_note">Automatikusan állítsa be a színt az alábbi beállítások szerint</string>
  <string name="pref_assign_colors">Szín beállítása</string>
  <string name="pref_color_reject">Nem érdekli</string>
  <string name="pref_color_visit">Látogatás</string>
  <string name="pref_color_return">Újralátogatás</string>
  <string name="pref_color_study">Bibliatanulmányozás</string>
  <string-array name="entries_color_preference">
    <item>Ne változtassa</item>
    <item>Kék</item>
    <item>Zöld</item>
    <item>Sárga</item>
    <item>Piros</item>
    <item>Sötétkék</item>
    <item>Sötétzöld</item>
    <item>Sötétsárga</item>
    <item>Sötétpiros</item>
  </string-array>
  <string-array name="months">
    <item>Január</item>
    <item>Február</item>
    <item>Március</item>
    <item>Április</item>
    <item>Május</item>
    <item>Június</item>
    <item>Július</item>
    <item>Augusztus</item>
    <item>Szeptember</item>
    <item>Október</item>
    <item>November</item>
    <item>December</item>
  </string-array>
  <string-array name="plural_magazines">
    <item>folyóirat</item>
    <item>folyóiratok</item>
    <item>folyóiratok</item>
  </string-array>
  <string-array name="plural_brochures">
    <item>brochure</item>
    <item>brochures</item>
    <item>brochures</item>
  </string-array>
  <string-array name="plural_books">
    <item>könyv</item>
    <item>könyvek</item>
    <item>könyvek</item>
  </string-array>
  <string-array name="plural_returns">
    <item>újralátogatás</item>
    <item>újralátogatások</item>
    <item>újralátogatások</item>
  </string-array>
  <string-array name="plural_studies">
    <item>bibliatanulmányozás</item>
    <item>bibliatanulmányozások</item>
    <item>bibliatanulmányozások</item>
  </string-array>
  <string-array name="plural_visits">
    <item>visit</item>
    <item>visits</item>
    <item>visits</item>
  </string-array>
  <string name="title_tip">Tip</string>

  <string name="msg_person">Érdeklődő</string>
  <string name="lbl_person_desc">Érdeklődő neve</string>
  <string name="lbl_male">Férfi</string>
  <string name="lbl_female">Nő</string>
  <string name="lbl_male_letter">F</string>
  <string name="lbl_female_letter">N</string>
  <string name="msg_choose_age">Válassz életkort:</string>
  <string name="lbl_visit_text">A látogatás tartalma</string>
  <string name="action_object_add_na_visit">Nincs otthon</string>
  <string name="msg_added_na_visit">NO -val megjelölve %s -kor</string>
  <string name="pref_hide_visited">A mai látogatások elrejtése</string>
  <string name="pref_hide_visited_note">Rejtse el azokat a háztartásokat, amelyeket ma már meglátogattuk</string>
  <string name="msg_delete_object">Itt minden érdeklődő és a hozzájuk kapcsolódó látogatások ki lesznek törölve. Biztosan ki akarod törölni ezt a háztartást?</string>
  <string name="menu_territory_sort">Sorrend</string>
  <string name="msg_territory_sort">Sorba rakod a háztartásokat a nevük szerint?</string>
  <string-array name="menu_move_list">
    <item>Set position</item>
    <item>Mozgatás felfelé</item>
    <item>Mozgatás lefelé</item>
  </string-array>
  <string name="pref_object_add_sorted">Auto sort</string>
  <string name="pref_object_add_sorted_note">Insert a new household with sorting by name (only for list view)</string>
  <string name="menu_backups">Backups</string>
  <string name="lbl_backup_list_empty">Backup list empty.</string>
  <string name="msg_backup_failed">Error creating backup copy</string>
  <string name="pref_title_backup">Backups</string>
  <string name="pref_autobackup">Auto backup</string>
  <string name="pref_autobackup_note">Automatically create a new backup after each service session</string>
  <string name="pref_num_backups">Copies number</string>
  <string name="pref_num_backups_note">Max number of stored backups</string>
  <string name="msg_create_backup">Create new backup?</string>
  <string name="msg_delete_backup">Delete this backup?</string>
  <string name="msg_restore_backup">Warning: ALL current data will be permanently lost and replaced with data from the backup. Are you sure?</string>
  <string name="action_backup_restore">Restore</string>
  <string name="action_backup_delete">Delete</string>
  <string name="msg_restore_backup_failed">Error restoring backup copy</string>
  <string name="msg_restore_backup_success">Backup has been successfully restored</string>
  <string name="msg_revision_notes">What\'s new</string>

  <string name="msg_backup_created">Backup created</string>
  <string name="pref_backups_manage">Manage backups</string>
  <string name="pref_backups_manage_note">View list of created backups</string>

  <string name="lbl_tracts">Tájékoztatólapok:</string>
  <string-array name="plural_tracts">
    <item>tájékoztatólap</item>
    <item>tájékoztatólapok</item>
    <item>tájékoztatólapok</item>
  </string-array>
  <string name="lbl_brochures_tracts">Füzetek & tájékoztatólapok:</string>
  <string-array name="plural_brochures_tracts">
    <item>brochure or tract</item>
    <item>brochures or tracts</item>
    <item>brochures or tracts</item>
  </string-array>
  <string name="lbl_please_wait">Please wait...</string>
  <string name="title_drive">Backup to Dropbox</string>
  <string name="lbl_drive">Dropbox</string>
  <string name="lbl_local_folder">Local Folder</string>
  <string name="lbl_drive_desc">Your data can be automatically uploaded to your Dropbox and synced across connected devices</string>
  <string name="lbl_drive_turn_on">Turn On</string>
  <string name="lbl_backups_empty">Backups list is empty</string>
  <string name="pref_dropbox_off">Disconnect from Dropbox</string>
  <string name="pref_dropbox_off_note">Log out from Dropbox account and stop syncing</string>

  <string name="msg_tip_hold_plus">Tip: press & hold the \"+\" button to add a big amount of time</string>

  <string name="lbl_placements">Kiadványok:</string>
  <string name="lbl_videos">Megnézett videók:</string>
  <string-array name="plural_placements">
    <item>placement</item>
    <item>placements</item>
    <item>placements</item>
  </string-array>
  <string-array name="plural_videos">
    <item>video showing</item>
    <item>video showings</item>
    <item>video showings</item>
  </string-array>
  <string name="lbl_service_year" formatted="false">%s/%s szolgálati év</string>
  <string name="msg_contribute">Úgy látjuk te is használtad a JW Jegyzetelőt, és nagyon örülünk, ha hasznosnak találtad!\n\n Az alkalmazást 2010-ben készítettük, most pedig azon dolgozunk, hogy tovább fejlesszük ezt a verziót, minél korszerűbbre, több funkcióval. Hozzájárulhatsz a fejlesztések mielőbbi elkészüléséhez azzal, hogy támogatod a projektet. Köszönjük!\n\n --- a JW Jegyzetelő Csapata</string>
  <string name="lbl_contribute">Nagyon örülünk, hogy hasznosnak találtad a JW Jegyzetelőt. Ezt az alkalmazást 2010-ben készítettük, most pedig azon dolgozunk, hogy tovább fejlesszük ezt a verziót, minél korszerűbbre, több funkcióval. Hozzájárulhatsz a fejlesztések mielőbbi elkészüléséhez azzal, hogy támogatod a projektet. Köszönjük!</string>
  <string name="btn_donate">Adományozhatsz a fejlesztések támogatására</string>
  <string name="btn_review">Értékelheted a Google Play-en</string>
  <string name="btn_translate">Segíthetsz a fordításban</string>
  <string name="btn_save">Mentés</string>
  <string name="btn_send">Küldés</string>
  <string name="btn_refresh">Frissités</string>
  <string name="btn_learn_more">További információ</string>
  <string name="btn_no_thanks">Köszönöm, nem</string>
  <string name="btn_rename">Átnevezés</string>
  <string name="title_contribute">Hozzájárulás</string>
  <string name="lbl_donation">Adomány:</string>
  <string name="lbl_recurring">Rendszeresség:</string>
  <string-array name="btn_recurring">
    <item>Csak egyszer</item>
    <item>Félévente</item>
    <item>Évente</item>
  </string-array>
  <string name="lbl_payments_processed_by">Az adományozást a Google Play-en keresztül lehet megtenni.</string>

  <string name="msg_revision_notes_1_4_1" formatted="true">Version 1.4.1\n\nAdded a link to Google+ Community to the main menu.\n\nAdded a link to the online translation service to the contribution dialog. Translators are welcome!\n\nVersion 1.4.0\n\nUpdated reports to the new 2016 format.\n\nNew modern visual theme.\n\nAdded service year total hour counters to the Reports section.\n\nRemoved placements text templates as they are unneccessary now.\n\nAdded an option to make an in-app donation payment to support the development.\n\nNew placements calculating mode in the Chronometer.\n\nFixed a bug when restoring from the backup failed sometimes.\n\nFixed a bug with disappearing of old report data.</string>
  <string name="chk_chrono_calc_auto">Add from visits</string>
  <string name="menu_community">Google+ Community</string>

  <string name="menu_about_app">Rólunk</string>
  <string name="lbl_calc_studies">Bible studies are taken from visits with the corresponding visit type.</string>

  <string name="action_save_data">Save all data</string>
  <string name="action_restore_data">Restore all data</string>
  <string name="msg_revision_notes_1_5" formatted="true">Version 1.5.0\n\nNow you can save and restore data using any file sharing application installed on the device.\n\nReports can be sent using any text messenger installed on the device.</string>
</resources>


text:
package au.edu.uts.eng.remotelabs.schedserver.permissions.intf.types;

import java.util.HashMap;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

import org.apache.axiom.om.OMConstants;
import org.apache.axiom.om.OMDataSource;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.llom.OMSourcedElementImpl;
import org.apache.axis2.databinding.ADBBean;
import org.apache.axis2.databinding.ADBDataSource;
import org.apache.axis2.databinding.ADBException;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReader;
import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl;
import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter;

/**
 * PersonaType bean class.
 */
public class PersonaType implements ADBBean
{
    private static final long serialVersionUID = 6780049826926191697L;

    public static final QName MY_QNAME = new QName("http://remotelabs.eng.uts.edu.au/schedserver/permissions",
            "persona_type1", "ns1");

    private static HashMap<String, PersonaType> _table_ = new HashMap<String, PersonaType>();

    public static final String _ADMIN = ConverterUtil.convertToString("ADMIN");
    public static final String _ACADEMIC = ConverterUtil.convertToString("ACADEMIC");
    public static final String _RESEARCH = ConverterUtil.convertToString("RESEARCH");
    public static final String _USER = ConverterUtil.convertToString("USER");
    public static final String _DEMO = ConverterUtil.convertToString("DEMO");
    public static final String _NOTFOUND = ConverterUtil.convertToString("NOTFOUND");

    public static final PersonaType ADMIN = new PersonaType(PersonaType._ADMIN, true);
    public static final PersonaType ACADEMIC = new PersonaType(PersonaType._ACADEMIC, true);
    public static final PersonaType RESEARCH = new PersonaType(PersonaType._RESEARCH, true);
    public static final PersonaType USER = new PersonaType(PersonaType._USER, true);
    public static final PersonaType DEMO = new PersonaType(PersonaType._DEMO, true);
    public static final PersonaType NOTFOUND = new PersonaType(PersonaType._NOTFOUND, true);

    protected String personaType;

    private static String generatePrefix(final String namespace)
    {
        if (namespace.equals("http://remotelabs.eng.uts.edu.au/schedserver/permissions"))
        {
            return "ns1";
        }
        return BeanUtil.getUniquePrefix();
    }

    protected PersonaType(final String value, final boolean isRegisterValue)
    {
        this.personaType = value;
        if (isRegisterValue)
        {
            PersonaType._table_.put(this.personaType, this);
        }
    }

    public String getValue()
    {
        return this.personaType;
    }

    @Override
    public boolean equals(final Object obj)
    {
        return (obj == this);
    }

    @Override
    public int hashCode()
    {
        return this.toString().hashCode();
    }

    @Override
    public String toString()
    {
        return this.personaType.toString();
    }

    public static boolean isReaderMTOMAware(final XMLStreamReader reader)
    {
        boolean isReaderMTOMAware = false;
        try
        {
            isReaderMTOMAware = Boolean.TRUE.equals(reader.getProperty(OMConstants.IS_DATA_HANDLERS_AWARE));
        }
        catch (final IllegalArgumentException e)
        {
            isReaderMTOMAware = false;
        }
        return isReaderMTOMAware;
    }

    public OMElement getOMElement(final QName parentQName, final OMFactory factory) throws ADBException
    {
        final OMDataSource dataSource = new ADBDataSource(this, PersonaType.MY_QNAME)
        {
            @Override
            public void serialize(final MTOMAwareXMLStreamWriter xmlWriter) throws XMLStreamException
            {
                PersonaType.this.serialize(PersonaType.MY_QNAME, factory, xmlWriter);
            }
        };
        return new OMSourcedElementImpl(PersonaType.MY_QNAME, factory, dataSource);
    }

    @Override
    public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter)
            throws XMLStreamException, ADBException
    {
        this.serialize(parentQName, factory, xmlWriter, false);
    }

    @Override
    public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter,
            final boolean serializeType) throws XMLStreamException, ADBException
    {
        final String namespace = parentQName.getNamespaceURI();
        final String localName = parentQName.getLocalPart();

        if (!namespace.equals(""))
        {
            String prefix = xmlWriter.getPrefix(namespace);
            if (prefix == null)
            {
                prefix = PersonaType.generatePrefix(namespace);
                xmlWriter.writeStartElement(prefix, localName, namespace);
                xmlWriter.writeNamespace(prefix, namespace);
                xmlWriter.setPrefix(prefix, namespace);
            }
            else
            {
                xmlWriter.writeStartElement(namespace, localName);
            }
        }
        else
        {
            xmlWriter.writeStartElement(localName);
        }

        if (serializeType)
        {
            final String namespacePrefix = this.registerPrefix(xmlWriter,
                    "http://remotelabs.eng.uts.edu.au/schedserver/permissions");
            if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0))
            {
                this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix
                        + ":persona_type1", xmlWriter);
            }
            else
            {
                this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "persona_type1",
                        xmlWriter);
            }
        }

        if (this.personaType == null)
        {
            throw new ADBException("Value cannot be null !!");
        }
        else
        {
            xmlWriter.writeCharacters(this.personaType);
        }

        xmlWriter.writeEndElement();
    }

    private void writeAttribute(final String prefix, final String namespace, final String attName,
            final String attValue, final XMLStreamWriter xmlWriter) throws XMLStreamException
    {
        if (xmlWriter.getPrefix(namespace) == null)
        {
            xmlWriter.writeNamespace(prefix, namespace);
            xmlWriter.setPrefix(prefix, namespace);
        }

        xmlWriter.writeAttribute(namespace, attName, attValue);
    }

    private String registerPrefix(final XMLStreamWriter xmlWriter, final String namespace) throws XMLStreamException
    {
        String prefix = xmlWriter.getPrefix(namespace);
        if (prefix == null)
        {
            prefix = PersonaType.generatePrefix(namespace);
            while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null)
            {
                prefix = BeanUtil.getUniquePrefix();
            }

            xmlWriter.writeNamespace(prefix, namespace);
            xmlWriter.setPrefix(prefix, namespace);
        }

        return prefix;
    }

    @Override
    public XMLStreamReader getPullParser(final QName qName) throws ADBException
    {

        return new ADBXMLStreamReaderImpl(PersonaType.MY_QNAME, new Object[] { ADBXMLStreamReader.ELEMENT_TEXT,
                ConverterUtil.convertToString(this.personaType) }, null);
    }

    public static class Factory
    {
        public static PersonaType fromValue(final String value) throws IllegalArgumentException
        {
            final PersonaType enumeration = PersonaType._table_.get(value);

            if (enumeration == null)
            {
                throw new IllegalArgumentException();
            }
            return enumeration;
        }

        public static PersonaType fromString(final String value, final String namespaceURI)
                throws IllegalArgumentException
        {
            try
            {
                return Factory.fromValue(ConverterUtil.convertToString(value));
            }
            catch (final Exception e)
            {
                throw new IllegalArgumentException();
            }
        }

        public static PersonaType fromString(final XMLStreamReader xmlStreamReader, final String content)
        {
            if (content.indexOf(":") > -1)
            {
                final String prefix = content.substring(0, content.indexOf(":"));
                final String namespaceUri = xmlStreamReader.getNamespaceContext().getNamespaceURI(prefix);
                return PersonaType.Factory.fromString(content, namespaceUri);
            }
            else
            {
                return PersonaType.Factory.fromString(content, "");
            }
        }

        public static PersonaType parse(final XMLStreamReader reader) throws Exception
        {
            PersonaType object = null;

            String prefix = "";
            String namespaceuri = "";
            try
            {
                while (!reader.isStartElement() && !reader.isEndElement())
                {
                    reader.next();
                }

                while (!reader.isEndElement())
                {
                    if (reader.isStartElement() || reader.hasText())
                    {
                        final String content = reader.getElementText();
                        if (content.indexOf(":") > 0)
                        {
                            prefix = content.substring(0, content.indexOf(":"));
                            namespaceuri = reader.getNamespaceURI(prefix);
                            object = PersonaType.Factory.fromString(content, namespaceuri);
                        }
                        else
                        {
                            object = PersonaType.Factory.fromString(content, "");
                        }
                    }
                    else
                    {
                        reader.next();
                    }
                }
            }
            catch (final XMLStreamException e)
            {
                throw new Exception(e);
            }

            return object;
        }
    }
}


text:
import logging
from abc import abstractmethod, ABC

from sn_agent.job.job_descriptor import JobDescriptor
from sn_agent.ontology.service_descriptor import ServiceDescriptor

logger = logging.getLogger(__name__)

class AgentABC(ABC):
    def __init__(self, app, agent_id):
        self.app = app
        self.agent_id = agent_id

    @abstractmethod
    def can_perform(self, service: ServiceDescriptor) -> bool:
        """
        :param service: the service to perform
        :result: can this agent perform the described service?
        """
        pass

    @abstractmethod
    def perform(self, job: JobDescriptor):
        """
        :param job: the service to perform
        """
        pass


text:
<?php

abstract class CM_Model_StorageAdapter_AbstractAdapter extends CM_Class_Abstract {

    /**
     * @param int   $type
     * @param array $id
     * @return array|false
     */
    abstract public function load($type, array $id);

    /**
     * @param array $idTypeList [['type' => int, 'id' => array],...]
     * @return array
     *
     * Return Array must preserve the keys of $idTypeList and omit entries that weren't found
     */
    abstract public function loadMultiple(array $idTypeList);

    /**
     * @param int   $type
     * @param array $id
     * @param array $data
     */
    abstract public function save($type, array $id, array $data);

    /**
     * @param int   $type
     * @param array $data
     * @return array
     */
    abstract public function create($type, array $data);

    /**
     * @param int   $type
     * @param array $id
     */
    abstract public function delete($type, array $id);
}


text:
let color = "red";
function displayColor() {
  alert(this.color);
}
displayColor.call(null);


text:
<?php

// Create new DOM Document for the response
$dom = new DOMDocument('1.0', 'UTF-8');

// Add response child
$response = $dom->createElement('Response');
$dom->appendChild($response);

// Add dial command as child in response
$dial = $dom->createElement('Dial');

// Add a number target and append it to the dial command, we're calling '+49211000000' - you should maybe change that... ;-)
$number = $dom->createElement('Number','49211000000');

$dial->appendChild($number);

$response->appendChild($dial);

header('Content-type: application/xml');
echo $dom->saveXML();


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.cassandra;

import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.camel.spi.EndpointUriFactory;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
public class CassandraEndpointUriFactory extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {

    private static final String BASE = ":beanRef:hosts:port/keyspace";

    private static final Set<String> PROPERTY_NAMES;
    private static final Set<String> SECRET_PROPERTY_NAMES;
    static {
        Set<String> props = new HashSet<>(36);
        props.add("basicPropertyBinding");
        props.add("backoffMultiplier");
        props.add("beanRef");
        props.add("session");
        props.add("synchronous");
        props.add("initialDelay");
        props.add("scheduler");
        props.add("prepareStatements");
        props.add("password");
        props.add("bridgeErrorHandler");
        props.add("useFixedDelay");
        props.add("runLoggingLevel");
        props.add("backoffErrorThreshold");
        props.add("clusterName");
        props.add("greedy");
        props.add("scheduledExecutorService");
        props.add("repeatCount");
        props.add("timeUnit");
        props.add("resultSetConversionStrategy");
        props.add("hosts");
        props.add("sendEmptyMessageWhenIdle");
        props.add("schedulerProperties");
        props.add("loadBalancingPolicyClass");
        props.add("exchangePattern");
        props.add("datacenter");
        props.add("backoffIdleThreshold");
        props.add("keyspace");
        props.add("lazyStartProducer");
        props.add("delay");
        props.add("pollStrategy");
        props.add("port");
        props.add("startScheduler");
        props.add("consistencyLevel");
        props.add("exceptionHandler");
        props.add("cql");
        props.add("username");
        PROPERTY_NAMES = Collections.unmodifiableSet(props);
        SECRET_PROPERTY_NAMES = Collections.emptySet();
    }

    @Override
    public boolean isEnabled(String scheme) {
        return "cql".equals(scheme);
    }

    @Override
    public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
        String syntax = scheme + BASE;
        String uri = syntax;

        Map<String, Object> copy = new HashMap<>(properties);

        uri = buildPathParameter(syntax, uri, "beanRef", null, false, copy);
        uri = buildPathParameter(syntax, uri, "hosts", null, false, copy);
        uri = buildPathParameter(syntax, uri, "port", null, false, copy);
        uri = buildPathParameter(syntax, uri, "keyspace", null, false, copy);
        uri = buildQueryParameters(uri, copy, encode);
        return uri;
    }

    @Override
    public Set<String> propertyNames() {
        return PROPERTY_NAMES;
    }

    @Override
    public Set<String> secretPropertyNames() {
        return SECRET_PROPERTY_NAMES;
    }

    @Override
    public boolean isLenientProperties() {
        return false;
    }
}


text:
<?php namespace App\Factory;

use App\ReferrerRedirect;
use Carbon\CarbonInterface;

class ReferrerRedirectFactory
{
    private $startsAt;
    private $expiresAt;

    public function create()
    {
        $model = $this->make();
        $model->save();

        return $model;
    }

    public function expired()
    {
        return $this->withStartsAt(now()->subDays(2))
            ->withExpiresAt(now()->subDay());
    }

    public function make()
    {
        $model = new ReferrerRedirect;
        $model->to = fake()->url();
        $model->from = '/life';
        $model->clicks = 0;
        $model->starts_at = $this->startsAt ?? now()->toDateTimeString();
        $model->expires_at = $this->expiresAt ?? now()->addDays()->toDateTimeString();

        return $model;
    }

    public static function new(): self
    {
        return new self;
    }

    public function withExpiresAt(CarbonInterface $expiresAt)
    {
        $factory = clone $this;
        $factory->expiresAt = $expiresAt;

        return $factory;
    }

    public function withStartsAt(CarbonInterface $startsAt)
    {
        $factory = clone $this;
        $factory->startsAt = $startsAt->toDateTimeString();

        return $factory;
    }
}


text:
fn main() {
    // Can't use a sign on unsigned conversions
    fmt!("%+u", 10u);
}


text:
from glob import glob
import os
import re

from lxml.html import fromstring
import unicodecsv

def get_file():
    for path in glob('data/*.txt'):
        with open(path, 'r') as f:
            html = fromstring(f.read())
            parse_html(html, path)

def parse_html(html, path):
    data = {}

    filename = path.split('/')[1]
    components = filename.split('-')
    year = components[0]

    try:
        body = html.findall('body')[0]

        # Get the title
        divider = body.find_class('divider')[0]
        h1 = divider.findall('h1')[0]
        # Skip titles about new designs
        if 'Unveils New Design' in h1.text_content():
            return
        data['title'] = h1.text_content()

        # Get all of the lists
        fulltext = html.find_class('rte')[0]
        uls = fulltext.findall('ul')
        if not uls:
            # Sometimes, there's a weird <value> tag inside of rte
            value_tag = fulltext.find_class('Text')[0]
            uls = value_tag.findall('ul')
            txt = value_tag.text_content().strip()

            if not uls:
                body_content = fulltext.find_class('bodyContent')[0]
                empty_div = body_content.findall('div')[0]
                uls = empty_div.findall('ul')
                txt = empty_div.text_content().strip()
        else:
            txt = fulltext.text_content().strip()

        print txt

    # if this stuff failed, this html does not match.
    # skip the file
    except:
        print '%s failed' % path
        return

    for ul in uls:
        # Get all the items in the list
        items = ul.findall('li')

        for item in items:
            # Search for various predictable beginnings
            if item.text_content().startswith('Location:'):
                data['location'] = item.text_content()

            if 'located at' in item.text_content() and not 'Formerly' in item.text_content():
                data['location'] = item.text_content()

            if item.text_content().startswith('Grand'):
                data['opening'] = item.text_content()

            if item.text_content().startswith('Store opens at'):
                data['opening'] = item.text_content()

    # If we still haven't found anything, revert to regex
    if not data.get('location'):
        r = re.search(r'(located\s)?(at)(\s)(\d+\s)(\S+\s){4}', txt)
        if r:
            data['location'] = r.group()

    if not data.get('opening'):
        r = re.search(r'([Oo]pe\w+)(\s\w+)?(\s\w+)?(\s)([M,T,W,F,S]\w+)(,\s)(\w+)(\W+\d+)', txt)

        if r:
            data['opening'] = r.group()
        else:
            r = re.search(r'(unveiled at\s)(\S+\s){1,6}(\d+\s)?([a-z].[a-z].,\s)?([M,T,W,F,S]\w+)(,\s)(\w+)(\W+\d+)', txt)
            if r:
                data['opening'] = r.group()

    print data

    writer = unicodecsv.writer(open('cleaned_data.csv', 'a'))
    writer.writerow([data.get('title'), data.get('location'), data.get('opening'), year])

if __name__ == '__main__':
    os.remove('cleaned_data.csv')
    get_file()


text:
namespace DbContextEf.Helper
{
  using System.Data.Entity.Core.Objects;
  using System.Linq;
  using System.Text;

  public static class IQueryableExtensions
  {
    /// <summary>
    /// For an Entity Framework IQueryable, returns the SQL with inlined Parameters.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <returns></returns>
    public static string ToSql<T>(this IQueryable<T> query)
    {
      ObjectQuery<T> objectQuery = GetQueryFromQueryable(query);

      var result = objectQuery.ToTraceString();
      foreach (var parameter in objectQuery.Parameters)
      {
        var name = "@" + parameter.Name;
        var value = "'" + parameter.Value.ToString() + "'";
        result = result.Replace(name, value);
      }

      return result;
    }

    /// <summary>
    /// For an Entity Framework IQueryable, returns the SQL and Parameters.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <returns></returns>
    public static string ToTraceString<T>(this IQueryable<T> query)
    {
      ObjectQuery<T> objectQuery = GetQueryFromQueryable(query);

      var traceString = new StringBuilder();

      traceString.AppendLine(objectQuery.ToTraceString());
      traceString.AppendLine();

      foreach (var parameter in objectQuery.Parameters)
      {
        traceString.AppendLine(parameter.Name + " [" + parameter.ParameterType.FullName + "] = " + parameter.Value);
      }

      return traceString.ToString();
    }

    private static System.Data.Entity.Core.Objects.ObjectQuery<T> GetQueryFromQueryable<T>(IQueryable<T> query)
    {
      var internalQueryField = query.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Where(f => f.Name.Equals("_internalQuery")).FirstOrDefault();
      var internalQuery = internalQueryField.GetValue(query);
      var objectQueryField = internalQuery.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Where(f => f.Name.Equals("_objectQuery")).FirstOrDefault();
      return objectQueryField.GetValue(internalQuery) as System.Data.Entity.Core.Objects.ObjectQuery<T>;
    }
  }
}


text:
import Database.HaskellDB
import Database.HaskellDB.DBLayout
import Database.HaskellDB.Database
import Database.HaskellDB.Query
import Database.HaskellDB.PrimQuery
import Database.HaskellDB.Sql hiding (tables)

import TestConnect

import Data.Maybe
import System.Time

now :: Expr CalendarTime
now = Expr (ConstExpr (OtherLit "NOW()"))

data Timefield = Timefield
instance FieldTag Timefield where fieldName _ = "timefield"
timefield = mkAttr Timefield :: Attr Timefield CalendarTime

q = project (timefield << now)

getTime :: Database -> IO CalendarTime
getTime db = do
	     (r:_) <- query db q
	     return (r!timefield)

printTime db = do
	       putStrLn $ show $ showSql q
	       t <- getTime db
	       putStrLn $ calendarTimeToString t

main = argConnect printTime


text:
<?php $this->layout('theme::layout/00_layout') ?>

        <?php $this->insert('theme::partials/navbar_content', ['params' => $params]); ?>

<?php if ($params['html']['repo']) { ?>
    <a href="https://github.com/<?= $params['html']['repo']; ?>" target="_blank" id="github-ribbon" class="hidden-print">
<?php } ?>

                <?php if ($params['tagline']) {
                    echo '
' . $params['tagline'] . '
';
                } ?>

                <?php if ($params['image']) {
                    echo '';
                } ?>

        <?php
        if ($params['html']['repo']) {
            echo 'View On GitHub';
        }
        foreach ($page['entry_page'] as $key => $node) {
            echo '' . $key . '';
        }
        ?>

                <?= $page['content']; ?>

                <?php if (!empty($params['html']['links'])) { ?>

                        <?php foreach ($params['html']['links'] as $name => $url) {
                            echo '
' . $name . '
';
                        } ?>

                <?php } ?>

                    <?php
                    if (!empty($params['html']['twitter'])) {
                        foreach ($params['html']['twitter'] as $handle) {
                            ?>

                                <iframe allowtransparency="true" frameborder="0" scrolling="no" style="width:162px; height:20px;" src="https://platform.twitter.com/widgets/follow_button.html?screen_name=<?= $handle; ?>&show_count=false">

                        <?php
                        }
                    }
                    ?>


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('home', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='community',
            name='subscribers',
            field=models.ManyToManyField(related_name='home_community_subscribers', to=settings.AUTH_USER_MODEL),
            # preserve_default=True,
        ),
        migrations.AlterField(
            model_name='community',
            name='creator',
            field=models.ForeignKey(related_name='home_community_creator', to=settings.AUTH_USER_MODEL),
            # preserve_default=True,
        ),
    ]


text:
package source

import (
	"io"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"

	"github.com/spf13/hugo/hugofs"
	"golang.org/x/text/unicode/norm"

	"github.com/spf13/viper"

	"github.com/spf13/hugo/helpers"
	jww "github.com/spf13/jwalterweatherman"
)

type Input interface {
	Files() []*File
}

type Filesystem struct {
	files      []*File
	Base       string
	AvoidPaths []string
}

func (f *Filesystem) FilesByExts(exts ...string) []*File {
	var newFiles []*File

	if len(exts) == 0 {
		return f.Files()
	}

	for _, x := range f.Files() {
		for _, e := range exts {
			if x.Ext() == strings.TrimPrefix(e, ".") {
				newFiles = append(newFiles, x)
			}
		}
	}
	return newFiles
}

func (f *Filesystem) Files() []*File {
	if len(f.files) < 1 {
		f.captureFiles()
	}
	return f.files
}

// add populates a file in the Filesystem.files
func (f *Filesystem) add(name string, reader io.Reader) (err error) {
	var file *File

	if runtime.GOOS == "darwin" {
		// When a file system is HFS+, its filepath is in NFD form.
		name = norm.NFC.String(name)
	}

	file, err = NewFileFromAbs(f.Base, name, reader)

	if err == nil {
		f.files = append(f.files, file)
	}
	return err
}

func (f *Filesystem) captureFiles() {
	walker := func(filePath string, fi os.FileInfo, err error) error {
		if err != nil {
			return nil
		}

		b, err := f.shouldRead(filePath, fi)
		if err != nil {
			return err
		}
		if b {
			rd, err := NewLazyFileReader(hugofs.Source(), filePath)
			if err != nil {
				return err
			}
			f.add(filePath, rd)
		}
		return err
	}

	err := helpers.SymbolicWalk(hugofs.Source(), f.Base, walker)

	if err != nil {
		jww.ERROR.Println(err)
	}

}

func (f *Filesystem) shouldRead(filePath string, fi os.FileInfo) (bool, error) {
	if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
		link, err := filepath.EvalSymlinks(filePath)
		if err != nil {
			jww.ERROR.Printf("Cannot read symbolic link '%s', error was: %s", filePath, err)
			return false, nil
		}
		linkfi, err := os.Stat(link)
		if err != nil {
			jww.ERROR.Printf("Cannot stat '%s', error was: %s", link, err)
			return false, nil
		}
		if !linkfi.Mode().IsRegular() {
			jww.ERROR.Printf("Symbolic links for directories not supported, skipping '%s'", filePath)
		}
		return false, nil
	}

	if fi.IsDir() {
		if f.avoid(filePath) || isNonProcessablePath(filePath) {
			return false, filepath.SkipDir
		}
		return false, nil
	}

	if isNonProcessablePath(filePath) {
		return false, nil
	}
	return true, nil
}

func (f *Filesystem) avoid(filePath string) bool {
	for _, avoid := range f.AvoidPaths {
		if avoid == filePath {
			return true
		}
	}
	return false
}

func isNonProcessablePath(filePath string) bool {
	base := filepath.Base(filePath)
	if strings.HasPrefix(base, ".") ||
		strings.HasPrefix(base, "#") ||
		strings.HasSuffix(base, "~") {
		return true
	}
	ignoreFiles := viper.GetStringSlice("IgnoreFiles")
	if len(ignoreFiles) > 0 {
		for _, ignorePattern := range ignoreFiles {
			match, err := regexp.MatchString(ignorePattern, filePath)
			if err != nil {
				helpers.DistinctErrorLog.Printf("Invalid regexp '%s' in ignoreFiles: %s", ignorePattern, err)
				return false
			} else if match {
				return true
			}
		}
	}
	return false
}


text:
require 'facter'

Facter.add('lsbminordistrelease') do
  confine do
    !Facter.value("os")["lsb"].nil?
  end

  setcode { Facter.value("os")["lsb"]["minordistrelease"] }
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app.metatron.discovery.util;

import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessageType;

/**
 * WebSocket 관련 Utility Class
 *
 */
public class WebSocketUtils {

  public static void sendMessage(SimpMessageSendingOperations messagingTemplate, String user, String destination,
                                 Object payload){
    messagingTemplate.convertAndSendToUser(user, destination, payload, createHeaders(user));
  }

  private static MessageHeaders createHeaders(String sessionId) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(sessionId);
    headerAccessor.setLeaveMutable(true);
    return headerAccessor.getMessageHeaders();
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>readscratch</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
    <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
    <link rel="prev" href="readscore.html" title="readscore" />
    <link rel="next" href="rect2pol.html" title="rect2pol" />

          readscratch

          Prev
          Orchestra Opcodes and Operators
           Next

          readscratch

readscratch —
      returns a value stored in the instance of an instrument.

Description

      The readscratch opcode returns one of four
      scalar values stored in the instance of an instrument.

Syntax

ival readscratch[index]

Initialisation

      ival --  variable for result.

      index --  which value to read, defaulting
      to zero.

Examples

      Here is an example of the readscratch opcode. It uses the file readscratch.csd.

            Example 780. Example of the readscratch opcode.

See the sections Real-time Audio and Command Line Flags for more information on using command line flags.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-n
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

instr 1

ilast readscratch
      writescratch p2
ilen  readscratch 1
      writescratch p3, 1
      printf_i "last run at %f for %f\n", ilen, ilast, ilen
endin

</CsInstruments>
<CsScore>
i 1 0 1
i 1 2 3
i 1 6 10
e
</CsScore>
</CsoundSynthesizer>

See Also

      writescratch,

Credits

            Author: John ffitch

            March 2013

New in Csound version 6.00

          Prev

            Up

           Next

          readscore

            Home

           rect2pol


text:
module Mhc
  class EtagStore
    def initialize(top_directory)
      @top_directory = top_directory
    end

    def put(key, value)
      if value.nil?
        unlink(key)
      else
        store(key, value)
      end
    end

    def get(uid)
      if value = load(uid)
        return value
      end
    end

    def uid_list
      keys
    end

    def report_etags(uids = nil)
      hash = {}
      uid_list.each do |uid|
        hash[uid] = get(uid)
      end
      return hash
    end

    private
    def keys
      Dir.glob(File.join(@top_directory, '*.etag')).map {|p| make_key(p)}
    end

    def store(key, value)
      File.open(make_path(key), "w") do |f|
        f.write(value)
      end
    end

    def load(key)
      begin
        File.open(make_path(key), "r") do |f|
          return f.read
        end
      rescue
        return nil
      end
    end

    def unlink(key)
      if File.exists?(path = make_path(key))
        File.unlink(path)
      end
    end

    def make_path(key)
      File.join(@top_directory, key.to_s + '.etag')
    end

    def make_key(path)
      File.basename(path, '.etag')
    end
  end # class EtagStore
end # module Mhc