text:
# The paket.template files

The `paket.template` files are used to specify rules to create nupkgs by using the [`paket pack` command](paket-pack.html).

An example `paket.template` file might look like the following:

    type file
    id Test.Paket.Package
    version 1.0
    authors Michael Newton
    description
	    description of this test package
    files
        src/Test.Paket.Package/bin/Debug ==> lib

This template file will create a nupkg called `Test.Paket.Package.[Version].nupkg` with the
contents of the `src/Test.Paket.Package/bin/Debug` directory in the `lib` directory
of the package file.

The `type` specifier must be the first line of the template file. It has two possible
values:

* file - All of the information to build the nupkg is contained within the template file
* project - Paket will look for a matching project file, and infer dependencies and metadata from the project

Matching project and template files must be in the same directory. If only one project is in the directory the template file
can be called `paket.template`, otherwise the name of the template file must be the name of the project file with ".paket.template" added to the end.

For example:

	Paket.Project.fsproj
	Paket.Project.fsproj.paket.template

are matching files.

### General Metadata

Metadata fields can be specified in two ways; either on a single line prefixed with the property
name (case insensitive), or in an indented block following a line containing nothing but the property name.

For example:

	description This is a valid description

	DESCRIPTION
	  So is this
	  description here

	description This would
	  cause an error

There are 4 compulsory fields required to create a nupkg. These can always be specified in the
template file, or in a project based template can be omitted and an attempt will be made to infer
them as below:

* id - the Id of the resulting nupkg (which also determines the output filename). If omitted in a
  project template, reflection will be used to determine the assembly name.
* version - the version of the resulting nupkg. If omitted in a project template, reflection will
  be used to obtain the value of the `AssemblyInformationalVersionAttribute` or if that is missing
  the `AssemblyVersionAttribute`.
* authors - a comma separated list of authors for the nuget package. Inferred as the value of the
  `AssemblyCompanyAttribute` if omitted in a project template.
* description - this will be displayed as the nupkg description. Inferred from the `AssemblyDescriptionAttribute`
  if unspecified.

The other general metadata properties are all optional, and map directly to the field of the same
name in the nupkg.

* title
* owners
* releaseNotes
* summary
* language
* projectUrl
* iconUrl
* licenseUrl
* copyright
* requireLicenseAcceptance (boolean)
* tags
* developmentDependency (boolean)

### Dependencies and Files

The dependencies the package relies on, and the files to package are specified in a slightly different format.
These two fields will be ignored in project templates if specified, and instead the rules below will be used
to decide on the files and dependencies added.

#### Files

A files block looks like this:

    files
	    relative/to/template/file ==> folder/in/nupkg
	    second/thing/to/pack ==> folder/in/nupkg
		second/thing/**/file.* ==> folder/in/nupkg

If the source part refers to a file then it is copied into the target directory. If it
refers to a directory, the contents of the directory will be copied into the target folder.
If you omit the target folder, then the source is copied into the `lib` folder of the package.

Excluding certain files looks like this:

    files
        relative/to/template/file ==> folder/in/nupkg
        second/thing/**/file.* ==> folder/in/nupkg
        !second/thing/**/file.zip
        ../outside/file.* ==> folder/in/nupkg/other
        !../outside/file.zip

The pattern needs to match file-names, excluding directories like `!second` won't have an effect, please use `!second/*.*` instead.

In a project template, the files included will be:

* the output assembly of the matching project (in the correct lib directory if a library, or tools if an exe)
* the output assemblies of any project references which do not have a matching template file

#### References

A references block looks like this:

    references
	    filename1.dll
	    filename2.dll

If you omit the references block then all libraries in the packages will get referenced.

#### Framework assembly references

A block with framework assembly references looks like this:

    frameworkAssemblies
	    System.Xml
		System.Xml.Linq

If you omit the references block then all libraries in the packages will get referenced.

#### Dependencies

A dependency block looks like this:

	dependencies
	  FSharp.Core >= 4.3.1
	  Other.Dep ~> 2.5
	  Any.Version

The syntax for specifying allowed dependency ranges are identical to in the ranges in [`paket.dependencies` files](dependencies-file.html).

It's possible to use `CURRENTVERSION` as a placeholder for the current version of the package:

	dependencies
	  FSharp.Core >= 4.3.1
	  Other.Dep ~> CURRENTVERSION

The `LOCKEDVERSION` placeholder allows to reference the currently used dependency version from the paket.lock file:

	dependencies
	  FSharp.Core >= 4.3.1
	  Other.Dep ~> LOCKEDVERSION

In a project file, the following dependencies will be added:

* any paket dependency with the range specified in the [`paket.dependencies` file](dependencies-file.html).
* any paket dependency with the range specified in the [`paket.lock` file](lock-file.html) (if `lock-dependencies` parameter is used in [`paket pack`](paket-pack.html)).
* any project reference with a matching paket.template file with a minimum version requirement of the version currently being packaged.

### Comments

A line starting with a # or // is considered a comment and will be ignored by the parser.


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

namespace Alaska.Foundation.Godzilla.Mongo.Attributes
{
    public class MongoDerivedTypeAttribute : Attribute
    {
        private readonly string _name;

        public MongoDerivedTypeAttribute(string name)
        {
            _name = name;
        }

        public string Name => _name;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: sean.james
 * Date: 10/05/2017
 * Time: 10:26
 */

namespace App\Action;

use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\JsonResponse;
use Swagger;
use App\Action\Action;

/**
 * Get an API doc response for a given route
 *
 * Class ApiDocAction
 * @package App\Action
 *
 * @SWG\Swagger(
 *      @SWG\Info(title="crAPI - A RESTful(ish) api for CRUD'ing stuff of different 'types'", version="0.1"),
 *      definitions={
 *          @SWG\Definition(
 *              definition="item",
 *              properties={
 *                  @SWG\Property(property="id", type="string", description="An ID string unique to things of this type"),
 *                  @SWG\Property(property="type", type="string", description="The type of the item"),
 *                  @SWG\Property(property="value", type="string", description="The value of this thing")
 *              }
 *          )
 *     }
 * )
 *
 * @see http://zircote.com/swagger-php/
 * @see https://github.com/zircote/swagger-php/blob/master/docs/Getting-started.md
 * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operationObject
 */
class ApiDocAction extends Action implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $swagger = Swagger\scan(__DIR__);
        return new JsonResponse($swagger);
    }
}


text:
package db

//go:generate counterfeiter . BaseResourceTypeFactory

type BaseResourceTypeFactory interface {
	Find(name string) (*UsedBaseResourceType, bool, error)
}

type baseResourceTypeFactory struct {
	conn Conn
}

func NewBaseResourceTypeFactory(conn Conn) BaseResourceTypeFactory {
	return &baseResourceTypeFactory{
		conn: conn,
	}
}

func (f *baseResourceTypeFactory) Find(name string) (*UsedBaseResourceType, bool, error) {
	brt := BaseResourceType{
		Name: name,
	}

	tx, err := f.conn.Begin()
	if err != nil {
		return nil, false, err
	}

	defer Rollback(tx)

	ubrt, found, err := brt.Find(tx)
	if err != nil {
		return nil, false, err
	}

	err = tx.Commit()
	if err != nil {
		return nil, false, err
	}

	return ubrt, found, nil
}


text:
package ecse414.fall2015.group21.game.shared.connection;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * Represents an Address, contains an IP number, port number, and shared secret.
 * Used by the networking.
 *
 */
public class Address {
    // TODO: register with IANA :P
    public static final int DEFAULT_SERVER_PORT = 28_392;
    // Zero is interpreted as any free port by netty
    public static final int DEFAULT_CLIENT_PORT = 0;
    private final int ip;
    private final int port;
    private final int sharedSecret;
    private final Type type;
    // A cache for conversion
    private InetAddress inetAddress = null;

    private Address(int ip, int port, int sharedSecret, Type type) {
        this.ip = ip;
        this.port = port;
        this.sharedSecret = sharedSecret;
        this.type = type;
    }

    /**
     * Determines if this Address represents a server.
     *
     * @return True is this address represents a server, False otherwise
     */
    public boolean isServer() {
        return type == Type.LOCAL_SERVER || type == Type.REMOTE_SERVER;
    }

    /**
     * Determines if this Address represents a connected client.
     *
     * @return True if this Address represents a connected client, False otherwise
     */
    public boolean isConnectedClient() {
        return type == Type.LOCAL_CLIENT || type == Type.REMOTE_CLIENT;
    }

    /**
     * Determines if thi Address represents an unconnected client.
     *
     * @return True if this Address represents an unconnected client, False otherwise
     */
    public boolean isUnconnectedClient() {
        return type == Type.UNCONNECTED_LOCAL_CLIENT || type == Type.UNCONNECTED_REMOTE_CLIENT;
    }

    /**
     * Determines whether this Address represents a client, either connected or unconnected.
     *
     * @return True if this Address respresents a client, False otherwise
     */
    public boolean isClient() {
        return isConnectedClient() || isUnconnectedClient();
    }

    /**
     * Determines whether this Address is local.
     *
     * @return True if the Address is local, False otherwise
     */
    public boolean isLocal() {
        return type == Type.LOCAL_SERVER || type == Type.UNCONNECTED_LOCAL_CLIENT || type == Type.LOCAL_CLIENT;
    }

    /**
     * Determines whether this Address is remote.
     *
     * @return True if this Address is remote, False otherwise
     */
    public boolean isRemote() {
        return type == Type.REMOTE_SERVER || type == Type.UNCONNECTED_REMOTE_CLIENT || type == Type.REMOTE_CLIENT;
    }

    /**
     * Determines whether this Address has an IP address associated with it. This will be the case when it is not a local Address.
     *
     * @return True if the Address has an IP address associated with it, False otherwise
     */
    public boolean hasIPAddress() {
        return !isLocal();
    }

    /**
     * Determine whether this Address has the shared secret from the server, used for synchronization between client and server.
     *
     * @return True if the Address has the shared secret
     */
    public boolean hasSharedSecret() {
        return isServer() || isConnectedClient();
    }

    /**
     * Get the IP address associated with this Address.
     *
     * @return the IP address associed with the Address
     */
    public int getIPAddress() {
        if (!hasIPAddress()) {
            throw new IllegalStateException("Address doesn't have an IP address");
        }
        return ip;
    }

    /**
     * Get the port number associated with this Address.
     *
     * @return the port number associed with the Address
     */
    public int getPort() {
        return port;
    }

    /**
     * Get the shared secret of this Address if it has one.
     *
     * @return  The shared secret number
     */
    public int getSharedSecret() {
        if (!hasSharedSecret()) {
            throw new IllegalStateException("Address doesn't have a shared secret");
        }
        return sharedSecret;
    }

    /**
     * Gets the Type of this Address. Types include 'REMOTE_SERVER', 'UNCONNECTED_REMOTE_CLIENT', and 'REMOTE_CLIENT'.
     *
      * @return the Type of this Address
     */
    public Type getType() {
        return type;
    }

    /**
     * Connect a client to an Address without specifying a shared secret.
     *
     * @return  the Adress of the connected client
     */
    public Address connectClient() {
        return connectClient(0);
    }

    /**
     * Connect a client to an Address with a given shared secret.
     *
     * @param sharedSecret  the shared secret that will be assocciated with the Address
     * @return              the Address with a given shared secret
     */
    public Address connectClient(int sharedSecret) {
        if (!isUnconnectedClient()) {
            throw new IllegalStateException("Address is not an unconnected client");
        }
        return isLocal() ? forLocalClient(port, sharedSecret) : forRemoteClient(ip, port, sharedSecret);
    }

    /**
     * Get the InetAddress associated with this Address.
     *
     * @return  the InetAddress associated with this Address
     */
    public InetAddress asInetAddress() {
        if (inetAddress == null) {
            try {
                inetAddress = InetAddress.getByAddress(new byte[]{
                        (byte) (ip & 0xFF),
                        (byte) (ip >> 8 & 0xFF),
                        (byte) (ip >> 16 & 0xFF),
                        (byte) (ip >> 24 & 0xFF),
                });
            } catch (UnknownHostException exception) {
                throw new RuntimeException(exception);
            }
        }
        return inetAddress;
    }

    /**
     * Get the InetSocketAddress associated with this Address. This is associated with a port number.
     *
     * @return  the InetSocketAddress associated with this Address
     */
    public InetSocketAddress asInetSocketAddress() {
        return new InetSocketAddress(asInetAddress(), port);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (!(other instanceof Address)) {
            return false;
        }
        final Address address = (Address) other;
        return ip == address.ip && port == address.port;
    }

    @Override
    public int hashCode() {
        int result = ip;
        result = 31 * result + port;
        return result;
    }

    @Override
    public String toString() {
        switch (type) {
            case LOCAL_SERVER:
                return "LocalSever(port = " + port + ")";
            case REMOTE_SERVER:
                return "RemoteServer(ip = " + ipToByteString(ip) + ", port = " + port + ")";
            case UNCONNECTED_LOCAL_CLIENT:
                return "UnconnectedLocalClient(port = " + port + ")";
            case UNCONNECTED_REMOTE_CLIENT:
                return "UnconnectedRemoteClient(ip = " + ipToByteString(ip) + ", port = " + port + ")";
            case LOCAL_CLIENT:
                return "LocalClient(port = " + port + ", sharedSecret = " + sharedSecret + ")";
            case REMOTE_CLIENT:
                return "RemoteClient(ip = " + ipToByteString(ip) + ", port = " + port + ", sharedSecret = " + sharedSecret + ")";
            default:
                throw new UnsupportedOperationException(type.toString());
        }
    }

    /**
     * Enumerator for the different Types of Address.
     */
    public enum Type {
        LOCAL_SERVER,
        REMOTE_SERVER,
        UNCONNECTED_LOCAL_CLIENT,
        UNCONNECTED_REMOTE_CLIENT,
        LOCAL_CLIENT,
        REMOTE_CLIENT
    }

    /**
     * Creates a new Address for a local server.
     *
     * @param port  the port that the local server is listening at
     * @return      the Address associated with the local server
     */
    public static Address forLocalServer(int port) {
        return new Address(0, port, 0, Type.LOCAL_SERVER);
    }

    /**
     * Creates a new Address for a remote server given it's IP address and a port number.
     *
     * @param ipAddress the IP address of the remote server
     * @param port      the port number of the remote server
     * @return          the Address for the remote server
     */
    public static Address forRemoteServer(int ipAddress, int port) {
        return new Address(ipAddress, port, 0, Type.REMOTE_SERVER);
    }

    /**
     * Creates a new Address for an unconnected local client.
     *
     * @param port  port number the local unconnected client will bind to
     * @return      the Address for the unconnected client
     */
    public static Address forUnconnectedLocalClient(int port) {
        return new Address(0, port, 0, Type.UNCONNECTED_LOCAL_CLIENT);
    }

    /**
     * Creates a new Address for an unconnected remote client.
     *
     * @param ipAddress IP address of the remote client
     * @param port      port number of the remote client
     * @return          the Address of the remote unconnectet client
     */
    public static Address forUnconnectedRemoteClient(int ipAddress, int port) {
        return new Address(ipAddress, port, 0, Type.UNCONNECTED_REMOTE_CLIENT);
    }

    /**
     * Creates a new Address for a local (connected) client.
     *
     * @param port          the port number for the connected client
     * @param sharedSecret  the shared secret for the connected client
     * @return              the Address of the connected local client
     */
    public static Address forLocalClient(int port, int sharedSecret) {
        return new Address(0, port, sharedSecret, Type.LOCAL_CLIENT);
    }

    /**
     * Creates a new Address for a remote (connected) client.
     *
     * @param ipAddress     the IP address of the remote client
     * @param port          the port number of the remote client
     * @param sharedSecret  the shared secret for the remote client
     * @return              the Address of the remote connected client
     */
    public static Address forRemoteClient(int ipAddress, int port, int sharedSecret) {
        return new Address(ipAddress, port, sharedSecret, Type.REMOTE_CLIENT);
    }

    /**
     * Creates a new Address for a local unconnected client using the default port number.
     *
     * @return  the Address of the local unconnected client
     */
    public static Address defaultUnconnectedLocalClient() {
        return forUnconnectedLocalClient(DEFAULT_CLIENT_PORT);
    }

    /**
     * Packs 4 bytes representing an IP address into a single integer.
     *
     * @param bytes the bytes representing an IP address that we wish to determine
     * @return      the IP address that the byte string represented
     */
    public static int ipAddressFromBytes(byte... bytes) {
        if (bytes.length != 4) {
            throw new IllegalArgumentException("Expected 4 bytes in IP address");
        }
        return bytes[0] & 0xFF | (bytes[1] & 0xFF) << 8 | (bytes[2] & 0xFF) << 16 | (bytes[3] & 0xFF) << 24;
    }

    /**
     * Get the byte string representation for a given IP address in the form xxx.xxx.xxx.xxx
     *
     * @param ipAddress an integer representing an IP address
     * @return          the IP address in the form xxx.xxx.xxx.xxx
     */
    public static String ipToByteString(int ipAddress) {
        return String.valueOf(ipAddress & 0xFF) + '.' + (ipAddress >> 8 & 0xFF) + '.' + (ipAddress >> 16 & 0xFF) + '.' + (ipAddress >> 24 & 0xFF);
    }
}


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

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >

    <item
        android:id="@+id/menu_count"
        android:icon="@drawable/ic_people_24dp"
        android:title="@string/dialog_title_player_number"
        app:showAsAction="always"
        />
    <item
        android:id="@+id/menu_chart"
        android:icon="@drawable/ic_show_chart_24dp"
        android:title="@string/menu_action_show_chart"
        app:showAsAction="always"
        />
    <item
        android:id="@+id/menu_clear"
        android:icon="@drawable/ic_clear_all_24dp"
        android:title="@string/menu_action_clear"
        app:showAsAction="ifRoom"
        />
    <item
        android:id="@+id/menu_save"
        android:icon="@drawable/ic_unarchive_24dp"
        android:title="@string/title_activity_saved_games"
        app:showAsAction="ifRoom"
        />
</menu>


text:
using System;
using System.IO;
using System.Threading.Tasks;

namespace Serverless.Getting.Started
{
    public class LambdaEntryPoint
    {
        public Task<Stream> FunctionHandlerAsync(Stream inputStream)
        {
            var response = new LambdaResponse(){
                body = "Hello, I came from AWS Lambda"
            };

            return Task.FromResult(ConvertToStream(response));
        }

        private Stream ConvertToStream(LambdaResponse response)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            var memStream = new MemoryStream();
            var writer = new StreamWriter(memStream);
            serializer.Serialize(writer, response);

            writer.Flush();

            memStream.Position = 0;

            return memStream;
        }
    }
}


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('eligibility-response-financial', 'Unit | Model | EligibilityResponse_Financial', {
  needs: [
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension',
    'model:codeable-concept',
    'model:money'
  ]
});

test('it exists', function(assert) {
  const model = this.subject();
  assert.ok(!!model);
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using GME.CSharp;
using GME.MGA;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace DesignExporterUnitTests
{
    public class LayoutFixture : ExporterFixture
    {
        public override String pathXME
        {
            get
            {
                return Path.Combine(META.VersionInfo.MetaPath,
                                    "test",
                                    "InterchangeTest",
                                    "DesignInterchangeTest",
                                    "ExportTestModels",
                                    "Layout",
                                    "Layout.xme");
            }
        }
    }

    internal static class Utils
    {
        public static void PerformInTransaction(this MgaProject project, MgaGateway.voidDelegate del)
        {
            var mgaGateway = new MgaGateway(project);
            project.CreateTerritoryWithoutSink(out mgaGateway.territory);
            mgaGateway.PerformInTransaction(del);
        }
    }

    public class Layout : IUseFixture<LayoutFixture>
    {
        #region Fixture
        LayoutFixture fixture;
        public void SetFixture(LayoutFixture data)
        {
            fixture = data;
        }
        #endregion

        private MgaProject proj { get { return fixture.proj; } }

        [Fact]
        public void Export()
        {
            avm.Design design = null;
            proj.PerformInTransaction(delegate
            {
                // Retrieve design contain as MgaObject
                MgaObject objDesignContainer = null;
                objDesignContainer = proj.get_ObjectByPath(@"DesignSpaces/DesignContainer");
                Assert.NotNull(objDesignContainer);

                // Cast as DesignContainer and run converter
                var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(objDesignContainer);
                design = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(designContainer);
            });
            Assert.NotNull(design);

            String pathXmlOut = Path.Combine(fixture.PathTest, "DesignContainer.adm");
            using (StreamWriter sw = new StreamWriter(pathXmlOut, false))
            {
                sw.Write(design.Serialize());
            }

            var checker = new LayoutDataChecker();
            var result = checker.Check(design.RootContainer);

            if (result.Any())
            {
                String msg = Environment.NewLine +
                             String.Join(Environment.NewLine,
                                         result);
                Assert.True(false, msg);
            }
        }
    }

    internal class LayoutDataChecker
    {
        private ConcurrentBag<String> ObjectsMissingLayout;

        public IEnumerable<String> Check(avm.Container container)
        {
            ObjectsMissingLayout = new ConcurrentBag<String>();
            RecursivelyCheckForLayoutData(container);
            return ObjectsMissingLayout.AsEnumerable();
        }

        private void TestLayoutData(object obj, String path)
        {
            Boolean pass = true;
            var objType = obj.GetType();

            var xpos = objType.GetProperty("XPositionSpecified");
            Boolean? xposSpecified = xpos.GetValue(obj, null) as Boolean?;
            if (xposSpecified.HasValue == false || xposSpecified.Value == false)
            {
                pass = false;
            }

            var ypos = objType.GetProperty("YPositionSpecified");
            Boolean? yposSpecified = ypos.GetValue(obj, null) as Boolean?;
            if (yposSpecified.HasValue == false || yposSpecified.Value == false)
            {
                pass = false;
            }

            if (!pass)
            {
                ObjectsMissingLayout.Add(String.Format("{0} ({1}) doesn't contain X&Y layout data", path, objType.Name));
            }
        }

        private void RecursivelyCheckForLayoutData(avm.Container container, String path = null)
        {
            String containerPath = String.Join("/", path, container.Name);

            // Test this container for layout data
            if (false == String.IsNullOrWhiteSpace(path))
            {
                TestLayoutData(container, containerPath);
            }

            // Test child objects for layout data
            container.ComponentInstance.ForEach(x => TestLayoutData(x, String.Join("/", containerPath, x.Name)));
            container.Connector.ForEach(x => TestLayoutData(x, String.Join("/", containerPath, x.Name)));
            container.Formula.ForEach(x => TestLayoutData(x, String.Join("/", containerPath, x.Name)));
            container.Port.ForEach(x => TestLayoutData(x, String.Join("/", containerPath, x.Name)));
            container.Property.ForEach(x => TestLayoutData(x, String.Join("/", containerPath, x.Name)));

            // Recursively check child containers
            container.Container1
                     .AsParallel()
                     .ForAll(c => RecursivelyCheckForLayoutData(c, containerPath));
        }
    }
}


text:
package rx.subjects;

import java.util.ArrayList;
import java.util.List;

import rx.annotations.Experimental;
import rx.exceptions.Exceptions;
import rx.functions.Action1;
import rx.internal.operators.NotificationLite;
import rx.subjects.SubjectSubscriptionManager.SubjectObserver;

/**
 * Subject that emits the most recent item it has observed and all subsequent observed items to each subscribed
 * {@link rx.Observer}.
 *

 *
 *

 * Example usage:
 *

 *
 {@code

  // observer will receive all events.
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.subscribe(observer);
  subject.onNext("one");
  subject.onNext("two");
  subject.onNext("three");

  // observer will receive the "one", "two" and "three" events, but not "zero"
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.onNext("zero");
  subject.onNext("one");
  subject.subscribe(observer);
  subject.onNext("two");
  subject.onNext("three");

  // observer will receive only onCompleted
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.onNext("zero");
  subject.onNext("one");
  subject.onCompleted();
  subject.subscribe(observer);

  // observer will receive only onError
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.onNext("zero");
  subject.onNext("one");
  subject.onError(new RuntimeException("error"));
  subject.subscribe(observer);
  }

 *
 * @param <T>
 *          the type of item expected to be observed by the Subject
 */
public final class ClearableBehaviorSubject<T> extends Subject<T, T> {
    /**
     * Creates a {@link ClearableBehaviorSubject} without a default item.
     *
     * @param <T>
     *            the type of item the Subject will emit
     * @return the constructed {@link ClearableBehaviorSubject}
     */
    public static <T> ClearableBehaviorSubject<T> create() {
        return create(null, false);
    }
    /**
     * Creates a {@link ClearableBehaviorSubject} that emits the last item it observed and all subsequent items to each
     * {@link rx.Observer} that subscribes to it.
     *
     * @param <T>
     *            the type of item the Subject will emit
     * @param defaultValue
     *            the item that will be emitted first to any {@link rx.Observer} as long as the
     *            {@link ClearableBehaviorSubject} has not yet observed any items from its source {@code Observable}
     * @return the constructed {@link ClearableBehaviorSubject}
     */
    public static <T> ClearableBehaviorSubject<T> create(T defaultValue) {
        return create(defaultValue, true);
    }
    private static <T> ClearableBehaviorSubject<T> create(T defaultValue, boolean hasDefault) {
        final SubjectSubscriptionManager<T> state = new SubjectSubscriptionManager<T>();
        if (hasDefault) {
            state.set(NotificationLite.instance().next(defaultValue));
        }
        state.onAdded = new Action1<SubjectObserver<T>>() {

            @Override
            public void call(SubjectObserver<T> o) {
                o.emitFirst(state.get(), state.nl);
            }

        };
        state.onTerminated = state.onAdded;
        return new ClearableBehaviorSubject<T>(state, state);
    }

    private final SubjectSubscriptionManager<T> state;
    private final NotificationLite<T> nl = NotificationLite.instance();

    protected ClearableBehaviorSubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T> state) {
        super(onSubscribe);
        this.state = state;
    }

    public void clear() {
        state.set(null);
    }

    @Override
    public void onCompleted() {
        Object last = state.get();
        if (last == null || state.active) {
            Object n = nl.completed();
            for (SubjectObserver<T> bo : state.terminate(n)) {
                bo.emitNext(n, state.nl);
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        Object last = state.get();
        if (last == null || state.active) {
            Object n = nl.error(e);
            List<Throwable> errors = null;
            for (SubjectObserver<T> bo : state.terminate(n)) {
                try {
                    bo.emitNext(n, state.nl);
                } catch (Throwable e2) {
                    if (errors == null) {
                        errors = new ArrayList<Throwable>();
                    }
                    errors.add(e2);
                }
            }

            Exceptions.throwIfAny(errors);
        }
    }

    @Override
    public void onNext(T v) {
        Object last = state.get();
        if (last == null || state.active) {
            Object n = nl.next(v);
            for (SubjectObserver<T> bo : state.next(n)) {
                bo.emitNext(n, state.nl);
            }
        }
    }

    /* test support */ int subscriberCount() {
        return state.observers().length;
    }

    @Override
    public boolean hasObservers() {
        return state.observers().length > 0;
    }
    /**
     * Check if the Subject has a value.
     *
Use the {@link #getValue()} method to retrieve such a value.
     *
Note that unless {@link #hasCompleted()} or {@link #hasThrowable()} returns true, the value
     * retrieved by {@code getValue()} may get outdated.
     * @return true if and only if the subject has some value and hasn't terminated yet.
     */
    @Experimental
    public boolean hasValue() {
        Object o = state.get();
        return nl.isNext(o);
    }
    /**
     * Check if the Subject has terminated with an exception.
     * @return true if the subject has received a throwable through {@code onError}.
     */
    @Experimental
    public boolean hasThrowable() {
        Object o = state.get();
        return nl.isError(o);
    }
    /**
     * Check if the Subject has terminated normally.
     * @return true if the subject completed normally via {@code onCompleted()}
     */
    @Experimental
    public boolean hasCompleted() {
        Object o = state.get();
        return nl.isCompleted(o);
    }
    /**
     * Returns the current value of the Subject if there is such a value and
     * the subject hasn't terminated yet.
     *
The can return {@code null} for various reasons. Use {@link #hasValue()}, {@link #hasThrowable()}
     * and {@link #hasCompleted()} to determine if such {@code null} is a valid value, there was an
     * exception or the Subject terminated (with or without receiving any value).
     * @return the current value or {@code null} if the Subject doesn't have a value,
     * has terminated or has an actual {@code null} as a valid value.
     */
    @Experimental
    public T getValue() {
        Object o = state.get();
        if (nl.isNext(o)) {
            return nl.getValue(o);
        }
        return null;
    }
    /**
     * Returns the Throwable that terminated the Subject.
     * @return the Throwable that terminated the Subject or {@code null} if the
     * subject hasn't terminated yet or it terminated normally.
     */
    @Experimental
    public Throwable getThrowable() {
        Object o = state.get();
        if (nl.isError(o)) {
            return nl.getError(o);
        }
        return null;
    }
}


text:
[![Build Status](https://travis-ci.org/lemmy/jclouds2p2.png?branch=master)](https://travis-ci.org/lemmy/jclouds2p2)

jclouds2p2
==========

Aggregates jclouds and its dependencies into a p2 repository

Make sure to start these jclouds bundles explicitly in a launch config to activate OSGi. Otherwise expect NoClassDefFoundExceptions:

* aws-ec2_1.9.1
* com.jcraft.jsch.agentproxy.connector-factory_0.0.7
* ec2_1.9.1
* jclouds-core_1.9.1
* sts_1.9.1

Additionally to Travis CI, a build is at http://tla.msr-inria.inria.fr/jclouds2p2/


text:
<?php

declare(strict_types=1);

namespace ProophTest\Common\Messaging;

use Assert\InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Prooph\Common\Messaging\DomainMessage;
use Prooph\Common\Messaging\Message;
use Prooph\Common\Messaging\NoOpMessageConverter;

class NoOpMessageConverterTest extends TestCase
{
    /**
     * @test
     */
    public function it_converts_to_array(): void
    {
        $messageMock = $this->getMockForAbstractClass(DomainMessage::class, [], '', true, true, true, ['toArray']);
        $messageMock->expects($this->once())->method('toArray');

        $converter = new NoOpMessageConverter();
        $converter->convertToArray($messageMock);
    }

    /**
     * @test
     */
    public function it_throws_exception_when_message_is_not_a_domain_message(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('was expected to be instanceof of "Prooph\Common\Messaging\DomainMessage" but is not');

        $messageMock = $this->getMockForAbstractClass(Message::class);

        $converter = new NoOpMessageConverter();
        $converter->convertToArray($messageMock);
    }
}


text:
<% var keyPrefix = angularAppName + '.'+ entityTranslationKey + '.'; %>
<form name="editForm" role="form" novalidate ng-submit="vm.save()"<% if (validation) { %> show-validation<% } %>>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                ng-click="vm.clear()">×</button>
        <h4 class="modal-title" id="my<%= entityClass %>Label" data-translate="<%= keyPrefix %>home.createOrEditLabel">Create or edit a <%= entityClassHumanized %>

        <jhi-alert-error></jhi-alert-error>
        <div class="form-group" ng-show="vm.<%=entityInstance %>.id">
            ID
            <input type="text" class="form-control" id="id" name="id"
                    ng-model="vm.<%=entityInstance %>.id" readonly />

        <%_ for (idx in fields) {
            var fieldName = fields[idx].fieldName;
            var fieldNameCapitalized = fields[idx].fieldNameCapitalized;
            var fieldNameHumanized = fields[idx].fieldNameHumanized;
            var fieldType = fields[idx].fieldType;
            var fieldTypeBlobContent = fields[idx].fieldTypeBlobContent;
            var fieldInputType = 'text';
            var ngModelOption = '';
            var translationKey = keyPrefix + fieldName;
            if (fieldType == 'Integer' || fieldType == 'Long' || fieldType == 'Float' || fieldType == 'Double' || fieldType == 'BigDecimal') {
                fieldInputType = 'number';
            } else if (fieldType == 'LocalDate') {
                fieldInputType = 'date';
            } else if (fieldType == 'ZonedDateTime') {
                fieldInputType = 'datetime-local';
            } else if (fieldType == 'Boolean') {
                fieldInputType = 'checkbox';
            } else if ((fieldType == 'byte[]' || fieldType == 'ByteBuffer') && fieldTypeBlobContent != 'text') {
                fieldInputType = 'hidden';
            } _%>
        <div class="form-group"<% if ((fieldType == 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent != 'text') { %> ngf-drop ngf-change="vm.set<%=fieldNameCapitalized %>($file, vm.<%= entityInstance %>)"<% if (fieldTypeBlobContent == 'image') { %> ngf-pattern="'image/*'"<% } %><% } %>>
            <label class="control-label" data-translate="<%= translationKey %>" for="field_<%= fieldName %>"><%= fieldNameHumanized %>
            <%_ if (fields[idx].fieldIsEnum) { _%>
            <select class="form-control" name="<%= fieldName %>" ng-model="vm.<%= entityInstance %>.<%= fieldName %>" id="field_<%= fieldName %>"<% if (fields[idx].fieldValidate == true && fields[idx].fieldValidateRules.indexOf('required') != -1) { %> required<% } %>>
                <%_ var enumPrefix = angularAppName + '.'+ fieldType;
                    var values = fields[idx].fieldValues.replace(/\s/g, '').split(',');
                    for (key in values) {
                        var value = values[key]; _%>
                <option value="<%= value %>" data-translate="<%=enumPrefix%>.<%=value%>"><%= value %></option>
                <%_ } _%>
            </select>
            <%_ } else { _%>
                <%_ if ((fieldType == 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent != 'text') { _%>

                    <%_ if (fieldTypeBlobContent == 'image') { _%>
                <img data-ng-src="{{'data:' + vm.<%=entityInstance %>.<%=fieldName%>ContentType + ';base64,' + vm.<%=entityInstance %>.<%=fieldName%>}}" style="max-height: 100px;" ng-if="vm.<%= entityInstance %>.<%= fieldName %>"/>
                    <%_ } _%>
                <div ng-if="vm.<%= entityInstance %>.<%= fieldName %>" class="help-block clearfix">
                    <%_ if (fieldTypeBlobContent == 'any') { _%>
                    <a class="pull-left" ng-click="vm.openFile(vm.<%= entityInstance %>.<%= fieldName %>ContentType, vm.<%= entityInstance %>.<%= fieldName %>)" data-translate="entity.action.open">open

                    {{vm.<%= entityInstance %>.<%= fieldName %>ContentType}}, {{vm.byteSize(vm.<%= entityInstance %>.<%= fieldName %>)}}
                    <%_ } else { _%>
                    {{vm.<%= entityInstance %>.<%= fieldName %>ContentType}}, {{vm.byteSize(vm.<%= entityInstance %>.<%= fieldName %>)}}
                    <%_ } _%>
                    <button type="button" ng-click="vm.<%= entityInstance %>.<%= fieldName %>=null;vm.<%= entityInstance %>.<%= fieldName %>ContentType=null;"
                            class="btn btn-default btn-xs pull-right">

                    </button>

                <button type="button" ngf-select class="btn btn-default btn-block"
                        ngf-change="vm.set<%=fieldNameCapitalized %>($file, vm.<%= entityInstance %>)"<% if (fieldTypeBlobContent == 'image') { %> accept="image/*" data-translate="entity.action.addimage"<% } else { %> data-translate="entity.action.addblob"<% } %>>
                    <% if (fieldTypeBlobContent == 'image') { %>Add image<% } else { %>Add blob<% } %>
                </button>

                <%_ } _%>
                <%_ if (fieldType == 'LocalDate') { _%>

                    <input id="field_<%= fieldName %>" type="text" class="form-control" name="<%= fieldName %>" uib-datepicker-popup="{{dateformat}}" ng-model="vm.<%= entityInstance %>.<%= fieldName %>" is-open="vm.datePickerOpenStatus.<%=fieldName %>"
                    <%- include ng_validators %>/>

                        <button type="button" class="btn btn-default" ng-click="vm.openCalendar('<%=fieldName %>')"></button>

                <%_ } else if(fieldType == 'ZonedDateTime') { _%>

                    <input id="field_<%= fieldName %>" type="text" class="form-control" name="<%= fieldName %>" datetime-picker="{{dateformat}}" ng-model="vm.<%= entityInstance %>.<%= fieldName %>" is-open="vm.datePickerOpenStatus.<%=fieldName %>"
                    <%- include ng_validators %>  />

                        <button type="button" class="btn btn-default" ng-click="vm.openCalendar('<%=fieldName %>')"></button>

                <%_ } else if(fieldTypeBlobContent == 'text') { _%>
                <textarea class="form-control" name="<%= fieldName %>" id="field_<%= fieldName %>"
                    ng-model="vm.<%= entityInstance %>.<%= fieldName %>" <%- include ng_validators %> ></textarea>
                <%_ } else { _%>
            <input type="<%= fieldInputType %>" class="form-control" name="<%= fieldName %>" id="field_<%= fieldName %>"
                    ng-model="vm.<%= entityInstance %>.<%= fieldName %>"
                    <%- include ng_validators %> />
                    <%_ if ((fieldType == 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent != 'text') { _%>
            <input type="hidden" class="form-control" name="<%= fieldName %>ContentType" id="field_<%= fieldName %>ContentType"
                    ng-model="vm.<%= entityInstance %>.<%= fieldName %>ContentType" />
                    <%_ } _%>
                <%_ } _%>
            <%_ } _%>
            <%_ if (fields[idx].fieldValidate == true) { _%>
            <div ng-show="editForm.<%= fieldName %>.$invalid">
                <%_ if (fields[idx].fieldValidateRules.indexOf('required') != -1) { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.required" data-translate="entity.validation.required">
                    This field is required.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('minlength') != -1) { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.minlength" data-translate="entity.validation.minlength" translate-value-min="<%= fields[idx].fieldValidateRulesMinlength %>">
                    This field is required to be at least <%= fields[idx].fieldValidateRulesMinlength %> characters.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('maxlength') != -1) { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.maxlength" data-translate="entity.validation.maxlength" translate-value-max="<%= fields[idx].fieldValidateRulesMaxlength %>">
                    This field cannot be longer than <%= fields[idx].fieldValidateRulesMaxlength %> characters.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('min') != -1) { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.min" data-translate="entity.validation.min" translate-value-min="<%= fields[idx].fieldValidateRulesMin %>">
                    This field should be more than <%= fields[idx].fieldValidateRulesMin %>.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('max') != -1) { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.max" data-translate="entity.validation.max" translate-value-max="<%= fields[idx].fieldValidateRulesMax %>">
                    This field cannot be more than <%= fields[idx].fieldValidateRulesMax %>.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('minbytes') != -1) { _%>
                <p class="help-block"
                   ng-show="editForm.<%= fieldName %>.$error.minbytes" data-translate="entity.validation.minbytes" translate-value-min="<%= fields[idx].fieldValidateRulesMinbytes %>">
                    This field should be more than <%= fields[idx].fieldValidateRulesMinbytes %>.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('maxbytes') != -1) { _%>
                <p class="help-block"
                   ng-show="editForm.<%= fieldName %>.$error.maxbytes" data-translate="entity.validation.maxbytes" translate-value-max="<%= fields[idx].fieldValidateRulesMaxbytes %>">
                    This field cannot be more than <%= fields[idx].fieldValidateRulesMaxbytes %>.

                <%_ } _%>
                <%_ if (fields[idx].fieldValidateRules.indexOf('pattern') != -1) { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.pattern" data-translate="entity.validation.pattern" translate-value-pattern="<%= fields[idx].fieldValidateRulesPattern %>">
                    This field should follow pattern "<%= fields[idx].fieldValidateRulesPattern %>".

                <%_ } _%>
                <%_ if (fieldType == 'Integer' || fieldType == 'Long' || fieldType == 'Float' || fieldType == 'Double' || fieldType == 'BigDecimal') { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.number" data-translate="entity.validation.number">
                    This field should be a number.

                <%_ } _%>
                <%_ if (fieldType == 'ZonedDateTime') { _%>
                <p class="help-block"
                    ng-show="editForm.<%= fieldName %>.$error.ZonedDateTimelocal" data-translate="entity.validation.ZonedDateTimelocal">
                    This field should be a date and time.

                <%_ } _%>

            <%_ } _%>

        <%_ } _%>

        <%_ for (idx in relationships) {
            var relationshipType = relationships[idx].relationshipType;
            var ownerSide = relationships[idx].ownerSide;
            var otherEntityName = relationships[idx].otherEntityName;
            var otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
            var relationshipName = relationships[idx].relationshipName;
            var relationshipNameHumanized = relationships[idx].relationshipNameHumanized;
            var relationshipFieldName = relationships[idx].relationshipFieldName;
            var relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
            var otherEntityField = relationships[idx].otherEntityField;
            var otherEntityFieldCapitalized = relationships[idx].otherEntityFieldCapitalized;
            var relationshipRequired = relationships[idx].relationshipRequired;
            var translationKey = keyPrefix + relationshipName; _%>
            <%_ if (relationshipType == 'many-to-one' || (relationshipType == 'one-to-one' && ownerSide == true && otherEntityName == 'user')) { _%>

            <label data-translate="<%= translationKey %>" for="field_<%= relationshipName %>"><%= relationshipNameHumanized %>
                <%_ if (dto == 'no') { _%>
            <select class="form-control" id="field_<%= relationshipName %>" name="<%= relationshipName %>" ng-model="vm.<%= entityInstance %>.<%=relationshipFieldName %>" ng-options="<%=otherEntityName %> as <%=otherEntityName %>.<%=otherEntityField %> for <%=otherEntityName %> in vm.<%=otherEntityNamePlural.toLowerCase() %> track by <%=otherEntityName %>.id"<% if (relationshipRequired) { %> required<% } %>>
                <option value=""></option>
            </select>
                <%_ } else { _%>
            <select class="form-control" id="field_<%= relationshipName %>" name="<%= relationshipName %>" ng-model="vm.<%= entityInstance %>.<%=relationshipFieldName %>Id" ng-options="<%=otherEntityName %>.id as <%=otherEntityName %>.<%=otherEntityField %> for <%=otherEntityName %> in vm.<%=otherEntityNamePlural.toLowerCase() %>"            <% if (relationshipRequired) { %> required<% } %>>
                <option value=""></option>
            </select>
            <%_ } _%>

            <%_ } else if (relationshipType == 'one-to-one' && ownerSide == true) { _%>

            <label data-translate="<%= translationKey %>" for="field_<%= relationshipName %>"><%= relationshipNameHumanized %>
                <%_ if (dto == 'no') { _%>
            <select class="form-control" id="field_<%= relationshipName %>" name="<%= relationshipName %>" ng-model="vm.<%= entityInstance %>.<%=relationshipFieldName %>" ng-options="<%=otherEntityName %> as <%=otherEntityName %>.<%=otherEntityField %> for <%=otherEntityName %> in vm.<%=relationshipFieldNamePlural.toLowerCase() %> | orderBy:'id' track by <%=otherEntityName %>.id"<% if (relationshipRequired) { %> required<% } %>>
                <option value=""></option>
            </select>
                <%_ } else { _%>
            <select class="form-control" id="field_<%= relationshipName %>" name="<%= relationshipName %>" ng-model="vm.<%= entityInstance %>.<%=relationshipFieldName %>Id" ng-options="<%=otherEntityName %>.id as <%=otherEntityName %>.<%=otherEntityField %> for <%=otherEntityName %> in vm.<%=relationshipFieldNamePlural.toLowerCase() %> | orderBy:'id'"<% if (relationshipRequired) { %> required<% } %>>
                <option value=""></option>
            </select>
                <%_ } _%>

            <%_ } else if (relationshipType == 'many-to-many' && relationships[idx].ownerSide == true) { _%>

            <label data-translate="<%= translationKey %>" for="field_<%= relationshipName %>"><%= relationshipNameHumanized %>
            <select class="form-control" id="field_<%= relationshipName %>" multiple name="<%= relationshipName %>" ng-model="vm.<%=entityInstance %>.<%=relationshipFieldNamePlural %>" ng-options="<%=otherEntityName %> as <%=otherEntityName %>.<%=otherEntityField %> for <%=otherEntityName %> in vm.<%=otherEntityNamePlural.toLowerCase() %> track by <%=otherEntityName %>.id"<% if (relationshipRequired) { %> required<% } %>></select>

            <%_ } _%>
            <%_ if (relationships[idx].relationshipValidate == true) { _%>
        <div ng-show="editForm.<%= relationshipName %>.$invalid">
                <%_ if (relationshipRequired) { _%>
            <p class="help-block"
                ng-show="editForm.<%= relationshipName %>.$error.required" data-translate="entity.validation.required">
                This field is required.

                <%_ } _%>

            <%_ } _%>
        <%_ } _%>

        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
             Cancel
        </button>
        <button type="submit" ng-disabled="editForm.$invalid || vm.isSaving" class="btn btn-primary">
             Save
        </button>

</form>


text:
using System;
using Rhino.ServiceBus.Transport;
using System.Linq;
using System.Collections.Generic;

namespace Rhino.ServiceBus.Util
{
    public static class UriExtensions
    {
        public static Uri AddSubQueue(this Uri self, SubQueue subQueue)
        {
            Uri subQueueUrl;
            if (self.AbsolutePath.EndsWith("/"))
                subQueueUrl = new Uri(self + SubQueue.Discarded.ToString());
            else
                subQueueUrl = new Uri(self + "/" + SubQueue.Discarded);
            return subQueueUrl;
        }

        public static string GetQueueName(this Uri self)
        {
            return self.AbsolutePath.Substring(1).Split('/').First();
        }

        private static HashSet<string> localhosts = new HashSet<string>(new[]{"localhost","127.0.0.1"}, StringComparer.OrdinalIgnoreCase);

        public static Uri NormalizeLocalhost(this Uri uri)
        {
            if (localhosts.Contains(uri.Host))
            {
                return new UriBuilder(uri){ Host = Environment.MachineName }.Uri;
            }
            return uri;
        }
    }
}


text:
Worflow for swithching back and forth between UNIX and Windows Paths, specifically between Mapped Drives and Mounted Network Volumes.
It features the actual switching of paths, optionally open the path in Finder, and configuration options to list, add and remove mappings between Windows drives and UNIX volumes.

## Setup
You'll need to add one or more mappings before doing the conversions. Check below on _usage_ for more info.

## Usage
* Type ```convertadd``` keyword to add a new mappping, for example ```convertadd R MyVolume```. This will map R:\ Windows Paths with /Volumes/MyVolume UNIX Paths. After ```convertadd``` you need to specify a Windows Drive letter, followed by a UNIX Volume name.

![add a mapping](https://raw.github.com/ramiroaraujo/alfred-convert-os-path-workflow/master/screenshots/convert-add.png)

* Type ```convertlist``` keyword to list current mappings. Hold down the ```alt``` key to delete a mapping.

![list mappings](https://raw.github.com/ramiroaraujo/alfred-convert-os-path-workflow/master/screenshots/convert-list.png)

* Type ```convert``` keyword followed by a valid and mapped Windows or UNIX path to have it converted and copied to the clipboard. Hold down ```Command``` to instead open the path in Finder if converting to UNIX.

![convert to UNIX](https://raw.github.com/ramiroaraujo/alfred-convert-os-path-workflow/master/screenshots/convert-to-unix.png)

![convert to Windows](https://raw.github.com/ramiroaraujo/alfred-convert-os-path-workflow/master/screenshots/convert-to-windows.png)

## Installation
For OS X 10.9 Mavericks, Download the [alfred-convert-os-path.alfredworkflow](https://github.com/ramiroaraujo/alfred-convert-os-path-workflow/raw/master/alfred-convert-os-path.alfredworkflow) and import to Alfred 2.

For Previous OS X Versions, Download the [alfred-convert-os-path.alfredworkflow](https://github.com/ramiroaraujo/alfred-convert-os-path-workflow/raw/pre-mavericks/alfred-convert-os-path.alfredworkflow) and import to Alfred 2.

## Changelog
* _2014-01-06_ - Released


text:
require 'rails_helper'

RSpec.describe MakeBasicNotification, type: :service do
  let(:user) { create(:named_user, name: "User") }
  let(:description) { "Hello, notifications!" }

  subject(:notification) { notification = MakeBasicNotification.new(
    to:   user,
    content: description
  ).call }

  describe "#call" do
    it "creates a new notification from sender to receiver for the game" do
      notification
      expect(user.notifications.reject(&:read?).length).to eq 1
    end

    it "has a correct description" do
      expect(notification.description).to eq description
    end

    it "has a correct action" do
      expect(notification.read_action).to eq :back
    end
  end
end


text:
import functools
import json
import urllib2
import os.path

from opus.project.deployment import models, forms
import opus.lib.builder
import opus.lib.deployer
from opus.lib.deployer import DeploymentException
import opus.lib.log
from opus.project.deployment import tasks
import opus.project.deployment.database
log = opus.lib.log.get_logger()

from django.conf import settings
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError

def render(templatename, params, request, code=200):
    response = render_to_response(templatename, params,
            context_instance=RequestContext(request))
    response.status_code = code
    response['Content-Type'] = "text/html"
    return response

# A few decorators that come in handy. Perhaps move these to another file for
# organization
def catch_deployerrors(f):
    """A decorator that catches ValidationError and DeploymentExceptions on
    views and renders error.html instead of letting the error propagate.

    I think this is unnecessary. Django has error handling built in, we should
    be using that outside of debug, and its built in error pages when
    debugging.

    """
    @functools.wraps(f)
    def newf(request, *args, **kwargs):
        try:
            return f(request, *args, **kwargs)
        except (ValidationError, DeploymentException), e:
            log.warning("Caught an error while running view %s, rendering error.html. %s", f.__name__, e)
            return render("error.html",
                    {'message': e},
                    request)
    return newf

def get_project_object(f):
    """A decorator that wraps views which takes a parameter called
    projectname. Attempts to fetch the object from the database and calls the
    view function with the object as the second parameter. Raises 404 if not
    found.

    Also checks access permission.

    """
    @functools.wraps(f)
    def newf(request, projectname, *args, **kwargs):
        obj = get_object_or_404(models.DeployedProject,
                name=projectname)
        if not obj.owner == request.user and not request.user.is_superuser:
            return render("error.html",
                    {"message":"Access Denied"},
                    request)
        return f(request, obj, *args, **kwargs)
    return newf

def debug_view(f):
    """Put this decorator on a view to dump to the log the request, post data,
    headers, and dump the returned data

    """
    @functools.wraps(f)
    def newf(request, *args, **kwargs):
        import pprint
        log.debug("{0} view called".format(f.__name__))
        log.debug("Method was {0}".format(request.method))
        log.debug(request.raw_post_data)
        log.debug(request.POST)
        log.debug(pprint.pformat(request.META))
        ret = f(request, *args, **kwargs)
        log.debug(str(ret))
        return ret
    return newf

# The actual views
# ################

@login_required
def list_or_new(request):
    """This view should render a page that displays currently deployed projects
    available to edit, and a form to create+deploy a new project.

    """
    message = ""
    if 'name' in request.GET:
        if not models.id_re.match(request.GET['name']):
            message = "Bad project name. Project names must consist of only letters, numbers, and the underscore character. They must not begin with a number. And they must be less than 25 characters long."
        else:
            return redirect("opus.project.deployment.views.edit_or_create",
                    projectname=request.GET['name'])

    # Get existing projects and list them
    deployments = models.DeployedProject.objects.all()
    if not request.user.is_superuser:
        deployments = deployments.filter(owner=request.user)

    return render("deployment/list_deployments.html", {
        'deployments': deployments,
        'message': message,
        'suffix': settings.OPUS_APACHE_SERVERNAME_SUFFIX,
        }, request)

@login_required
def edit_or_create(request, projectname):
    """This view does four things:
    When called with a GET method and a projectname that doesn't exist,
    displays the necessary forms for creating and deploying a new project

    When called with a POST method and a projectname that doesn't exist, uses
    the POST data to create and deploy a new project

    When called with a GET method and a projectname that does exist, displays a
    form to edit attributes of a depolyed project.

    When called with a POST method and a projectname that does exist, uses the
    POST data to edit the project attributes.

    """
    # Check the max length of the project name to provide a better error
    # message. Let me know if anyone knows an easier way to extract the
    # max_length attribute of the 'name' field of a database model object.
    max_length = models.DeployedProject._meta.get_field_by_name('name')[0].max_length
    if len(projectname) > max_length:
        return render("error.html", {
            "message": "Project names must be less than {0} characters"\
                    .format(max_length),
            }, request)

    # Try and fetch the database object to see if the project exists
    projectquery = models.DeployedProject.objects.filter(
            name=projectname)
    if projectquery.exists():
        # Project does exist, we're in edit mode
        return edit(request, projectname)
    else:
        # Project does not exist, we're in create mode
        return create(request, projectname)

def _get_initial_edit_data(project):
    # Get the initial values for this form, so we can tell what changed when
    # the user submits it
    database = project.config['DATABASES']['default']
    initial = {}
    initial['dbname'] = database['NAME']
    initial['dbengine'] = database['ENGINE'].rsplit(".",1)[1]
    initial['dbpassword'] = "12345" # Nobody would use this password
    initial['dbhost'] = database['HOST']
    initial['dbport'] = database['PORT']
    initial['active'] = project.active
    initial['debug'] = project.config['DEBUG']
    return initial

@login_required
@get_project_object
def edit(request, project):
    """Configuration editor view for an already deployed project

    """
    initial = _get_initial_edit_data(project)

    if request.method == "POST":
        form = forms.DeploymentForm(request.POST, initial=initial)
        if form.is_valid():
            log.info("Edit form submitted and is valid. Editing project parameters")
            cd = form.cleaned_data
            # Go and modify the project/config parameters. Don't save yet
            for field in form.changed_data:
                if field == "dbengine":
                    database['ENGINE'] = 'django.db.backends.' + cd['dbengine']
                    log.debug("dbengine changed to %s", cd['dbengine'])
                elif field == "dbpassword":
                    database['PASSWORD'] = cd['dbpassword']
                    log.debug("dbpassword changed",)
                elif field == "dbhost":
                    database['HOST'] = cd['dbhost']
                    log.debug("dbhost changed to %s", cd['dbhost'])
                elif field == "dbport":
                    database['PORT'] = cd['dbport']
                    log.debug("dbport changed to %s", cd['dbport'])

            project.set_debug(cd['debug'])

            messages = []

            # Validate the modified model
            try:
                # This may error if there's a port conflict or something
                project.full_clean()
            except ValidationError, e:
                log.info("Project model didn't clean. %s", e)
                messages.extend(e.messages)
                # Re-load the project object with the old data, for the "Info"
                # section
                project = models.DeployedProject.objects.get(pk=project.pk)
            else:
                log.info("Model cleaned, saving")
                # save model and config, activate/deactivate if requested,
                # add new superuser if requested
                project.save()
                if "superusername" in form.changed_data:
                    # Should this code be offloaded to a method in the model?
                    log.debug("Adding new superuser")
                    deployer = opus.lib.deployer.ProjectDeployer(project.projectdir)
                    try:
                        deployer.create_superuser(cd['superusername'],
                                cd['superemail'],
                                cd['superpassword'],
                                )
                    except DeploymentException, e:
                        if "column username is not unique" in e.message:
                            messages.append("User with that name already exists!")
                        else:
                            raise e
                    else:
                        messages.append("New superuser created")
                        # Don't re-render the username and password in the form
                        # First make it mutable
                        form.data = form.data.copy()
                        # Then delete these properties
                        del form.data['superusername']
                        del form.data['superemail']
                        del form.data['superpassword']
                        del form.data['superpasswordconfirm']
                # Do this after everything else. If activate fails due to
                # missing app settings, it redirects. Everything else should
                # still be saved though.
                if 'active' in form.changed_data:
                    if cd['active']:
                        if not project.all_settings_set():
                            log.debug("Tried to activate, but still needs settings set. Rendering app settings page")

                            appforms = _get_app_settings_forms(project.get_app_settings(),
                                    project.config)
                            if messages:
                                messages.append("")
                                messages.append("BUT...")
                            messages.append("You asked me to activate the project, but you must set all the settings below first.")

                            return render("deployment/appsettings.html", dict(
                                    appforms=appforms,
                                    project=project,
                                    messages=messages,
                                    ), request)
                        log.debug("Activating")
                        project.activate()
                        messages.append("Project activated")
                    else:
                        log.debug("Deactivating")
                        project.deactivate()
                        messages.append("Project deactivated")
            return render("deployment/edit.html",
                    {'project': project,
                        'form': form,
                        'message': "<br />".join(messages),
                        'applist': _get_apps(project),
                        'appform': forms.AppForm(),
                        }, request)
    else:
        form = forms.DeploymentForm(initial=initial)

    newappform = forms.AppForm()
    return render("deployment/edit.html",
            {'project': project,
                'form': form,
                'appform': newappform,
                'applist': _get_apps(project),
                },
            request)

@login_required
def create(request, projectname):
    """Create and deploy a new project. Displays the form to do so on GET, goes
    and does a create + deploy operation on POST.
    Also has the feature to pre-fill out the form from an incomming JSON token.

    """
    if request.method == "POST" and \
        request.META['CONTENT_TYPE'].find("application/x-www-form-urlencoded") != -1:
        # If the submitted type is not form encoded data, it's probably a json
        # spec of applications, which should instead go to populate and display
        # the forms.
        pform = forms.ProjectForm(request.POST)
        appsform = forms.AppFormSet(request.POST)
        dform = forms.DeploymentForm(request.POST, noactive=True)
        allforms = [pform, appsform, dform]
        # If forms aren't valid, fall through and display the (invalid) forms
        # with error text
        if all(f.is_valid() for f in allforms):
            log.info("Preparing to create+deploy %s", projectname)

            pdata = pform.cleaned_data

            # Create the deployment object to do some early validation checks
            deployment = models.DeployedProject()
            deployment.name = projectname
            deployment.owner = request.user
            deployment.full_clean()

            # Configure the new project. None of these actions actually execute
            # until we enter the try block below
            builder = opus.lib.builder.ProjectBuilder(projectname)
            for appdata in appsform.cleaned_data:
                if not appdata:
                    # Left blank, nothing to add
                    continue
                log.debug(" ... with app %r", appdata['apppath'])
                builder.add_app(appdata['appname'], appdata['apppath'],
                        appdata['apptype'])
            if pdata['idprovider'] != 'local':
                log.debug(" ... and the idp app %r", pdata['idprovider'])
                appname, apptype, apppath = \
                        settings.OPUS_ALLOWED_AUTH_APPS[pdata['idprovider']]
                builder.add_app(appname, apppath, apptype)

            # Now actually execute the tasks. This is done in a try block which
            # catches all exceptions so that we can roll back failed partial
            # deployments in any error cases.
            log.debug("Executing create action on %r...", projectname)
            try:
                # Create the project directory
                projectdir = builder.create(settings.OPUS_BASE_DIR)
                log.info("%r created, starting deploy process", projectname)

                # Prepare deployment parameters
                info = models.DeploymentInfo()
                info.dbengine = dform.cleaned_data['dbengine']
                # If requested, create a database for it
                if info.dbengine == "postgresql_psycopg2" and \
                        settings.OPUS_AUTO_POSTGRES_CONFIG:
                    autodb = opus.project.deployment.database.\
                            setup_postgres(projectname)
                    info.dbname, info.dbuser, info.dbpassword, \
                            info.dbhost, info.dbport = autodb
                elif info.dbengine == "sqlite3":
                    # SQLite database locations get set automatically by the
                    # deployment libraries. No other options are set.
                    # SQLite is handled differently (as far as the location of
                    # the code) since the file must be secured properly.  So
                    # the deployer handles that correctly along side its
                    # routines to change permissions on the directory.
                    pass
                else:
                    info.dbname = dform.cleaned_data['dbname']
                    info.dbuser = dform.cleaned_data['dbuser']
                    info.dbpassword = dform.cleaned_data['dbpassword']
                    info.dbhost = dform.cleaned_data['dbhost']
                    info.dbport = dform.cleaned_data['dbport']
                info.superusername = dform.cleaned_data['superusername']
                info.superemail = dform.cleaned_data['superemail']
                info.superpassword = dform.cleaned_data['superpassword']

                # Deploy it now! But don't activate it.
                deployment.deploy(info, False)

                deployment.set_debug(dform.cleaned_data['debug'])
                deployment.save()

            except Exception, e:
                # The project didn't deploy for whatever reason. Delete the
                # project directory and re-raise the exception
                # Careful that this method isn't called on an existing project,
                # since it could be tricked into deleting an existing project.
                # edit_or_create() ought to check that for us, this function
                # shouldn't be called on an existing project.
                log.error("Project didn't fully create or deploy, rolling back deployment. %s", e)
                # Schedule a task to delete the project
                tasks.destroy_project_by_name.delay(deployment.name)
                raise

            log.info("Project %r successfully deployed", projectname)

            return redirect("opus.project.deployment.views.set_app_settings", projectname)

        else:
            log.debug(request.POST)
            log.debug("Create view called, but forms didn't validate")

    else:
        # Request was either a GET, or was a POST with non-form data
        # Display blank forms
        log.debug("create view called, displaying form")
        appsform = forms.AppFormSet()
        pform = forms.ProjectForm()
        dform = forms.DeploymentForm(noactive=True)

        # If a token was passed in to the GET params, try and use it to
        # populate the app list formset
        token = request.GET.get("token", False)
        if token:
            metadata = urllib2.urlopen(opus.COMMUNITY_URL + "/metadata/" + token)
            metaobj = json.load(metadata)
            # Fill the app form set with this initial data
            appsform = forms.AppFormSet(initial=metaobj['applist'])
            pform = forms.ProjectForm()

    return render("deployment/newform.html", dict(
            pform=pform,
            appsform=appsform,
            dform=dform,
            projectname=projectname,
            ), request)

def _get_app_settings_forms(app_settings, initial=None, data=None):
    """Returns a dict mapping app names to UserSettingForm objects given a
    dictionary as returned by DeployedProject.get_app_settings()

    """
    appforms = {}
    for appname, s in app_settings.iteritems():
        appforms[appname] = forms.UserSettingsForm(s, data, prefix=appname,
                initial=initial)
    return appforms

@login_required
@get_project_object
def set_app_settings(request, project):
    """Asks the user about application specific settings.  This includes any
    chosen projects, as well as hardcoded ldap or openid features"""
    if request.method == "POST":
        appforms = _get_app_settings_forms(project.get_app_settings(),
                project.config,
                request.POST)
        if all(x.is_valid() for x in appforms.itervalues()):
            # Save the settings
            for app, appform in appforms.iteritems():
                opus.lib.builder.merge_settings(
                        project.config, appform.cleaned_data)
            project.config.save()

            # Either way, the config needs to be reloaded, either by calling
            # activate() wich writes the config file, or by calling save()
            # which touches the wsgi config
            if "activate" in request.POST:
                # Writes apache config and restarts apache
                project.activate()
                message = "Settings saved, and project activated"
            elif "active" in request.POST:
                # GWT submits this hidden field to activate or deactivate
                if request.POST['active'] == 'false':
                    project.deactivate()
                else:
                    project.activate()
            else:
                # Saves model, writes config file, touches wsgi config
                project.save()
                message = "Settings saved"

            return render("deployment/appsettings.html", dict(
                    appforms=appforms,
                    project=project,
                    message=message,
                    ), request)

    else:
        appforms = _get_app_settings_forms(project.get_app_settings(),
                project.config)

    return render("deployment/appsettings.html", dict(
            appforms=appforms,
            project=project,
            ), request)

@login_required
@get_project_object
def destroy(request, project):
    """Destroys a project"""
    if request.method == "POST":
        tasks.destroy_project.delay(project.pk)
        return render("deployment/destroyed.html", {
            'projectname': project.name
            }, request)
    else:
        return redirect(project)

@login_required
@get_project_object
def addapp(request, project):
    """Adds an application on submission of an app form"""
    if request.method == "POST":
        appform = forms.AppForm(request.POST)
        if appform.is_valid():
            # Go and add an app
            editor = opus.lib.builder.ProjectEditor(project.projectdir)
            editor.add_app(appform.cleaned_data['appname'],
                    appform.cleaned_data['apppath'],
                    appform.cleaned_data['apptype'],
                    secureops=settings.OPUS_SECUREOPS_COMMAND)
            editor.restart_celery(settings.OPUS_SECUREOPS_COMMAND)
            return render("deployment/addappform.html", dict(
                message='Application added',
                appform=forms.AppForm(),
                project=project,
                ), request)
    else:
        appform = forms.AppForm()

    return render("deployment/addappform.html", dict(
        appform=appform,
        project=project,
        ), request)

def _get_apps(project):
    apps = []
    for potential in project.config['INSTALLED_APPS']:
        if "." in potential:
            continue
        if os.path.exists(os.path.join(project.projectdir,potential)):
            apps.append(dict(appname=potential))
    return apps

@login_required
@get_project_object
def editapp(request, project):
    if request.method == "POST":
        form = forms.EditAppFormSet(request.POST, initial=_get_apps(project))
        if form.is_valid():
            editor = opus.lib.builder.ProjectEditor(project.projectdir)
            deletecount = 0
            upgradecount = 0
            failures = []
            for appform in form.forms:

                if appform in form.deleted_forms:
                    # So that cleaned_data gets populated
                    appform.full_clean()
                    try:
                        editor.del_app(appform.cleaned_data['appname'])
                    except opus.lib.builder.BuildException, e:
                        failures.append((appform.cleaned_data['appname'], 'delete', e))
                    else:
                        deletecount += 1
                        # Remove the app from the installed app in the config.
                        # This is also done by the call to del_app(), but since
                        # the config has been loaded into memory already by the
                        # model object, that data becomes stale. This line is
                        # mostly just a hack so the next call to _get_apps()
                        # returns correct data. This change isn't saved, since
                        # there's no reason to. The change was already saved by
                        # del_app()
                        project.config['INSTALLED_APPS'].remove(
                                appform.cleaned_data['appname'])
                elif appform.cleaned_data['upgradever']:
                    try:
                        editor.upgrade_app(appform.cleaned_data['appname'],
                                appform.cleaned_data['upgradever'])
                    except opus.lib.builder.BuildException, e:
                        failures.append((appform.cleaned_data['appname'], 'upgrade', e))
                    else:
                        upgradecount += 1
            if upgradecount > 0 or deletecount > 0:
                editor.restart_celery(settings.OPUS_SECUREOPS_COMMAND)

            message = "{upcnt} {upproj} upgraded successfully. {delcnt} {delproj} deleted successfully.".format(
                    upcnt = upgradecount,
                    upproj = "projects" if upgradecount != 1 else "project",
                    delcnt = deletecount,
                    delproj = "projects" if deletecount != 1 else "project",
                    )

            # Render a new formset, to get the upgraded info and to not render
            # any recently deleted projects
            form = forms.EditAppFormSet(initial=_get_apps(project))
            return render("deployment/appedit.html", dict(
                form=form,
                project=project,
                message=message,
                failures=failures,
                ), request)
    else:
        form = forms.EditAppFormSet(initial=_get_apps(project))
    return render("deployment/appedit.html", dict(
        form=form,
        project=project,
        ), request)

def gwt(request):
    """GWT view. Login is not required, the GWT interface handles that itself.

    """
    if 'token' in request.GET:
        token = request.GET['token']
    else:
        token = None

    if request.is_secure():
        deployerurl = "https://" + request.get_host()
    else:
        deployerurl = "http://" + request.get_host()

    return render("OPUSManagementConsoleGWT.html",
            dict(mediaprefix = settings.OPUS_GWT_MEDIA,
                baseurl = settings.OPUS_APACHE_SERVERNAME_SUFFIX,
                repourl = opus.REPO_URL,
                communityurl = opus.COMMUNITY_URL,
                deployerurl = deployerurl,
                project_token = token
                ),
            request)


text:
<?php

namespace Antares\UI\UIComponents\Templates;

use Antares\UI\UIComponents\Adapter\AbstractTemplate;

class Ajax extends AbstractTemplate
{

    /**
     * Name of template used by ui component
     *
     * @var String
     */
    protected $template = 'ajax';

    /**
     * Constructing
     */
    public function __construct()
    {
        parent::__construct();
        $url = array_get($this->attributes, 'remote');
        if (!is_null($url)) {
            $handles = handles($url);
            $script  = $this->load($handles, $this->id);
            if (app('request')->ajax()) {
                echo '';
            } else {
                $this->attributes['script'] = $script;
                app('antares.asset')->container('antares/foundation::scripts')->inlineScript('ajax_widget_' . str_random(3), $script);
            }
        }
    }

    /**
     * Renders widget content
     */
    public function render()
    {

    }

    /**
     * default process results
     *
     * @return String
     */
    protected function load($url, $id)
    {
        return <<< JS
                $(document).ready(function(){
                var widgetContainer=$('.grid-stack-item[id=$id]').find('.widget-content');
                var parentWidgetContainer=widgetContainer.parent();
                if($('.jquery-modal.current').length>0){
                    widgetContainer=$('.jquery-modal').find('.widget-content');
                    parentWidgetContainer=widgetContainer.closest('.card--enlarged');
                }
                //parentWidgetContainer.LoadingOverlay('show');
                $.ajax({
                   url:"$url",
                   type: "GET",
                   success:function(response){
                        widgetContainer.html(response);
                   },
                   error:function(response){
                        widgetContainer.html('
Unable to load widget content:
'+response.statusText+'
');
                   },
                   complete:function(){
                        //parentWidgetContainer.LoadingOverlay('hide');
                   }
                });
                });
JS;
    }

}


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

Contents:

.. toctree::
   :maxdepth: 2

   installation
   quickstart
   tutorial/index
   patterns
   development
   reference


text:
import random
from parlai.core.opt import Opt
from parlai.core.message import Message
from parlai.core.mutators import register_mutator, MessageMutator

@register_mutator("word_reverse")
class WordReverseMutator(MessageMutator):
    """
    Reverses the words of each turn.

    Only the text (prompt) is modified, not the labels. Utterances separated by newlines
    will not be shuffled across boundaries. You may wish to combine it with the flatten
    mutator to reverse both labels and texts.
    """

    def __init__(self, opt: Opt):
        super().__init__(opt)
        self.rng = random.Random(42)

    def message_mutation(self, message: Message) -> Message:
        texts = message.pop('text').split('\n')
        output_texts = []
        for text in texts:
            words = text.split(' ')
            words = list(reversed(words))
            output_texts.append(' '.join(words))
        message['text'] = '\n'.join(output_texts)
        return message


text:
using namespace std;
using namespace Util;
using namespace SteerLib;

int main(int argc, char** argv)
{
	try {

		std::string unitTestName = "";
		std::string validationFileName = "";
		std::string infoFileName = "";
		std::string testCaseSearchPath = "";

		std::string endianFileNames[2];
		endianFileNames[0] = "";
		endianFileNames[1] = "";

		CommandLineParser opts;
		opts.addOption("-test",     &unitTestName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-unit",     &unitTestName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-unittest", &unitTestName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-unitTest", &unitTestName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-validate", &validationFileName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-verify",   &validationFileName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-info", &infoFileName, OPTION_DATA_TYPE_STRING);
		opts.addOption("-swapendian", endianFileNames, OPTION_DATA_TYPE_STRING, 2);
		opts.addOption("-swapEndian", endianFileNames, OPTION_DATA_TYPE_STRING, 2);
		opts.addOption("-testcasepath", &testCaseSearchPath, OPTION_DATA_TYPE_STRING);
		opts.addOption("-testCasePath", &testCaseSearchPath, OPTION_DATA_TYPE_STRING);

		opts.parse(argc, argv, true, true);

		if (unitTestName != "") {
			runUnitTest(unitTestName);
		}
		else if (validationFileName != "") {
			throw GenericException("Validating rec files is not implemented yet.");
		}
		else if (infoFileName != "") {
			if (SteerLib::RecFileReader::isAValidRecFile(infoFileName)) {
				SteerLib::RecFileReader recFile;
				recFile.open(infoFileName);
				std::cout << "           filename: " << basename(infoFileName,"") << "\n";
				std::cout << "            version: " << recFile.getVersion() << "\n";
				std::cout << " Test case recorded: " << recFile.getTestCaseName() << "\n";
				std::cout << "    Simulation time: " << recFile.getTotalElapsedTime() << "\n";
				std::cout << "   Number of frames: " << recFile.getNumFrames() << "\n";
				std::cout << "   Number of agents: " << recFile.getNumAgents() << "\n";
				std::cout << "Number of obstacles: " << recFile.getNumObstacles() << "\n";
			}
			else if (endsWith(infoFileName, ".xml")) {
				SteerLib::TestCaseReader testCase;
				testCase.readTestCaseFromFile(infoFileName);
				std::cout << "           filename: " << basename(infoFileName,"") << "\n";
				std::cout << "            version: " << testCase.getVersion() << "\n";
				std::cout << "     Test case name: " << testCase.getTestCaseName() << "\n";
				std::cout << "        Description: " << testCase.getDescription() << "\n";
				std::cout << "   Number of agents: " << testCase.getNumAgents() << "\n";
				std::cout << "Number of obstacles: " << testCase.getNumObstacles() << "\n";
				std::cout << "      X-axis bounds: " << testCase.getWorldBounds().xmin << " to " << testCase.getWorldBounds().xmax << "\n";
				std::cout << "      Y-axis bounds: " << testCase.getWorldBounds().ymin << " to " << testCase.getWorldBounds().ymax << "\n";
				std::cout << "      Z-axis bounds: " << testCase.getWorldBounds().zmin << " to " << testCase.getWorldBounds().zmax << "\n";
			}
			else {
				throw GenericException("Specified file does not seem to be a valid rec file or test case.");
			}

		}
		else if (endianFileNames[0] != "") {
			throw GenericException("Swapping endian-ness is not implemented yet.");
		}
		else {
			throw GenericException(std::string("Please specify an action for SteerTool.\nPossible actions include:\n")
				+ std::string("    -test <testName> - performs a hard-coded unit test\n")
				+ std::string("    -validate <filename> - validates a recording against the corresponding XML test case\n")
				+ std::string("    -info <filename> - outputs human-readable information of the recording or XML test case\n")
				+ std::string("    -swapendian <inputFilename> <outputFilename> - changes the endian-ness of a rec file\n"));
		}

	}
	catch (std::exception &e) {
		std::cerr << "\nERROR: exception caught in main:\n" << e.what() << "\n";
		exit(1);
	}

	return EXIT_SUCCESS;
}


text:
require 'spec_helper'

describe Grape::Validations::ExactlyOneOfValidator do
  describe '#validate!' do
    let(:scope) do
      Struct.new(:opts) do
        def params(arg); end
      end
    end
    let(:exactly_one_of_params) { [:beer, :wine, :grapefruit] }
    let(:validator) { described_class.new(exactly_one_of_params, {}, false, scope.new) }

    context 'when all restricted params are present' do
      let(:params) { { beer: true, wine: true, grapefruit: true } }

      it 'raises a validation exception' do
        expect {
          validator.validate! params
        }.to raise_error(Grape::Exceptions::Validation)
      end

      context 'mixed with other params' do
        let(:mixed_params) { params.merge!(other: true, andanother: true) }

        it 'still raises a validation exception' do
          expect {
            validator.validate! mixed_params
          }.to raise_error(Grape::Exceptions::Validation)
        end
      end
    end

    context 'when a subset of restricted params are present' do
      let(:params) { { beer: true, grapefruit: true } }

      it 'raises a validation exception' do
        expect {
          validator.validate! params
        }.to raise_error(Grape::Exceptions::Validation)
      end
    end

    context 'when params keys come as strings' do
      let(:params) { { 'beer' => true, 'grapefruit' => true } }

      it 'raises a validation exception' do
        expect {
          validator.validate! params
        }.to raise_error(Grape::Exceptions::Validation)
      end
    end

    context 'when none of the restricted params is selected' do
      let(:params) { { somethingelse: true } }

      it 'raises a validation exception' do
        expect {
          validator.validate! params
        }.to raise_error(Grape::Exceptions::Validation)
      end
    end

    context 'when exactly one of the restricted params is selected' do
      let(:params) { { beer: true, somethingelse: true } }

      it 'params' do
        expect(validator.validate!(params)).to eql params
      end
    end
  end
end


text:
import run from './run'

/*
 * Determine whether we have a wifi connection with the `wpa_cli
 * status` command. This function returns a Promise that resolves to a
 * string.  On my Rasberry Pi, the string is 'DISCONNECTED' or
 * 'INACTIVE' when there is no connection and is 'COMPLETED' when
 * there is a connection. There are other possible string values when
 * a connection is being established
 */
export const getStatus = () => run("sudo wpa_cli -iwlan0 status | sed -n -e '/^wpa_state=/{s/wpa_state=//;p;q}'")

/*
 * Determine the ssid of the wifi network we are connected to.
 * This function returns a Promise that resolves to a string.
 * The string will be empty if not connected.
 */
export const getConnectedNetwork = () => run("sudo wpa_cli -iwlan0 status | sed -n -e '/^ssid=/{s/ssid=//;p;q}'")

/*
 * Scan for available wifi networks using `iwlist wlan0 scan`.
 * Returns a Promise that resolves to an array of strings. Each string
 * is the ssid of a wifi network. They are sorted by signal strength from
 * strongest to weakest. On a Raspberry Pi, a scan seems to require root
 * privileges.
 *
 * On a Raspberry Pi 3, this function works when the device is in AP mode.
 * The Intel Edison, however, cannot scan while in AP mode: iwlist fails
 * with an error. iwlist sometimes also fails with an error when the
 * hardware is busy, so this function will try multiple times if you
 * pass a number. If all attempts fail, the promise is resolved to
 * an empty array.
 */
const scanCommand = `iwlist wlan0 scan |\
sed -n -e '
export const /Quality=/,/ESSID =/H
export const /ESSID =/{
  g
export const   s/^.*Quality=\\([0-9]\\+\\).*ESSID ="\\([^"]*\\)".*$/\\1\t\\2/
  p
  s/.*//
  x
}' |\
sort -nr |\
cut -f 2 |\
sed -e '/^$/d;/\\x00/d'`

export const scan = (numAttempts=1) =>
  new Promise(resolve => {
    let attempts = 0

    const tryScan = () => {
      attempts++

      run(scanCommand)
      .then(out => resolve(out.length ? out.split('\n') : []))
      .catch(err => {
        console.error('Scan attempt', attempts, 'failed:', err.message || err)

        if(attempts >= numAttempts){
          console.error('Giving up. No scan results available.')
          resolve([])
          return
        }

        console.error('Will try again in 3 seconds.')
        setTimeout(tryScan, 3000)
      })
    }

    tryScan()
  })

/*
 * Enable an access point that users can connect to to configure the device.
 *
 * This command runs different commands on Raspbery Pi Rasbian and Edison Yocto.
 *
 * It requires that hostapd and udhcpd are installed on the system but not
 * enabled, so that they do not automatically run when the device boots up.
 * It also requires that hostapd and udhcpd have appropriate config files
 * that define the ssid for the wifi network to be created, for example.
 * Also, the udhcpd config file should be set up to work with 10.0.0.1 as
 * the IP address of the device.
 *
 * XXX
 * It would probably be better if the IP address, SSID and password were
 * options to this function rather than being hardcoded in system config
 * files. (Each device ought to be able to add a random number to its
 * SSID, for example, so that when you've got multiple devices they don't
 * all try to create the same network).
 *
 * This function returns a Promise that resolves when the necessary
 * commands have been run.  This does not necessarily mean that the AP
 * will be functional, however. The setup process might take a few
 * seconds to complete before the user will be able to see and connect
 * to the network.
 */
export const startAP = () => run('sudo ifconfig wlan0 down; sudo wpa_cli terminate; sudo ifconfig wlan0 10.0.0.1; sudo systemctl start hostapd; sudo systemctl start udhcpd')

/*
 * Like startAP(), but take the access point down, using platform-dependent
 * commands.
 *
 * Returns a promise that resolves when the commands have been run. At
 * this point, the AP should be in the process of stopping but may not
 * yet be completely down.
 */
export const stopAP = () => run('sudo ifconfig wlan0 down; sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf; sudo systemctl stop udhcpd; sudo systemctl stop hostapd; sudo ifconfig wlan0 0.0.0.0; sudo wpa_cli reconfigure')

/*
 * This function uses wpa_cli to add the specified network ssid and password
 * to the wpa_supplicant.conf file. This assumes that wpa_supplicant is
 * configured to run automatically at boot time and is configured to work
 * with wpa_cli.
 *
 * If the system is not connected to a wifi network, calling this
 * command with a valid ssid and password should cause it to connect.
 */
const closed = 'ID=`sudo wpa_cli -iwlan0 add_network` && sudo wpa_cli -iwlan0 set_network $ID ssid \\"$SSID\\" && sudo wpa_cli -iwlan0 set_network $ID psk \\"$PSK\\" && sudo wpa_cli -iwlan0 enable_network $ID && sudo wpa_cli -iwlan0 save_config'
const open = 'ID=`sudo wpa_cli -iwlan0 add_network` && sudo wpa_cli -iwlan0 set_network $ID ssid \\"$SSID\\" && sudo wpa_cli -iwlan0 set_network $ID key_mgmt NONE && sudo wpa_cli -iwlan0 enable_network $ID && sudo wpa_cli -iwlan0 save_config'

export const defineNetwork = (ssid, password) =>
  run(password ? closed : open, {
    SSID: ssid,
    PSK: password
  })

/*
 * Return a Promise that resolves to an array of known wifi network names
 */
export const getKnownNetworks = () =>
  run("wpa_cli -iwlan0 list_networks | sed -e '1d' | cut -f 2")
  .then(out => (out.length ? out.split('\n') : []))

export const waitForWifi = async (attemptsLeft, interval) => {
  console.log('Attempts Left', attemptsLeft)
  if(!attemptsLeft) return false

  const retry = () => new Promise(resolve => setTimeout(() => resolve(waitForWifi(attemptsLeft - 1, interval)), interval))
  const status = await getStatus().catch(() => 'ERROR')

  console.log(status)
  if(status === 'COMPLETED'){
    console.log('Wifi connection found')
    return true
  }

  if(status === 'ERROR'){
    console.log('Attempt Error, retrying')
    return retry()
  }

  console.log('No wifi connection on attempt')
  return retry()
}