text:
package org.cometd.javascript;

import java.util.Map;

import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.server.DefaultSecurityPolicy;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CometDMessagesAfterFailedHandshakeTest extends AbstractCometDTest
{
    @Before
    public void init()
    {
        bayeuxServer.setSecurityPolicy(new Policy());
    }

    @Test
    public void testSubscribeAfterFailedHandshake() throws Exception
    {
        defineClass(Latch.class);

        evaluateScript("var handshakeLatch = new Latch(1);");
        Latch handshakeLatch = get("handshakeLatch");
        evaluateScript("var subscribeLatch = new Latch(1);");
        Latch subscribeLatch = get("subscribeLatch");
        evaluateScript("" +
                "cometd.addListener('/meta/handshake', function(message)" +
                "{" +
                "    if (!message.successful)" +
                "    {" +
                "        cometd.subscribe('/foo', function(m) {});" +
                "        handshakeLatch.countDown();" +
                "    }" +
                "});" +
                "cometd.addListener('/meta/subscribe', function(message)" +
                "{" +
                "    if (!message.successful)" +
                "    {" +
                "        subscribeLatch.countDown();" +
                "    }" +
                "});" +
                "cometd.init({url: '" + cometdURL + "', logLevel: '" + getLogLevel() + "'});");

        Assert.assertTrue(handshakeLatch.await(5000));
        Assert.assertTrue(subscribeLatch.await(5000));

        evaluateScript("cometd.disconnect(true);");
    }

    @Test
    public void testPublishAfterFailedHandshake() throws Exception
    {
        defineClass(Latch.class);

        evaluateScript("var handshakeLatch = new Latch(1);");
        Latch handshakeLatch = get("handshakeLatch");
        evaluateScript("var publishLatch = new Latch(1);");
        Latch publishLatch = get("publishLatch");
        evaluateScript("" +
                "cometd.addListener('/meta/handshake', function(message)" +
                "{" +
                "    if (!message.successful)" +
                "    {" +
                "        cometd.publish('/foo', {});" +
                "        handshakeLatch.countDown();" +
                "    }" +
                "});" +
                "cometd.addListener('/meta/publish', function(message)" +
                "{" +
                "    if (!message.successful)" +
                "    {" +
                "        publishLatch.countDown();" +
                "    }" +
                "});" +
                "cometd.init({url: '" + cometdURL + "', logLevel: '" + getLogLevel() + "'});");

        Assert.assertTrue(handshakeLatch.await(5000));
        Assert.assertTrue(publishLatch.await(5000));

        evaluateScript("cometd.disconnect(true);");
    }

    private class Policy extends DefaultSecurityPolicy
    {
        @Override
        public boolean canHandshake(BayeuxServer server, ServerSession session, ServerMessage message)
        {
            return false;
        }
    }
}


text:
"""Tests for compression.py"""

import unittest

from deltacompression.backend import compression

class DummyCompressionTest(unittest.TestCase):

    def setUp(self):
        self._compression = compression.DummyCompression()

    def testCompression(self):
        data = "Lorem ipsum dolor sit amet"
        self.assertEqual(self._compression.compress(data), data)

    def testDecompression(self):
        data = "Lorem ipsum dolor sit amet"
        self.assertEqual(self._compression.decompress(data), data)

class LzoCompression(unittest.TestCase):

    def setUp(self):
        self._compression = compression.LzoCompression()
        self._input = "Lorem ipsum dolor sit amet"
        self._compressed = ("\xf1\x00\x00\x00\x1a+Lorem ipsum dolor " +
                            "sit amet\x11\x00\x00")

    def testCompression(self):
        self.assertEqual(self._compression.compress(self._input),
                         self._compressed)

    def testDecompression(self):
        self.assertEqual(self._compression.decompress(self._compressed),
                         self._input)

class ZipCompression(unittest.TestCase):

    def setUp(self):
        self._compression = compression.ZipCompression()
        self._input = "Lorem ipsum dolor sit amet"
        self._compressed = ("x\xda\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf" +
                            "\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5")

    def testCompresion(self):
        self.assertEqual(self._compression.compress(self._input),
                         self._compressed)

    def testDecompression(self):
        self.assertEqual(self._compression.decompress(self._compressed),
                         self._input)

class LzmaCompression(unittest.TestCase):

    def setUp(self):
        self._compression = compression.LzmaCompression()
        self._input = "Lorem ipsum dolor sit amet"
        self._compressed = ("]\x00\x00\x80\x00\x00&\x1b\xcaFgZ\xf2w\xb8}" +
                            "\x86\xd8A\xdb\x055\xcd\x83\xa5|\x12\xa5\x05" +
                            "\xdb\x90\xbd0\xa4\xa6\x7f_\xff\x11\xb1\x00\x00")

    def testCompresion(self):
        self.assertEqual(self._compression.compress(self._input),
                         self._compressed)

    def testDecompression(self):
        self.assertEqual(self._compression.decompress(self._compressed),
                         self._input)

redpajama_set_name: RedPajamaGithub


text:
<ListLookupErrorResponse xmlns="http://ecs.amazonaws.com/doc/2011-08-01/">
  <Error>
    Deprecated
    <Message>Feature ListLookup is deprecated.</Message>
  </Error>
  <RequestID>2054b873-919f-412b-8ab6-7d6d61821adb</RequestID>
</ListLookupErrorResponse>


text:
const RegTestingSetup* g_setup;

void initialize()
{
    static RegTestingSetup setup{};
    g_setup = &setup;

    for (int i = 0; i < 2 * COINBASE_MATURITY; i++) {
        MineBlock(g_setup->m_node, CScript() << OP_TRUE);
    }
    SyncWithValidationInterfaceQueue();
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());

    ConnmanTestMsg& connman = *(ConnmanTestMsg*)g_setup->m_node.connman.get();
    std::vector<CNode*> peers;

    const auto num_peers_to_add = fuzzed_data_provider.ConsumeIntegralInRange(1, 3);
    for (int i = 0; i < num_peers_to_add; ++i) {
        const ServiceFlags service_flags = ServiceFlags(fuzzed_data_provider.ConsumeIntegral<uint64_t>());
        const bool inbound{fuzzed_data_provider.ConsumeBool()};
        const bool block_relay_only{fuzzed_data_provider.ConsumeBool()};
        peers.push_back(MakeUnique<CNode>(i, service_flags, 0, INVALID_SOCKET, CAddress{CService{in_addr{0x0100007f}, 7777}, NODE_NETWORK}, 0, 0, CAddress{}, std::string{}, inbound, block_relay_only).release());
        CNode& p2p_node = *peers.back();

        p2p_node.fSuccessfullyConnected = true;
        p2p_node.fPauseSend = false;
        p2p_node.nVersion = PROTOCOL_VERSION;
        p2p_node.SetSendVersion(PROTOCOL_VERSION);
        g_setup->m_node.peer_logic->InitializeNode(&p2p_node);

        connman.AddTestNode(p2p_node);
    }

    while (fuzzed_data_provider.ConsumeBool()) {
        const std::string random_message_type{fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE).c_str()};

        CSerializedNetMsg net_msg;
        net_msg.command = random_message_type;
        net_msg.data = ConsumeRandomLengthByteVector(fuzzed_data_provider);

        CNode& random_node = *peers.at(fuzzed_data_provider.ConsumeIntegralInRange<int>(0, peers.size() - 1));

        (void)connman.ReceiveMsgFrom(random_node, net_msg);
        random_node.fPauseSend = false;

        try {
            connman.ProcessMessagesOnce(random_node);
        } catch (const std::ios_base::failure&) {
        }
    }
    connman.ClearTestNodes();
    SyncWithValidationInterfaceQueue();
}


text:
package com.midi_automator.view.windows.MainFrame.actions;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.midi_automator.view.windows.MainFrame.MainFrame;
import com.midi_automator.view.windows.PreferencesDialog.PreferencesDialog;

/**
 * Opens the preferences window
 *
 * @author aguelle
 *
 */
@Component
public class PreferencesAction extends AbstractAction {

	private static final long serialVersionUID = 1L;
	static Logger log = Logger.getLogger(PreferencesAction.class.getName());

	@Autowired
	private MainFrame mainFrame;
	@Autowired
	private PreferencesDialog preferencesDialog;

	@Override
	public void actionPerformed(ActionEvent e) {

		log.info("Opening Preferences Dialog..");
		preferencesDialog.init();
		preferencesDialog.setLocation(mainFrame.getLocationOnScreen());
		preferencesDialog.showDialog();
	}
}


text:
package dsdk

import (
	"context"
	_path "path"

	greq "github.com/levigross/grequests"
)

type StorageNode struct {
	Path                string                 `json:"path,omitempty" mapstructure:"path"`
	AdminState          string                 `json:"admin_state,omitempty" mapstructure:"admin_state"`
	AvailableCapacity   int                    `json:"available_capacity,omitempty" mapstructure:"available_capacity"`
	BiosVersion         string                 `json:"bios_version,omitempty" mapstructure:"bios_version"`
	BootDrives          []*BootDrive           `json:"boot_drives,omitempty" mapstructure:"boot_drives"`
	BuildVersion        string                 `json:"build_version,omitempty" mapstructure:"build_version"`
	Causes              []string               `json:"causes,omitempty" mapstructure:"causes"`
	Compression         bool                   `json:"compression_enabled,omitempty" mapstructure:"compression_enabled"`
	CompressionRatio    string                 `json:"compression_ratio,omitempty" mapstructure:"compression_ratio"`
	Disconnected        bool                   `json:"disconnected,omitempty" mapstructure:"disconnected"`
	FailureDomains      []*FailureDomain       `json:"failure_domains,omitempty" mapstructure:"failure_domains"`
	FlashDevices        []*FlashDevice         `json:"flash_devices,omitempty" mapstructure:"flash_devices"`
	Hdds                []*Hdd                 `json:"hdds,omitempty" mapstructure:"hdds"`
	Health              string                 `json:"health,omitempty" mapstructure:"health"`
	HwHealth            string                 `json:"hw_health,omitempty" mapstructure:"hw_health"`
	HwState             string                 `json:"hw_state,omitempty" mapstructure:"hw_state"`
	InternalIp1         string                 `json:"internal_ip_1,omitempty" mapstructure:"internal_ip_1"`
	InternalIp2         string                 `json:"internal_ip_2,omitempty" mapstructure:"internal_ip_2"`
	LastRebootTimestamp string                 `json:"last_reboot_timestamp,omitempty" mapstructure:"last_reboot_timestamp"`
	MediaPolicy         string                 `json:"media_policy,omitempty" mapstructure:"media_policy"`
	MgmtIp1             string                 `json:"mgmt_ip_1,omitempty" mapstructure:"mgmt_ip_1"`
	MgmtIp2             string                 `json:"mgmt_ip_2,omitempty" mapstructure:"mgmt_ip_2"`
	Model               string                 `json:"model,omitempty" mapstructure:"model"`
	Name                string                 `json:"name,omitempty" mapstructure:"name"`
	Nics                []*Nic                 `json:"nics,omitempty" mapstructure:"nics"`
	NvmFlashDevices     []*NvmFlashDevice      `json:"nvm_flash_devices,omitempty" mapstructure:"nvm_flash_devices"`
	OpProgress          map[string]interface{} `json:"op_progress,omitempty" mapstructure:"op_progress"`
	OpState             string                 `json:"op_state,omitempty" mapstructure:"op_state"`
	OpStatus            string                 `json:"op_status,omitempty" mapstructure:"op_status"`
	OsVersion           string                 `json:"os_version,omitempty" mapstructure:"os_version"`
	Psus                []*Psu                 `json:"psus,omitempty" mapstructure:"psus"`
	SerialNo            string                 `json:"serial_no,omitempty" mapstructure:"serial_no"`
	StorageInstances    []*StorageInstance     `json:"storage_instances,omitempty" mapstructure:"storage_instances"`
	SubsystemHealth     []*Subsystem           `json:"subsystem_health,omitempty" mapstructure:"subsystem_health"`
	SubsystemStates     *Subsystem             `json:"subsystem_states,omitempty" mapstructure:"subsystem_states"`
	SwHealth            string                 `json:"sw_health,omitempty" mapstructure:"sw_health"`
	SwState             string                 `json:"sw_state,omitempty" mapstructure:"sw_state"`
	SwVersion           string                 `json:"sw_version,omitempty" mapstructure:"sw_version"`
	TotalCapacity       int                    `json:"total_capacity,omitempty" mapstructure:"total_capacity"`
	TotalRawCapacity    int                    `json:"total_raw_capacity,omitempty" mapstructure:"total_raw_capacity"`
	Type                string                 `json:"type,omitempty" mapstructure:"type"`
	Upgrade             *Upgrade               `json:"upgrade,omitempty" mapstructure:"upgrade"`
	Uuid                string                 `json:"uuid,omitempty" mapstructure:"uuid"`
	Vendor              string                 `json:"vendor,omitempty" mapstructure:"vendor"`
	Volumes             []*Volume              `json:"volumes,omitempty" mapstructure:"volumes"`
	BootDrivesEp        *BootDrives
}

func RegisterStorageNodeEndpoints(a *StorageNode) {
	a.BootDrivesEp = newBootDrives(a.Path)
	for _, si := range a.StorageInstances {
		RegisterStorageInstanceEndpoints(si)
	}
	for _, vol := range a.Volumes {
		RegisterVolumeEndpoints(vol)
	}
}

type StorageNodes struct {
	Path string
}

func newStorageNodes(path string) *StorageNodes {
	return &StorageNodes{
		Path: _path.Join(path, "storage_nodes"),
	}
}

type StorageNodesListRequest struct {
	Ctxt   context.Context `json:"-"`
	Params ListParams      `json:"params,omitempty"`
}

func (e *StorageNodes) List(ro *StorageNodesListRequest) ([]*StorageNode, *ApiErrorResponse, error) {
	gro := &greq.RequestOptions{
		JSON:   ro,
		Params: ro.Params.ToMap()}
	rs, apierr, err := GetConn(ro.Ctxt).GetList(ro.Ctxt, e.Path, gro)
	if apierr != nil {
		return nil, apierr, err
	}
	if err != nil {
		return nil, nil, err
	}
	resp := []*StorageNode{}
	for _, data := range rs.Data {
		elem := &StorageNode{}
		adata := data.(map[string]interface{})
		if err = FillStruct(adata, elem); err != nil {
			return nil, nil, err
		}
		resp = append(resp, elem)
		RegisterStorageNodeEndpoints(elem)
	}
	return resp, nil, nil
}

type StorageNodesGetRequest struct {
	Ctxt context.Context `json:"-"`
	Uuid string          `json:"-"`
}

func (e *StorageNodes) Get(ro *StorageNodesGetRequest) (*StorageNode, *ApiErrorResponse, error) {
	gro := &greq.RequestOptions{JSON: ro}
	rs, apierr, err := GetConn(ro.Ctxt).Get(ro.Ctxt, _path.Join(e.Path, ro.Uuid), gro)
	if apierr != nil {
		return nil, apierr, err
	}
	if err != nil {
		return nil, nil, err
	}
	resp := &StorageNode{}
	if err = FillStruct(rs.Data, resp); err != nil {
		return nil, nil, err
	}
	RegisterStorageNodeEndpoints(resp)
	return resp, nil, nil
}

type StorageNodeSetRequest struct {
	Ctxt        context.Context `json:"-"`
	AdminState  string          `json:"admin_state,omitempty" mapstructure:"admin_state"`
	MediaPolicy string          `json:"media_policy,omitempty" mapstructure:"media_policy"`
}

func (e *StorageNode) Set(ro *StorageNodeSetRequest) (*StorageNode, *ApiErrorResponse, error) {
	gro := &greq.RequestOptions{JSON: ro}
	rs, apierr, err := GetConn(ro.Ctxt).Put(ro.Ctxt, e.Path, gro)
	if apierr != nil {
		return nil, apierr, err
	}
	if err != nil {
		return nil, nil, err
	}
	resp := &StorageNode{}
	if err = FillStruct(rs.Data, resp); err != nil {
		return nil, nil, err
	}
	RegisterStorageNodeEndpoints(resp)
	return resp, nil, nil

}

type StorageNodeReloadRequest struct {
	Ctxt context.Context `json:"-"`
}

func (e *StorageNode) Reload(ro *StorageNodeReloadRequest) (*StorageNode, *ApiErrorResponse, error) {
	gro := &greq.RequestOptions{JSON: ro}
	rs, apierr, err := GetConn(ro.Ctxt).Get(ro.Ctxt, e.Path, gro)
	if apierr != nil {
		return nil, apierr, err
	}
	if err != nil {
		return nil, nil, err
	}
	resp := &StorageNode{}
	if err = FillStruct(rs.Data, resp); err != nil {
		return nil, nil, err
	}
	RegisterStorageNodeEndpoints(resp)
	return resp, nil, nil
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Box.V2.Models;

namespace Box.V2.Test.Integration.Configuration.Commands.DisposableCommands
{
    public class CreateWebhookCommand : CommandBase, IDisposableCommand
    {
        private readonly string _targetId;
        private readonly BoxType _targetType;
        private readonly string _address;
        private readonly List<string> _triggers;

        private string _webhookId;
        public BoxWebhook Webhook;

        public CreateWebhookCommand(string targetId, BoxType targetType, string address, List<string> triggers,
            CommandScope scope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.User) : base(scope, accessLevel)
        {
            _targetId = targetId;
            _targetType = targetType;
            _address = address;
            _triggers = triggers;
        }

        public async Task<string> Execute(IBoxClient client)
        {
            var webhookRequest = new BoxWebhookRequest()
            {
                Target = new BoxRequestEntity()
                {
                    Id = _targetId,
                    Type = _targetType
                },
                Address = _address,
                Triggers = _triggers,
            };

            Webhook = await client.WebhooksManager.CreateWebhookAsync(webhookRequest);
            _webhookId = Webhook.Id;

            return _webhookId;
        }

        public async Task Dispose(IBoxClient client)
        {
            await client.WebhooksManager.DeleteWebhookAsync(_webhookId);
        }
    }
}


text:
A user's profile preferences page allows the user to customize various aspects
of GitLab to their liking.

To navigate to your profile's preferences, click your avatar icon in the top
right corner, select **Settings** and then choose **Preferences** from the
left sidebar.

## Navigation theme

The GitLab navigation theme setting allows you to personalize your GitLab experience.
You can choose from several color themes that add unique colors to the top navigation
and left side navigation.
Using individual color themes might help you differentiate between your different
GitLab instances.

The default palette is Indigo. You can choose between 10 different themes:

- Indigo
- Light Indigo
- Blue
- Light Blue
- Green
- Light Green
- Red
- Light Red
- Dark
- Light

![Profile preferences navigation themes](img/profil-preferences-navigation-theme.png)

## Syntax highlighting theme

NOTE: **Note:**
GitLab uses the [rouge Ruby library](http://rouge.jneen.net/ "Rouge website")
for syntax highlighting. For a list of supported languages visit the rouge website.

Changing this setting allows you to customize the color theme when viewing any
syntax highlighted code on GitLab.

The default syntax theme is White, and you can choose among 5 different colors:

- White
- Dark
- Solarized light
- Solarized dark
- Monokai

![Profile preferences syntax highlighting themes](img/profile-preferences-syntax-themes.png)

## Behavior

The following settings allow you to customize the behavior of GitLab's layout
and default views of your dashboard and the projects' landing pages.

### Layout width

GitLab can be set up to use different widths depending on your liking. Choose
between the fixed (max. 1200px) and the fluid (100%) application layout.

### Default dashboard

For users who have access to a large number of projects but only keep up with a
select few, the amount of activity on the default Dashboard page can be
overwhelming. Changing this setting allows you to redefine what your default
dashboard will be.

You have 8 options here that you can use for your default dashboard view:

- Your projects (default)
- Starred projects
- Your projects' activity
- Starred projects' activity
- Your groups
- Your [Todos](../../workflow/todos.md)
- Assigned Issues
- Assigned Merge Requests

### Project overview content

The project overview content setting allows you to choose what content you want to
see on a project's home page.

You can choose between 3 options:

- Files and Readme (default)
- Readme
- Activity


text:
package org.apache.kafka.streams.state.internals;

import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.state.WindowBytesStoreSupplier;
import org.apache.kafka.streams.state.WindowStore;

public class RocksDbWindowBytesStoreSupplier implements WindowBytesStoreSupplier {
    public enum WindowStoreTypes {
        DEFAULT_WINDOW_STORE,
        TIMESTAMPED_WINDOW_STORE
    }

    private final String name;
    private final long retentionPeriod;
    private final long segmentInterval;
    private final long windowSize;
    private final boolean retainDuplicates;
    private final WindowStoreTypes windowStoreType;

    public RocksDbWindowBytesStoreSupplier(final String name,
                                           final long retentionPeriod,
                                           final long segmentInterval,
                                           final long windowSize,
                                           final boolean retainDuplicates,
                                           final boolean returnTimestampedStore) {
        this(name, retentionPeriod, segmentInterval, windowSize, retainDuplicates,
            returnTimestampedStore
                ? WindowStoreTypes.TIMESTAMPED_WINDOW_STORE
                : WindowStoreTypes.DEFAULT_WINDOW_STORE);
    }

    public RocksDbWindowBytesStoreSupplier(final String name,
                                           final long retentionPeriod,
                                           final long segmentInterval,
                                           final long windowSize,
                                           final boolean retainDuplicates,
                                           final WindowStoreTypes windowStoreType) {
        this.name = name;
        this.retentionPeriod = retentionPeriod;
        this.segmentInterval = segmentInterval;
        this.windowSize = windowSize;
        this.retainDuplicates = retainDuplicates;
        this.windowStoreType = windowStoreType;
    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public WindowStore<Bytes, byte[]> get() {
        switch (windowStoreType) {
            case DEFAULT_WINDOW_STORE:
                return new RocksDBWindowStore(
                    new RocksDBSegmentedBytesStore(
                        name,
                        metricsScope(),
                        retentionPeriod,
                        segmentInterval,
                        new WindowKeySchema()),
                    retainDuplicates,
                    windowSize);
            case TIMESTAMPED_WINDOW_STORE:
                return new RocksDBTimestampedWindowStore(
                    new RocksDBTimestampedSegmentedBytesStore(
                        name,
                        metricsScope(),
                        retentionPeriod,
                        segmentInterval,
                        new WindowKeySchema()),
                    retainDuplicates,
                    windowSize);
            default:
                throw new IllegalArgumentException("invalid window store type: " + windowStoreType);
        }
    }

    @Override
    public String metricsScope() {
        return "rocksdb-window";
    }

    @Override
    public long segmentIntervalMs() {
        return segmentInterval;
    }

    @Override
    public long windowSize() {
        return windowSize;
    }

    @Override
    public boolean retainDuplicates() {
        return retainDuplicates;
    }

    @Override
    public long retentionPeriod() {
        return retentionPeriod;
    }

    @Override
    public String toString() {
        return "RocksDbWindowBytesStoreSupplier{" +
                   "name='" + name + '\'' +
                   ", retentionPeriod=" + retentionPeriod +
                   ", segmentInterval=" + segmentInterval +
                   ", windowSize=" + windowSize +
                   ", retainDuplicates=" + retainDuplicates +
                   ", windowStoreType=" + windowStoreType +
                   '}';
    }
}


text:
#ifndef QQUICKIMAGEPROVIDER_H
#define QQUICKIMAGEPROVIDER_H

#include <QtQuick/qtquickglobal.h>
#include <QtGui/qimage.h>
#include <QtGui/qpixmap.h>
#include <QtQml/qqmlengine.h>

QT_BEGIN_NAMESPACE

class QQuickImageProviderPrivate;
class QSGTexture;
class QQuickWindow;

class Q_QUICK_EXPORT QQuickTextureFactory : public QObject
{
public:
    QQuickTextureFactory();
    virtual ~QQuickTextureFactory();

    virtual QSGTexture *createTexture(QQuickWindow *window) const = 0;
    virtual QSize textureSize() const = 0;
    virtual int textureByteCount() const = 0;
    virtual QImage image() const;
};

class Q_QUICK_EXPORT QQuickImageProvider : public QQmlImageProviderBase
{
public:
    QQuickImageProvider(ImageType type, Flags flags = 0);
    virtual ~QQuickImageProvider();

    ImageType imageType() const;
    Flags flags() const;

    virtual QImage requestImage(const QString &id, QSize *size, const QSize& requestedSize);
    virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize& requestedSize);
    virtual QQuickTextureFactory *requestTexture(const QString &id, QSize *size, const QSize &requestedSize);

private:
    QQuickImageProviderPrivate *d;
};

QT_END_NAMESPACE

#endif // QQUICKIMAGEPROVIDER_H


text:
.. include:: ../README.rst

Developer Guide
---------------

Here is the API reference for mistune.

.. module:: mistune

.. autoclass:: Renderer
   :members:

.. autoclass:: Markdown
   :members:

.. autofunction:: markdown
.. autofunction:: escape

Changelog
----------

Here is the full history of mistune.

Version 0.4.1
~~~~~~~~~~~~~

Released on Oct. 12, 2014

* Add option for parse markdown in block level html.
* Fix on lheading, any number of underline = or - will work.
* Patch for setup if Cython is available but no C compiler.

Version 0.4
~~~~~~~~~~~

Released on Aug. 14, 2014

* Bugfix. Use inspect to detect renderer class.
* Move all meth:`escape` to renderer. Use renderer to escape everything.
* A little changes in code style and parameter naming.
* Don't parse text in a block html, behave like sundown.

Version 0.3.1
~~~~~~~~~~~~~

Released on Jul. 31, 2014

* Fix in meth:`Renderer.block_code`, no need to add ``\n`` in ``<code>``.
* Trim whitespace of code in code span via `#15`_.

.. _`#15`: https://github.com/lepture/mistune/issues/15

Version 0.3
~~~~~~~~~~~

Released on Jun. 27, 2014

* Add ``<hr>`` in footnotes renderer
* Add hard_wrap configuration for GFM linebreaks.
* Add text renderer, via `#9`_.
* Define features for lexers available via `#11`_.

.. _`#9`: https://github.com/lepture/mistune/pull/9
.. _`#11`: https://github.com/lepture/mistune/pull/11

Version 0.2
~~~~~~~~~~~

Released on Mar. 12, 2014

* Use tuple instead of list for efficient
* Add ``line_match`` and ``line_started`` property on InlineLexer, via `#4`_

.. _`#4`: https://github.com/lepture/mistune/pull/4

Version 0.1
~~~~~~~~~~~

First preview release.


text:
#ifndef WebMediaPlayerEncryptedMediaClient_h
#define WebMediaPlayerEncryptedMediaClient_h

namespace blink {

class WebMediaPlayerEncryptedMediaClient {
public:
    enum MediaKeyErrorCode {
        MediaKeyErrorCodeUnknown = 1,
        MediaKeyErrorCodeClient,
        MediaKeyErrorCodeService,
        MediaKeyErrorCodeOutput,
        MediaKeyErrorCodeHardwareChange,
        MediaKeyErrorCodeDomain
    };

    virtual void keyAdded(const WebString& keySystem, const WebString& sessionId) = 0;
    virtual void keyError(const WebString& keySystem, const WebString& sessionId, MediaKeyErrorCode, unsigned short systemCode) = 0;
    virtual void keyMessage(const WebString& keySystem, const WebString& sessionId, const unsigned char* message, unsigned messageLength, const WebURL& defaultURL) = 0;
    virtual void encrypted(WebEncryptedMediaInitDataType, const unsigned char* initData, unsigned initDataLength) = 0;
    virtual void didBlockPlaybackWaitingForKey() = 0;
    virtual void didResumePlaybackBlockedForKey() = 0;

protected:
    ~WebMediaPlayerEncryptedMediaClient() { }
};

} // namespace blink

#endif


text:
<component name="libraryTable">
  <library name="rulighttestdata">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/lucene/analysis/common/src/test/org/apache/lucene/analysis/ru/rulighttestdata.zip!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
from django.test import TestCase
from django.core.urlresolvers import reverse

class PageTests(TestCase):

    def test_url_home(self):
        resp = self.client.get(reverse('home'))
        self.assertEqual(resp.status_code, 200)

    def test_url_about(self):
        resp = self.client.get(reverse('page-about'))
        self.assertEqual(resp.status_code, 200)

    def test_url_faq(self):
        resp = self.client.get(reverse('page-faq'))
        self.assertEqual(resp.status_code, 200)

class HomeViewTestCase(TestCase):

    """Tests for the ``HomeView`` generic view class."""

    def get_view_name(self):
        """
        I would advise to always define this method.

        As your view grows you will add many more tests which will all call
        ``self.client.get(reverse('name_of_your_view'))``. If you ever decide
        to change that name in your ``urls.py`` you would only have to change
        this string at this central position.

        And trust me: You _will_ change your view name after a while ;)

        """
        return 'home'

    def test_view(self):
        resp = self.client.get(reverse(self.get_view_name()))
        self.assertEqual(resp.status_code, 200)


text:
package psidev.psi.mi.jami.enricher.impl;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import psidev.psi.mi.jami.bridges.fetcher.mock.MockCvTermFetcher;
import psidev.psi.mi.jami.enricher.exception.EnricherException;
import psidev.psi.mi.jami.enricher.impl.full.FullInteractionEnricher;
import psidev.psi.mi.jami.enricher.impl.minimal.MinimalCvTermEnricher;
import psidev.psi.mi.jami.enricher.impl.minimal.MinimalInteractionEnricher;
import psidev.psi.mi.jami.enricher.impl.minimal.MinimalParticipantEnricher;
import psidev.psi.mi.jami.enricher.listener.EnrichmentStatus;
import psidev.psi.mi.jami.enricher.listener.InteractionEnricherListener;
import psidev.psi.mi.jami.enricher.listener.impl.InteractionEnricherListenerManager;
import psidev.psi.mi.jami.enricher.listener.impl.log.InteractionEnricherLogger;
import psidev.psi.mi.jami.model.*;
import psidev.psi.mi.jami.model.impl.DefaultCvTerm;
import psidev.psi.mi.jami.model.impl.DefaultInteraction;
import psidev.psi.mi.jami.model.impl.DefaultInteractor;
import psidev.psi.mi.jami.model.impl.DefaultParticipant;

import java.util.Collections;
import java.util.Date;

import static junit.framework.Assert.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author Gabriel Aldam (galdam@ebi.ac.uk)
 * @since 26/07/13
 */
public class MinimalInteractionEnricherTest {

    private MinimalInteractionEnricher interactionEnricher;
    MockCvTermFetcher mockCvTermFetcher;
    private  Interaction persistentInteraction;
    private int persistentInt = 0;

    @Before
    public void setup(){
        persistentInt = 0;
        interactionEnricher = new FullInteractionEnricher();
        persistentInteraction = new DefaultInteraction("shortName");
    }

    @Test
    public void test_enrichers_begin_empty(){
        assertNull(interactionEnricher.getParticipantEnricher());
        assertNull(interactionEnricher.getCvTermEnricher());
        assertNull(interactionEnricher.getInteractionEnricherListener());
    }

    @Test
    public void test_enrichment_without_enrichers_succeeds() throws EnricherException {
        assertNull(interactionEnricher.getCvTermEnricher() );
        assertNull(interactionEnricher.getParticipantEnricher() );

        interactionEnricher.setInteractionEnricherListener(new InteractionEnricherListenerManager(
                //  new InteractionEnricherLogger(),
                new InteractionEnricherListener() {

                    public void onEnrichmentError(Interaction object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onUpdatedRigid(Interaction interaction, String oldRigid) {
                        Assert.fail();                    }

                    public void onEnrichmentComplete(Object object, EnrichmentStatus status, String message) {
                        assertTrue(object == persistentInteraction);
                        assertEquals(EnrichmentStatus.SUCCESS, status);
                        persistentInt++;
                    }

                    public void onEnrichmentError(Object object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onShortNameUpdate(Interaction interaction, String oldName) {
                        Assert.fail();
                    }

                    public void onUpdatedDateUpdate(Interaction interaction, Date oldUpdate) {
                        Assert.fail();
                    }

                    public void onCreatedDateUpdate(Interaction interaction, Date oldCreated) {
                        Assert.fail();
                    }

                    public void onInteractionTypeUpdate(Interaction interaction, CvTerm oldType) {
                        Assert.fail();
                    }

                    public void onAddedParticipant(Interaction interaction, Participant addedParticipant) {
                        Assert.fail();
                    }

                    public void onRemovedParticipant(Interaction interaction, Participant removedParticipant) {
                        Assert.fail();
                    }

                    public void onAddedAnnotation(Object o, Annotation added) {
                        Assert.fail();
                    }

                    public void onRemovedAnnotation(Object o, Annotation removed) {
                        Assert.fail();
                    }

                    public void onAddedChecksum(Object interactor, Checksum added) {
                        Assert.fail();
                    }

                    public void onRemovedChecksum(Object interactor, Checksum removed) {
                        Assert.fail();
                    }

                    public void onAddedIdentifier(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedIdentifier(Object o, Xref removed) {
                        Assert.fail();
                    }

                    public void onAddedXref(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedXref(Object o, Xref removed) {
                        Assert.fail();
                    }
                }
        ));
        interactionEnricher.enrich(persistentInteraction);
        assertEquals(1 , persistentInt);
    }

    @Test
    public void test_enrichment_with_cvTermEnricher_but_no_cvTerms() throws EnricherException {

        interactionEnricher.setCvTermEnricher(new MinimalCvTermEnricher(new MockCvTermFetcher()));

        assertNull(persistentInteraction.getInteractionType());

        interactionEnricher.setInteractionEnricherListener( new InteractionEnricherListenerManager(
                // new InteractionEnricherLogger() ,
                new InteractionEnricherListener() {

                    public void onEnrichmentError(Interaction object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onUpdatedRigid(Interaction interaction, String oldRigid) {
                        Assert.fail();
                    }

                    public void onEnrichmentComplete(Object object, EnrichmentStatus status, String message) {
                        assertTrue(object == persistentInteraction);
                        assertEquals(EnrichmentStatus.SUCCESS, status);
                        persistentInt++;
                    }

                    public void onEnrichmentError(Object object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onShortNameUpdate(Interaction interaction, String oldName) {
                        Assert.fail();
                    }

                    public void onUpdatedDateUpdate(Interaction interaction, Date oldUpdate) {
                        Assert.fail();
                    }

                    public void onCreatedDateUpdate(Interaction interaction, Date oldCreated) {
                        Assert.fail();
                    }

                    public void onInteractionTypeUpdate(Interaction interaction, CvTerm oldType) {
                        Assert.fail();
                    }

                    public void onAddedParticipant(Interaction interaction, Participant addedParticipant) {
                        Assert.fail();
                    }

                    public void onRemovedParticipant(Interaction interaction, Participant removedParticipant) {
                        Assert.fail();
                    }

                    public void onAddedAnnotation(Object o, Annotation added) {
                        Assert.fail();
                    }

                    public void onRemovedAnnotation(Object o, Annotation removed) {
                        Assert.fail();
                    }

                    public void onAddedChecksum(Object interactor, Checksum added) {
                        Assert.fail();
                    }

                    public void onRemovedChecksum(Object interactor, Checksum removed) {
                        Assert.fail();
                    }

                    public void onAddedIdentifier(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedIdentifier(Object o, Xref removed) {
                        Assert.fail();
                    }

                    public void onAddedXref(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedXref(Object o, Xref removed) {
                        Assert.fail();
                    }
                }
        ));
        interactionEnricher.enrich(persistentInteraction);

        assertNull(persistentInteraction.getInteractionType());
        assertEquals(1 , persistentInt);
    }

    @Test
    public void test_enrichment_with_CvTermEnricher_with_CvTerm() throws EnricherException {
        mockCvTermFetcher = new MockCvTermFetcher();
        interactionEnricher.setCvTermEnricher(new MinimalCvTermEnricher(mockCvTermFetcher));

        mockCvTermFetcher.addEntry("MI:0001", new DefaultCvTerm("ShortName", "FullName", "MI:0001"));

        persistentInteraction.setInteractionType(new DefaultCvTerm("ShortName" , "MI:0001"));
        assertNotNull(persistentInteraction.getInteractionType());
        assertNull(persistentInteraction.getInteractionType().getFullName());

        interactionEnricher.setInteractionEnricherListener( new InteractionEnricherListenerManager(
                // new InteractionEnricherLogger() ,
                new InteractionEnricherListener() {

                    public void onEnrichmentError(Interaction object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onUpdatedRigid(Interaction interaction, String oldRigid) {
                        Assert.fail();
                    }

                    public void onEnrichmentComplete(Object object, EnrichmentStatus status, String message) {
                        assertTrue(object == persistentInteraction);
                        assertEquals(EnrichmentStatus.SUCCESS, status);
                        persistentInt++;
                    }

                    public void onEnrichmentError(Object object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onShortNameUpdate(Interaction interaction, String oldName) {
                        Assert.fail();
                    }

                    public void onUpdatedDateUpdate(Interaction interaction, Date oldUpdate) {
                        Assert.fail();
                    }

                    public void onCreatedDateUpdate(Interaction interaction, Date oldCreated) {
                        Assert.fail();
                    }

                    public void onInteractionTypeUpdate(Interaction interaction, CvTerm oldType) {
                        Assert.fail();
                    }

                    public void onAddedParticipant(Interaction interaction, Participant addedParticipant) {
                        Assert.fail();
                    }

                    public void onRemovedParticipant(Interaction interaction, Participant removedParticipant) {
                        Assert.fail();
                    }

                    public void onAddedAnnotation(Object o, Annotation added) {
                        Assert.fail();
                    }

                    public void onRemovedAnnotation(Object o, Annotation removed) {
                        Assert.fail();
                    }

                    public void onAddedChecksum(Object interactor, Checksum added) {
                        Assert.fail();
                    }

                    public void onRemovedChecksum(Object interactor, Checksum removed) {
                        Assert.fail();
                    }

                    public void onAddedIdentifier(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedIdentifier(Object o, Xref removed) {
                        Assert.fail();
                    }

                    public void onAddedXref(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedXref(Object o, Xref removed) {
                        Assert.fail();
                    }
                } )
        );
        interactionEnricher.enrich(persistentInteraction);

        assertNotNull(persistentInteraction.getInteractionType());
        assertNotNull(persistentInteraction.getInteractionType().getFullName());
        assertEquals(1 , persistentInt);
    }

    @Test
    public void test_enrichment_with_participantEnricher_but_no_participant() throws EnricherException {

        interactionEnricher.setParticipantEnricher(new CompositeParticipantEnricher(new MinimalParticipantEnricher<Participant, Feature>()));

        assertEquals(Collections.EMPTY_LIST, persistentInteraction.getParticipants());

        interactionEnricher.setInteractionEnricherListener(new InteractionEnricherListenerManager(
                new InteractionEnricherLogger(),
                new InteractionEnricherListener() {

                    public void onEnrichmentError(Interaction object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onUpdatedRigid(Interaction interaction, String oldRigid) {
                        Assert.fail();
                    }

                    public void onEnrichmentComplete(Object object, EnrichmentStatus status, String message) {
                        assertTrue(object == persistentInteraction);
                        assertEquals(EnrichmentStatus.SUCCESS, status);
                        persistentInt++;
                    }

                    public void onEnrichmentError(Object object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onShortNameUpdate(Interaction interaction, String oldName) {
                        Assert.fail();
                    }

                    public void onUpdatedDateUpdate(Interaction interaction, Date oldUpdate) {
                        Assert.fail();
                    }

                    public void onCreatedDateUpdate(Interaction interaction, Date oldCreated) {
                        Assert.fail();
                    }

                    public void onInteractionTypeUpdate(Interaction interaction, CvTerm oldType) {
                        Assert.fail();
                    }

                    public void onAddedParticipant(Interaction interaction, Participant addedParticipant) {
                        Assert.fail();
                    }

                    public void onRemovedParticipant(Interaction interaction, Participant removedParticipant) {
                        Assert.fail();
                    }

                    public void onAddedAnnotation(Object o, Annotation added) {
                        Assert.fail();
                    }

                    public void onRemovedAnnotation(Object o, Annotation removed) {
                        Assert.fail();
                    }

                    public void onAddedChecksum(Object interactor, Checksum added) {
                        Assert.fail();
                    }

                    public void onRemovedChecksum(Object interactor, Checksum removed) {
                        Assert.fail();
                    }

                    public void onAddedIdentifier(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedIdentifier(Object o, Xref removed) {
                        Assert.fail();
                    }

                    public void onAddedXref(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedXref(Object o, Xref removed) {
                        Assert.fail();
                    }
                }
        ));
        interactionEnricher.enrich(persistentInteraction);

        assertNull(persistentInteraction.getInteractionType());
        assertEquals(1 , persistentInt);
    }

    @Test
    public void test_enrichment_with_participantEnricher_with_participant() throws EnricherException {

        persistentInteraction.addParticipant(new DefaultParticipant(new DefaultInteractor("InteractorName")));

        interactionEnricher.setParticipantEnricher(new CompositeParticipantEnricher(new MinimalParticipantEnricher()));

        //TODO assertEquals(Collections.EMPTY_LIST, persistentInteraction.getParticipants());

        interactionEnricher.setInteractionEnricherListener(new InteractionEnricherListenerManager(
                new InteractionEnricherLogger(),
                new InteractionEnricherListener() {

                    public void onEnrichmentError(Interaction object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onUpdatedRigid(Interaction interaction, String oldRigid) {
                        Assert.fail();
                    }

                    public void onEnrichmentComplete(Object object, EnrichmentStatus status, String message) {
                        assertTrue(object == persistentInteraction);
                        assertEquals(EnrichmentStatus.SUCCESS, status);
                        persistentInt++;
                    }

                    public void onEnrichmentError(Object object, String message, Exception e) {
                        Assert.fail();
                    }

                    public void onShortNameUpdate(Interaction interaction, String oldName) {
                        Assert.fail();
                    }

                    public void onUpdatedDateUpdate(Interaction interaction, Date oldUpdate) {
                        Assert.fail();
                    }

                    public void onCreatedDateUpdate(Interaction interaction, Date oldCreated) {
                        Assert.fail();
                    }

                    public void onInteractionTypeUpdate(Interaction interaction, CvTerm oldType) {
                        Assert.fail();
                    }

                    public void onAddedParticipant(Interaction interaction, Participant addedParticipant) {
                        Assert.fail();
                    }

                    public void onRemovedParticipant(Interaction interaction, Participant removedParticipant) {
                        Assert.fail();
                    }

                    public void onAddedAnnotation(Object o, Annotation added) {
                        Assert.fail();
                    }

                    public void onRemovedAnnotation(Object o, Annotation removed) {
                        Assert.fail();
                    }

                    public void onAddedChecksum(Object interactor, Checksum added) {
                        Assert.fail();
                    }

                    public void onRemovedChecksum(Object interactor, Checksum removed) {
                        Assert.fail();
                    }

                    public void onAddedIdentifier(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedIdentifier(Object o, Xref removed) {
                        Assert.fail();
                    }

                    public void onAddedXref(Object o, Xref added) {
                        Assert.fail();
                    }

                    public void onRemovedXref(Object o, Xref removed) {
                        Assert.fail();
                    }
                }
        ));
        interactionEnricher.enrich(persistentInteraction);

        assertNull(persistentInteraction.getInteractionType());
        assertEquals(1 , persistentInt);
    }

}


text:
require 'topical_map_integration/engine'

# Include hook code here
#I18n.load_path << File.join(File.dirname(__FILE__), 'config', 'locales')
I18n.load_path += Dir[File.join(__dir__, '..', 'config', 'locales', '*.yml')]
# ActionView::Base.send :include, TopicalMapCategoriesHelper

module TopicalMapIntegration
  module Util
    MARGIN = " " * 5
  end
end


text: This is my website. It's pretty alright.


text:
namespace mono {

    namespace filters {

        class Header {
        public:
            explicit Header(const std::string &header) {
              for (const auto &value : StringUtil::Split(header, ' ')) {
                if (value.find("tld:") == 0) {
                  tld_ = value.substr(4);
                } else if (value.find("uri:") == 0) {
                  uri_ = value.substr(4);
                } else if (value.find("encoding:") == 0) {
                  encoding_ = value.substr(9);
                }
              }
            }

            const std::string get_tld() const { return tld_; }

            const std::string get_uri() const { return uri_; }

            const std::string get_encoding() const { return encoding_; }

        private:
            std::string uri_;
            std::string tld_;
            std::string encoding_;
        };

    }

}

#endif //EXTRACTOR_MONO_FILTERS_HEADER_H


text:
using System;
using Binance.Net.Converters;
using Binance.Net.Enums;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;

namespace Binance.Net.Objects.Models.Spot.Lending
{
    /// <summary>
    /// Customized fixed project position
    /// </summary>
    public class BinanceCustomizedFixedProjectPosition
    {
        /// <summary>
        /// Asset name
        /// </summary>
        public string Asset { get; set; } = string.Empty;
        /// <summary>
        /// Can transfer
        /// </summary>
        public bool CanTransfer { get; set; }
        /// <summary>
        /// Create timestamp
        /// </summary>
        [JsonConverter(typeof(DateTimeConverter))]
        [JsonProperty("createTimestamp")]
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// Duration
        /// </summary>
        public int Duration { get; set; }
        /// <summary>
        /// End time
        /// </summary>
        [JsonConverter(typeof(DateTimeConverter))]
        public DateTime EndTime { get; set; }
        /// <summary>
        /// Interest
        /// </summary>
        public decimal Interest { get; set; }
        /// <summary>
        /// Interest rate
        /// </summary>
        public decimal InterestRate { get; set; }
        /// <summary>
        /// Lot
        /// </summary>
        public int Lot { get; set; }
        /// <summary>
        /// Position id
        /// </summary>
        public int PositionId { get; set; }
        /// <summary>
        /// Principal
        /// </summary>
        public decimal Principal { get; set; }
        /// <summary>
        /// Project id
        /// </summary>
        public string ProjectId { get; set; } = string.Empty;
        /// <summary>
        /// Project name
        /// </summary>
        public string ProjectName { get; set; } = string.Empty;
        /// <summary>
        /// Time of purchase
        /// </summary>
        [JsonConverter(typeof(DateTimeConverter))]
        public DateTime PurchaseTime { get; set; }
        /// <summary>
        /// Redeem date
        /// </summary>
        public string RedeemDate { get; set; } = string.Empty;
        /// <summary>
        /// Start time
        /// </summary>
        [JsonConverter(typeof(DateTimeConverter))]
        public DateTime StartTime { get; set; }
        /// <summary>
        /// Status
        /// </summary>
        [JsonConverter(typeof(ProjectStatusConverter))]
        public ProjectStatus Status { get; set; }
        /// <summary>
        /// Type
        /// </summary>
        [JsonConverter(typeof(ProjectTypeConverter))]
        public ProjectType Type { get; set; }

    }
}


text:
package at.alladin.rmbt.android.util;

import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;

/**
 *
 * @author lb
 *
 */
public class AsyncHtmlStatusCodeRetriever extends AsyncTask<String, Void, Integer> {

	private ContentRetrieverListener listener;

	/**
	 *
	 * @author lb
	 *
	 */
	public static interface ContentRetrieverListener {
		public void onContentFinished(Integer statusCode);
	}

	/**
	 *
	 * @param listener
	 */
	public void setContentRetrieverListener(ContentRetrieverListener listener) {
		this.listener = listener;
	}

	@Override
	protected Integer doInBackground(String... params) {
        try
        {
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            try {
                connection.setConnectTimeout(3000);
                connection.connect();
                final int statusCode = connection.getResponseCode();
                System.out.println("response code: " + statusCode);
                return statusCode;

            }
            catch (Exception e) {
                return null;
            }
            finally {
                connection.disconnect();
            }
        }
        catch (Exception e)
        {
            return null;
        }

	}

	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);

		if (this.listener != null) {
			listener.onContentFinished(result);
		}
	}
}


text:
import type {
  ComponentList,
  ExamplesList,
  RNTesterModuleInfo,
  RNTesterState,
  SectionData,
} from '../types/RNTesterTypes';

import RNTesterList from './RNTesterList';
import {AsyncStorage} from 'react-native';

export const Screens = {
  COMPONENTS: 'components',
  APIS: 'apis',
  BOOKMARKS: 'bookmarks',
};

export const initialState: RNTesterState = {
  activeModuleKey: null,
  activeModuleTitle: null,
  activeModuleExampleKey: null,
  screen: null,
  bookmarks: null,
  recentlyUsed: null,
};

const filterEmptySections = (examplesList: ExamplesList): any => {
  const filteredSections: {
    ['apis' | 'bookmarks' | 'components']: Array<
      SectionData<RNTesterModuleInfo>,
    >,
  } = {};
  const sectionKeys = Object.keys(examplesList);

  sectionKeys.forEach(key => {
    filteredSections[key] = examplesList[key].filter(
      section => section.data.length > 0,
    );
  });

  return filteredSections;
};

export const getExamplesListWithBookmarksAndRecentlyUsed = ({
  bookmarks,
  recentlyUsed,
}: {
  bookmarks: ComponentList,
  recentlyUsed: ComponentList,
}): ExamplesList | null => {
  // Return early if state has not been initialized from storage
  if (!bookmarks || !recentlyUsed) {
    return null;
  }

  const components = RNTesterList.Components.map(componentExample => ({
    ...componentExample,
    isBookmarked: bookmarks.components.includes(componentExample.key),
    exampleType: Screens.COMPONENTS,
  }));

  const recentlyUsedComponents = recentlyUsed.components
    .map(recentComponentKey =>
      components.find(component => component.key === recentComponentKey),
    )
    .filter(Boolean);

  const bookmarkedComponents = components.filter(
    component => component.isBookmarked,
  );

  const apis = RNTesterList.APIs.map(apiExample => ({
    ...apiExample,
    isBookmarked: bookmarks.apis.includes(apiExample.key),
    exampleType: Screens.APIS,
  }));

  const recentlyUsedAPIs = recentlyUsed.apis
    .map(recentAPIKey => apis.find(apiEample => apiEample.key === recentAPIKey))
    .filter(Boolean);

  const bookmarkedAPIs = apis.filter(apiEample => apiEample.isBookmarked);

  const examplesList: ExamplesList = {
    [Screens.COMPONENTS]: [
      {
        key: 'RECENT_COMPONENTS',
        data: recentlyUsedComponents,
        title: 'Recently Viewed',
      },
      {
        key: 'COMPONENTS',
        data: components,
        title: 'Components',
      },
    ],
    [Screens.APIS]: [
      {
        key: 'RECENT_APIS',
        data: recentlyUsedAPIs,
        title: 'Recently viewed',
      },
      {
        key: 'APIS',
        data: apis,
        title: 'APIs',
      },
    ],
    [Screens.BOOKMARKS]: [
      {
        key: 'COMPONENTS',
        data: bookmarkedComponents,
        title: 'Components',
      },
      {
        key: 'APIS',
        data: bookmarkedAPIs,
        title: 'APIs',
      },
    ],
  };

  return filterEmptySections(examplesList);
};

export const getInitialStateFromAsyncStorage = async (
  storageKey: string,
): Promise<RNTesterState> => {
  const initialStateString = await AsyncStorage.getItem(storageKey);

  if (!initialStateString) {
    return {
      activeModuleKey: null,
      activeModuleTitle: null,
      activeModuleExampleKey: null,
      screen: Screens.COMPONENTS,
      bookmarks: {components: [], apis: []},
      recentlyUsed: {components: [], apis: []},
    };
  } else {
    return JSON.parse(initialStateString);
  }
};


text:
import requests
import os
from csvkit.py3 import CSVKitDictReader, CSVKitDictWriter
import shutil
# Parallel execution libs
from joblib import Parallel, delayed
from collections import defaultdict
import joblib.parallel

# PARALLEL EXECUTION SETTINGS
# Override joblib callback default callback behavior
class BatchCompletionCallBack(object):
    completed = defaultdict(int)

    def __init__(self, dispatch_timestamp, batch_size, parallel):
        self.dispatch_timestamp = dispatch_timestamp
        self.batch_size = batch_size
        self.parallel = parallel

    def __call__(self, out):
        BatchCompletionCallBack.completed[self.parallel] += 1
        if BatchCompletionCallBack.completed[self.parallel] % 10 == 0:
            print("processed {} items"
                  .format(BatchCompletionCallBack.completed[self.parallel]))
        if self.parallel._original_iterator is not None:
            self.parallel.dispatch_next()
# MonkeyPatch BatchCompletionCallBack
joblib.parallel.BatchCompletionCallBack = BatchCompletionCallBack

# GLOBAL SETTINGS
cwd = os.path.dirname(__file__)
INPUT_PATH = os.path.join(cwd, '../../data/input')
OUTPUT_AUDIO_PATH = os.path.abspath(os.path.join(
    cwd,
    '../../data/output/mp3s'))
INPUT_FILES = {
    'train': 'labeled_audios',
    'test': 'unlabeled_audios'
}
OUTPUT_FILES = {
    'train': 'labeled_mp3_local',
    'test': 'unlabeled_mp3_local'
}
HEADER = ['title', 'audio_file', 'length', 'label']
N_CORES = 7

def download_audio(labeled, row):
    '''Download an audio file'''
    result = {'title': row['Document Title']}
    dataset = 'train' if labeled else 'test'
    audio_file = '%s/%s/%s' % (
        OUTPUT_AUDIO_PATH,
        dataset,
        row['Document Title'])
    result['audio_file'] = audio_file
    result['length'] = row['length']
    if labeled:
        answering = row['answer_El audio parece estar relacionado con:']
        result['label'] = 1 if answering.startswith('Descartar:') else 0
    else:
        result['label'] = None
    if os.path.isfile(audio_file):
        # Already downloaded skip
        pass
    else:
        # Download audio
        try:
            response = requests.get(row['Document Url'], stream=True)
            with open(audio_file, 'wb') as of:
                shutil.copyfileobj(response.raw, of)
            del response
        except Exception:
            print('Error while downloading {}...skipping'
                  .format(row['Document Url']))
    return result

def process_audios(labeled=True):
    '''Download audio data'''
    dataset = 'train' if labeled else 'test'
    with open('%s/%s.csv' % (INPUT_PATH, OUTPUT_FILES[dataset]), 'w') as fout:
        writer = CSVKitDictWriter(fout, fieldnames=HEADER)
        writer.writeheader()
        with open('%s/%s.csv' % (INPUT_PATH, INPUT_FILES[dataset]), 'r') as f:
            reader = CSVKitDictReader(f)
            r = Parallel(n_jobs=N_CORES,)(delayed(download_audio)(labeled, row)
                                          for row in reader)
            print('finished processing {}.csv'.format(INPUT_FILES[dataset]))
            writer.writerows(r)

def create_folders(paths=None):
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path)

def create_folder_structure():
    '''Create a list of the required folders for the script execution'''
    paths = [
        # Input path
        INPUT_PATH,
        # Training set audio files
        '%s/train' % OUTPUT_AUDIO_PATH,
        # Test set audio files
        '%s/test' % OUTPUT_AUDIO_PATH]
    create_folders(paths)

def run():
    # Initialize execution context
    create_folder_structure()
    # Download training set
    # Download test set
    process_audios(labeled=True)
    process_audios(labeled=False)

if __name__ == '__main__':
    run()


text:
<?php

/**
 *
 */

namespace RDF\JobDefinitionFormatBundle\Type;

/**
 * Represents a duration of time. Based on [ISO8601:2004]. The single infinity
 * limit token INF is permitted.
 *
 * @author Richard Fullmer <richardfullmer@gmail.com>
 */
class Duration extends \DateInterval
{
    const INFINITY = 'INF';

    const FORMAT = '%rP%yY%mM%dDT%hH%iM%sS';

    protected $infinity;

    public function __construct($interval_spec)
    {
        if (self::INFINITY == $interval_spec) {
            $this->infinity = self::INFINITY;
        } else {
            parent::__construct($interval_spec);
        }
    }

    public function isInfinity()
    {
        return null !== $this->infinity;
    }

    public function format($format)
    {
        if (null !== $this->infinity) {
            return self::INFINITY;
        } else {
            return parent::format($format);
        }
    }
}


text:
{-|
This is a module of cross-platform file handling for Unix\/Mac\/Windows.

The standard module "System.Directory" and "System.FilePath" have
following shortcomings:

* getModificationTime exists in "System.Directory". But getAccessTime,
  getChangeTime, getCreationTime do not exist.

* getModificationTime returns obsoleted type, 'ClockTime'. It should
  return modern type, 'UTCTime', I believe.

* Some file functions are missing. A function to tell the link counter,
  for instance.

* Path separator is not unified. Even though Windows accepts \'\/\' as a
  file separator, getCurrentDirectory in "System.Directory" returns \'\\\'
  as a file separator. So, we need to specify regular expression like
  this: \"[\/\\\\]foo[\/\\\\]bar[\/\\\\]baz\".

* getHomeDirectory returns @HOMEDRIVE@\/@HOMEPATH@ instead of the @HOME@
  environment variable on Windows.

This module aims to resolve these problems and provides:

* 'getModificationTime', 'getAccessTime', 'getChangeTime', and
  'getCreationTime'. They return 'UTCTime'.

* 'isSymlink', 'getLinkCount', and 'hasSubDirectories'.

* \'\/\' as the single 'pathSeparator'. For instance,
  'getCurrentDirectory' returns a path whose separator is \'\/\'
  even on Windows.

* 'getHomeDirectory2' which refers the @HOME@ environment variable.

* Necessary functions in "System.Directory" and "System.FilePath".

-}

module System.EasyFile (
  -- * Actions on directories
    createDirectory
  , createDirectoryIfMissing
  , removeDirectory
  , removeDirectoryRecursive
  , renameDirectory
  , getDirectoryContents
  , getCurrentDirectory
  , setCurrentDirectory
  -- * Pre-defined directories
  , getHomeDirectory
  , getHomeDirectory2 -- missing
  , getAppUserDataDirectory
  , getUserDocumentsDirectory
  , getTemporaryDirectory
  -- * Actions on files
  , removeFile
  , renameFile
  , copyFile
  , canonicalizePath
--   , makeRelativeToCurrentDirectory -- xxx
--   , findExecutable -- xxx
  -- * Existence tests
  , doesFileExist
  , doesDirectoryExist
  -- * Permissions
  , Permissions(..)
  , getPermissions
  , setPermissions
  , copyPermissions
  -- * Timestamps
  , getCreationTime
  , getChangeTime
  , getModificationTime
  , getAccessTime
  -- * Size
  , getFileSize
  -- * File\/directory information
  , isSymlink
  , getLinkCount
  , hasSubDirectories
  , module System.EasyFile.FilePath
  ) where

----------------------------------------------------------------

import System.EasyFile.Directory
import System.EasyFile.FilePath
import System.EasyFile.Missing


text:
from time import time

import pandas as pd
from scipy.stats import kendalltau

from algorithms.EM import em
from algorithms.PageRank import page_rank
from algorithms.borda_ordering import borda_ordering
from algorithms.random_circle_removal import random_circle_removal
from utils.gradings import get_gradings

def experiment(n, k_list, repetition):
    algos = [random_circle_removal, page_rank, em, borda_ordering]
    algo_names = ['Random Priority', 'Random Walk', 'EM', 'Order Score']

    df = pd.DataFrame(columns=['n', 'k', 'rep', 'algo', 'time', 'distance', 'ranking'])
    for rep in range(repetition):
        for k in k_list:
            gradings = get_gradings(n, k)
            for j in range(len(algos)):
                start = time()
                ranking = algos[j](gradings)
                duration = time() - start
                df.loc[df.index.size] = [n, k, rep, algo_names[j], duration,
                                         kendalltau(list(range(1, n + 1)), ranking)[0], str(ranking)]

        df.to_csv('./out/results_n_{}_k_{}.csv'.format(n, str(k_list)), index=False)

if __name__ == '__main__':
    repetition = 2
    n = 100
    k_list = [6, 8]

    experiment(n, k_list, repetition)


text:
[![Keras question answering for bAbi](http://i.imgur.com/RuINg4m.jpg)](https://www.flickr.com/photos/isherwoodchris/6917253693/in/photolist)

# Keras question answering for bAbi

**Note: This code has been merged as an example into Keras -- see [babi_rnn.py](https://github.com/fchollet/keras/blob/master/examples/babi_rnn.py)**

This repository contains Keras code to train two recurrent neural networks based upon a story and a question.
The resulting merged vector is then queried to answer a range of bAbI tasks.

An example from the first task, QA1, is below:

    1 Mary moved to the bathroom.
    2 John went to the hallway.
    3 Where is Mary? bathroom 1
    4 Daniel went back to the hallway.
    5 Sandra moved to the garden.
    6 Where is Daniel? hallway 4

The results are comparable (or superior) to those for the LSTM baseline provided in Weston et al.'s [Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks](http://arxiv.org/abs/1502.05698) given only 1000 samples and without any hyperparamater tuning.

Task Number                  | FB LSTM Baseline | Keras QA
---                          | ---              | ---
QA1 - Single Supporting Fact | 50               | 52.1
QA2 - Two Supporting Facts   | 20               | 37.0
QA3 - Three Supporting Facts | 20               | 20.5
QA4 - Two Arg. Relations     | 61               | 62.9
QA5 - Three Arg. Relations   | 70               | 61.9
QA6 - Yes/No Questions       | 48               | 50.7
QA7 - Counting               | 49               | 78.9
QA8 - Lists/Sets             | 45               | 77.2
QA9 - Simple Negation        | 64               | 64.0
QA10 - Indefinite Knowledge  | 44               | 47.7
QA11 - Basic Coreference     | 72               | 74.9
QA12 - Conjunction           | 74               | 76.4
QA13 - Compound Coreference  | 94               | 94.4
QA14 - Time Reasoning        | 27               | 34.8
QA15 - Basic Deduction       | 21               | 32.4
QA16 - Basic Induction       | 23               | 50.6
QA17 - Positional Reasoning  | 51               | 49.1
QA18 - Size Reasoning        | 52               | 90.8
QA19 - Path Finding          | 8                | 9.0
QA20 - Agent's Motivations   | 91               | 90.7

For the resources related to the bAbI project, refer to the [Facebook AI Research bAbI project page](https://research.facebook.com/researchers/1543934539189348).

# License

MIT License, as per `LICENSE`


text:
class ApprovePage < BasePage
  set_url_matcher %r{/applications/[0-9]+/approve}

  section :content, '#content' do
    element :header, 'h1', text: 'Ask a manager'
    element :first_name, '#application_fee_manager_firstname'
    element :last_name, '#application_fee_manager_lastname'
    element :error_first_name, 'label', text: 'Enter a manager\'s first name'
    element :error_last_name, 'label', text: 'Enter a manager\'s last name'
    element :next, 'input[value="Next"]'
  end

  def submit_full_name
    content.wait_until_first_name_visible
    content.first_name.set 'Mary'
    content.wait_until_last_name_visible
    content.last_name.set 'Smith'
    click_next
  end

  def submit_first_name
    content.wait_until_first_name_visible
    content.first_name.set 'Mary'
    click_next
  end

  def submit_last_name
    content.wait_until_last_name_visible
    content.last_name.set 'Smith'
    click_next
  end

  def click_next
    content.wait_until_next_visible
    content.next.click
  end
end


text:
package org.spongepowered.api.world.storage;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.flowpowered.math.vector.Vector3i;
import org.spongepowered.api.util.Direction;
import org.spongepowered.api.util.Direction.Division;

import java.util.Optional;

/**
 * A class for information about the chunk coordinate space, aka the layout.
 * This can be used to obtain information about the chunk size and the space
 * bounds, validate coordinates, convert from chunk to world and vice-versa and
 * translate coordinates; among other things.
 */
public interface ChunkLayout {

    /**
     * Returns the size of the chunks in blocks. The axes are matched to the
     * corresponding vector components.
     *
     * @return The size of chunks
     */
    Vector3i getChunkSize();

    /**
     * Returns the maximum coordinates for chunks for each axis. The axes are
     * matched to the corresponding vector components. Due to the limited
     * precision of 32bit integers, there always is a practical limit.
     *
     * @return The maximum coordinates of chunks
     */
    Vector3i getSpaceMax();

    /**
     * Returns the minimum coordinates for chunks for each axis. The axes are
     * matched to the corresponding vector components. Due to the limited
     * precision of 32bit integers, there always is a practical limit.
     *
     * @return The minimum coordinates of chunks
     */
    Vector3i getSpaceMin();

    /**
     * Gets the total size of the chunk space, which is equivalent to
     * {@link #getSpaceMax()} - {@link #getSpaceMin()} + 1.
     *
     * @return The total size of the chunk space
     */
    Vector3i getSpaceSize();

    /**
     * Returns the origin of the chunk coordinate space. Normally
     * {@link Vector3i#ZERO}.
     *
     * @return The origin of the chunk coordinate space
     */
    Vector3i getSpaceOrigin();

    /**
     * Returns true if the coordinates are valid chunk coordinates. False if
     * otherwise.
     *
     * @param coords The coordinates to validate
     * @return Whether or not the coordinates are valid for chunks
     */
    default boolean isValidChunk(Vector3i coords) {
        checkNotNull(coords, "coords");
        return isValidChunk(coords.getX(), coords.getY(), coords.getZ());
    }

    /**
     * Returns true if the coordinates are valid chunk coordinates. False if
     * otherwise.
     *
     * @param x The x coordinate to validate
     * @param y The y coordinate to validate
     * @param z The z coordinate to validate
     * @return Whether or not the coordinates are valid for chunks
     */
    default boolean isValidChunk(int x, int y, int z) {
        return x >= getSpaceMin().getX() && x <= getSpaceMax().getX()
            && y >= getSpaceMin().getY() && y <= getSpaceMax().getY()
            && z >= getSpaceMin().getZ() && z <= getSpaceMax().getZ();
    }

    /**
     * Returns true if the local coordinates fit in a chunk. That is they are
     * positive and smaller than the chunk's size.
     *
     * @param localCoords The coordinates to check
     * @return Whether or not the coordinates fit in a chunk
     */
    default boolean isInChunk(Vector3i localCoords) {
        checkNotNull(localCoords, "localCoords");
        return isInChunk(localCoords.getX(), localCoords.getY(), localCoords.getZ());
    }

    /**
     * Returns true if the local coordinates fit in a chunk. That is they are
     * positive and smaller than the chunk's size.
     *
     * @param x The x local coordinate to validate
     * @param y The y local coordinate to validate
     * @param z The z local coordinate to validate
     * @return Whether or not the coordinates fit in a chunk
     */
    boolean isInChunk(int x, int y, int z);

    /**
     * Returns true if the world coordinates fit in the chunk at the given
     * coordinates.
     *
     * @param worldCoords The world coordinates to validate
     * @param chunkCoords The chunk coordinates in which they must fit
     * @return Whether or not the world coordinates fit in the chunk
     */
    default boolean isInChunk(Vector3i worldCoords, Vector3i chunkCoords) {
        checkNotNull(worldCoords, "worldCoords");
        checkNotNull(chunkCoords, "chunkCoords");
        return isInChunk(worldCoords.getX(), worldCoords.getY(), worldCoords.getZ(), chunkCoords.getX(), chunkCoords.getY(), chunkCoords.getZ());
    }

    /**
     * Returns true if the world coordinates fit in the chunk at the given
     * coordinates.
     *
     * @param wx The x world coordinate to validate
     * @param wy The y world coordinate to validate
     * @param wz The z world coordinate to validate
     * @param cx The x chunk coordinate in which they must fit
     * @param cy The y chunk coordinate in which they must fit
     * @param cz The z chunk coordinate in which they must fit
     * @return Whether or not the world coordinates fit in the chunk
     */
    boolean isInChunk(int wx, int wy, int wz, int cx, int cy, int cz);

    /**
     * Converts world coordinates to chunk coordinates. Returns nothing if the
     * conversion failed because the resulting chunk coordinates aren't valid.
     *
     * @param worldCoords The world coordinates to convert to chunk coordinates
     * @return The chunk coordinates on success, else nothing
     */
    default Optional<Vector3i> toChunk(Vector3i worldCoords) {
        checkNotNull(worldCoords, "worldCoords");
        return toChunk(worldCoords.getX(), worldCoords.getY(), worldCoords.getZ());
    }

    /**
     * Converts world coordinates to chunk coordinates. Returns nothing if the
     * conversion failed because the resulting chunk coordinates aren't valid.
     *
     * @param x The x world coordinate to convert to chunk coordinates
     * @param y The y world coordinate to convert to chunk coordinates
     * @param z The z world coordinate to convert to chunk coordinates
     * @return The chunk coordinates on success, else nothing
     */
    default Optional<Vector3i> toChunk(int x, int y, int z) {
        final Vector3i chunkCoords = forceToChunk(x, y, z);
        return isValidChunk(chunkCoords) ? Optional.of(chunkCoords) : Optional.<Vector3i>empty();
    }

    /**
     * Converts chunk coordinates to world coordinates. Returns nothing if the
     * conversion failed because the given chunk coordinates aren't valid.
     *
     * @param chunkCoords The chunk coordinates to convert to world coordinates
     * @return The world coordinates on success, else nothing
     */
    default Optional<Vector3i> toWorld(Vector3i chunkCoords) {
        checkNotNull(chunkCoords, "chunkCoords");
        return toWorld(chunkCoords.getX(), chunkCoords.getY(), chunkCoords.getZ());
    }

    /**
     * Converts chunk coordinates to world coordinates. Returns nothing if the
     * conversion failed because the given chunk coordinates aren't valid.
     *
     * @param x The x chunk coordinate to convert to world coordinates
     * @param y The y chunk coordinate to convert to world coordinates
     * @param z The z chunk coordinate to convert to world coordinates
     * @return The world coordinates on success, else nothing
     */
    default Optional<Vector3i> toWorld(int x, int y, int z) {
        return isValidChunk(x, y, z) ? Optional.of(forceToWorld(x, y, z)) : Optional.<Vector3i>empty();
    }

    /**
     * Converts world coordinates to chunk coordinates. This method never fails
     * and can returns invalid chunk coordinates.
     *
     * @param worldCoords The world coordinates to convert to chunk coordinates
     * @return The chunk coordinates
     */
    default Vector3i forceToChunk(Vector3i worldCoords) {
        checkNotNull(worldCoords, "worldCoords");
        return forceToChunk(worldCoords.getX(), worldCoords.getY(), worldCoords.getZ());
    }

    /**
     * Converts world coordinates to chunk coordinates. This method never fails
     * and can returns invalid chunk coordinates.
     *
     * @param x The x world coordinate to convert to chunk coordinates
     * @param y The y world coordinate to convert to chunk coordinates
     * @param z The z world coordinate to convert to chunk coordinates
     * @return The chunk coordinates
     */
    Vector3i forceToChunk(int x, int y, int z);

    /**
     * Converts chunk coordinates to world coordinates. This method never fails
     * and can returns invalid world coordinates.
     *
     * @param chunkCoords The chunk coordinates to convert to world coordinates
     * @return The world coordinates
     */
    default Vector3i forceToWorld(Vector3i chunkCoords) {
        checkNotNull(chunkCoords, "chunkCoords");
        return forceToWorld(chunkCoords.getX(), chunkCoords.getY(), chunkCoords.getZ());
    }

    /**
     * Converts chunk coordinates to world coordinates. This method never fails
     * and can returns invalid world coordinates.
     *
     * @param x The x chunk coordinate to convert to world coordinates
     * @param y The y chunk coordinate to convert to world coordinates
     * @param z The z chunk coordinate to convert to world coordinates
     * @return The world coordinates
     */
    Vector3i forceToWorld(int x, int y, int z);

    /**
     * Adds the chunk offset to the chunk coordinates. Returns nothing if the
     * new coordinates are not valid.
     *
     * @param chunkCoords The chunk coordinates to add to
     * @param chunkOffset The chunk offset to add to the chunk coordinates
     * @return The new chunk coordinates if they are valid
     */
    default Optional<Vector3i> addToChunk(Vector3i chunkCoords, Vector3i chunkOffset) {
        checkNotNull(chunkCoords, "chunkCoords");
        checkNotNull(chunkOffset, "chunkOffset");
        return addToChunk(chunkCoords.getX(), chunkCoords.getY(), chunkCoords.getZ(), chunkOffset.getX(), chunkOffset.getY(), chunkOffset.getZ());
    }

    /**
     * Adds the chunk offset to the chunk coordinates. Returns nothing if the
     * new coordinates are not valid.
     *
     * @param cx The x chunk coordinate to add to
     * @param cy The y chunk coordinate to add to
     * @param cz The z chunk coordinate to add to
     * @param ox The x chunk offset to add to the chunk coordinates
     * @param oy The y chunk offset to add to the chunk coordinates
     * @param oz The z chunk offset to add to the chunk coordinates
     * @return The new chunk coordinates if they are valid
     */
    default Optional<Vector3i> addToChunk(int cx, int cy, int cz, int ox, int oy, int oz) {
        final Vector3i newChunkCoords = new Vector3i(cx + ox, cy + oy, cz + oz);
        return isValidChunk(newChunkCoords) ? Optional.of(newChunkCoords) : Optional.<Vector3i>empty();
    }

    /**
     * Moves chunk coordinates one step in the given direction. Returns nothing
     * if the new coordinates are not valid. {@link Division#SECONDARY_ORDINAL}
     * directions are not a valid argument. These will throw an exception.
     *
     * @param chunkCoords The chunk coordinates to move from
     * @param direction The direction in which to move a step
     * @return The new chunk coordinates if they are valid
     * @throws IllegalArgumentException If the direction is a
     * {@link Division#SECONDARY_ORDINAL}
     */
    default Optional<Vector3i> moveToChunk(Vector3i chunkCoords, Direction direction) {
        return moveToChunk(chunkCoords, direction, 1);
    }

    /**
     * Moves chunk coordinates one step in the given direction. Returns nothing
     * if the new coordinates are not valid.
     * {@link Division#SECONDARY_ORDINAL} directions are not a valid
     * argument. These will throw an exception.
     *
     * @param x The x chunk coordinate to move from
     * @param y The y chunk coordinate to move from
     * @param z The z chunk coordinate to move from
     * @param direction The direction in which to move a step
     * @return The new chunk coordinates if they are valid
     * @throws IllegalArgumentException If the direction is a
     * {@link Division#SECONDARY_ORDINAL}
     */
    default Optional<Vector3i> moveToChunk(int x, int y, int z, Direction direction) {
        return moveToChunk(new Vector3i(x, y, z), direction);
    }

    /**
     * Moves chunk coordinates a number of steps in the given direction. Returns
     * nothing if the new coordinates are not valid.
     * {@link Division#SECONDARY_ORDINAL} directions are not a valid
     * argument. These will throw an exception.
     *
     * @param chunkCoords The chunk coordinates to move from
     * @param direction The direction in which to move
     * @param steps The number of steps to take
     * @return The new chunk coordinates if they are valid
     * @throws IllegalArgumentException If the direction is a
     * {@link Division#SECONDARY_ORDINAL}
     */
    default Optional<Vector3i> moveToChunk(Vector3i chunkCoords, Direction direction, int steps) {
        checkNotNull(direction, "direction");
        checkArgument(!direction.isSecondaryOrdinal(), "Secondary cardinal directions can't be used here");
        return addToChunk(chunkCoords, direction.asBlockOffset().mul(steps));
    }

    /**
     * Moves chunk coordinates a number of steps in the given direction. Returns
     * nothing if the new coordinates are not valid.
     * {@link Division#SECONDARY_ORDINAL} directions are not a valid
     * argument. These will throw an exception.
     *
     * @param x The x chunk coordinate to move from
     * @param y The y chunk coordinate to move from
     * @param z The z chunk coordinate to move from
     * @param direction The direction in which to move
     * @param steps The number of steps to take
     * @return The new chunk coordinates if they are valid
     * @throws IllegalArgumentException If the direction is a
     * {@link Division#SECONDARY_ORDINAL}
     */
    default Optional<Vector3i> moveToChunk(int x, int y, int z, Direction direction, int steps) {
        return moveToChunk(new Vector3i(x, y, z), direction, steps);
    }

}


text:
'''
Created on Jan 15, 2015
'''

import ost_support
from actuator.provisioners.openstack import openstack_class_factory as ocf
from actuator.namespace import NamespaceModel, with_variables
ocf.set_neutron_client_class(ost_support.MockNeutronClient)
ocf.set_nova_client_class(ost_support.MockNovaClient)

from actuator import (InfraModel, ProvisionerException, MultiResourceGroup,
                      MultiResource, ctxt, Var, ResourceGroup, Role,
                      MultiRole, NullTask, LOG_DEBUG, LOG_INFO, ConfigModel,
                      MultiTask, ConfigClassTask)
from actuator.provisioners.openstack.resource_tasks import OpenstackProvisioner
from actuator.provisioners.openstack.resources import (Server, Network,
                                                        Router, FloatingIP,
                                                        Subnet, SecGroup,
                                                        SecGroupRule, RouterGateway,
                                                        RouterInterface)
from actuator.exec_agents.ansible.agent import AnsibleExecutionAgent
from actuator.modeling import AbstractModelReference

external_connection = ResourceGroup("route_out",
                                     net=Network("ro_net"),
                                     subnet=Subnet("ro_subnet",
                                                   ctxt.comp.container.net,
                                                   u"192.168.23.0/24",
                                                   dns_nameservers=[u'8.8.8.8']),
                                     router=Router("ro_router"),
                                     gateway=RouterGateway("ro_gateway",
                                                           ctxt.comp.container.router,
                                                           "external"),
                                     interface=RouterInterface("ro_inter",
                                                               ctxt.comp.container.router,
                                                               ctxt.comp.container.subnet))

make_std_secgroup = ResourceGroup("make_std_secgroup",
                              group=SecGroup("group", "standard security group"),
                              ping_rule=SecGroupRule("ping_rule",
                                                     ctxt.comp.container.group,
                                                     ip_protocol="icmp",
                                                     from_port=-1, to_port=-1),
                              ssh_rule=SecGroupRule("ssh_rule",
                                                    ctxt.comp.container.group,
                                                    ip_protocol="tcp",
                                                    from_port=22, to_port=22))

ubuntu_img = "Ubuntu 13.10"

common_kwargs = {"key_name":"actuator-dev-key"}

def host_list(ctx_exp, sep_char=" "):
    def host_list_inner(ctx):
        return sep_char.join([h.host_ref.get_ip() for h in ctx_exp(ctx).values()])
    return host_list_inner

def test001():
    class Infra(InfraModel):
        fip_pool = "external"
        #add the standard secgroup and connectivity components
        gateway = external_connection
        slave_secgroup = make_std_secgroup

        #HADOOP slaves
        slaves = MultiResourceGroup("slaves",
                                     slave=Server("slave", ubuntu_img,
                                                  "m1.small",
                                                  nics=[ctxt.model.gateway.net],
                                                  security_groups=[ctxt.model.slave_secgroup.group],
                                                  **common_kwargs),
                                     slave_fip=FloatingIP("sn_fip",
                                                          ctxt.comp.container.slave,
                                                          ctxt.comp.container.slave.iface0.addr0,
                                                          pool=fip_pool))
    infra = Infra("infra")

    class Namespace(NamespaceModel):
        with_variables(Var("SLAVE_IPS", host_list(ctxt.model.slaves)))

        slaves = MultiRole(Role("slave",
                                host_ref=ctxt.model.infra.slaves[ctxt.name].slave_fip,
                                variables=[Var("COMP_NAME", "slave_!{COMP_KEY}"),
                                           Var("COMP_KEY", ctxt.name)]))
    ns = Namespace()

    class InnerConfig(ConfigModel):
        task = NullTask("inner_task", "summat")

    class Config(ConfigModel):
        do_it = MultiTask("multi", ConfigClassTask("suite", InnerConfig),
                          Namespace.q.slaves.all())
    cfg = Config()

    uid = "it"
    pwd = "doesn't"
    url = "matter"

    os_prov = OpenstackProvisioner(uid, pwd, uid, url, num_threads=1)
    for i in range(5):
        _ = ns.slaves[i]
    ns.compute_provisioning_for_environ(infra)
    _ = infra.refs_for_components()
    import traceback
    try:
        os_prov.provision_infra_model(infra)
    except Exception, e:
        print "Provision failed with %s; details below" % e.message
        for t, et, ev, tb in os_prov.agent.get_aborted_tasks():
            print "prov task %s failed with:" % t.name
            traceback.print_exception(et, ev, tb)
            print
        assert False, "can't proceed due to provisioning errors"

    ea = AnsibleExecutionAgent(config_model_instance=cfg,
                               namespace_model_instance=ns,
                               num_threads = 1,
                               no_delay=True, log_level=LOG_DEBUG)
    try:
        ea.perform_config()
    except Exception, e:
        print "Config failed with %s; details below" % e.message
        for t, et, ev, tb in ea.get_aborted_tasks():
            print "task %s failed with:" % t.name
            traceback.print_exception(et, ev, tb)
            print
        assert False, "The config had errors; see output"

    assert (cfg.do_it.value().instances[0].instance.task.get_task_role().host_ref is not None and
            cfg.do_it.value().instances[0].instance.task.get_task_host() is not None and
            isinstance(cfg.do_it.value().instances[0].instance.task.get_task_host(),
                           basestring))

def do_all():
    for k, v in globals().items():
        if k.startswith("test") and callable(v):
            v()

if __name__ == "__main__":
    do_all()