text:
using System.Buffers;
using System.Text;
using Xunit;

namespace System.Buffers.Text.Tests
{
    public class Base64EncoderUnitTests
    {
        [Fact]
        public void BasicEncodingAndDecoding()
        {
            var bytes = new byte[byte.MaxValue + 1];
            for (int i = 0; i < byte.MaxValue + 1; i++)
            {
                bytes[i] = (byte)i;
            }

            for (int value = 0; value < 256; value++)
            {
                Span<byte> sourceBytes = bytes.AsSpan().Slice(0, value + 1);
                Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(sourceBytes.Length)];
                Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(sourceBytes, encodedBytes, out int consumed, out int encodedBytesCount));
                Assert.Equal(sourceBytes.Length, consumed);
                Assert.Equal(encodedBytes.Length, encodedBytesCount);

                string encodedText = Encoding.ASCII.GetString(encodedBytes.ToArray());
                string expectedText = Convert.ToBase64String(bytes, 0, value + 1);
                Assert.Equal(expectedText, encodedText);

                if (encodedBytes.Length % 4 == 0)
                {
                    Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(encodedBytes.Length)];
                    Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8(encodedBytes, decodedBytes, out consumed, out int decodedByteCount));
                    Assert.Equal(encodedBytes.Length, consumed);
                    Assert.Equal(sourceBytes.Length, decodedByteCount);
                    Assert.True(sourceBytes.SequenceEqual(decodedBytes.Slice(0, decodedByteCount)));
                }
            }
        }

        [Fact]
        public void BasicEncoding()
        {
            var rnd = new Random(42);
            for (int i = 0; i < 10; i++)
            {
                int numBytes = rnd.Next(100, 1000 * 1000);
                Span<byte> source = new byte[numBytes];
                Base64TestHelper.InitalizeBytes(source, numBytes);

                Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
                Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount));
                Assert.Equal(source.Length, consumed);
                Assert.Equal(encodedBytes.Length, encodedBytesCount);
                Assert.True(Base64TestHelper.VerifyEncodingCorrectness(source.Length, encodedBytes.Length, source, encodedBytes));
            }
        }

        [Fact]
        public void EncodeEmptySpan()
        {
            Span<byte> source = Span<byte>.Empty;
            Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];

            Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount));
            Assert.Equal(source.Length, consumed);
            Assert.Equal(encodedBytes.Length, encodedBytesCount);
            Assert.True(Base64TestHelper.VerifyEncodingCorrectness(source.Length, encodedBytes.Length, source, encodedBytes));
        }

        [Fact]
        [OuterLoop]
        public void EncodeTooLargeSpan()
        {
            // int.MaxValue - (int.MaxValue % 4) => 2147483644, largest multiple of 4 less than int.MaxValue
            // CLR default limit of 2 gigabytes (GB).
            try
            {
                 // 1610612734, larger than MaximumEncodeLength, requires output buffer of size 2147483648 (which is > int.MaxValue)
                Span<byte> source = new byte[(int.MaxValue >> 2) * 3 + 1];
                Span<byte> encodedBytes = new byte[2000000000];
                Assert.Equal(OperationStatus.DestinationTooSmall, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount));
                Assert.Equal((encodedBytes.Length >> 2) * 3, consumed); // encoding 1500000000 bytes fits into buffer of 2000000000 bytes
                Assert.Equal(encodedBytes.Length, encodedBytesCount);
            }
            catch (OutOfMemoryException)
            {
                // do nothing
            }
        }

        [Fact]
        public void BasicEncodingWithFinalBlockFalse()
        {
            var rnd = new Random(42);
            for (int i = 0; i < 10; i++)
            {
                int numBytes = rnd.Next(100, 1000 * 1000);
                Span<byte> source = new byte[numBytes];
                Base64TestHelper.InitalizeBytes(source, numBytes);
                Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];
                int expectedConsumed = source.Length / 3 * 3; // only consume closest multiple of three since isFinalBlock is false
                int expectedWritten = source.Length / 3 * 4;

                Assert.Equal(OperationStatus.NeedMoreData, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount, isFinalBlock: false));
                Assert.Equal(expectedConsumed, consumed);
                Assert.Equal(expectedWritten, encodedBytesCount);
                Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, expectedWritten, source, encodedBytes));
            }
        }

        [Theory]
        [InlineData(1, "", 0, 0)]
        [InlineData(2, "", 0, 0)]
        [InlineData(3, "AQID", 3, 4)]
        [InlineData(4, "AQID", 3, 4)]
        [InlineData(5, "AQID", 3, 4)]
        [InlineData(6, "AQIDBAUG", 6, 8)]
        [InlineData(7, "AQIDBAUG", 6, 8)]
        public void BasicEncodingWithFinalBlockFalseKnownInput(int numBytes, string expectedText, int expectedConsumed, int expectedWritten)
        {
            Span<byte> source = new byte[numBytes];
            for (int i = 0; i < numBytes; i++)
            {
                source[i] = (byte)(i + 1);
            }
            Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];

            Assert.Equal(OperationStatus.NeedMoreData, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount, isFinalBlock: false));
            Assert.Equal(expectedConsumed, consumed);
            Assert.Equal(expectedWritten, encodedBytesCount);

            string encodedText = Encoding.ASCII.GetString(encodedBytes.Slice(0, expectedWritten).ToArray());
            Assert.Equal(expectedText, encodedText);
        }

        [Theory]
        [InlineData(1, "AQ==", 1, 4)]
        [InlineData(2, "AQI=", 2, 4)]
        [InlineData(3, "AQID", 3, 4)]
        [InlineData(4, "AQIDBA==", 4, 8)]
        [InlineData(5, "AQIDBAU=", 5, 8)]
        [InlineData(6, "AQIDBAUG", 6, 8)]
        [InlineData(7, "AQIDBAUGBw==", 7, 12)]
        public void BasicEncodingWithFinalBlockTrueKnownInput(int numBytes, string expectedText, int expectedConsumed, int expectedWritten)
        {
            Span<byte> source = new byte[numBytes];
            for (int i = 0; i < numBytes; i++)
            {
                source[i] = (byte)(i + 1);
            }
            Span<byte> encodedBytes = new byte[Base64.GetMaxEncodedToUtf8Length(source.Length)];

            Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount, isFinalBlock: true));
            Assert.Equal(expectedConsumed, consumed);
            Assert.Equal(expectedWritten, encodedBytesCount);

            string encodedText = Encoding.ASCII.GetString(encodedBytes.Slice(0, expectedWritten).ToArray());
            Assert.Equal(expectedText, encodedText);
        }

        [Fact]
        public void EncodingOutputTooSmall()
        {
            for (int numBytes = 4; numBytes < 20; numBytes++)
            {
                Span<byte> source = new byte[numBytes];
                Base64TestHelper.InitalizeBytes(source, numBytes);

                Span<byte> encodedBytes = new byte[4];
                Assert.Equal(OperationStatus.DestinationTooSmall,
                    Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int written));
                int expectedConsumed = 3;
                Assert.Equal(expectedConsumed, consumed);
                Assert.Equal(encodedBytes.Length, written);
                Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, encodedBytes.Length, source, encodedBytes));
            }
        }

        [Fact]
        public void EncodingOutputTooSmallRetry()
        {
            Span<byte> source = new byte[750];
            Base64TestHelper.InitalizeBytes(source);

            int outputSize = 320;
            int requiredSize = Base64.GetMaxEncodedToUtf8Length(source.Length);

            Span<byte> encodedBytes = new byte[outputSize];
            Assert.Equal(OperationStatus.DestinationTooSmall,
                Base64.EncodeToUtf8(source, encodedBytes, out int consumed, out int written));
            int expectedConsumed = encodedBytes.Length / 4 * 3;
            Assert.Equal(expectedConsumed, consumed);
            Assert.Equal(encodedBytes.Length, written);
            Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, encodedBytes.Length, source, encodedBytes));

            encodedBytes = new byte[requiredSize - outputSize];
            source = source.Slice(consumed);
            Assert.Equal(OperationStatus.Done,
                Base64.EncodeToUtf8(source, encodedBytes, out consumed, out written));
            expectedConsumed = encodedBytes.Length / 4 * 3;
            Assert.Equal(expectedConsumed, consumed);
            Assert.Equal(encodedBytes.Length, written);
            Assert.True(Base64TestHelper.VerifyEncodingCorrectness(expectedConsumed, encodedBytes.Length, source, encodedBytes));
        }

        [Fact]
        public void GetMaxEncodedLength()
        {
            // (int.MaxValue - 4)/(4/3) => 1610612733, otherwise integer overflow
            int[] input = { 0, 1, 2, 3, 4, 5, 6, 1610612728, 1610612729, 1610612730, 1610612731, 1610612732, 1610612733 };
            int[] expected = { 0, 4, 4, 4, 8, 8, 8, 2147483640, 2147483640, 2147483640, 2147483644, 2147483644, 2147483644 };
            for (int i = 0; i < input.Length; i++)
            {
                Assert.Equal(expected[i], Base64.GetMaxEncodedToUtf8Length(input[i]));
            }

            // integer overflow
            Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(1610612734));
            Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(int.MaxValue));

            // negative input
            Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(-1));
            Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxEncodedToUtf8Length(int.MinValue));
        }

        [Fact]
        public void EncodeInPlace()
        {
            const int numberOfBytes = 15;
            Span<byte> testBytes = new byte[numberOfBytes / 3 * 4]; // slack since encoding inflates the data
            Base64TestHelper.InitalizeBytes(testBytes);

            for (int numberOfBytesToTest = 0; numberOfBytesToTest <= numberOfBytes; numberOfBytesToTest++)
            {
                var expectedText = Convert.ToBase64String(testBytes.Slice(0, numberOfBytesToTest).ToArray());

                Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8InPlace(testBytes, numberOfBytesToTest, out int bytesWritten));
                Assert.Equal(Base64.GetMaxEncodedToUtf8Length(numberOfBytesToTest), bytesWritten);

                var encodedText = Encoding.ASCII.GetString(testBytes.Slice(0, bytesWritten).ToArray());
                Assert.Equal(expectedText, encodedText);
            }
        }

        [Fact]
        public void EncodeInPlaceOutputTooSmall()
        {
            byte[] testBytes = {1, 2, 3};

            for (int numberOfBytesToTest = 1; numberOfBytesToTest <= testBytes.Length; numberOfBytesToTest++)
            {
                Assert.Equal(OperationStatus.DestinationTooSmall, Base64.EncodeToUtf8InPlace(testBytes, numberOfBytesToTest, out int bytesWritten));
                Assert.Equal(0, bytesWritten);
            }
        }

        [Fact]
        public void EncodeInPlaceDataLengthTooLarge()
        {
            byte[] testBytes = {1, 2, 3};
            Assert.Equal(OperationStatus.DestinationTooSmall, Base64.EncodeToUtf8InPlace(testBytes, testBytes.Length + 1, out int bytesWritten));
            Assert.Equal(0, bytesWritten);
        }
    }
}


text:
package network

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// HubVirtualNetworkConnectionsClient is the network Client
type HubVirtualNetworkConnectionsClient struct {
	BaseClient
}

// NewHubVirtualNetworkConnectionsClient creates an instance of the HubVirtualNetworkConnectionsClient client.
func NewHubVirtualNetworkConnectionsClient(subscriptionID string) HubVirtualNetworkConnectionsClient {
	return NewHubVirtualNetworkConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewHubVirtualNetworkConnectionsClientWithBaseURI creates an instance of the HubVirtualNetworkConnectionsClient
// client using a custom endpoint.  Use this when interacting with an Azure cloud that uses a non-standard base URI
// (sovereign clouds, Azure stack).
func NewHubVirtualNetworkConnectionsClientWithBaseURI(baseURI string, subscriptionID string) HubVirtualNetworkConnectionsClient {
	return HubVirtualNetworkConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// CreateOrUpdate creates a hub virtual network connection if it doesn't exist else updates the existing one.
// Parameters:
// resourceGroupName - the resource group name of the HubVirtualNetworkConnection.
// virtualHubName - the name of the VirtualHub.
// connectionName - the name of the HubVirtualNetworkConnection.
// hubVirtualNetworkConnectionParameters - parameters supplied to create or update a hub virtual network
// connection.
func (client HubVirtualNetworkConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection) (result HubVirtualNetworkConnectionsCreateOrUpdateFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.CreateOrUpdate")
		defer func() {
			sc := -1
			if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
				sc = result.FutureAPI.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, connectionName, hubVirtualNetworkConnectionParameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	result, err = client.CreateOrUpdateSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
		return
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client HubVirtualNetworkConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"connectionName":    autorest.Encode("path", connectionName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"virtualHubName":    autorest.Encode("path", virtualHubName),
	}

	const APIVersion = "2020-11-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	hubVirtualNetworkConnectionParameters.Etag = nil
	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters),
		autorest.WithJSON(hubVirtualNetworkConnectionParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client HubVirtualNetworkConnectionsClient) CreateOrUpdateSender(req *http.Request) (future HubVirtualNetworkConnectionsCreateOrUpdateFuture, err error) {
	var resp *http.Response
	future.FutureAPI = &azure.Future{}
	resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = future.result
	return
}

// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client HubVirtualNetworkConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result HubVirtualNetworkConnection, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Delete deletes a HubVirtualNetworkConnection.
// Parameters:
// resourceGroupName - the resource group name of the VirtualHub.
// virtualHubName - the name of the VirtualHub.
// connectionName - the name of the HubVirtualNetworkConnection.
func (client HubVirtualNetworkConnectionsClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result HubVirtualNetworkConnectionsDeleteFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.Delete")
		defer func() {
			sc := -1
			if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
				sc = result.FutureAPI.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, connectionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Delete", nil, "Failure preparing request")
		return
	}

	result, err = client.DeleteSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Delete", result.Response(), "Failure sending request")
		return
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client HubVirtualNetworkConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"connectionName":    autorest.Encode("path", connectionName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"virtualHubName":    autorest.Encode("path", virtualHubName),
	}

	const APIVersion = "2020-11-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client HubVirtualNetworkConnectionsClient) DeleteSender(req *http.Request) (future HubVirtualNetworkConnectionsDeleteFuture, err error) {
	var resp *http.Response
	future.FutureAPI = &azure.Future{}
	resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = future.result
	return
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client HubVirtualNetworkConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get retrieves the details of a HubVirtualNetworkConnection.
// Parameters:
// resourceGroupName - the resource group name of the VirtualHub.
// virtualHubName - the name of the VirtualHub.
// connectionName - the name of the vpn connection.
func (client HubVirtualNetworkConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result HubVirtualNetworkConnection, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, connectionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure responding to request")
		return
	}

	return
}

// GetPreparer prepares the Get request.
func (client HubVirtualNetworkConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"connectionName":    autorest.Encode("path", connectionName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"virtualHubName":    autorest.Encode("path", virtualHubName),
	}

	const APIVersion = "2020-11-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client HubVirtualNetworkConnectionsClient) GetSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client HubVirtualNetworkConnectionsClient) GetResponder(resp *http.Response) (result HubVirtualNetworkConnection, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// List retrieves the details of all HubVirtualNetworkConnections.
// Parameters:
// resourceGroupName - the resource group name of the VirtualHub.
// virtualHubName - the name of the VirtualHub.
func (client HubVirtualNetworkConnectionsClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List")
		defer func() {
			sc := -1
			if result.lhvncr.Response.Response != nil {
				sc = result.lhvncr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listNextResults
	req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListSender(req)
	if err != nil {
		result.lhvncr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure sending request")
		return
	}

	result.lhvncr, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure responding to request")
		return
	}
	if result.lhvncr.hasNextLink() && result.lhvncr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListPreparer prepares the List request.
func (client HubVirtualNetworkConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"virtualHubName":    autorest.Encode("path", virtualHubName),
	}

	const APIVersion = "2020-11-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client HubVirtualNetworkConnectionsClient) ListSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client HubVirtualNetworkConnectionsClient) ListResponder(resp *http.Response) (result ListHubVirtualNetworkConnectionsResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listNextResults retrieves the next set of results, if any.
func (client HubVirtualNetworkConnectionsClient) listNextResults(ctx context.Context, lastResults ListHubVirtualNetworkConnectionsResult) (result ListHubVirtualNetworkConnectionsResult, err error) {
	req, err := lastResults.listHubVirtualNetworkConnectionsResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client HubVirtualNetworkConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.List(ctx, resourceGroupName, virtualHubName)
	return
}

redpajama_set_name: RedPajamaGithub


text:
namespace m7 {

template <typename Alloc> class AllocatorDeleter;

} //namespace m7


text:
require 'rack'
require 'rack/request'
require 'rack/response'
require 'rack/server'
require 'rack/lint'

require 'rack_fake_s3/file_store'
require 'rack_fake_s3/xml_adapter'
require 'rack_fake_s3/bucket_query'
require 'rack_fake_s3/errors'

module RackFakeS3
  require 'webrick'
  class Request
    CREATE_BUCKET = "CREATE_BUCKET"
    LIST_BUCKETS = "LIST_BUCKETS"
    LS_BUCKET = "LS_BUCKET"
    HEAD = "HEAD"
    STORE = "STORE"
    OPTIONS = "OPTIONS"
    COPY = "COPY"
    GET = "GET"
    GET_ACL = "GET_ACL"
    SET_ACL = "SET_ACL"
    MOVE = "MOVE"
    DELETE_OBJECT = "DELETE_OBJECT"
    DELETE_BUCKET = "DELETE_BUCKET"

    attr_accessor :bucket,:object,:type,:src_bucket,
                  :src_object,:method,:rack_request,
                  :path,:is_path_style,:query,:http_verb

    def inspect
      puts "-----Inspect RackFakeS3 Request"
      puts "Type: #{@type}"
      puts "Is Path Style: #{@is_path_style}"
      puts "Request Method: #{@method}"
      puts "Bucket: #{@bucket}"
      puts "Object: #{@object}"
      puts "Src Bucket: #{@src_bucket}"
      puts "Src Object: #{@src_object}"
      puts "Query: #{@query}"
      puts "-----Done"
    end
  end

  class Servlet
    def initialize(app,store,hostname)
      raise "store can't be nil" if store.nil?
      raise "hostname can't be nil" if hostname.nil?

      @app = app
      @store = store
      @hostname = hostname
      @root_hostnames = [hostname,'localhost','s3.amazonaws.com','s3.localhost']
    end

    def call(env)
      request = Rack::Request.new(env)
      s_req = normalize_request(request)

      if s_req
        dup.perform(env, s_req)
      elsif @app
        @app.call(env)
      else
        halt 404
      end
    end

    def perform(env, s_req)
      response = Rack::Response.new

      send(:"do_#{s_req.http_verb}", s_req, response)

      response.finish
    end

    def do_GET(s_req, response)
      request = s_req.rack_request

      case s_req.type
      when 'LIST_BUCKETS'
        response.status = 200
        response['Content-Type'] = 'application/xml'
        buckets = @store.buckets
        response.write XmlAdapter.buckets(buckets)
      when 'LS_BUCKET'
        bucket_obj = @store.get_bucket(s_req.bucket)
        if bucket_obj
          response.status = 200
          response['Content-Type'] = "application/xml"
          query = {
            :marker => s_req.query["marker"] ? s_req.query["marker"].to_s : nil,
            :prefix => s_req.query["prefix"] ? s_req.query["prefix"].to_s : nil,
            :max_keys => s_req.query["max-keys"] ? s_req.query["max-keys"].to_i : nil,
            :delimiter => s_req.query["delimiter"] ? s_req.query["delimiter"].to_s : nil
          }

          bq = bucket_obj.query_for_range(query)
          response.write XmlAdapter.bucket_query(bq)
        else
          response.status = 404
          response.write XmlAdapter.error_no_such_bucket(s_req.bucket)
          response['Content-Type'] = "application/xml"
        end
      when 'GET_ACL'
        response.status = 200
        response.write XmlAdapter.acl()
        response['Content-Type'] = 'application/xml'
      when 'GET'
        real_obj = @store.get_object(s_req.bucket,s_req.object,request)
        if !real_obj
          response.status = 404
          response.write ""
          return
        end

        response.status = 200
        response['Content-Type'] = real_obj.content_type
        content_length = File::Stat.new(real_obj.io.path).size
        response['Etag'] = real_obj.md5
        response['Accept-Ranges'] = "bytes"

        # Added Range Query support
        if range = request.env["HTTP_RANGE"]
          response.status = 206
          if range =~ /bytes=(\d*)-(\d*)/
            start = $1.to_i
            finish = $2.to_i
            finish_str = ""
            if finish == 0
              finish = content_length - 1
              finish_str = "#{finish}"
            else
              finish_str = finish.to_s
            end

            bytes_to_read = finish - start + 1
            response['Content-Range'] = "bytes #{start}-#{finish_str}/#{content_length}"
            real_obj.io.pos = start
            response.write real_obj.io.read(bytes_to_read)
            return
          end
        end
        response['Content-Length'] = File::Stat.new(real_obj.io.path).size.to_s
        if s_req.http_verb == 'HEAD'
          response.write ""
        else
          response.length = real_obj.io.size.to_s
          response.body = real_obj.io
        end
      end
    end
    alias :do_HEAD :do_GET

    def do_PUT(s_req,response)
      request = s_req.rack_request

      case s_req.type
      when Request::COPY
        @store.copy_object(s_req.src_bucket,s_req.src_object,s_req.bucket,s_req.object)
      when Request::STORE
        bucket_obj = @store.get_bucket(s_req.bucket)
        if !bucket_obj
          # Lazily create a bucket.  TODO fix this to return the proper error
          bucket_obj = @store.create_bucket(s_req.bucket)
        end

        real_obj = @store.store_object(bucket_obj,s_req.object,s_req.rack_request)

        response['Etag'] = real_obj.md5
      when Request::CREATE_BUCKET
        @store.create_bucket(s_req.bucket)
      end

      response.status = 200
      response.write ""
      response['Content-Type'] = "text/xml"
    end

    def do_POST(request,response)
       # check that we've received file data
       unless request.rack_request.content_type =~ /^multipart\/form-data; boundary=(.+)/
         raise 'bad request'
       end

       key=request.path
       success_action_redirect=request.rack_request.params['success_action_redirect']
       success_action_status=request.rack_request.params['success_action_status']

       filename = 'default'
       filename = $1 if request.rack_request.body =~ /filename="(.*)"/
       key=key.gsub('${filename}', filename)

       bucket_obj = @store.get_bucket(request.bucket) || @store.create_bucket(request.bucket)
       real_obj=@store.store_object(bucket_obj, key, request.rack_request)

       response['Etag'] = "\"#{real_obj.md5}\""
       response.body = []
       if success_action_redirect
         response.status = 307
         response['Location']=success_action_redirect
       else
         response.status = success_action_status || 204
         if response.status=="201"
           response.body << <<-eos.strip
             <?xml version="1.0" encoding="UTF-8"?>
             <PostResponse>
               <Location>#{request.rack_request.scheme}://#{request.rack_request.host_with_port}/#{key}</Location>
               <Bucket>#{request.bucket}</Bucket>
               <Key>#{key}</Key>
               <ETag>#{response['Etag']}</ETag>
             </PostResponse>
           eos
         end
       end
       response['Content-Type'] = 'text/xml'
       response['Access-Control-Allow-Origin']='*'
     end

    def do_DELETE(s_req,response)
      request = s_req.rack_request
      case s_req.type
      when Request::DELETE_OBJECT
        bucket_obj = @store.get_bucket(s_req.bucket)
        @store.delete_object(bucket_obj,s_req.object,s_req.rack_request)
      when Request::DELETE_BUCKET
        @store.delete_bucket(s_req.bucket)
      end

      response.status = 204
      response.write ""
    end

    def do_OPTIONS(request, response)
      response["Access-Control-Allow-Origin"]="*"
    end

    private

    def normalize_delete(rack_req,s_req)
      path = path_for_rack_request(rack_req)
      path_len = path.size
      query = rack_req.params
      if path == "/" and s_req.is_path_style
        # Probably do a 404 here
      else
        if s_req.is_path_style
          elems = path[1,path_len].split("/")
          s_req.bucket = elems[0]
        else
          elems = path.split("/")
        end

        if elems.size == 0
          raise UnsupportedOperation
        elsif elems.size == 1
          s_req.type = Request::DELETE_BUCKET
          s_req.query = query
        else
          s_req.type = Request::DELETE_OBJECT
          object = elems[1,elems.size].join('/')
          s_req.object = object
        end
      end
    end

    def normalize_get(rack_req,s_req)
      path = path_for_rack_request(rack_req)
      path_len = path.size
      query = rack_req.params
      if path == "/" and s_req.is_path_style
        s_req.type = Request::LIST_BUCKETS
      else
        if s_req.is_path_style
          elems = path[1,path_len].split("/")
          s_req.bucket = elems[0]
        else
          elems = path.split("/")
        end

        if elems.size == 0
          # List buckets
          s_req.type = Request::LIST_BUCKETS
        elsif elems.size == 1
          s_req.type = Request::LS_BUCKET
          s_req.query = query
        else
          if query.has_key?("acl")
            s_req.type = Request::GET_ACL
          else
            s_req.type = Request::GET
          end
          object = elems[1,elems.size].join('/')
          s_req.object = object
        end
      end
    end

    def normalize_put(rack_req,s_req)
      path = path_for_rack_request(rack_req)
      path_len = path.size
      if path == "/"
        if s_req.bucket
          s_req.type = Request::CREATE_BUCKET
        end
      else
        if s_req.is_path_style
          elems = path[1,path_len].split("/")
          s_req.bucket = elems[0]
          if elems.size == 1
            s_req.type = Request::CREATE_BUCKET
          else
            if rack_req.fullpath =~ /\?acl/
              s_req.type = Request::SET_ACL
            else
              s_req.type = Request::STORE
            end
            s_req.object = elems[1,elems.size].join('/')
          end
        else
          if rack_req.fullpath =~ /\?acl/
            s_req.type = Request::SET_ACL
          else
            s_req.type = Request::STORE
          end
          s_req.object = rack_req.path
        end
      end

      copy_source = rack_req.env["HTTP_X_AMZ_COPY_SOURCE"]
      if copy_source
        src_elems = copy_source.split("/")
        root_offset = src_elems[0] == "" ? 1 : 0
        s_req.src_bucket = src_elems[root_offset]
        s_req.src_object = src_elems[1 + root_offset,src_elems.size].join("/")
        s_req.type = Request::COPY
      end
    end

    def normalize_post(rack_req,s_req)
      path = path_for_rack_request(rack_req)
      path_len = path.size
      s_req.path = rack_req.params['key']
      s_req.type = Request::STORE

      s_req.rack_request = rack_req
    end

    def nomalize_options(rack_req, s_req)
      s_req.type = Request::OPTIONS
    end

    # This method takes a rack request and generates a normalized RackFakeS3 request
    def normalize_request(rack_req)
      host = rack_req.host

      s_req = Request.new
      s_req.path = path_for_rack_request(rack_req)
      s_req.is_path_style = true
      s_req.rack_request = rack_req

      if !@root_hostnames.include?(host)
        s_req.bucket = host.split(".")[0]
        s_req.is_path_style = false
      end

      s_req.http_verb = rack_req.request_method

      case rack_req.request_method
      when 'PUT'
        normalize_put(rack_req,s_req)
      when 'GET','HEAD'
        normalize_get(rack_req,s_req)
      when 'DELETE'
        normalize_delete(rack_req,s_req)
      when 'POST'
        normalize_post(rack_req,s_req)
      when 'OPTIONS'
        nomalize_options(rack_req,s_req)
      else
        return false
      end

      if s_req.type.nil?
        return false
      end

      return s_req
    end

    def dump_request(request)
      puts "----------Dump Request-------------"
      puts request.request_method
      puts request.path
      request.each do |k,v|
        puts "#{k}:#{v}"
      end
      puts "----------End Dump -------------"
    end

    # For Rails3 applications path given by the rack response is prefixed with
    # a slash. For rails4 this slash is removed, so we ensure that our path
    # always has a forward slash prefix here
    def path_for_rack_request(rack_request)
      if rack_request.path.start_with?('/')
        rack_request.path
      else
        "/#{rack_request.path}"
      end
    end
  end

  class App
    def initialize(path, hostname)
      @servlet = Servlet.new(nil, RackFakeS3::FileStore.new(path), hostname)
    end

    def call(env)
      @servlet.call(env)
    end

    def inspect
      self.class.inspect
    end
  end

  class Server
    def initialize(port,root,hostname)
      @port = port
      @root = root
      @hostname = hostname
    end

    def serve
      ENV['FAKE_S3_ROOT'] = @root
      ENV['FAKE_S3_HOSTNAME'] = @hostname

      @server = Rack::Server.new(:Port => @port, :config => config_ru)

      @server.start
    end

    def config_ru
      File.expand_path("../../../config.ru", __FILE__)
    end

    def shutdown
      @server.shutdown
    end
  end
end


text:
Sequel.migration do
  up do
    create_table(:suppliers) do
      String  :sid
      String  :name
      Integer :status
      String  :city
      primary_key [:sid]
      index :name, :unique => true
    end
    create_table(:parts) do
      String :pid
      String :name
      String :color
      Float  :weight
      String :city
      primary_key [:pid]
    end
    create_table(:supplies) do
      String :sid
      String :pid
      Integer :qty
      primary_key [:sid, :pid]
      foreign_key [:sid], :suppliers, :null=>false, :key=>[:sid], :deferrable=>true
      foreign_key [:pid], :parts,     :null=>false, :key=>[:pid], :deferrable=>true
    end
    create_table(:cities) do
      String :city
      String :country
      primary_key [:city]
    end
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.tomahim.json-utils</groupId>
	<artifactId>json-utils</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>json-utils</name>
	<url>http://maven.apache.org</url>

	 <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

	<dependencies>
		<dependency>
		    <groupId>javax.json</groupId>
		    <artifactId>javax.json-api</artifactId>
		    <version>1.0</version>
		</dependency>

		<!-- Needed for jUnit tests -->
       <dependency>
			<groupId>org.glassfish</groupId>
			<artifactId>javax.json</artifactId>
			<version>1.0.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>org.jacoco</groupId>
			<artifactId>jacoco-maven-plugin</artifactId>
			<version>0.7.3.201502191951</version>
		</dependency>
	</dependencies>
	<build>
    <plugins>
	  <plugin>
	        <groupId>org.codehaus.mojo</groupId>
	        <artifactId>sonar-maven-plugin</artifactId>
	        <version>2.3</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.18.1</version>
      </plugin>
	 <plugin>
		<groupId>org.jacoco</groupId>
		<artifactId>jacoco-maven-plugin</artifactId>
		<version>0.7.3.201502191951</version>
		<executions>
			<execution>
				<id>default-prepare-agent</id>
				<goals>
					<goal>prepare-agent</goal>
				</goals>
			</execution>
			<execution>
				<id>default-report</id>
				<phase>prepare-package</phase>
				<goals>
				<goal>report</goal>
				</goals>
			</execution>
				<execution>
					<id>default-check</id>
					<goals>
						<goal>check</goal>
					</goals>
					<configuration>
						<rules>
						<!--  implmentation is needed only for Maven 2  -->
							<rule implementation="org.jacoco.maven.RuleConfiguration">
								<element>BUNDLE</element>
								<limits>
								<!--  implmentation is needed only for Maven 2  -->
								<limit implementation="org.jacoco.report.check.Limit">
									<counter>COMPLEXITY</counter>
									<value>COVEREDRATIO</value>
									<minimum>0.60</minimum>
								</limit>
							</limits>
							</rule>
						</rules>
					</configuration>
				</execution>
			</executions>
		</plugin>
    </plugins>
  </build>
	<profiles>
	    <profile>
	    <id>everything</id>
	    <build>
	      <plugins>
	        <plugin>
	          <artifactId>maven-jar-plugin</artifactId>
	          <configuration>
	            <classifier>everything</classifier>
	            <includes>
	              <include>**/*</include>
	            </includes>
	          </configuration>
	        </plugin>
	      </plugins>
	    </build>
	  </profile>
  </profiles>
</project>


text: Create customized csv files easily


text:
package org.apache.beam.learning.katas.coretransforms.combine.combineperkey;

import org.apache.beam.learning.katas.util.Log;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.Combine.BinaryCombineFn;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;

public class Task {

  static final String PLAYER_1 = "Player 1";
  static final String PLAYER_2 = "Player 2";
  static final String PLAYER_3 = "Player 3";

  public static void main(String[] args) {
    PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
    Pipeline pipeline = Pipeline.create(options);

    PCollection<KV<String, Integer>> scores =
        pipeline.apply(
            Create.of(
                KV.of(PLAYER_1, 15), KV.of(PLAYER_2, 10), KV.of(PLAYER_1, 100),
                KV.of(PLAYER_3, 25), KV.of(PLAYER_2, 75)
            ));

    PCollection<KV<String, Integer>> output = applyTransform(scores);

    output.apply(Log.ofElements());

    pipeline.run();
  }

  static PCollection<KV<String, Integer>> applyTransform(PCollection<KV<String, Integer>> input) {
    return input.apply(Combine.perKey(new SumIntBinaryCombineFn()));
  }

  static class SumIntBinaryCombineFn extends BinaryCombineFn<Integer> {

    @Override
    public Integer apply(Integer left, Integer right) {
      return left + right;
    }

  }

}


text:
package hudson.model;

import com.gargoylesoftware.htmlunit.WebResponse;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

//TODO after the security fix, it could be merged inside ApiTest
public class ApiSecurity1129Test {
    @Rule
    public JenkinsRule j = new JenkinsRule();

    /**
     * Test the wrapper parameter for the api/xml urls to avoid XSS.
     * @throws Exception See {@link #checkWrapperParam(String, Integer, String)}
     */
    @Issue("SECURITY-1129")
    @Test
    public void wrapperXss() throws Exception {
        String wrapper = "html%20xmlns=\"http://www.w3.org/1999/xhtml\"><script>alert(%27XSS%20Detected%27)</script></html><!--";

        checkWrapperParam(wrapper, HttpServletResponse.SC_BAD_REQUEST, Messages.Api_WrapperParamInvalid());
    }

    /**
     * Test the wrapper parameter for the api/xml urls with a bad name.
     * @throws Exception See {@link #checkWrapperParam(String, Integer, String)}
     */
    @Issue("SECURITY-1129")
    @Test
    public void wrapperBadName() throws Exception {
        String wrapper = "-badname";
        checkWrapperParam(wrapper, HttpServletResponse.SC_BAD_REQUEST, Messages.Api_WrapperParamInvalid());

    }

    /**
     * Test the wrapper parameter with a good name, to ensure the security fix doesn't break anything.
     * @throws Exception See {@link #checkWrapperParam(String, Integer, String)}
     */
    @Issue("SECURITY-1129")
    @Test
    public void wrapperGoodName() throws Exception {
        String wrapper = "__GoodName-..-OK";
        checkWrapperParam(wrapper, HttpServletResponse.SC_OK, null);

    }

    /**
     * Check the response for a XML api with the wrapper param specified. At least the statusCode or the responseMessage
     * should be indicated.
     * @param wrapper the wrapper param passed in the url.
     * @param statusCode the status code expected in the response. If it's null, it's not checked.
     * @param responseMessage the message expected in the response. If it's null, it's not checked.
     * @throws IOException See {@link org.jvnet.hudson.test.JenkinsRule.WebClient#goTo(String, String)}
     * @throws SAXException See {@link org.jvnet.hudson.test.JenkinsRule.WebClient#goTo(String, String)}
     */
    private void checkWrapperParam(String wrapper, Integer statusCode, String responseMessage) throws IOException, SAXException {
        if (statusCode == null && responseMessage == null) {
            fail("You should check at least one, the statusCode or the responseMessage when testing the wrapper param");
        }

        JenkinsRule.WebClient wc = j.createWebClient();
        wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
        WebResponse response = wc.goTo(String.format("whoAmI/api/xml?xpath=*&wrapper=%s", wrapper), null).getWebResponse();

        if (response != null) {
            if (statusCode != null) {
                assertEquals(statusCode.intValue(), response.getStatusCode());
            }
            if (responseMessage != null) {
                assertEquals(responseMessage, response.getContentAsString());
            }
        } else {
            fail("The response shouldn't be null");
        }
    }
}


text:
/*
 * Bus.h
 *
 *  Created on: 2 avr. 2015
 *      Author: mailis
 */

#ifndef BUS_H_
#define BUS_H_

#include "Composant.h"
#include <vector>

class Composant;

class Bus {
private:
	///////////////////////////////////// attributs /////////////////////////////////////

    short int taille;
    short int valeur;
    bool actif;

public:
	///////////////////////////////////// constructeurs /////////////////////////////////////

    Bus(short int, short int, bool);

	///////////////////////////////////// destructeurs /////////////////////////////////////
	virtual ~Bus();
	///////////////////////////////////// methodes ///////////////////////////////////////
	void activer(void){actif = true;}
	void desactiver(void){actif = false;}
	///////////////////////////////////// get ////////////////////////////////////////
	short int getTaille(void){return taille;}
	short int getValeur(void){return valeur;}
	bool getActif(void){return actif;}
	///////////////////////////////////// set ////////////////////////////////////////
	void setTaille(short int t){taille= t;}
	void setValeur(short int v){valeur= v;}

};

#endif /* BUS_H_ */


text:
"""
Copyright (c) 2017, 2019 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""

from copy import deepcopy
from atomic_reactor.utils.cachito import CachitoAPI
from atomic_reactor.plugin import PreBuildPlugin
from atomic_reactor.constants import (CONTAINER_BUILD_METHODS, CONTAINER_DEFAULT_BUILD_METHOD,
                                      CONTAINER_BUILDAH_BUILD_METHOD)
from atomic_reactor.util import (read_yaml, read_yaml_from_file_path,
                                 get_build_json, DefaultKeyDict)
from osbs.utils import RegistryURI

import logging
import os

# Key used to store the config object in the plugin workspace
WORKSPACE_CONF_KEY = 'reactor_config'
NO_FALLBACK = object()

def get_config(workflow):
    """
    Obtain configuration object
    Does not fail

    :return: ReactorConfig instance
    """
    try:
        workspace = workflow.plugin_workspace[ReactorConfigPlugin.key]
        return workspace[WORKSPACE_CONF_KEY]
    except KeyError:
        # The plugin did not run or was not successful: use defaults
        conf = ReactorConfig()
        workspace = workflow.plugin_workspace.get(ReactorConfigPlugin.key, {})
        workspace[WORKSPACE_CONF_KEY] = conf
        workflow.plugin_workspace[ReactorConfigPlugin.key] = workspace
        return conf

def get_value(workflow, name, fallback):
    try:
        # make a deep copy to prevent plugins from changing the value for other plugins
        value = deepcopy(get_config(workflow).conf[name])
        return value
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

def get_koji(workflow):
    koji_map = get_value(workflow, 'koji', NO_FALLBACK)

    if 'auth' in koji_map:
        krb_principal = koji_map['auth'].get('krb_principal')
        krb_keytab = koji_map['auth'].get('krb_keytab_path')
        if bool(krb_principal) != bool(krb_keytab):
            raise RuntimeError("specify both koji_principal and koji_keytab or neither")

    return koji_map

def get_koji_session(workflow):
    config = get_koji(workflow)

    from atomic_reactor.utils.koji import create_koji_session

    auth_info = {
        "proxyuser": config['auth'].get('proxyuser'),
        "ssl_certs_dir": config['auth'].get('ssl_certs_dir'),
        "krb_principal": config['auth'].get('krb_principal'),
        "krb_keytab": config['auth'].get('krb_keytab_path')
    }

    use_fast_upload = config.get('use_fast_upload', True)

    return create_koji_session(config['hub_url'], auth_info, use_fast_upload)

def get_koji_path_info(workflow):
    config = get_koji(workflow)
    from koji import PathInfo

    # Make sure koji root_url doesn't end with a slash since the url
    # is used to construct resource urls (e.g. log links)
    root_url = config['root_url'].rstrip('/')
    return PathInfo(topdir=root_url)

def get_odcs(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'odcs', fallback)

def get_odcs_session(workflow):
    config = get_odcs(workflow)
    from atomic_reactor.utils.odcs import ODCSClient

    client_kwargs = {
        'insecure': config.get('insecure', False),
        'timeout': config.get('timeout', None),
    }

    openidc_dir = config['auth'].get('openidc_dir')
    if openidc_dir:
        token_path = os.path.join(openidc_dir, 'token')
        with open(token_path, "r") as f:
            client_kwargs['token'] = f.read().strip()

    ssl_certs_dir = config['auth'].get('ssl_certs_dir')
    if ssl_certs_dir:
        cert_path = os.path.join(ssl_certs_dir, 'cert')
        if os.path.exists(cert_path):
            client_kwargs['cert'] = cert_path
        else:
            raise KeyError("ODCS ssl_certs_dir doesn't exist")

    return ODCSClient(config['api_url'], **client_kwargs)

def get_smtp(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'smtp', fallback)

def get_smtp_session(workflow, fallback):
    config = get_smtp(workflow, fallback)

    import smtplib
    return smtplib.SMTP(config['host'])

def get_cachito(workflow):
    return get_value(workflow, 'cachito', NO_FALLBACK)

def get_cachito_session(workflow):
    config = get_cachito(workflow)

    api_kwargs = {
        'insecure': config.get('insecure', False),
        'timeout': config.get('timeout'),
    }

    ssl_certs_dir = config['auth'].get('ssl_certs_dir')
    if ssl_certs_dir:
        cert_path = os.path.join(ssl_certs_dir, 'cert')
        if os.path.exists(cert_path):
            api_kwargs['cert'] = cert_path
        else:
            raise RuntimeError("Cachito ssl_certs_dir doesn't exist")

    return CachitoAPI(config['api_url'], **api_kwargs)

def get_arrangement_version(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'arrangement_version', fallback)

def get_artifacts_allowed_domains(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'artifacts_allowed_domains', fallback)

def get_yum_repo_allowed_domains(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'yum_repo_allowed_domains', fallback)

def get_image_labels(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'image_labels', fallback)

def get_image_label_info_url_format(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'image_label_info_url_format', fallback)

def get_image_equal_labels(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'image_equal_labels', fallback)

def get_openshift(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'openshift', fallback)

def get_openshift_session(workflow, fallback):
    config = get_openshift(workflow, fallback)
    namespace = get_build_json().get('metadata', {}).get('namespace', None)

    from osbs.api import OSBS
    from osbs.conf import Configuration

    config_kwargs = {
        'verify_ssl': not config.get('insecure', False),
        'namespace': namespace,
        'use_auth': False,
        'conf_file': None,
        'openshift_url': config['url'],
        'build_json_dir': config.get('build_json_dir')
    }

    if config.get('auth'):
        krb_keytab_path = config['auth'].get('krb_keytab_path')
        if krb_keytab_path:
            config_kwargs['kerberos_keytab'] = krb_keytab_path
        krb_principal = config['auth'].get('krb_principal')
        if krb_principal:
            config_kwargs['kerberos_principal'] = krb_principal
        krb_cache_path = config['auth'].get('krb_cache_path')
        if krb_cache_path:
            config_kwargs['kerberos_ccache'] = krb_cache_path
        ssl_certs_dir = config['auth'].get('ssl_certs_dir')
        if ssl_certs_dir:
            config_kwargs['client_cert'] = os.path.join(ssl_certs_dir, 'cert')
            config_kwargs['client_key'] = os.path.join(ssl_certs_dir, 'key')
        config_kwargs['use_auth'] = config['auth'].get('enable', False)

    osbs_conf = Configuration(**config_kwargs)
    return OSBS(osbs_conf, osbs_conf)

def get_group_manifests(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'group_manifests', fallback)

def get_platform_descriptors(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'platform_descriptors', fallback)

def get_prefer_schema1_digest(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'prefer_schema1_digest', fallback)

def get_content_versions(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'content_versions', fallback)

def get_registries_organization(workflow):
    return get_config(workflow).conf.get('registries_organization')

def get_registries(workflow, fallback=NO_FALLBACK):
    try:
        all_registries = get_config(workflow).conf['registries']
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

    registries_cm = {}
    for registry in all_registries:
        reguri = RegistryURI(registry.get('url'))
        regdict = {}
        regdict['version'] = reguri.version
        if registry.get('auth'):
            regdict['secret'] = registry['auth']['cfg_path']
        regdict['insecure'] = registry.get('insecure', False)
        regdict['expected_media_types'] = registry.get('expected_media_types', [])

        registries_cm[reguri.docker_uri] = regdict

    return registries_cm

def get_docker_registry(workflow, fallback=NO_FALLBACK):
    try:
        all_registries = get_config(workflow).conf['registries']
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

    for registry in all_registries:
        reguri = RegistryURI(registry.get('url'))
        if reguri.version == 'v2':
            regdict = {
                'url': reguri.uri,
                'insecure': registry.get('insecure', False)
            }
            if registry.get('auth'):
                regdict['secret'] = registry['auth']['cfg_path']
            return regdict

    raise RuntimeError("Expected V2 registry but none in REACTOR_CONFIG")

def get_yum_proxy(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'yum_proxy', fallback)

def _as_source_registry(registry):
    return {
        'uri': RegistryURI(registry['url']),
        'insecure': registry.get('insecure', False),
        'dockercfg_path': registry.get('auth', {}).get('cfg_path', None)
    }

def get_source_registry(workflow, fallback=NO_FALLBACK):
    try:
        source_registry = get_config(workflow).conf['source_registry']
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

    return _as_source_registry(source_registry)

def get_pull_registries(workflow, fallback=NO_FALLBACK):
    """
    Get list of pull_registries from config map, list entries follow the same
    format as the result of get_source_registry()
    """
    try:
        pull_registries = get_config(workflow).conf['pull_registries']
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

    return [_as_source_registry(reg) for reg in pull_registries]

def get_sources_command(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'sources_command', fallback)

def get_list_rpms_from_scratch(workflow):
    return get_value(workflow, 'list_rpms_from_scratch', True)

def get_required_secrets(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'required_secrets', fallback)

def get_worker_token_secrets(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'worker_token_secrets', fallback)

def get_clusters(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'clusters', fallback)

def get_clusters_client_config_path(workflow, fallback=NO_FALLBACK):
    client_config_dir = get_value(workflow, 'clusters_client_config_dir', fallback)
    return os.path.join(client_config_dir, 'osbs.conf')

def get_platform_to_goarch_mapping(workflow,
                                   descriptors_fallback=NO_FALLBACK):
    platform_descriptors = get_platform_descriptors(
        workflow,
        fallback=descriptors_fallback,
    )
    return DefaultKeyDict(
        (descriptor['platform'], descriptor['architecture'])
        for descriptor in platform_descriptors)

def get_goarch_to_platform_mapping(workflow,
                                   descriptors_fallback=NO_FALLBACK):
    platform_descriptors = get_platform_descriptors(
        workflow,
        fallback=descriptors_fallback,
    )
    return DefaultKeyDict(
        (descriptor['architecture'], descriptor['platform'])
        for descriptor in platform_descriptors)

def get_build_image_override(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'build_image_override', fallback)

def get_default_image_build_method(workflow, fallback=CONTAINER_DEFAULT_BUILD_METHOD):
    value = get_value(workflow, 'default_image_build_method', fallback)
    assert value in CONTAINER_BUILD_METHODS, (
        "unknown default_image_build_method '{}' in reactor config; "
        "config schema validation should have caught this."
    ).format(value)
    return value

def get_buildstep_alias(workflow):
    return get_value(workflow, 'buildstep_alias', {})

def get_flatpak_base_image(workflow, fallback=NO_FALLBACK):
    flatpak = get_value(workflow, 'flatpak', {})
    try:
        return flatpak['base_image']
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

def get_flatpak_metadata(workflow, fallback=NO_FALLBACK):
    flatpak = get_value(workflow, 'flatpak', {})
    try:
        return flatpak['metadata']
    except KeyError:
        if fallback != NO_FALLBACK:
            return fallback
        raise

def get_package_comparison_exceptions(workflow):
    return set(get_config(workflow).conf.get('package_comparison_exceptions', []))

def get_hide_files(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'hide_files', fallback)

def get_skip_koji_check_for_base_image(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'skip_koji_check_for_base_image', fallback)

def get_omps_config(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'omps', fallback)

def get_deep_manifest_list_inspection(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'deep_manifest_list_inspection', fallback)

def get_fail_on_digest_mismatch(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'fail_on_digest_mismatch', fallback)

def get_source_container(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'source_container', fallback)

def get_operator_manifests(workflow, fallback=NO_FALLBACK):
    return get_value(workflow, 'operator_manifests', fallback)

def get_image_size_limit(workflow):
    config = get_value(workflow, 'image_size_limit', {})
    return {
        'binary_image': config.get('binary_image', 0),
    }

class ClusterConfig(object):
    """
    Configuration relating to a particular cluster
    """

    def __init__(self, name, max_concurrent_builds, enabled=True, priority=0):
        self.name = str(name)
        self.max_concurrent_builds = int(max_concurrent_builds)
        self.enabled = enabled
        self.priority = priority

class ReactorConfigKeys(object):
    """
    Symbolic names to use for the key names in the configuration file

    Use the symbols defined in this class to fetch key values from
    the configuration file rather than using string literals. This
    way if you mis-spell one it will cause an exception to be raised
    rather than the key seeming not to be present in the config file.

    At top level:
    - VERSION_KEY: this is the version of the config file schema
    - CLUSTERS_KEY: this holds details about clusters, by platform
    """

    VERSION_KEY = 'version'
    CLUSTERS_KEY = 'clusters'
    ODCS_KEY = 'odcs'

class ReactorConfig(object):
    """
    Class to parse the atomic-reactor configuration file
    """

    DEFAULT_CONFIG = {ReactorConfigKeys.VERSION_KEY: 1}

    def __init__(self, config=None):
        self.conf = deepcopy(config or self.DEFAULT_CONFIG)

        version = self.conf[ReactorConfigKeys.VERSION_KEY]
        if version != 1:
            raise ValueError("version %r unknown" % version)

        # Prepare cluster configurations
        self.cluster_configs = {}
        for platform, clusters in self.conf.get(ReactorConfigKeys.CLUSTERS_KEY,
                                                {}).items():
            cluster_configs = [ClusterConfig(priority=priority, **cluster)
                               for priority, cluster in enumerate(clusters)]
            self.cluster_configs[platform] = [conf for conf in cluster_configs
                                              if conf.enabled]

    def get_enabled_clusters_for_platform(self, platform):
        return self.cluster_configs.get(platform, [])

    def get_odcs_config(self):
        """
        Return an odcs config object created from the odcs config configured in
        reactor config

        :return: the object of ODCSConfig. If there is no odcs configured in
            reactor config, None is returned.
        :rtype: :class:`ODCSConfig` or None
        """
        odcs_config = self.conf.get('odcs')
        if odcs_config:
            return ODCSConfig(
                signing_intents=odcs_config['signing_intents'],
                default_signing_intent=odcs_config['default_signing_intent']
            )

    def is_default(self):
        return self.conf == self.DEFAULT_CONFIG

class ODCSConfig(object):
    """
    Configuration for ODCS integration.
    """

    def __init__(self, signing_intents, default_signing_intent):
        self.log = logging.getLogger(self.__class__.__name__)

        self.default_signing_intent = default_signing_intent

        self.signing_intents = []
        # Signing intents are listed in reverse restrictive order in configuration.
        # Since the input signing_intents will be modified by inserting a new
        # key restrictiveness, this deepcopy ensures the original
        # signing_intent dict objects are not modified accidentally.
        for restrictiveness, intent in enumerate(reversed(deepcopy(signing_intents))):
            intent['restrictiveness'] = restrictiveness
            self.signing_intents.append(intent)

        # Verify default_signing_intent is valid
        self.get_signing_intent_by_name(self.default_signing_intent)

    def get_signing_intent_by_name(self, name):
        valid = []
        for entry in self.signing_intents:
            this_name = entry['name']
            if this_name == name:
                return entry

            valid.append(this_name)

        raise ValueError('unknown signing intent name "{}", valid names: {}'
                         .format(name, ', '.join(valid)))

    def get_signing_intent_by_keys(self, keys):
        if isinstance(keys, str):
            keys = keys.split()
        keys = set(keys)
        intents_matching_deprecated_keys = []
        for entry in reversed(self.signing_intents):
            keys_set = set(entry['keys'])
            if (keys and keys_set >= keys) or keys == keys_set:
                return entry

            permissive_keys_set = set(entry['keys'] + entry.get('deprecated_keys', []))
            if keys and permissive_keys_set >= keys:
                intents_matching_deprecated_keys.append(entry)

        if not intents_matching_deprecated_keys:
            raise ValueError('unknown signing intent keys "{}"'.format(keys))

        self.log.warning(
            'signing intent keys "%s" contain deprecated entries in the "%s" signing intent',
            keys,
            intents_matching_deprecated_keys[0]['name']
         )
        return intents_matching_deprecated_keys[0]

class ReactorConfigPlugin(PreBuildPlugin):
    """
    Parse atomic-reactor configuration file
    """

    # Name of this plugin
    key = 'reactor_config'

    # Exceptions from this plugin should fail the build
    is_allowed_to_fail = False

    def __init__(self, tasker, workflow, config_path=None, basename='config.yaml'):
        """
        constructor

        :param tasker: ContainerTasker instance
        :param workflow: DockerBuildWorkflow instance
        :param config_path: str, configuration path (directory); default is None
        :param basename: str, filename within directory; default is config.yaml
        """
        # call parent constructor
        super(ReactorConfigPlugin, self).__init__(tasker, workflow)
        self.config_path = config_path
        self.basename = basename
        self.reactor_config_map = os.environ.get('REACTOR_CONFIG', None)

    def run(self):
        """
        Run the plugin

        Parse and validate config.
        Store in workflow workspace for later retrieval.
        """
        if self.reactor_config_map:
            self.log.info("reading config from REACTOR_CONFIG env variable")
            conf = read_yaml(self.reactor_config_map, 'schemas/config.json')
        else:
            config_filename = os.path.join(self.config_path, self.basename)
            self.log.info("reading config from %s", config_filename)
            conf = read_yaml_from_file_path(config_filename, 'schemas/config.json')
        reactor_conf = ReactorConfig(conf)
        workspace = self.workflow.plugin_workspace.setdefault(self.key, {})
        workspace[WORKSPACE_CONF_KEY] = reactor_conf

        self.log.info("reading config content %s", reactor_conf.conf)

        # need to stash this on the workflow for access in a place that can't import this module
        buildstep_aliases = get_buildstep_alias(self.workflow)
        default_image_build_method = get_default_image_build_method(self.workflow)
        source_image_build_method = self.workflow.builder.source.config.image_build_method

        if source_image_build_method in buildstep_aliases:
            source_image_build_method = buildstep_aliases[source_image_build_method]
        if default_image_build_method in buildstep_aliases:
            default_image_build_method = buildstep_aliases[default_image_build_method]

        if (source_image_build_method == CONTAINER_BUILDAH_BUILD_METHOD or
                default_image_build_method == CONTAINER_BUILDAH_BUILD_METHOD):
            raise NotImplementedError('{} method not yet fully implemented'.
                                      format(CONTAINER_BUILDAH_BUILD_METHOD))

        self.workflow.builder.source.config.image_build_method = source_image_build_method
        self.workflow.default_image_build_method = default_image_build_method
        self.workflow.builder.tasker.build_method = (source_image_build_method or
                                                     default_image_build_method)

        # set source registry and organization
        if self.workflow.builder.dockerfile_images:
            source_registry_docker_uri = get_source_registry(self.workflow)['uri'].docker_uri
            organization = get_registries_organization(self.workflow)
            self.workflow.builder.dockerfile_images.set_source_registry(source_registry_docker_uri,
                                                                        organization)


text:
<?php

namespace Zotlabs\Module;

class Authorize extends \Zotlabs\Web\Controller {

	function get() {

			// workaround for HTTP-auth in CGI mode
			if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
				$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
				if(strlen($userpass)) {
					list($name, $password) = explode(':', $userpass);
					$_SERVER['PHP_AUTH_USER'] = $name;
					$_SERVER['PHP_AUTH_PW'] = $password;
				}
			}

			if (x($_SERVER, 'HTTP_AUTHORIZATION')) {
				$userpass = base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"], 6)) ;
				if(strlen($userpass)) {
					list($name, $password) = explode(':', $userpass);
					$_SERVER['PHP_AUTH_USER'] = $name;
					$_SERVER['PHP_AUTH_PW'] = $password;
				}
			}

	require_once('include/oauth2.php');

	$request = \OAuth2\Request::createFromGlobals();
	$response = new \OAuth2\Response();

	// validate the authorize request
	if (! $oauth2_server->validateAuthorizeRequest($request, $response)) {
	    $response->send();
    	killme();
	}

	// display an authorization form
	if (empty($_POST)) {

	  return '
<form method="post">
  Do You Authorize TestClient?

  <input type="submit" name="authorized" value="yes">
  <input type="submit" name="authorized" value="no">
</form>';
	}

	// print the authorization code if the user has authorized your client
	$is_authorized = ($_POST['authorized'] === 'yes');
	$oauth2_server->handleAuthorizeRequest($request, $response, $is_authorized);
	if ($is_authorized) {
		// this is only here so that you get to see your code in the cURL request. Otherwise,
		// we'd redirect back to the client
		$code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
		echo("SUCCESS! Authorization Code: $code");

	}

	$response->send();
	killme();
	}

}


text:
using System;
using System.Web.Services;
using AspxCommerce.Core;
using AspxCommerce.AdminNotification;
using System.Collections.Generic;

/// <summary>
/// Summary description for AdminNotificationWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AdminNotificationWebService : System.Web.Services.WebService
{

    [WebMethod]
    public void NotificationSaveUpdateSettings(NotificationSettingsInfo saveUpdateInfo, AspxCommonInfo aspxCommonObj)
    {
        try
        {
            AdminNotificationController.NotificationSaveUpdateSettings(saveUpdateInfo, aspxCommonObj);
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    [WebMethod]
    public NotificationSettingsInfo NotificationSettingsGetAll(AspxCommonInfo aspxCommonObj)
    {
        try
        {

            NotificationSettingsInfo listInfo = AdminNotificationController.NotificationSettingsGetAll(aspxCommonObj);
            return listInfo;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    [WebMethod]
    public NotificationGetAllInfo NotificationGetAll(AspxCommonInfo aspxCommonObj)
    {
        try
        {

            NotificationGetAllInfo listInfo = AdminNotificationController.NotificationGetAll(aspxCommonObj.StoreID, aspxCommonObj.PortalID);
            return listInfo;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
       [WebMethod]
    public List<SubscriptionInfo> NotificationUsersGetAll(AspxCommonInfo aspxCommonObj)
    {
        try
        {

            List<SubscriptionInfo> listInfo = AdminNotificationController.NotificationUsersGetAll(aspxCommonObj);
            return listInfo;
        }
        catch (Exception e)
        {
            throw e;
        }

    }

       [WebMethod]
       public List<OutOfStockInfo> NotificationItemsGetAll(AspxCommonInfo aspxCommonObj)
       {
           try
           {

               List<OutOfStockInfo> listInfo = AdminNotificationController.NotificationItemsGetAll(aspxCommonObj);
               return listInfo;
           }
           catch (Exception e)
           {
               throw e;
           }

       }
      [WebMethod]
       public List<NotificationOrdersInfo> NotificationOrdersGetAll(AspxCommonInfo aspxCommonObj)
       {
           try
           {
               List<NotificationOrdersInfo> listInfo = AdminNotificationController.NotificationOrdersGetAll(aspxCommonObj);
               return listInfo;
           }
           catch (Exception e)
           {
               throw e;
           }
       }

}


text:
require File.dirname(__FILE__) + '/../test_helper'

class ArgsTest < Test::Unit::TestCase
  include TestHelper

  define_method :"test call arguments positions" do
    src = "t('a' , 'b', 'c' => 'd', &e) { |f| g }"
    assert_build(src) do |node|
      assert_equal Ruby::ArgsList, node.first.arguments.class
      assert_position [0, 0],  node.select(:token => 't')
      assert_position [0, 1],  node.select(:token => '(')
      assert_position [0, 2],  node.select(:value => 'a')
      assert_position [0, 6],  node.select(:token => ',')
      assert_position [0, 8],  node.select(:value => 'b')
      assert_position [0, 13], node.select(:value => 'c')
      assert_position [0, 17], node.select(:token => '=>')
      assert_position [0, 20], node.select(:value => 'd')
      assert_position [0, 25], node.select(Ruby::Arg).last
      assert_position [0, 27], node.select(:token => ')')
      assert_position [0, 29], node.select(:token => '{')
      assert_position [0, 31], node.select(:token => '|')[0]
      assert_position [0, 32], node.select(:token => 'f')
      assert_position [0, 33], node.select(:token => '|')[1]
      assert_position [0, 35], node.select(:token => 'g')
      assert_position [0, 37], node.select(:token => '}')
    end
  end

  define_method :'test call arguments: t("foo") (string)' do
    src = 't("foo")'
    assert_build(src)
  end

  define_method :'test call arguments: t(:a => a, :b => b, &block)' do
    src = 't(:a => a, :b => b, &c)'
    assert_build(src) do |node|
    end
  end

  define_method :'test call arguments: t("foo") (string, no parentheses)' do
    src = 't foo'
    assert_build(src)
  end

  define_method :"test call arguments: t :foo, :bar, :baz (3 symbols, no parentheses)" do
    src = "t :foo, :bar, :baz"
    assert_build(src)
  end

  define_method :"test method call: t(:foo => :bar, :baz => :buz) (bare hash)" do
    src = "t(:foo => :bar, :baz => :buz)"
    assert_build(src)
  end

  define_method :"test method call: t :a => :a do end (bare hash, no parentheses, do block)" do
    src = "t :a => :a do end"
    assert_build(src)
  end

  define_method :"test method call: t({ :foo => :bar, :baz => :buz }) (hash)" do
    src = "t({ :foo => :bar, :baz => :buz })"
    assert_build(src)
  end

  define_method :"test method call: t({ :foo => :bar }) (hash, leading whitespace)" do
    src = 't ({ :foo => :bar })'
    assert_build(src)
  end

  define_method :"test method call: t([:foo, :bar]) (array)" do
    src = "(t[:foo, :bar, :baz])"
    assert_build(src)
  end

  define_method :"test method call: t(nil) (keyword)" do
    src = "t(nil)"
    assert_build(src)
  end

  define_method :"test: args with a splat call" do
    src = "t(*a.b)"
    assert_build(src)
  end

  define_method :"test: args with a splat and block" do
    src = "t(*a.b { |c| c.d })"
    assert_build(src)
  end

  define_method :"test: replace argument" do
    src = "(:foo, :bar)"
    args = build('t' + src).first.arguments
    foo, bar = args

    args[0] = baz = Ruby.from_native(:baz)
    assert_equal args, baz.parent.parent # baz is wrapped into an Arg
    assert_equal [0, 2], baz.position.to_a
  end
end


text:
package gov.nih.nci.ncicb.cadsr.loader;

import gov.nih.nci.ncicb.cadsr.loader.ui.*;

import java.awt.Component;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Toolkit;

import java.util.*;

import gov.nih.nci.ncicb.cadsr.loader.event.*;
import gov.nih.nci.ncicb.cadsr.loader.util.*;

import java.awt.event.ComponentAdapter;

import java.awt.event.ComponentEvent;

import org.apache.log4j.*;

/**
 * The main starting point for the UI.
 *

 *
 * @author Christophe Ludet
 *
 */
public class UMLLoaderGUI
{

  private static Logger logger = Logger.getLogger(UMLLoaderGUI.class.getName());
  private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

  private UserSelections userSelections = UserSelections.getInstance();

  private RoundtripPanelDescriptor roundtripDesc;
  private GMEDefaultsPanelDescriptor gmeDefaultsDesc;

  private List<WizardPanelDescriptor> descriptors;

  private MainFrame mainFrame;

  private Appender appender;

  private List<RunModeListener> runModeListeners = new ArrayList<RunModeListener>();

  private UserPreferences prefs;

  public UMLLoaderGUI()
  {
  }

  public void start() {
    InitClass initClass = new InitClass(this);
    Thread t = new Thread(initClass);
    t.setPriority(Thread.MIN_PRIORITY);
//     t.start();

    logger.getParent().addAppender(appender);

    System.setProperty("java.security.auth.login.config", Thread.currentThread().getContextClassLoader().getResource("jaas.config").toExternalForm());

    Frame f = new Frame();
    Wizard wizard = new Wizard(f);

    wizard.getDialog().setTitle(PropertyAccessor.getProperty("siw.title"));

    WizardPanelDescriptor modeSelDesc = new ModeSelectionPanelDescriptor();
    wizard.registerWizardPanel(ModeSelectionPanelDescriptor.IDENTIFIER, modeSelDesc);

    WizardPanelDescriptor packageDesc = new PackageFilterSelectionPanelDescriptor();
    wizard.registerWizardPanel(PackageFilterSelectionPanelDescriptor.IDENTIFIER, packageDesc);

    WizardPanelDescriptor packageClassFilterDesc = new PackageClassFilterPanelDescriptor();
    wizard.registerWizardPanel(PackageClassFilterPanelDescriptor.IDENTIFIER, packageClassFilterDesc);

    WizardPanelDescriptor descriptor2 = new FileSelectionPanelDescriptor();
    wizard.registerWizardPanel(FileSelectionPanelDescriptor.IDENTIFIER, descriptor2);

//     WizardPanelDescriptor fpDescForRoundtrip = new FileSelectionPanelDescriptor(FileSelectionPanelDescriptor.MODE_ROUNDTRIP);
//     wizard.registerWizardPanel(FileSelectionPanelDescriptor.ROUNDTRIP_IDENTIFIER, fpDescForRoundtrip);

//     WizardPanelDescriptor fpDescForPackageFilter = new FileSelectionPanelDescriptor(FileSelectionPanelDescriptor.MODE_SC);
//     wizard.registerWizardPanel(FileSelectionPanelDescriptor.PACKAGE_FILTER_IDENTIFIER, fpDescForPackageFilter);

//     wizard.registerWizardPanel(RoundtripPanelDescriptor.IDENTIFIER, roundtripDesc);

//     wizard.registerWizardPanel(GMEDefaultsPanelDescriptor.IDENTIFIER, gmeDefaultsDesc);

    for(WizardPanelDescriptor _desc : descriptors) {
      wizard.registerWizardPanel(_desc.getPanelDescriptorIdentifier(), _desc);
    }

    WizardPanelDescriptor fileProgress = new ProgressFileSelectionPanelDescriptor();
    wizard.registerWizardPanel(ProgressFileSelectionPanelDescriptor.IDENTIFIER, fileProgress);

    WizardPanelDescriptor reportConfirmDesc = new ReportConfirmPanelDescriptor();
    wizard.registerWizardPanel(ReportConfirmPanelDescriptor.IDENTIFIER, reportConfirmDesc);

    WizardPanelDescriptor validationDesc = new ValidationPanelDescriptor();
    wizard.registerWizardPanel(ValidationPanelDescriptor.IDENTIFIER, validationDesc);

    WizardPanelDescriptor descriptor3 = new SemanticConnectorPanelDescriptor();
    wizard.registerWizardPanel(SemanticConnectorPanelDescriptor.IDENTIFIER, descriptor3);

    WizardPanelDescriptor descriptor4 = new ProgressSemanticConnectorPanelDescriptor();
    wizard.registerWizardPanel(ProgressSemanticConnectorPanelDescriptor.IDENTIFIER, descriptor4);

    wizard.setCurrentPanel(ModeSelectionPanelDescriptor.IDENTIFIER);
    int wizResult = wizard.showModalDialog();

    if(wizResult != 0) {
      System.exit(0);
    }

    RunMode mode = (RunMode)userSelections.getProperty("MODE");

    if(!(mode.equals(RunMode.Reviewer) || mode.equals(RunMode.Curator) || mode.equals(RunMode.UnannotatedXmi)))
      System.exit(0);

    mainFrame.init();
    putToCenter(mainFrame);
    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainFrame.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e){
         mainFrame.exit();
        }
      });
    mainFrame.addWindowStateListener(new WindowAdapter(){
        public void windowStateChanged(WindowEvent e) {
          mainFrame.stateChanged(e);
        }
      });
    mainFrame.addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent evt) {
          mainFrame.componentResized(evt);
        }
      });

    mainFrame.setWorkingTitle(null);

    mainFrame.setVisible(true);

  }

  public void setMainFrame(MainFrame frame) {
    this.mainFrame = frame;
  }

  public void setCustomAppender(Appender a) {
    this.appender = a;
  }

//   /**
//    *
//    * @param args
//    */
//   public static void main(String[] args)
//   {
//     try
//     {
//       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//     }
//     catch(Exception e)
//     {
//       e.printStackTrace();
//     }

//     new UMLLoaderGUI();
//   }

//   public void setRoundtripDescriptor(RoundtripPanelDescriptor desc) {
//     roundtripDesc = desc;
//   }

//   public void setGmeDefaulsDescriptor(GMEDefaultsPanelDescriptor desc) {
//     gmeDefaultsDesc = desc;
//   }

  public void setPanelDescriptors(List<WizardPanelDescriptor> descriptors) {
    this.descriptors = descriptors;
  }

  public void setUserPreferences(UserPreferences preferences) {
    prefs = preferences;
  }

  private void putToCenter(Component comp) {
    comp.setLocation((screenSize.width - comp.getSize().width) / 2, (screenSize.height - comp.getSize().height) / 2);
  }

}


text:
package de.fun2code.android.piratebox;

import de.fun2code.android.piratebox.util.NetworkUtil.WrapResult;

/**
 * State changed listener interface
 *
 * @author joschi
 *
 */
public interface StateChangedListener {
	/**
	 * Is called when the access point was enabled
	 *
	 * @param isAutomatic	@{code true} if the access point was started by the app,
	 * 						otherwise {@code false}
	 */
	public void apEnabled(boolean isAutomatic);

	/**
	 * Is called when the access point was disabled
	 *
	 * @param isAutomatic	@{code true} if the access point was started by the app,
	 * 						otherwise {@code false}
	 */
	public void apDisabled(boolean isAutomatic);

	/**
	 * Is called when the network has been configured as PirateBox
	 */
	public void networkUp();

	/**
	 * Is called when the non-PirateBox network configuration has been restored
	 */
	public void networkDown();

	/**
	 * Called when the web server has been started
	 *
	 * @param success	state of the web server, {@code true} if the server is
	 * 					stopped, otherwiese {@code false}
	 */
	public void serverUp(boolean success);

	/**
	 * Called when the web server has been stopped
	 *
	 * @param success	state of the web server, {@code true} if the server is
	 * 					stopped, otherwiese {@code false}
	 */
	public void serverDown(boolean success);

	/**
	 * Called aftre the dnsmasq has been executed
	 *
	 * @param result	{@code WrapResult} result codes
	 */
	public void dnsMasqWrapped(WrapResult result);

	/**
	 * Called after the dnsmasq backup has been restored
	 */
	public void dnsMasqUnWrapped();
}


text:
'use strict';

angular.module('core', ['core.map']);


text:
<!--
Copyright 2015 Hewlett-Packard Development Company, L.P.

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.

 -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.verigreen</groupId>
		<artifactId>verigreen-root</artifactId>
		<version>2.5.6-SNAPSHOT</version>
	</parent>
	<artifactId>vg-common</artifactId>
	<name>${project.artifactId}</name>
	<packaging>jar</packaging>

	<!-- repositories to get artifacts from -->
	<repositories>
		<repository>
			<id>repo.jenkins-ci.org</id>
			<url>http://repo.jenkins-ci.org/public/</url>
		</repository>
		<repository>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
			<id>central</id>
			<name>Maven Repository Switchboard</name>
			<url>http://repo1.maven.org/maven2</url>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>repo.jenkins-ci.org</id>
			<url>http://repo.jenkins-ci.org/public/</url>
		</pluginRepository>
		<pluginRepository>
			<releases>
				<updatePolicy>never</updatePolicy>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
			<id>central</id>
			<name>Maven Plugin Repository</name>
			<url>http://repo1.maven.org/maven2</url>
		</pluginRepository>
	</pluginRepositories>

	<properties>
		<spring.version>3.2.2.RELEASE</spring.version>
	</properties>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<testSourceDirectory>utest</testSourceDirectory>
		<resources>
			<resource>
				<directory>src</directory>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>utest</directory>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</testResource>
		</testResources>
		<pluginManagement>
			<plugins>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>2.4</version>
					<configuration>
						<fork>true</fork>
						<!-- <compilerArgument>-Xlint" "-Xlint:-path" "-Xlint:-options" "-Werror</compilerArgument> -->
						<showWarnings>true</showWarnings>
						<showDeprecation>true</showDeprecation>
						<source>1.7</source>
						<target>1.7</target>
						<encoding>UTF-8</encoding>
					</configuration>
				</plugin>
				<plugin>
					<artifactId>maven-surefire-plugin</artifactId>
					<version>2.12.3</version>
					<configuration>
						<runOrder>alphabetical</runOrder>
						<includes>
							<include>**/Test*.java</include>
							<include>**/*Test.java</include>
							<include>**/*TestCase.java</include>
							<include>**/*Tester.java</include>
						</includes>
						<skipTests>true</skipTests>
						<testFailureIgnore>true</testFailureIgnore>
						<argLine>-Xmx512m</argLine>
					</configuration>
				</plugin>
				<plugin>
					<artifactId>maven-jar-plugin</artifactId>
					<executions>
						<execution>
							<phase>package</phase>
							<goals>
								<goal>test-jar</goal>
							</goals>
						</execution>
					</executions>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.easymock</groupId>
			<artifactId>easymock</artifactId>
			<version>3.2</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.3</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.cache</groupId>
			<artifactId>jbosscache-core</artifactId>
			<version>3.2.5.GA</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4</version>
		</dependency>
	</dependencies>
	<profiles>
		<profile>
			<id>test</id>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-surefire-plugin</artifactId>
						<configuration>
							<skipTests>false</skipTests>
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
	</project>