text:
[![CircleCI](https://circleci.com/gh/nats-io/nats.ex/tree/master.svg?style=svg)](https://circleci.com/gh/nats-io/nats.ex/tree/master)

![gnat](gnat.png)

# Gnat

A [nats.io](https://nats.io/) client for elixir.
The goals of the project are resiliency, performance, and ease of use.

## Usage

```elixir
{:ok, gnat} = Gnat.start_link(%{host: '127.0.0.1', port: 4222})
# Or if the server requires TLS you can start a connection with:
# {:ok, gnat} = Gnat.start_link(%{host: '127.0.0.1', port: 4222, tls: true})

{:ok, subscription} = Gnat.sub(gnat, self(), "pawnee.*")
:ok = Gnat.pub(gnat, "pawnee.news", "Leslie Knope recalled from city council (Jammed)")
receive do
  {:msg, %{body: body, topic: "pawnee.news", reply_to: nil}} ->
    IO.puts(body)
end
```

## Instrumentation

Gnat uses [telemetry](https://hex.pm/packages/telemetry) to make instrumentation data available to clients.
If you want to record metrics around the number of messages or latency of message publishes, subscribes, requests, etc you can do the following in your project:

```elixir
iex(1)> metrics_function = fn(event_name, measurements, event_meta, config) ->
  IO.inspect([event_name, measurements, event_meta, config])
  :ok
end
#Function<4.128620087/4 in :erl_eval.expr/5>
iex(2)> names = [[:gnat, :pub], [:gnat, :sub], [:gnat, :message_received], [:gnat, :request], [:gnat, :unsub]]
[
  [:gnat, :pub],
  [:gnat, :sub],
  [:gnat, :message_received],
  [:gnat, :request],
  [:gnat, :unsub]
]
iex(3)> :telemetry.attach_many("my listener", names, metrics_function, %{my_config: true})
:ok
iex(4)> {:ok, gnat} = Gnat.start_link()
{:ok, #PID<0.203.0>}
iex(5)> Gnat.sub(gnat, self(), "topic")
[[:gnat, :sub], %{latency: 128000}, %{topic: "topic"}, %{my_config: true}]
{:ok, 1}
iex(6)> Gnat.pub(gnat, "topic", "ohai")
[[:gnat, :pub], %{latency: 117000}, %{topic: "topic"}, %{my_config: true}]
[[:gnat, :message_received], %{count: 1}, %{topic: "topic"}, %{my_config: true}]
:ok
```

The `pub`, `sub`, `request`, and `unsub` events all report the latency of those respective calls.
The `message_received` event reports a number of messages like `%{count: 1}` because there isn't a good latency metric to report.
All of the events (except `unsub`) include metadata with a `:topic` key so you can split your metrics by topic.

## Benchmarks

Part of the motivation for building this library is to get better performance.
To this end, there is a `bench` branch on this project which includes a `server.exs` and `client.exs` that can be used for benchmarking various scenarios.

As of this commit, the [latest benchmark on a 16-core server](https://gist.github.com/mmmries/08fe44fdd47a6f8838936f41170f270a) shows that you can make 170k+ req/sec or up to 192MB/sec.

The `bench/*.exs` files also contain some straight-line single-cpu performance tests.
As of this commit my 2018 macbook pro shows.

|   | ips | average | deviation | median |
| - | --- | ------- | --------- | ------ |
| parse-128 | 487.67 K | 2.19 μs | ±1701.54% | 2 μs |
| pub - 128 | 96.37 K | 10.38 μs | ±102.94% | 10 μs |
| req-reply-128 | 8.32 K | 120.16 μs | ±23.68% | 114 μs |

## Development

Before running the tests make sure you have a locally running copy of `gnatsd` (`brew install gnatsd`).
We currently use version `1.4.1` in CI, but anything higher than `0.9.6` should be fine.
The typical `mix test` will run all the basic unit tests.

You can also run the `multi_server` set of tests that test connectivity to different
`gnatsd` configurations. You can run these with `mix test --only multi_server`.
The tests will tell you how to start the different configurations.

There are also some property-based tests that generate a lot of test cases.
You can tune how many test cases by setting the environment variable `N=200 mix test --only property` (default it 100).

For more details you can look at how Travis runs these things in the CI flow.


text:
package com.amazonaws.services.workspaces;

import org.w3c.dom.*;

import java.net.*;
import java.util.*;
import java.util.Map.Entry;

import org.apache.commons.logging.*;

import com.amazonaws.*;
import com.amazonaws.auth.*;
import com.amazonaws.handlers.*;
import com.amazonaws.http.*;
import com.amazonaws.internal.*;
import com.amazonaws.metrics.*;
import com.amazonaws.regions.*;
import com.amazonaws.transform.*;
import com.amazonaws.util.*;
import com.amazonaws.util.json.*;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.annotation.ThreadSafe;

import com.amazonaws.services.workspaces.model.*;
import com.amazonaws.services.workspaces.model.transform.*;

/**
 * Client for accessing Amazon WorkSpaces. All service calls made using this
 * client are blocking, and will not return until the service call completes.
 *

 * <fullname>Amazon WorkSpaces Service</fullname>
 *

 * This is the Amazon WorkSpaces API Reference. This guide provides
 * detailed information about Amazon WorkSpaces operations, data types,
 * parameters, and errors.
 *

 */
@ThreadSafe
public class AmazonWorkspacesClient extends AmazonWebServiceClient implements
        AmazonWorkspaces {
    /** Provider for AWS credentials. */
    private AWSCredentialsProvider awsCredentialsProvider;

    private static final Log log = LogFactory.getLog(AmazonWorkspaces.class);

    /** Default signing name for the service. */
    private static final String DEFAULT_SIGNING_NAME = "workspaces";

    /** The region metadata service name for computing region endpoints. */
    private static final String DEFAULT_ENDPOINT_PREFIX = "workspaces";

    /**
     * Client configuration factory providing ClientConfigurations tailored to
     * this client
     */
    protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory();

    /**
     * List of exception unmarshallers for all Amazon WorkSpaces exceptions.
     */
    protected List<JsonErrorUnmarshallerV2> jsonErrorUnmarshallers = new ArrayList<JsonErrorUnmarshallerV2>();

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces. A
     * credentials provider chain will be used that searches for credentials in
     * this order:
     *

     *
Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY

     *
Java System Properties - aws.accessKeyId and aws.secretKey

     *
Instance profile credentials delivered through the Amazon EC2
     * metadata service

     *

     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @see DefaultAWSCredentialsProviderChain
     */
    public AmazonWorkspacesClient() {
        this(new DefaultAWSCredentialsProviderChain(), configFactory
                .getConfig());
    }

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces. A
     * credentials provider chain will be used that searches for credentials in
     * this order:
     *

     *
Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY

     *
Java System Properties - aws.accessKeyId and aws.secretKey

     *
Instance profile credentials delivered through the Amazon EC2
     * metadata service

     *

     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @param clientConfiguration
     *        The client configuration options controlling how this client
     *        connects to Amazon WorkSpaces (ex: proxy settings, retry counts,
     *        etc.).
     *
     * @see DefaultAWSCredentialsProviderChain
     */
    public AmazonWorkspacesClient(ClientConfiguration clientConfiguration) {
        this(new DefaultAWSCredentialsProviderChain(), clientConfiguration);
    }

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces
     * using the specified AWS account credentials.
     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @param awsCredentials
     *        The AWS credentials (access key ID and secret key) to use when
     *        authenticating with AWS services.
     */
    public AmazonWorkspacesClient(AWSCredentials awsCredentials) {
        this(awsCredentials, configFactory.getConfig());
    }

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces
     * using the specified AWS account credentials and client configuration
     * options.
     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @param awsCredentials
     *        The AWS credentials (access key ID and secret key) to use when
     *        authenticating with AWS services.
     * @param clientConfiguration
     *        The client configuration options controlling how this client
     *        connects to Amazon WorkSpaces (ex: proxy settings, retry counts,
     *        etc.).
     */
    public AmazonWorkspacesClient(AWSCredentials awsCredentials,
            ClientConfiguration clientConfiguration) {
        super(clientConfiguration);
        this.awsCredentialsProvider = new StaticCredentialsProvider(
                awsCredentials);
        init();
    }

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces
     * using the specified AWS account credentials provider.
     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @param awsCredentialsProvider
     *        The AWS credentials provider which will provide credentials to
     *        authenticate requests with AWS services.
     */
    public AmazonWorkspacesClient(AWSCredentialsProvider awsCredentialsProvider) {
        this(awsCredentialsProvider, configFactory.getConfig());
    }

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces
     * using the specified AWS account credentials provider and client
     * configuration options.
     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @param awsCredentialsProvider
     *        The AWS credentials provider which will provide credentials to
     *        authenticate requests with AWS services.
     * @param clientConfiguration
     *        The client configuration options controlling how this client
     *        connects to Amazon WorkSpaces (ex: proxy settings, retry counts,
     *        etc.).
     */
    public AmazonWorkspacesClient(
            AWSCredentialsProvider awsCredentialsProvider,
            ClientConfiguration clientConfiguration) {
        this(awsCredentialsProvider, clientConfiguration, null);
    }

    /**
     * Constructs a new client to invoke service methods on Amazon WorkSpaces
     * using the specified AWS account credentials provider, client
     * configuration options, and request metric collector.
     *
     *

     * All service calls made using this new client object are blocking, and
     * will not return until the service call completes.
     *
     * @param awsCredentialsProvider
     *        The AWS credentials provider which will provide credentials to
     *        authenticate requests with AWS services.
     * @param clientConfiguration
     *        The client configuration options controlling how this client
     *        connects to Amazon WorkSpaces (ex: proxy settings, retry counts,
     *        etc.).
     * @param requestMetricCollector
     *        optional request metric collector
     */
    public AmazonWorkspacesClient(
            AWSCredentialsProvider awsCredentialsProvider,
            ClientConfiguration clientConfiguration,
            RequestMetricCollector requestMetricCollector) {
        super(clientConfiguration, requestMetricCollector);
        this.awsCredentialsProvider = awsCredentialsProvider;
        init();
    }

    private void init() {
        jsonErrorUnmarshallers
                .add(new JsonErrorUnmarshallerV2(
                        com.amazonaws.services.workspaces.model.ResourceUnavailableException.class,
                        "ResourceUnavailableException"));
        jsonErrorUnmarshallers
                .add(new JsonErrorUnmarshallerV2(
                        com.amazonaws.services.workspaces.model.ResourceLimitExceededException.class,
                        "ResourceLimitExceededException"));
        jsonErrorUnmarshallers
                .add(new JsonErrorUnmarshallerV2(
                        com.amazonaws.services.workspaces.model.InvalidParameterValuesException.class,
                        "InvalidParameterValuesException"));
        jsonErrorUnmarshallers
                .add(JsonErrorUnmarshallerV2.DEFAULT_UNMARSHALLER);

        setServiceNameIntern(DEFAULT_SIGNING_NAME);
        setEndpointPrefix(DEFAULT_ENDPOINT_PREFIX);
        // calling this.setEndPoint(...) will also modify the signer accordingly
        setEndpoint("https://workspaces.us-east-1.amazonaws.com");
        HandlerChainFactory chainFactory = new HandlerChainFactory();
        requestHandler2s
                .addAll(chainFactory
                        .newRequestHandlerChain("/com/amazonaws/services/workspaces/request.handlers"));
        requestHandler2s
                .addAll(chainFactory
                        .newRequestHandler2Chain("/com/amazonaws/services/workspaces/request.handler2s"));
    }

    /**
     *

     * Creates one or more WorkSpaces.
     *

     * <note>
     *

     * This operation is asynchronous and returns before the WorkSpaces are
     * created.
     *

     * </note>
     *
     * @param createWorkspacesRequest
     *        Contains the inputs for the CreateWorkspaces operation.
     * @return Result of the CreateWorkspaces operation returned by the service.
     * @throws ResourceLimitExceededException
     *         Your resource limits have been exceeded.
     * @sample AmazonWorkspaces.CreateWorkspaces
     */
    @Override
    public CreateWorkspacesResult createWorkspaces(
            CreateWorkspacesRequest createWorkspacesRequest) {
        ExecutionContext executionContext = createExecutionContext(createWorkspacesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<CreateWorkspacesRequest> request = null;
        Response<CreateWorkspacesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new CreateWorkspacesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(createWorkspacesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<CreateWorkspacesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new CreateWorkspacesResultJsonUnmarshaller(), false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    /**
     *

     * Obtains information about the WorkSpace bundles that are available to
     * your account in the specified region.
     *

     *

     * You can filter the results with either the BundleIds
     * parameter, or the Owner parameter, but not both.
     *

     *

     * This operation supports pagination with the use of the
     * NextToken request and response parameters. If more results
     * are available, the NextToken response member contains a
     * token that you pass in the next call to this operation to retrieve the
     * next set of items.
     *

     *
     * @param describeWorkspaceBundlesRequest
     *        Contains the inputs for the DescribeWorkspaceBundles
     *        operation.
     * @return Result of the DescribeWorkspaceBundles operation returned by the
     *         service.
     * @throws InvalidParameterValuesException
     *         One or more parameter values are not valid.
     * @sample AmazonWorkspaces.DescribeWorkspaceBundles
     */
    @Override
    public DescribeWorkspaceBundlesResult describeWorkspaceBundles(
            DescribeWorkspaceBundlesRequest describeWorkspaceBundlesRequest) {
        ExecutionContext executionContext = createExecutionContext(describeWorkspaceBundlesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<DescribeWorkspaceBundlesRequest> request = null;
        Response<DescribeWorkspaceBundlesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new DescribeWorkspaceBundlesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(describeWorkspaceBundlesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<DescribeWorkspaceBundlesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new DescribeWorkspaceBundlesResultJsonUnmarshaller(),
                            false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    @Override
    public DescribeWorkspaceBundlesResult describeWorkspaceBundles() {
        return describeWorkspaceBundles(new DescribeWorkspaceBundlesRequest());
    }

    /**
     *

     * Retrieves information about the AWS Directory Service directories in the
     * region that are registered with Amazon WorkSpaces and are available to
     * your account.
     *

     *

     * This operation supports pagination with the use of the
     * NextToken request and response parameters. If more results
     * are available, the NextToken response member contains a
     * token that you pass in the next call to this operation to retrieve the
     * next set of items.
     *

     *
     * @param describeWorkspaceDirectoriesRequest
     *        Contains the inputs for the DescribeWorkspaceDirectories
     *        operation.
     * @return Result of the DescribeWorkspaceDirectories operation returned by
     *         the service.
     * @throws InvalidParameterValuesException
     *         One or more parameter values are not valid.
     * @sample AmazonWorkspaces.DescribeWorkspaceDirectories
     */
    @Override
    public DescribeWorkspaceDirectoriesResult describeWorkspaceDirectories(
            DescribeWorkspaceDirectoriesRequest describeWorkspaceDirectoriesRequest) {
        ExecutionContext executionContext = createExecutionContext(describeWorkspaceDirectoriesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<DescribeWorkspaceDirectoriesRequest> request = null;
        Response<DescribeWorkspaceDirectoriesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new DescribeWorkspaceDirectoriesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(describeWorkspaceDirectoriesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<DescribeWorkspaceDirectoriesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new DescribeWorkspaceDirectoriesResultJsonUnmarshaller(),
                            false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    @Override
    public DescribeWorkspaceDirectoriesResult describeWorkspaceDirectories() {
        return describeWorkspaceDirectories(new DescribeWorkspaceDirectoriesRequest());
    }

    /**
     *

     * Obtains information about the specified WorkSpaces.
     *

     *

     * Only one of the filter parameters, such as BundleId,
     * DirectoryId, or WorkspaceIds, can be specified
     * at a time.
     *

     *

     * This operation supports pagination with the use of the
     * NextToken request and response parameters. If more results
     * are available, the NextToken response member contains a
     * token that you pass in the next call to this operation to retrieve the
     * next set of items.
     *

     *
     * @param describeWorkspacesRequest
     *        Contains the inputs for the DescribeWorkspaces operation.
     * @return Result of the DescribeWorkspaces operation returned by the
     *         service.
     * @throws InvalidParameterValuesException
     *         One or more parameter values are not valid.
     * @throws ResourceUnavailableException
     *         The specified resource is not available.
     * @sample AmazonWorkspaces.DescribeWorkspaces
     */
    @Override
    public DescribeWorkspacesResult describeWorkspaces(
            DescribeWorkspacesRequest describeWorkspacesRequest) {
        ExecutionContext executionContext = createExecutionContext(describeWorkspacesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<DescribeWorkspacesRequest> request = null;
        Response<DescribeWorkspacesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new DescribeWorkspacesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(describeWorkspacesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<DescribeWorkspacesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new DescribeWorkspacesResultJsonUnmarshaller(),
                            false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    @Override
    public DescribeWorkspacesResult describeWorkspaces() {
        return describeWorkspaces(new DescribeWorkspacesRequest());
    }

    /**
     *

     * Reboots the specified WorkSpaces.
     *

     *

     * To be able to reboot a WorkSpace, the WorkSpace must have a State
     * of AVAILABLE, IMPAIRED, or
     * INOPERABLE.
     *

     * <note>
     *

     * This operation is asynchronous and will return before the WorkSpaces have
     * rebooted.
     *

     * </note>
     *
     * @param rebootWorkspacesRequest
     *        Contains the inputs for the RebootWorkspaces operation.
     * @return Result of the RebootWorkspaces operation returned by the service.
     * @sample AmazonWorkspaces.RebootWorkspaces
     */
    @Override
    public RebootWorkspacesResult rebootWorkspaces(
            RebootWorkspacesRequest rebootWorkspacesRequest) {
        ExecutionContext executionContext = createExecutionContext(rebootWorkspacesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<RebootWorkspacesRequest> request = null;
        Response<RebootWorkspacesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new RebootWorkspacesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(rebootWorkspacesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<RebootWorkspacesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new RebootWorkspacesResultJsonUnmarshaller(), false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    /**
     *

     * Rebuilds the specified WorkSpaces.
     *

     *

     * Rebuilding a WorkSpace is a potentially destructive action that can
     * result in the loss of data. Rebuilding a WorkSpace causes the following
     * to occur:
     *

     *

     *
The system is restored to the image of the bundle that the WorkSpace
     * is created from. Any applications that have been installed, or system
     * settings that have been made since the WorkSpace was created will be
     * lost.

     *
The data drive (D drive) is re-created from the last automatic
     * snapshot taken of the data drive. The current contents of the data drive
     * are overwritten. Automatic snapshots of the data drive are taken every 12
     * hours, so the snapshot can be as much as 12 hours old.

     *

     *

     * To be able to rebuild a WorkSpace, the WorkSpace must have a State
     * of AVAILABLE or ERROR.
     *

     * <note>
     *

     * This operation is asynchronous and will return before the WorkSpaces have
     * been completely rebuilt.
     *

     * </note>
     *
     * @param rebuildWorkspacesRequest
     *        Contains the inputs for the RebuildWorkspaces operation.
     * @return Result of the RebuildWorkspaces operation returned by the
     *         service.
     * @sample AmazonWorkspaces.RebuildWorkspaces
     */
    @Override
    public RebuildWorkspacesResult rebuildWorkspaces(
            RebuildWorkspacesRequest rebuildWorkspacesRequest) {
        ExecutionContext executionContext = createExecutionContext(rebuildWorkspacesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<RebuildWorkspacesRequest> request = null;
        Response<RebuildWorkspacesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new RebuildWorkspacesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(rebuildWorkspacesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<RebuildWorkspacesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new RebuildWorkspacesResultJsonUnmarshaller(),
                            false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    /**
     *

     * Terminates the specified WorkSpaces.
     *

     *

     * Terminating a WorkSpace is a permanent action and cannot be undone. The
     * user's data is not maintained and will be destroyed. If you need to
     * archive any user data, contact Amazon Web Services before terminating the
     * WorkSpace.
     *

     *

     * You can terminate a WorkSpace that is in any state except
     * SUSPENDED.
     *

     * <note>
     *

     * This operation is asynchronous and will return before the WorkSpaces have
     * been completely terminated.
     *

     * </note>
     *
     * @param terminateWorkspacesRequest
     *        Contains the inputs for the TerminateWorkspaces operation.
     * @return Result of the TerminateWorkspaces operation returned by the
     *         service.
     * @sample AmazonWorkspaces.TerminateWorkspaces
     */
    @Override
    public TerminateWorkspacesResult terminateWorkspaces(
            TerminateWorkspacesRequest terminateWorkspacesRequest) {
        ExecutionContext executionContext = createExecutionContext(terminateWorkspacesRequest);
        AWSRequestMetrics awsRequestMetrics = executionContext
                .getAwsRequestMetrics();
        awsRequestMetrics.startEvent(Field.ClientExecuteTime);
        Request<TerminateWorkspacesRequest> request = null;
        Response<TerminateWorkspacesResult> response = null;

        try {
            awsRequestMetrics.startEvent(Field.RequestMarshallTime);
            try {
                request = new TerminateWorkspacesRequestMarshaller()
                        .marshall(super
                                .beforeMarshalling(terminateWorkspacesRequest));
                // Binds the request metrics to the current request.
                request.setAWSRequestMetrics(awsRequestMetrics);
            } finally {
                awsRequestMetrics.endEvent(Field.RequestMarshallTime);
            }

            JsonResponseHandler<TerminateWorkspacesResult> responseHandler = SdkJsonProtocolFactory
                    .createResponseHandler(
                            new TerminateWorkspacesResultJsonUnmarshaller(),
                            false);
            responseHandler.setIsPayloadJson(true);
            response = invoke(request, responseHandler, executionContext);

            return response.getAwsResponse();

        } finally {

            endClientExecution(awsRequestMetrics, request, response);
        }
    }

    /**
     * Returns additional metadata for a previously executed successful,
     * request, typically used for debugging issues where a service isn't acting
     * as expected. This data isn't considered part of the result data returned
     * by an operation, so it's available through this separate, diagnostic
     * interface.
     *

     * Response metadata is only cached for a limited period of time, so if you
     * need to access this extra diagnostic information for an executed request,
     * you should use this method to retrieve it as soon as possible after
     * executing the request.
     *
     * @param request
     *        The originally executed request
     *
     * @return The response metadata for the specified request, or null if none
     *         is available.
     */
    public ResponseMetadata getCachedResponseMetadata(
            AmazonWebServiceRequest request) {
        return client.getResponseMetadataForRequest(request);
    }

    /**
     * Normal invoke with authentication. Credentials are required and may be
     * overriden at the request level.
     **/
    private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(
            Request<Y> request,
            HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
            ExecutionContext executionContext) {

        executionContext.setCredentialsProvider(CredentialUtils
                .getCredentialsProvider(request.getOriginalRequest(),
                        awsCredentialsProvider));

        return doInvoke(request, responseHandler, executionContext);
    }

    /**
     * Invoke with no authentication. Credentials are not required and any
     * credentials set on the client or request will be ignored for this
     * operation.
     **/
    private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke(
            Request<Y> request,
            HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
            ExecutionContext executionContext) {

        return doInvoke(request, responseHandler, executionContext);
    }

    /**
     * Invoke the request using the http client. Assumes credentials (or lack
     * thereof) have been configured in the ExecutionContext beforehand.
     **/
    private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(
            Request<Y> request,
            HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
            ExecutionContext executionContext) {
        request.setEndpoint(endpoint);
        request.setTimeOffset(timeOffset);

        JsonErrorResponseHandlerV2 errorResponseHandler = SdkJsonProtocolFactory
                .createErrorResponseHandler(jsonErrorUnmarshallers, false);

        return client.execute(request, responseHandler, errorResponseHandler,
                executionContext);
    }

}

redpajama_set_name: RedPajamaGithub


text:
import {
  async,
  fakeAsync,
  inject,
  TestBed,
  tick,
  ComponentFixture,
} from '@angular/core/testing';

import {RioLoginForm} from './index';
import {RioLoginModule} from './login.module';
import {configureTests} from '../../tests.configure';

describe('Component: Login Form', () => {
  let fixture: ComponentFixture<RioLoginForm>;

  beforeEach(done => {
    const configure = (testBed: TestBed) => {
      testBed.configureTestingModule({
        imports: [RioLoginModule],
      });
    };

    configureTests(configure).then(testBed => {
      fixture = testBed.createComponent(RioLoginForm);
      fixture.detectChanges();
      done();
    });
  });

  it('should create the component', fakeAsync(inject([], () => {
    fixture.whenStable().then(() => {
      const element = fixture.nativeElement;
      expect(element.querySelector('#qa-pending-alert')).toBeNull();
      expect(element.querySelector('#qa-alert')).toBeNull();
      expect(element.querySelector('#qa-uname-input')).not.toBeNull();
      expect(element.querySelector('#qa-uname-validation').className)
        .toContain('hide');
      expect(element.querySelector('#qa-password-input')).not.toBeNull();
      expect(element.querySelector('#qa-password-validation').className)
        .toContain('hide');
      expect(element.querySelector('#qa-login-button')).not.toBeNull();
      expect(element.querySelector('#qa-clear-button')).not.toBeNull();
      expect(fixture.componentInstance.login).toBeTruthy();
    });
  })));

  it('should display alert if the form hasError', fakeAsync(inject([], () => {
    fixture.whenStable().then(() => {
      fixture.componentInstance.hasError = true;
      fixture.autoDetectChanges();
      const alert = fixture.nativeElement.querySelector('#qa-alert');
      expect(alert).not.toBeNull();
      expect(alert.innerText).toEqual('Invalid username and password');
    });
  })));

  it('should display alert if the form isPending', fakeAsync(inject([], () => {
    fixture.whenStable().then(() => {
      fixture.componentInstance.isPending = true;
      fixture.detectChanges();
      tick();
      const alert = fixture.nativeElement.querySelector('#qa-pending');
      expect(alert).not.toBeNull();
      expect(alert.innerText).toEqual('Loading...');
    });
  })));

  it('should display name warning for invalid username',
    fakeAsync(inject([], () => {
      fixture.whenStable().then(() => {
        fixture.componentInstance.username = '';
        fixture.detectChanges();
        tick();
        const alert =
          fixture.nativeElement.querySelector('#qa-uname-validation');
        expect(alert).not.toBeNull();
        expect(alert.innerText).toEqual('Username is required.');
      });
    })
  ));

  it('should display password warning for invalid password',
    fakeAsync(inject([], () => {
      fixture.whenStable().then(() => {
        fixture.componentInstance.password = '';
        fixture.detectChanges();
        tick();
        const alert = fixture.nativeElement
          .querySelector('#qa-password-validation');
        expect(alert).not.toBeNull();
        expect(alert.innerText).toEqual('Password is required.');
      });
    })
  ));

  it('should emit an event when the login button is clicked',
    async(inject([], () => {
      fixture.whenStable().then(() => {
        fixture.componentInstance.username = 'user';
        fixture.componentInstance.password = 'pass';
        fixture.detectChanges();

        const button = fixture.nativeElement.querySelector('#qa-login-button');
        button.click();

        fixture.componentInstance.login.subscribe(data => {
          expect(data).toBeDefined();
          expect(data.username).toEqual('user');
          expect(data.password).toEqual('pass');
        });
      });
    }))
  );

  it('should call reset when the clear button is clicked',
    fakeAsync(inject([], () => {
      fixture.whenStable().then(() => {
        fixture.componentInstance.username = 'user';
        fixture.componentInstance.password = 'pass';
        fixture.detectChanges();
        tick();

        expect(fixture.componentInstance.username).toEqual('user');
        expect(fixture.componentInstance.password).toEqual('pass');

        spyOn(fixture.componentInstance, 'onReset').and.callThrough();
        const button = fixture.nativeElement.querySelector('#qa-clear-button');
        button.click();

        fixture.detectChanges();
        tick();

        expect(fixture.componentInstance.onReset).toHaveBeenCalled();
        expect(fixture.componentInstance.username).toBeFalsy();
        expect(fixture.componentInstance.password).toBeFalsy();
      });
    }))
  );
});


text:
  MINI_CHROMIUM_INTERNAL_BUILDFLAG_CAT_INDIRECT(a, b)

#define BUILDFLAG(flag)                  \
  (MINI_CHROMIUM_INTERNAL_BUILDFLAG_CAT( \
      MINI_CHROMIUM_INTERNAL_BUILDFLAG_VALUE_, flag)())

#endif  // BUILD_BUILDFLAG_H_


text:
#ifndef _VKTDRAWSHADERINVOCATIONTESTS_HPP
#define _VKTDRAWSHADERINVOCATIONTESTS_HPP
/*!
 * \file
 * \brief Shader invocations tests
 *//*--------------------------------------------------------------------*/

#include "vktTestCase.hpp"

namespace vkt
{
namespace Draw
{

	tcu::TestCaseGroup* createShaderInvocationTests(tcu::TestContext& testCtx);

} // Draw
} // vkt

#endif // _VKTDRAWSHADERINVOCATIONTESTS_HPP


text:
require 'rubygems'
require 'pp'
require 'jira'
require 'uri'

class Service::Jira < Service::Base
  title "Jira"

  string :project_url, :placeholder => "https://domain.atlassian.net/browse/projectkey",
         :label => 'URL to your Jira project:
' \
                   'This should be your URL after you select your project ' \
                   'under the "Projects" tab.'
  string :username, :placeholder => 'username',
         :label => "These values are encrypted to ensure your security.

" \
                   'Your Jira username:'
  password :password, :placeholder => 'password',
         :label => 'Your Jira password:'

  page "Project", [ :project_url ]
  page "Login Information", [ :username, :password ] # TODO - See comment above, :sync_issues ]

  # Create an issue on Jira
  def receive_issue_impact_change(config, payload)
    url_components = parse_url(config[:project_url])
    client = jira_client(config, url_components[:context_path])

    project = client.Project.find(url_components[:project_key])

    users_text = if payload[:impacted_devices_count] == 1
      'This issue is affecting at least 1 user who has crashed '
    else
      "This issue is affecting at least #{ payload[:impacted_devices_count] } users who have crashed "
    end

    crashes_text = if payload[:crashes_count] == 1
      "at least 1 time.\n\n"
    else
      "at least #{ payload[:crashes_count] } times.\n\n"
    end

    issue_description = "Crashlytics detected a new issue.\n" + \
                 "#{ payload[:title] } in #{ payload[:method] }\n\n" + \
                 users_text + \
                 crashes_text + \
                 "More information: #{ payload[:url] }"

    post_body = { 'fields' => {
      'project' => {'id' => project.id},
      'summary'     => payload[:title] + ' [Crashlytics]',
      'description' => issue_description,
      'issuetype' => {'id' => '1'} } }

    # The Jira client raises an HTTPError if the response is not of the type Net::HTTPSuccess
    issue = client.Issue.build
    if issue.save(post_body)
      { :jira_story_id => issue.id, :jira_story_key => issue.key }
    else
      raise "Jira Issue Create Failed: #{issue.respond_to?(:errors) ? issue.errors : {}}"
    end

  rescue JIRA::HTTPError => e
    raise "Jira Issue Create Failed. Message: #{ e.message }, Status: #{ e.code }, Body: #{ e.response.body }"
  end

  def receive_verification(config, payload)
    url_components = parse_url(config[:project_url])
    client = jira_client(config, url_components[:context_path])

    resp = client.Project.find(url_components[:project_key])
    verification_response = [true,  'Successfully verified Jira settings']

    if config[:sync_issues]
      begin
        register_webhook(client, payload)
      rescue JIRA::HTTPError => e
        log "HTTP Error: webhook request(status: #{ e.code }, message: #{ e.message })"
        verification_response = [true, 'Successfully verified Jira settings but Jira\'s webhook could not be registered. You need to use an Admin account to set it up.']
      end
    end
    verification_response
  rescue JIRA::HTTPError => e
    log "HTTP Error: status code: #{ e.code }, body: #{ e.response.body }"
    [false, 'Oops! Please check your settings again.']
  rescue => e
    log "Rescued a verification error in jira: (url=#{config[:project_url]}) #{e}"
    [false, 'Oops! Is your project url correct?']
  end

  def jira_client(config, context_path)
    url = config[:project_url]
    ssl_enabled = (URI(url).scheme == 'https')
    ssl_verify_mode = ssl_enabled ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
    JIRA::Client.new(
      :username =>     config[:username],
      :password =>     config[:password],
      :site =>         config[:project_url],
      :context_path => context_path,
      :auth_type =>    :basic,
      :use_ssl =>      ssl_enabled,
      :ssl_verify_mode => ssl_verify_mode
    )
  end

  def parse_url(url)
    matches = url.match(/(https?:\/\/.+?)(\/.+)?\/(projects|browse)\/([\w\-]+)/)
    if matches.nil?
      raise "Unexpected URL format"
    end
    { :url_prefix => matches[1], :context_path => matches[2] || '', :project_key => matches[4] }
  end

  private

  def callback_webhook_url(payload)
    "https://www.crashlytics.com/api/v3/projects/#{ payload[:app][:id] }/service_hooks/jira/responses"
  end

  def register_webhook(client, payload)
    new_webhook = callback_webhook_url(payload)

    # Unregister webhooks that look identical to avoid duplicates
    response = client.get('/rest/webhooks/1.0/webhook')
    current_hooks = JSON.parse(response.body)
    current_hooks.each do |hook|
      if hook['url'] == new_webhook
        client.delete(hook['self'])
      end
    end

    webhook_params = {
      'name' => 'Crashlytics Issue sync',
      'url' => new_webhook,
      'events' => ['jira:issue_updated'],
      'excludeIssueDetails' => false }

    client.post('/rest/webhooks/1.0/webhook', webhook_params.to_json)
  end

    JIRA_FIELDS = [
    'assignee',
    'created',
    'creator',
    'description',
    'issuetype',
    'priority',
    'project',
    'reporter',
    'resolution',
    'resolutiondate',
    'status',
    'summary',
    'updated'
  ]

  def format_jira_issue(jira_issue)
    response = {
      'id' => jira_issue.id,
      'key' => jira_issue.key
    }

    JIRA_FIELDS.each do |field|
      response[field] = jira_issue.fields[field]
      if response[field].respond_to? :delete
        response[field].delete 'self'
      end
    end

    if jira_issue.comments.present? && jira_issue.comments.size
      response['comments'] = []
      jira_issue.comments.each do |comment|
        comment.attrs.delete 'self'
        response['comments'] << comment.attrs
      end
    end

    response
  end
end


text:
import collections
import os
import subprocess

import smoke_zephyr.utilities

def get_revision():
	"""
	Retrieve the current git revision identifier. If the git binary can not be
	found or the repository information is unavailable, None will be returned.

	:return: The git revision tag if it's available.
	:rtype: str
	"""
	git_bin = smoke_zephyr.utilities.which('git')
	if not git_bin:
		return None
	proc_h = subprocess.Popen(
		(git_bin, 'rev-parse', 'HEAD'),
		stdout=subprocess.PIPE,
		stderr=subprocess.PIPE,
		close_fds=True,
		cwd=os.path.dirname(os.path.abspath(__file__))
	)
	rev = proc_h.stdout.read().strip()
	proc_h.wait()
	if not len(rev):
		return None
	return rev.decode('utf-8')

revision = get_revision()
"""The git revision identifying the latest commit if available."""

version_info = collections.namedtuple('version_info', ('major', 'minor', 'micro'))(1, 8, 0)
"""A tuple representing the version information in the format ('major', 'minor', 'micro')"""

version_label = 'beta'
"""A version label such as alpha or beta."""

version = "{0}.{1}.{2}".format(version_info.major, version_info.minor, version_info.micro)
"""A string representing the full version information."""

# distutils_version is compatible with distutils.version classes
distutils_version = version
"""A string suitable for being parsed by :py:mod:`distutils.version` classes."""

if version_label:
	version += '-' + version_label
	if revision:
		version += " (rev: {0})".format(revision[:12])
	distutils_version += version_label[0]
	if version_label[-1].isdigit():
		distutils_version += version_label[-1]
	else:
		distutils_version += '0'

rpc_api_version = collections.namedtuple('rpc_api_version', ('major', 'minor'))(5, 5)
"""
A tuple representing the local version of the RPC API for use with compatibility
checks. The major version is incremented when backwards incompatible changes are
made and the minor version is incremented when backwards compatible changes are
made.
"""


text:
import React from 'react';
import { isObject } from 'lodash';
import Loader from '../../components/Loader';
import Button, { Buttons } from '../../components/Button';
import Style from './NewCard.css';

type State = {
  action: () => Promise<*>,
  customerType: string,
  newCustomer: Object
};

type Props = {
  loading: boolean,
  system: Object,
  location: Object,
  newCustomer: Object,
  push: () => void,
  fetchCustomer: () => Promise<*>,
  createCustomer: () => Promise<*>,
  updateCustomer: () => Promise<*>
};

export default class ReviewComponent extends React.Component {

  state: State = {
    newCustomer: this.props.newCustomer,
    action: this.props.createCustomer,
    customerType: this.props.location.query.customerType
  };

  componentDidMount = () => {
    if (this.state.customerType === 'internal') this.fetchCustomer();
  }

  onConfirm = () => {
    this.state.action(this.state.newCustomer)
      .then(() => this.props.fetchCustomer(this.state.newCustomer.rfid))
      .then(() => this.props.push('sales'))
      .catch(() => {
        this.props.push('sales');
      });
  }

  fetchCustomer = () => {
    this.props.fetchCustomer(this.state.newCustomer.username, 'username')
        .then((response) => this.setState({
          action: this.props.updateCustomer,
          newCustomer: {
            ...response.value.json,
            ...this.state.newCustomer
          }
        }))
        .catch(() => {
          this.setState({
            action: this.props.createCustomer
          });
        });
  }

  props: Props;

  render() {
    const { loading, push } = this.props;
    const additionalFields = this.state.action === this.props.createCustomer ? [] : ['balance', 'customerRole'];

    if (loading) {
      return <Loader />;
    }

    return (

        {
          ['displayName', 'rfid', 'username', ...additionalFields].map((field) => {
            if (!isObject(this.state.newCustomer[field])) {
              return (

                  {field}
                  {this.state.newCustomer[field]}

              );
            }
            return (

                {field}
                {this.state.newCustomer[field].role}

            );
          })
        }

        {this.state.action === this.props.createCustomer &&

            Balance
            0 kr

        }

        {this.state.action === this.props.createCustomer &&

            Customer Role
            {this.props.system.get('defaultCustomerRole').get('role')}

        }

          <Buttons>
            <Button onClick={() => { this.props.push(`new/info?customerType=${this.state.customerType}`); }} label='Back' />
            <Button cancel onClick={() => { push('sales'); }} label='Cancel' />
            <Button
              confirm
              loading={loading}
              onClick={this.onConfirm}
              label={this.state.action === this.props.createCustomer ? 'Create' : 'Update'}
            />
          </Buttons>

    );
  }
}


text:
from datetime import datetime
import encodings
import json
from os.path import expanduser
import re

import oursql

from .user import User
from .util import to_wiki_format
from .wikidata import Wikidata
from .wikiproject import WikiProject

__all__ = ["Bot"]

class Bot:
    """Represents an instance of the Reports bot on a particular wiki.

    An instance of this class is accessible from all tasks as their '_bot'
    attribute, and is their primary way of interacting with the external world.
    It provides access to databases and structured representations of many
    objects like WikiProjects and users.
    """

    def __init__(self, config, project, lang):
        self._config = config
        self._project = project
        self._lang = lang

        self._site = None
        self._wikidb = None
        self._localdb = None
        self._wikidata = None
        self._project_config = None

    @staticmethod
    def _register_utf8mb4():
        """Install utf8mb4 as a valid alias for utf_8."""
        if "utf8mb4" not in encodings.aliases.aliases:
            encodings.aliases.aliases["utf8mb4"] = "utf_8"
        if hasattr(encodings, "_cache") and "utf8mb4" in encodings._cache:
            del encodings._cache["utf8mb4"]

    def _sql_connect(self, **kwargs):
        """Return a new SQL connection using the given arguments.

        We apply some transformations: a default file is configured if not
        username or password is provided, a default charset is set, and
        autocommit is turned off.

        The default charset really should be utf8mb4, but because of a bug in
        oursql's handling of charsets (conflating Python codecs with MySQL
        charsets, which are sometimes different), we cannot. Instead, if
        utf8mb4 is chosen, we'll install it as an alias first.
        """
        if ("read_default_file" not in kwargs and "user" not in kwargs
                and "password" not in kwargs):
            kwargs["read_default_file"] = expanduser("~/.my.cnf")
        if "charset" not in kwargs:
            kwargs["charset"] = "utf8mb4"
        if "autoping" not in kwargs:
            kwargs["autoping"] = True
        if "autoreconnect" not in kwargs:
            kwargs["autoreconnect"] = True

        if kwargs["charset"] == "utf8mb4":
            self._register_utf8mb4()

        return oursql.connect(**kwargs)

    def _load_project_config(self):
        """Load the project config JSON blob from the database.

        After calling this function, the config is available from and cached in
        self._project_config.
        """
        if self._project_config is not None:
            return

        query = "SELECT config_json FROM project_config WHERE config_site = ?"
        with self.localdb as cursor:
            cursor.execute(query, (self.wikiid,))
            results = cursor.fetchall()
            if not results:
                self._project_config = {"defaults": {}, "projects": {}}
                return
            raw = json.loads(results[0][0])

        config = {"defaults": raw["defaults"], "projects": {}}
        for project in raw["projects"]:
            config["projects"][project["name"]] = project
        self._project_config = config

    def _get_project_config(self, name):
        """Return the on-wiki JSON configuration for the given project.

        Default values are automatically resolved. If the project doesn't
        exist, None is returned.
        """
        self._load_project_config()

        name = to_wiki_format(self.site, name)
        if name not in self._project_config["projects"]:
            return None

        config = self._project_config["defaults"].copy()
        config.update(self._project_config["projects"][name])
        return config

    @property
    def config(self):
        """Return the bot's Config object."""
        return self._config

    @property
    def wikiid(self):
        """Return the site's ID; e.g. "enwiki" from "en" and "wikipedia"."""
        # TODO: This is somewhat hacky; should really be using the API here...
        if self._project == "wikipedia":
            res = self._lang + "wiki"
        else:
            res = self._lang + self._project
        return re.sub(r"[^a-zA-Z0-9_-]", "", res).replace("-", "_")

    @property
    def site(self):
        """Return a Pywikibot Site instance."""
        import pywikibot
        if not self._site:
            self._site = pywikibot.Site(self._lang, self._project,
                                        self._config.username)
        return self._site

    @property
    def wikidb(self):
        """Return a connection to the wiki replica SQL database."""
        if not self._wikidb:
            kwargs = self._config.get_wiki_sql(self.wikiid)
            self._wikidb = self._sql_connect(**kwargs)
        return self._wikidb

    @property
    def localdb(self):
        """Return a connection to the local Reports bot/WPX SQL database."""
        if not self._localdb:
            self._localdb = self._sql_connect(**self._config.get_local_sql())
        return self._localdb

    @property
    def wikidata(self):
        """Return an interface to Wikidata."""
        if not self._wikidata:
            sql_kwargs = self._config.get_wiki_sql("wikidatawiki")
            sql_conn = self._sql_connect(**sql_kwargs)
            self._wikidata = Wikidata(self.site, sql_conn)
        return self._wikidata

    def get_page(self, title):
        """Return a Pywikibot Page instance for the given page."""
        import pywikibot
        return pywikibot.Page(self.site, title)

    def get_project(self, name):
        """Return a WikiProject object corresponding to the given name.

        The name is the page title of the project's base page, including the
        namespace.
        """
        return WikiProject(self, name, self._get_project_config(name))

    def get_user(self, name):
        """Return a User object corresponding to the given username."""
        return User(self, name)

    def get_configured_projects(self):
        """Return a list of all WikiProjects that are configured."""
        self._load_project_config()
        projects = self._project_config["projects"]
        return [self.get_project(name) for name in projects]

    def get_last_updated(self, key):
        """Get the last update timestamp for the given key."""
        query = """SELECT lu_timestamp
            FROM last_update
            WHERE lu_site = ? AND lu_key = ?"""

        with self.localdb as cursor:
            cursor.execute(query, (self.wikiid, key))
            results = cursor.fetchall()

        if results:
            return results[0][0]
        return datetime.min

    def set_last_updated(self, key, timestamp=None):
        """Set the last update timestamp for the given key."""
        query = """INSERT INTO last_update (lu_site, lu_key, lu_timestamp)
            VALUES(?, ?, ?)
            ON DUPLICATE KEY UPDATE lu_timestamp = ?"""

        if not timestamp:
            timestamp = datetime.utcnow()

        with self.localdb as cursor:
            cursor.execute(query, (self.wikiid, key, timestamp, timestamp))


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace GoogleOpenIdSSO
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            log4net.Config.XmlConfigurator.Configure();
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends.
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer
            // or SQLServer, the event is not raised.

        }

    }
}


text:
FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );

#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <byteswap.h>
#include <ipxe/netdevice.h>
#include <ipxe/ethernet.h>
#include <ipxe/if_ether.h>
#include <ipxe/iobuf.h>
#include <ipxe/malloc.h>
#include <ipxe/pci.h>
#include "intelx.h"

/** @file
 *
 * Intel 10 Gigabit Ethernet network card driver
 *
 */

/******************************************************************************
 *
 * MAC address
 *
 ******************************************************************************
 */

/**
 * Try to fetch initial MAC address
 *
 * @v intel		Intel device
 * @v ral0		RAL0 register address
 * @v hw_addr		Hardware address to fill in
 * @ret rc		Return status code
 */
static int intelx_try_fetch_mac ( struct intel_nic *intel, unsigned int ral0,
				  uint8_t *hw_addr ) {
	union intel_receive_address mac;

	/* Read current address from RAL0/RAH0 */
	mac.reg.low = cpu_to_le32 ( readl ( intel->regs + ral0 ) );
	mac.reg.high = cpu_to_le32 ( readl ( intel->regs + ral0 +
					     ( INTELX_RAH0 - INTELX_RAL0 ) ) );

	/* Use current address if valid */
	if ( is_valid_ether_addr ( mac.raw ) ) {
		DBGC ( intel, "INTEL %p has autoloaded MAC address %s at "
		       "%#05x\n", intel, eth_ntoa ( mac.raw ), ral0 );
		memcpy ( hw_addr, mac.raw, ETH_ALEN );
		return 0;
	}

	return -ENOENT;
}

/**
 * Fetch initial MAC address
 *
 * @v intel		Intel device
 * @v hw_addr		Hardware address to fill in
 * @ret rc		Return status code
 */
static int intelx_fetch_mac ( struct intel_nic *intel, uint8_t *hw_addr ) {
	int rc;

	/* Try to fetch address from INTELX_RAL0 */
	if ( ( rc = intelx_try_fetch_mac ( intel, INTELX_RAL0,
					   hw_addr ) ) == 0 ) {
		return 0;
	}

	/* Try to fetch address from INTELX_RAL0_ALT */
	if ( ( rc = intelx_try_fetch_mac ( intel, INTELX_RAL0_ALT,
					   hw_addr ) ) == 0 ) {
		return 0;
	}

	DBGC ( intel, "INTEL %p has no MAC address to use\n", intel );
	return -ENOENT;
}

/******************************************************************************
 *
 * Device reset
 *
 ******************************************************************************
 */

/**
 * Reset hardware
 *
 * @v intel		Intel device
 * @ret rc		Return status code
 */
static int intelx_reset ( struct intel_nic *intel ) {
	uint32_t ctrl;

	/* Perform a global software reset */
	ctrl = readl ( intel->regs + INTELX_CTRL );
	writel ( ( ctrl | INTELX_CTRL_RST | INTELX_CTRL_LRST ),
		 intel->regs + INTELX_CTRL );
	mdelay ( INTELX_RESET_DELAY_MS );

	DBGC ( intel, "INTEL %p reset (ctrl %08x)\n", intel, ctrl );
	return 0;
}

/******************************************************************************
 *
 * Link state
 *
 ******************************************************************************
 */

/**
 * Check link state
 *
 * @v netdev		Network device
 */
static void intelx_check_link ( struct net_device *netdev ) {
	struct intel_nic *intel = netdev->priv;
	uint32_t links;

	/* Read link status */
	links = readl ( intel->regs + INTELX_LINKS );
	DBGC ( intel, "INTEL %p link status is %08x\n", intel, links );

	/* Update network device */
	if ( links & INTELX_LINKS_UP ) {
		netdev_link_up ( netdev );
	} else {
		netdev_link_down ( netdev );
	}
}

/******************************************************************************
 *
 * Network device interface
 *
 ******************************************************************************
 */

/**
 * Open network device
 *
 * @v netdev		Network device
 * @ret rc		Return status code
 */
static int intelx_open ( struct net_device *netdev ) {
	struct intel_nic *intel = netdev->priv;
	union intel_receive_address mac;
	uint32_t ral0;
	uint32_t rah0;
	uint32_t dmatxctl;
	uint32_t fctrl;
	uint32_t srrctl;
	uint32_t hlreg0;
	uint32_t maxfrs;
	uint32_t rdrxctl;
	uint32_t rxctrl;
	uint32_t dca_rxctrl;
	int rc;

	/* Create transmit descriptor ring */
	if ( ( rc = intel_create_ring ( intel, &intel->tx ) ) != 0 )
		goto err_create_tx;

	/* Create receive descriptor ring */
	if ( ( rc = intel_create_ring ( intel, &intel->rx ) ) != 0 )
		goto err_create_rx;

	/* Program MAC address */
	memset ( &mac, 0, sizeof ( mac ) );
	memcpy ( mac.raw, netdev->ll_addr, sizeof ( mac.raw ) );
	ral0 = le32_to_cpu ( mac.reg.low );
	rah0 = ( le32_to_cpu ( mac.reg.high ) | INTELX_RAH0_AV );
	writel ( ral0, intel->regs + INTELX_RAL0 );
	writel ( rah0, intel->regs + INTELX_RAH0 );
	writel ( ral0, intel->regs + INTELX_RAL0_ALT );
	writel ( rah0, intel->regs + INTELX_RAH0_ALT );

	/* Allocate interrupt vectors */
	writel ( ( INTELX_IVAR_RX0_DEFAULT | INTELX_IVAR_RX0_VALID |
		   INTELX_IVAR_TX0_DEFAULT | INTELX_IVAR_TX0_VALID ),
		 intel->regs + INTELX_IVAR );

	/* Enable transmitter  */
	dmatxctl = readl ( intel->regs + INTELX_DMATXCTL );
	dmatxctl |= INTELX_DMATXCTL_TE;
	writel ( dmatxctl, intel->regs + INTELX_DMATXCTL );

	/* Configure receive filter */
	fctrl = readl ( intel->regs + INTELX_FCTRL );
	fctrl |= ( INTELX_FCTRL_BAM | INTELX_FCTRL_UPE | INTELX_FCTRL_MPE );
	writel ( fctrl, intel->regs + INTELX_FCTRL );

	/* Configure receive buffer sizes */
	srrctl = readl ( intel->regs + INTELX_SRRCTL );
	srrctl &= ~INTELX_SRRCTL_BSIZE_MASK;
	srrctl |= INTELX_SRRCTL_BSIZE_DEFAULT;
	writel ( srrctl, intel->regs + INTELX_SRRCTL );

	/* Configure jumbo frames.  Required to allow the extra 4-byte
	 * headroom for VLANs, since we don't use the hardware's
	 * native VLAN offload.
	 */
	hlreg0 = readl ( intel->regs + INTELX_HLREG0 );
	hlreg0 |= INTELX_HLREG0_JUMBOEN;
	writel ( hlreg0, intel->regs + INTELX_HLREG0 );

	/* Configure frame size */
	maxfrs = readl ( intel->regs + INTELX_MAXFRS );
	maxfrs &= ~INTELX_MAXFRS_MFS_MASK;
	maxfrs |= INTELX_MAXFRS_MFS_DEFAULT;
	writel ( maxfrs, intel->regs + INTELX_MAXFRS );

	/* Configure receive DMA */
	rdrxctl = readl ( intel->regs + INTELX_RDRXCTL );
	rdrxctl |= INTELX_RDRXCTL_SECRC;
	writel ( rdrxctl, intel->regs + INTELX_RDRXCTL );

	/* Clear "must-be-zero" bit for direct cache access (DCA).  We
	 * leave DCA disabled anyway, but if we do not clear this bit
	 * then the received packets contain garbage data.
	 */
	dca_rxctrl = readl ( intel->regs + INTELX_DCA_RXCTRL );
	dca_rxctrl &= ~INTELX_DCA_RXCTRL_MUST_BE_ZERO;
	writel ( dca_rxctrl, intel->regs + INTELX_DCA_RXCTRL );

	/* Enable receiver */
	rxctrl = readl ( intel->regs + INTELX_RXCTRL );
	rxctrl |= INTELX_RXCTRL_RXEN;
	writel ( rxctrl, intel->regs + INTELX_RXCTRL );

	/* Fill receive ring */
	intel_refill_rx ( intel );

	/* Update link state */
	intelx_check_link ( netdev );

	return 0;

	intel_destroy_ring ( intel, &intel->rx );
 err_create_rx:
	intel_destroy_ring ( intel, &intel->tx );
 err_create_tx:
	return rc;
}

/**
 * Close network device
 *
 * @v netdev		Network device
 */
static void intelx_close ( struct net_device *netdev ) {
	struct intel_nic *intel = netdev->priv;
	uint32_t rxctrl;
	uint32_t dmatxctl;

	/* Disable receiver */
	rxctrl = readl ( intel->regs + INTELX_RXCTRL );
	rxctrl &= ~INTELX_RXCTRL_RXEN;
	writel ( rxctrl, intel->regs + INTELX_RXCTRL );

	/* Disable transmitter  */
	dmatxctl = readl ( intel->regs + INTELX_DMATXCTL );
	dmatxctl &= ~INTELX_DMATXCTL_TE;
	writel ( dmatxctl, intel->regs + INTELX_DMATXCTL );

	/* Destroy receive descriptor ring */
	intel_destroy_ring ( intel, &intel->rx );

	/* Discard any unused receive buffers */
	intel_empty_rx ( intel );

	/* Destroy transmit descriptor ring */
	intel_destroy_ring ( intel, &intel->tx );

	/* Reset the NIC, to flush the transmit and receive FIFOs */
	intelx_reset ( intel );
}

/**
 * Poll for completed and received packets
 *
 * @v netdev		Network device
 */
static void intelx_poll ( struct net_device *netdev ) {
	struct intel_nic *intel = netdev->priv;
	uint32_t eicr;

	/* Check for and acknowledge interrupts */
	eicr = readl ( intel->regs + INTELX_EICR );
	if ( ! eicr )
		return;

	/* Poll for TX completions, if applicable */
	if ( eicr & INTELX_EIRQ_TX0 )
		intel_poll_tx ( netdev );

	/* Poll for RX completions, if applicable */
	if ( eicr & ( INTELX_EIRQ_RX0 | INTELX_EIRQ_RXO ) )
		intel_poll_rx ( netdev );

	/* Report receive overruns */
	if ( eicr & INTELX_EIRQ_RXO )
		netdev_rx_err ( netdev, NULL, -ENOBUFS );

	/* Check link state, if applicable */
	if ( eicr & INTELX_EIRQ_LSC )
		intelx_check_link ( netdev );

	/* Refill RX ring */
	intel_refill_rx ( intel );
}

/**
 * Enable or disable interrupts
 *
 * @v netdev		Network device
 * @v enable		Interrupts should be enabled
 */
static void intelx_irq ( struct net_device *netdev, int enable ) {
	struct intel_nic *intel = netdev->priv;
	uint32_t mask;

	mask = ( INTELX_EIRQ_LSC | INTELX_EIRQ_RXO | INTELX_EIRQ_TX0 |
		 INTELX_EIRQ_RX0 );
	if ( enable ) {
		writel ( mask, intel->regs + INTELX_EIMS );
	} else {
		writel ( mask, intel->regs + INTELX_EIMC );
	}
}

/** Network device operations */
static struct net_device_operations intelx_operations = {
	.open		= intelx_open,
	.close		= intelx_close,
	.transmit	= intel_transmit,
	.poll		= intelx_poll,
	.irq		= intelx_irq,
};

/******************************************************************************
 *
 * PCI interface
 *
 ******************************************************************************
 */

/**
 * Probe PCI device
 *
 * @v pci		PCI device
 * @ret rc		Return status code
 */
static int intelx_probe ( struct pci_device *pci ) {
	struct net_device *netdev;
	struct intel_nic *intel;
	int rc;

	/* Allocate and initialise net device */
	netdev = alloc_etherdev ( sizeof ( *intel ) );
	if ( ! netdev ) {
		rc = -ENOMEM;
		goto err_alloc;
	}
	netdev_init ( netdev, &intelx_operations );
	intel = netdev->priv;
	pci_set_drvdata ( pci, netdev );
	netdev->dev = &pci->dev;
	memset ( intel, 0, sizeof ( *intel ) );
	intel->port = PCI_FUNC ( pci->busdevfn );
	intel_init_ring ( &intel->tx, INTEL_NUM_TX_DESC, INTELX_TD,
			  intel_describe_tx );
	intel_init_ring ( &intel->rx, INTEL_NUM_RX_DESC, INTELX_RD,
			  intel_describe_rx );

	/* Fix up PCI device */
	adjust_pci_device ( pci );

	/* Map registers */
	intel->regs = ioremap ( pci->membase, INTEL_BAR_SIZE );
	if ( ! intel->regs ) {
		rc = -ENODEV;
		goto err_ioremap;
	}

	/* Reset the NIC */
	if ( ( rc = intelx_reset ( intel ) ) != 0 )
		goto err_reset;

	/* Fetch MAC address */
	if ( ( rc = intelx_fetch_mac ( intel, netdev->hw_addr ) ) != 0 )
		goto err_fetch_mac;

	/* Register network device */
	if ( ( rc = register_netdev ( netdev ) ) != 0 )
		goto err_register_netdev;

	/* Set initial link state */
	intelx_check_link ( netdev );

	return 0;

	unregister_netdev ( netdev );
 err_register_netdev:
 err_fetch_mac:
	intelx_reset ( intel );
 err_reset:
	iounmap ( intel->regs );
 err_ioremap:
	netdev_nullify ( netdev );
	netdev_put ( netdev );
 err_alloc:
	return rc;
}

/**
 * Remove PCI device
 *
 * @v pci		PCI device
 */
static void intelx_remove ( struct pci_device *pci ) {
	struct net_device *netdev = pci_get_drvdata ( pci );
	struct intel_nic *intel = netdev->priv;

	/* Unregister network device */
	unregister_netdev ( netdev );

	/* Reset the NIC */
	intelx_reset ( intel );

	/* Free network device */
	iounmap ( intel->regs );
	netdev_nullify ( netdev );
	netdev_put ( netdev );
}

/** PCI device IDs */
static struct pci_device_id intelx_nics[] = {
	PCI_ROM ( 0x8086, 0x10f7, "82599-kx4", "82599 (KX/KX4)", 0 ),
	PCI_ROM ( 0x8086, 0x10f8, "82599-combo-backplane", "82599 (combined backplane; KR/KX4/KX)", 0 ),
	PCI_ROM ( 0x8086, 0x10f9, "82599-cx4", "82599 (CX4)", 0 ),
	PCI_ROM ( 0x8086, 0x10fb, "82599-sfp", "82599 (SFI/SFP+)", 0 ),
	PCI_ROM ( 0x8086, 0x10fc, "82599-xaui", "82599 (XAUI/BX4)", 0 ),
	PCI_ROM ( 0x8086, 0x1528, "x540t", "X540-AT2/X540-BT2", 0 ),
	PCI_ROM ( 0x8086, 0x154d, "82599-sfp-sf2", "82599 (SFI/SFP+)", 0 ),
	PCI_ROM ( 0x8086, 0x1557, "82599en-sfp", "82599 (Single Port SFI Only)", 0 ),
	PCI_ROM ( 0x8086, 0x1560, "x540t1", "X540-AT2/X540-BT2 (with single port NVM)", 0 ),
	PCI_ROM ( 0x8086, 0x1563, "x550t2", "X550-T2", 0 ),
};

/** PCI driver */
struct pci_driver intelx_driver __pci_driver = {
	.ids = intelx_nics,
	.id_count = ( sizeof ( intelx_nics ) / sizeof ( intelx_nics[0] ) ),
	.probe = intelx_probe,
	.remove = intelx_remove,
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.googlecode.jmxtrans.model.output (jmxlogger javadoc)</title>
<meta name="date" content="2013-08-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.googlecode.jmxtrans.model.output

Class Summary

Class
Description

DailyKeyOutWriter

This class is derived from KeyOutWriter.

GangliaWriter

OutputWriter for Ganglia.

GraphiteWriter

This low latency and thread save output writer sends data to a host/port combination
 in the Graphite format.

KeyOutWriter

Writes out data in the same format as the GraphiteWriter, except to a file
 and tab delimited.

NagiosWriter

Writes out data in Nagios format to a file, it should be used with Nagios external command file.

RRDToolWriter

This takes a JRobin template.xml file and then creates the database if it
 doesn't already exist.

RRDWriter

This takes a JRobin template.xml file and then creates the database if it
 doesn't already exist.

StackdriverWriter

Stackdriver implementation of the
 OutputWriter.

StatsDWriter

This output writer sends data to a host/port combination in the StatsD
 format.

StdOutWriter

Basic filter good for testing that just outputs the Result objects using
 System.out.

VelocityWriter

This class isn't finished yet.

Enum Summary

Enum
Description

GraphiteWriterStatus

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

			Copyright © 2013 Jon Stevens and a gang of pencils. All Rights Reserved. Build version: 20130828-162948-517c4427f5


text:
module Holidays
  # This file is generated by the Ruby Holidays gem.
  #
  # Definitions loaded: definitions/federal_reserve.yaml
  #
  # All the definitions are available at https://github.com/holidays/holidays
  module FEDERAL_RESERVE # :nodoc:
    def self.defined_regions
      [:federal_reserve]
    end

    def self.holidays_by_month
      {
              1 => [{:mday => 1, :observed => "to_monday_if_sunday(date)", :observed_arguments => [:date], :name => "New Year's Day", :regions => [:federal_reserve]},
            {:wday => 1, :week => 3, :name => "Birthday of Martin Luther King, Jr", :regions => [:federal_reserve]}],
      2 => [{:wday => 1, :week => 3, :name => "Washington's Birthday", :regions => [:federal_reserve]}],
      5 => [{:wday => 1, :week => -1, :name => "Memorial Day", :regions => [:federal_reserve]}],
      7 => [{:mday => 4, :observed => "to_monday_if_sunday(date)", :observed_arguments => [:date], :name => "Independence Day", :regions => [:federal_reserve]}],
      9 => [{:wday => 1, :week => 1, :name => "Labor Day", :regions => [:federal_reserve]}],
      10 => [{:wday => 1, :week => 2, :name => "Columbus Day", :regions => [:federal_reserve]}],
      11 => [{:mday => 11, :observed => "to_monday_if_sunday(date)", :observed_arguments => [:date], :name => "Veterans Day", :regions => [:federal_reserve]},
            {:wday => 4, :week => 4, :name => "Thanksgiving Day", :regions => [:federal_reserve]}],
      12 => [{:mday => 25, :observed => "to_monday_if_sunday(date)", :observed_arguments => [:date], :name => "Christmas Day", :regions => [:federal_reserve]}]
      }
    end

    def self.custom_methods
      {

      }
    end
  end
end


text: module.exports = require('./lib/<%= name %>');