text:
package com.google.cloud.dialogflow.cx.v3beta1;

import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.paging.AbstractFixedSizeCollection;
import com.google.api.gax.paging.AbstractPage;
import com.google.api.gax.paging.AbstractPagedListResponse;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.dialogflow.cx.v3beta1.stub.ChangelogsStub;
import com.google.cloud.dialogflow.cx.v3beta1.stub.ChangelogsStubSettings;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * Service Description: Service for managing
 * [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog].
 *
 *
This class provides the ability to make remote calls to the backing service through method
 * calls that map to API methods. Sample code to get started:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
 *   ChangelogName name = ChangelogName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[CHANGELOG]");
 *   Changelog response = changelogsClient.getChangelog(name);
 * }
 * }

 *
 *
Note: close() needs to be called on the ChangelogsClient object to clean up resources such as
 * threads. In the example above, try-with-resources is used, which automatically calls close().
 *
 *
The surface of this class includes several types of Java methods for each of the API's
 * methods:
 *
 *

 *
A "flattened" method. With this type of method, the fields of the request type have been
 *       converted into function parameters. It may be the case that not all fields are available as
 *       parameters, and not every API method will have a flattened method entry point.
 *
A "request object" method. This type of method only takes one parameter, a request object,
 *       which must be constructed before the call. Not every API method will have a request object
 *       method.
 *
A "callable" method. This type of method takes no parameters and returns an immutable API
 *       callable object, which can be used to initiate calls to the service.
 *

 *
 *
See the individual methods for example code.
 *
 *
Many parameters require resource names to be formatted in a particular way. To assist with
 * these names, this class includes a format method for each type of name, and additionally a parse
 * method to extract the individual identifiers contained within names that are returned.
 *
 *
This class can be customized by passing in a custom instance of ChangelogsSettings to
 * create(). For example:
 *
 *
To customize credentials:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * ChangelogsSettings changelogsSettings =
 *     ChangelogsSettings.newBuilder()
 *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
 *         .build();
 * ChangelogsClient changelogsClient = ChangelogsClient.create(changelogsSettings);
 * }

 *
 *
To customize the endpoint:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * ChangelogsSettings changelogsSettings =
 *     ChangelogsSettings.newBuilder().setEndpoint(myEndpoint).build();
 * ChangelogsClient changelogsClient = ChangelogsClient.create(changelogsSettings);
 * }

 *
 *
To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over
 * the wire:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * ChangelogsSettings changelogsSettings =
 *     ChangelogsSettings.newBuilder()
 *         .setTransportChannelProvider(
 *             ChangelogsSettings.defaultHttpJsonTransportProviderBuilder().build())
 *         .build();
 * ChangelogsClient changelogsClient = ChangelogsClient.create(changelogsSettings);
 * }

 *
 *
Please refer to the GitHub repository's samples for more quickstart code snippets.
 */
@BetaApi
@Generated("by gapic-generator-java")
public class ChangelogsClient implements BackgroundResource {
  private final ChangelogsSettings settings;
  private final ChangelogsStub stub;

  /** Constructs an instance of ChangelogsClient with default settings. */
  public static final ChangelogsClient create() throws IOException {
    return create(ChangelogsSettings.newBuilder().build());
  }

  /**
   * Constructs an instance of ChangelogsClient, using the given settings. The channels are created
   * based on the settings passed in, or defaults for any settings that are not set.
   */
  public static final ChangelogsClient create(ChangelogsSettings settings) throws IOException {
    return new ChangelogsClient(settings);
  }

  /**
   * Constructs an instance of ChangelogsClient, using the given stub for making calls. This is for
   * advanced usage - prefer using create(ChangelogsSettings).
   */
  public static final ChangelogsClient create(ChangelogsStub stub) {
    return new ChangelogsClient(stub);
  }

  /**
   * Constructs an instance of ChangelogsClient, using the given settings. This is protected so that
   * it is easy to make a subclass, but otherwise, the static factory methods should be preferred.
   */
  protected ChangelogsClient(ChangelogsSettings settings) throws IOException {
    this.settings = settings;
    this.stub = ((ChangelogsStubSettings) settings.getStubSettings()).createStub();
  }

  protected ChangelogsClient(ChangelogsStub stub) {
    this.settings = null;
    this.stub = stub;
  }

  public final ChangelogsSettings getSettings() {
    return settings;
  }

  public ChangelogsStub getStub() {
    return stub;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the list of Changelogs.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   AgentName parent = AgentName.of("[PROJECT]", "[LOCATION]", "[AGENT]");
   *   for (Changelog element : changelogsClient.listChangelogs(parent).iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   *
   * @param parent Required. The agent containing the changelogs. Format: `projects/<Project
   *     ID>/locations/<Location ID>/agents/<Agent ID>`.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ListChangelogsPagedResponse listChangelogs(AgentName parent) {
    ListChangelogsRequest request =
        ListChangelogsRequest.newBuilder()
            .setParent(parent == null ? null : parent.toString())
            .build();
    return listChangelogs(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the list of Changelogs.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   String parent = AgentName.of("[PROJECT]", "[LOCATION]", "[AGENT]").toString();
   *   for (Changelog element : changelogsClient.listChangelogs(parent).iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   *
   * @param parent Required. The agent containing the changelogs. Format: `projects/<Project
   *     ID>/locations/<Location ID>/agents/<Agent ID>`.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ListChangelogsPagedResponse listChangelogs(String parent) {
    ListChangelogsRequest request = ListChangelogsRequest.newBuilder().setParent(parent).build();
    return listChangelogs(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the list of Changelogs.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ListChangelogsRequest request =
   *       ListChangelogsRequest.newBuilder()
   *           .setParent(AgentName.of("[PROJECT]", "[LOCATION]", "[AGENT]").toString())
   *           .setFilter("filter-1274492040")
   *           .setPageSize(883849137)
   *           .setPageToken("pageToken873572522")
   *           .build();
   *   for (Changelog element : changelogsClient.listChangelogs(request).iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ListChangelogsPagedResponse listChangelogs(ListChangelogsRequest request) {
    return listChangelogsPagedCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the list of Changelogs.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ListChangelogsRequest request =
   *       ListChangelogsRequest.newBuilder()
   *           .setParent(AgentName.of("[PROJECT]", "[LOCATION]", "[AGENT]").toString())
   *           .setFilter("filter-1274492040")
   *           .setPageSize(883849137)
   *           .setPageToken("pageToken873572522")
   *           .build();
   *   ApiFuture<Changelog> future =
   *       changelogsClient.listChangelogsPagedCallable().futureCall(request);
   *   // Do something.
   *   for (Changelog element : future.get().iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   */
  public final UnaryCallable<ListChangelogsRequest, ListChangelogsPagedResponse>
      listChangelogsPagedCallable() {
    return stub.listChangelogsPagedCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the list of Changelogs.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ListChangelogsRequest request =
   *       ListChangelogsRequest.newBuilder()
   *           .setParent(AgentName.of("[PROJECT]", "[LOCATION]", "[AGENT]").toString())
   *           .setFilter("filter-1274492040")
   *           .setPageSize(883849137)
   *           .setPageToken("pageToken873572522")
   *           .build();
   *   while (true) {
   *     ListChangelogsResponse response = changelogsClient.listChangelogsCallable().call(request);
   *     for (Changelog element : response.getChangelogsList()) {
   *       // doThingsWith(element);
   *     }
   *     String nextPageToken = response.getNextPageToken();
   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
   *       request = request.toBuilder().setPageToken(nextPageToken).build();
   *     } else {
   *       break;
   *     }
   *   }
   * }
   * }

   */
  public final UnaryCallable<ListChangelogsRequest, ListChangelogsResponse>
      listChangelogsCallable() {
    return stub.listChangelogsCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Retrieves the specified Changelog.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ChangelogName name = ChangelogName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[CHANGELOG]");
   *   Changelog response = changelogsClient.getChangelog(name);
   * }
   * }

   *
   * @param name Required. The name of the changelog to get. Format: `projects/<Project
   *     ID>/locations/<Location ID>/agents/<Agent ID>/changelogs/<Changelog
   *     ID>`.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final Changelog getChangelog(ChangelogName name) {
    GetChangelogRequest request =
        GetChangelogRequest.newBuilder().setName(name == null ? null : name.toString()).build();
    return getChangelog(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Retrieves the specified Changelog.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   String name =
   *       ChangelogName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[CHANGELOG]").toString();
   *   Changelog response = changelogsClient.getChangelog(name);
   * }
   * }

   *
   * @param name Required. The name of the changelog to get. Format: `projects/<Project
   *     ID>/locations/<Location ID>/agents/<Agent ID>/changelogs/<Changelog
   *     ID>`.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final Changelog getChangelog(String name) {
    GetChangelogRequest request = GetChangelogRequest.newBuilder().setName(name).build();
    return getChangelog(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Retrieves the specified Changelog.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   GetChangelogRequest request =
   *       GetChangelogRequest.newBuilder()
   *           .setName(
   *               ChangelogName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[CHANGELOG]").toString())
   *           .build();
   *   Changelog response = changelogsClient.getChangelog(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final Changelog getChangelog(GetChangelogRequest request) {
    return getChangelogCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Retrieves the specified Changelog.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   GetChangelogRequest request =
   *       GetChangelogRequest.newBuilder()
   *           .setName(
   *               ChangelogName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[CHANGELOG]").toString())
   *           .build();
   *   ApiFuture<Changelog> future = changelogsClient.getChangelogCallable().futureCall(request);
   *   // Do something.
   *   Changelog response = future.get();
   * }
   * }

   */
  public final UnaryCallable<GetChangelogRequest, Changelog> getChangelogCallable() {
    return stub.getChangelogCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Lists information about the supported locations for this service.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ListLocationsRequest request =
   *       ListLocationsRequest.newBuilder()
   *           .setName("name3373707")
   *           .setFilter("filter-1274492040")
   *           .setPageSize(883849137)
   *           .setPageToken("pageToken873572522")
   *           .build();
   *   for (Location element : changelogsClient.listLocations(request).iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ListLocationsPagedResponse listLocations(ListLocationsRequest request) {
    return listLocationsPagedCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Lists information about the supported locations for this service.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ListLocationsRequest request =
   *       ListLocationsRequest.newBuilder()
   *           .setName("name3373707")
   *           .setFilter("filter-1274492040")
   *           .setPageSize(883849137)
   *           .setPageToken("pageToken873572522")
   *           .build();
   *   ApiFuture<Location> future =
   *       changelogsClient.listLocationsPagedCallable().futureCall(request);
   *   // Do something.
   *   for (Location element : future.get().iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   */
  public final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
      listLocationsPagedCallable() {
    return stub.listLocationsPagedCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Lists information about the supported locations for this service.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   ListLocationsRequest request =
   *       ListLocationsRequest.newBuilder()
   *           .setName("name3373707")
   *           .setFilter("filter-1274492040")
   *           .setPageSize(883849137)
   *           .setPageToken("pageToken873572522")
   *           .build();
   *   while (true) {
   *     ListLocationsResponse response = changelogsClient.listLocationsCallable().call(request);
   *     for (Location element : response.getLocationsList()) {
   *       // doThingsWith(element);
   *     }
   *     String nextPageToken = response.getNextPageToken();
   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
   *       request = request.toBuilder().setPageToken(nextPageToken).build();
   *     } else {
   *       break;
   *     }
   *   }
   * }
   * }

   */
  public final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() {
    return stub.listLocationsCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Gets information about a location.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
   *   Location response = changelogsClient.getLocation(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final Location getLocation(GetLocationRequest request) {
    return getLocationCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Gets information about a location.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (ChangelogsClient changelogsClient = ChangelogsClient.create()) {
   *   GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
   *   ApiFuture<Location> future = changelogsClient.getLocationCallable().futureCall(request);
   *   // Do something.
   *   Location response = future.get();
   * }
   * }

   */
  public final UnaryCallable<GetLocationRequest, Location> getLocationCallable() {
    return stub.getLocationCallable();
  }

  @Override
  public final void close() {
    stub.close();
  }

  @Override
  public void shutdown() {
    stub.shutdown();
  }

  @Override
  public boolean isShutdown() {
    return stub.isShutdown();
  }

  @Override
  public boolean isTerminated() {
    return stub.isTerminated();
  }

  @Override
  public void shutdownNow() {
    stub.shutdownNow();
  }

  @Override
  public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
    return stub.awaitTermination(duration, unit);
  }

  public static class ListChangelogsPagedResponse
      extends AbstractPagedListResponse<
          ListChangelogsRequest,
          ListChangelogsResponse,
          Changelog,
          ListChangelogsPage,
          ListChangelogsFixedSizeCollection> {

    public static ApiFuture<ListChangelogsPagedResponse> createAsync(
        PageContext<ListChangelogsRequest, ListChangelogsResponse, Changelog> context,
        ApiFuture<ListChangelogsResponse> futureResponse) {
      ApiFuture<ListChangelogsPage> futurePage =
          ListChangelogsPage.createEmptyPage().createPageAsync(context, futureResponse);
      return ApiFutures.transform(
          futurePage,
          input -> new ListChangelogsPagedResponse(input),
          MoreExecutors.directExecutor());
    }

    private ListChangelogsPagedResponse(ListChangelogsPage page) {
      super(page, ListChangelogsFixedSizeCollection.createEmptyCollection());
    }
  }

  public static class ListChangelogsPage
      extends AbstractPage<
          ListChangelogsRequest, ListChangelogsResponse, Changelog, ListChangelogsPage> {

    private ListChangelogsPage(
        PageContext<ListChangelogsRequest, ListChangelogsResponse, Changelog> context,
        ListChangelogsResponse response) {
      super(context, response);
    }

    private static ListChangelogsPage createEmptyPage() {
      return new ListChangelogsPage(null, null);
    }

    @Override
    protected ListChangelogsPage createPage(
        PageContext<ListChangelogsRequest, ListChangelogsResponse, Changelog> context,
        ListChangelogsResponse response) {
      return new ListChangelogsPage(context, response);
    }

    @Override
    public ApiFuture<ListChangelogsPage> createPageAsync(
        PageContext<ListChangelogsRequest, ListChangelogsResponse, Changelog> context,
        ApiFuture<ListChangelogsResponse> futureResponse) {
      return super.createPageAsync(context, futureResponse);
    }
  }

  public static class ListChangelogsFixedSizeCollection
      extends AbstractFixedSizeCollection<
          ListChangelogsRequest,
          ListChangelogsResponse,
          Changelog,
          ListChangelogsPage,
          ListChangelogsFixedSizeCollection> {

    private ListChangelogsFixedSizeCollection(List<ListChangelogsPage> pages, int collectionSize) {
      super(pages, collectionSize);
    }

    private static ListChangelogsFixedSizeCollection createEmptyCollection() {
      return new ListChangelogsFixedSizeCollection(null, 0);
    }

    @Override
    protected ListChangelogsFixedSizeCollection createCollection(
        List<ListChangelogsPage> pages, int collectionSize) {
      return new ListChangelogsFixedSizeCollection(pages, collectionSize);
    }
  }

  public static class ListLocationsPagedResponse
      extends AbstractPagedListResponse<
          ListLocationsRequest,
          ListLocationsResponse,
          Location,
          ListLocationsPage,
          ListLocationsFixedSizeCollection> {

    public static ApiFuture<ListLocationsPagedResponse> createAsync(
        PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
        ApiFuture<ListLocationsResponse> futureResponse) {
      ApiFuture<ListLocationsPage> futurePage =
          ListLocationsPage.createEmptyPage().createPageAsync(context, futureResponse);
      return ApiFutures.transform(
          futurePage,
          input -> new ListLocationsPagedResponse(input),
          MoreExecutors.directExecutor());
    }

    private ListLocationsPagedResponse(ListLocationsPage page) {
      super(page, ListLocationsFixedSizeCollection.createEmptyCollection());
    }
  }

  public static class ListLocationsPage
      extends AbstractPage<
          ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage> {

    private ListLocationsPage(
        PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
        ListLocationsResponse response) {
      super(context, response);
    }

    private static ListLocationsPage createEmptyPage() {
      return new ListLocationsPage(null, null);
    }

    @Override
    protected ListLocationsPage createPage(
        PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
        ListLocationsResponse response) {
      return new ListLocationsPage(context, response);
    }

    @Override
    public ApiFuture<ListLocationsPage> createPageAsync(
        PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
        ApiFuture<ListLocationsResponse> futureResponse) {
      return super.createPageAsync(context, futureResponse);
    }
  }

  public static class ListLocationsFixedSizeCollection
      extends AbstractFixedSizeCollection<
          ListLocationsRequest,
          ListLocationsResponse,
          Location,
          ListLocationsPage,
          ListLocationsFixedSizeCollection> {

    private ListLocationsFixedSizeCollection(List<ListLocationsPage> pages, int collectionSize) {
      super(pages, collectionSize);
    }

    private static ListLocationsFixedSizeCollection createEmptyCollection() {
      return new ListLocationsFixedSizeCollection(null, 0);
    }

    @Override
    protected ListLocationsFixedSizeCollection createCollection(
        List<ListLocationsPage> pages, int collectionSize) {
      return new ListLocationsFixedSizeCollection(pages, collectionSize);
    }
  }
}


text:
package org.apache.servicecomb.swagger.invocation.arguments.producer;

import java.util.HashMap;
import java.util.Map;

import org.apache.servicecomb.swagger.engine.SwaggerEnvironment;
import org.apache.servicecomb.swagger.engine.SwaggerProducer;
import org.apache.servicecomb.swagger.invocation.SwaggerInvocation;
import org.apache.servicecomb.swagger.invocation.schemas.PojoAddBodyV1;
import org.apache.servicecomb.swagger.invocation.schemas.PojoAddV1;
import org.apache.servicecomb.swagger.invocation.schemas.PojoAddWithContextV1;
import org.junit.Assert;
import org.junit.Test;

public class TestPojo {
  static Map<String, Object> addBody = new HashMap<>();

  static {
    addBody.put("x", 1);
    addBody.put("y", 2);
  }

  @Test
  public void add() {
    SwaggerProducer swaggerProducer = new SwaggerEnvironment().createProducer(new PojoAddV1(), null);
    ProducerArgumentsMapper mapper = swaggerProducer.findOperation("add").getArgumentsMapper();

    SwaggerInvocation invocation = new SwaggerInvocation();
    Map<String, Object> arguments = new HashMap<>();
    arguments.put("addBody", addBody);

    Map<String, Object> result = mapper.swaggerArgumentToInvocationArguments(invocation, arguments);

    Assert.assertEquals(2, result.size());
    Assert.assertEquals(1, (int) result.get("x"));
    Assert.assertEquals(2, (int) result.get("y"));
  }

  @Test
  public void addBody() {
    SwaggerProducer swaggerProducer = new SwaggerEnvironment().createProducer(new PojoAddBodyV1(), null);
    ProducerArgumentsMapper mapper = swaggerProducer.findOperation("add").getArgumentsMapper();

    SwaggerInvocation invocation = new SwaggerInvocation();
    Map<String, Object> arguments = new HashMap<>();
    arguments.put("addBody", addBody);

    Map<String, Object> result = mapper.swaggerArgumentToInvocationArguments(invocation, arguments);

    Assert.assertEquals(1, result.size());
    Assert.assertSame(addBody, result.get("addBody"));
  }

  @Test
  public void addWithContext_add() {
    SwaggerProducer swaggerProducer = new SwaggerEnvironment().createProducer(new PojoAddWithContextV1(), null);
    ProducerArgumentsMapper mapper = swaggerProducer.findOperation("add").getArgumentsMapper();

    SwaggerInvocation invocation = new SwaggerInvocation();
    Map<String, Object> arguments = new HashMap<>();
    arguments.put("addBody", addBody);

    Map<String, Object> result = mapper.swaggerArgumentToInvocationArguments(invocation, arguments);

    Assert.assertEquals(3, result.size());
    Assert.assertSame(invocation, result.get("context"));
    Assert.assertEquals(1, result.get("x"));
    Assert.assertEquals(2, result.get("y"));
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
Plugin Name: Service Locations
Description: Allows you to bind locations to your services.
Plugin URI: http://premium.wpmudev.org/project/appointments-plus/
Version: 1.0
AddonType: Locations
Requires: Locations add-on
Author: WPMU DEV
*/

class App_Locations_ServiceLocations {

	const STORAGE_PREFIX = 'app-service_location-';

	private $_data;
	private $_locations;

	private function __construct () {}

	public static function serve () {
		$me = new App_Locations_ServiceLocations;
		$me->_add_hooks();
	}

	private function _add_hooks () {
		// Init and dispatch post-init actions
		add_action('app-locations-initialized', array($this, 'initialize'));

		// Augment service settings pages
		add_filter('app-settings-services-service-name', array($this, 'add_service_selection'), 10, 2);
		add_action('app-services-service-updated', array($this, 'save_service_location'));

		// Add settings
		add_action('app-locations-settings-after_locations_list', array($this, 'show_settings'));
		add_filter('app-locations-before_save', array($this, 'save_settings'));

		add_action('admin_notices', array($this, 'show_nags'));

		// Record appointment location
		add_action('app_new_appointment', array($this, 'record_appointment_location'), 20);
	}

	function show_nags () {
		if (!class_exists('App_Locations_Location') || !$this->_locations) {
			echo '

' .
				__("You'll need Locations add-on activated for Service Locations integration add-on to work", 'appointments') .
			'

';
		}
	}

	public function initialize () {
		if (!class_exists('App_Locations_Model')) return false;
		global $appointments;
		$this->_data = $appointments->options;
		if (empty($this->_data['service_locations'])) $this->_data['service_locations'] = array();
		$this->_locations = App_Locations_Model::get_instance();

		if (empty($this->_data['service_locations']['insert']) || 'manual' == $this->_data['service_locations']['insert']) {
			add_shortcode('app_service_location', array($this, 'process_shortcode'));
		} else {
			add_shortcode('app_service_location', '__return_false');
			add_filter('app-services-service_description', array($this, 'inject_location_markup'), 10, 3);
		}

		if (!class_exists('App_Shortcode_ServiceLocationsShortcode')) {
			require_once(dirname(__FILE__) . '/lib/app_service_locations_shortcode.php');
			App_Shortcode_ServiceLocationsShortcode::serve();
			App_Shortcode_RequiredServiceLocationsShortcode::serve();
		}
	}

	public function record_appointment_location ($appointment_id) {
		global $wpdb, $appointments;
		$appointment = $appointments->get_app($appointment_id);
		if (empty($appointment->service)) return false;

		$location_id = self::service_to_location_id($appointment->service);
		if (!$location_id) return false;

		return $wpdb->update(
			$appointments->app_table,
			array('location' => $location_id),
			array('ID' => $appointment_id)
		);
	}

	public function show_settings () {
		?>

<?php _e('Service Locations Settings', 'appointments') ?>

				<?php _e('Show service location', 'appointments')?>

					<select name="service_locations[insert]">
						<option value="manual" <?php selected($this->_data['service_locations']['insert'], 'manual'); ?> ><?php _e('I will add location info manually, using shortcode', 'appointments'); ?></option>
						<option value="before" <?php selected($this->_data['service_locations']['insert'], 'before'); ?> ><?php _e('Automatic, before service description', 'appointments'); ?></option>
						<option value="after" <?php selected($this->_data['service_locations']['insert'], 'after'); ?> ><?php _e('Automatic, after service description', 'appointments'); ?></option>
					</select>

<?php _e('You can use the shortcode like this: [app_service_location]', 'appointments'); ?>

		<?php
	}

	public function save_settings ($options) {
		if (empty($_POST['service_locations'])) return $options;

		$data = stripslashes_deep($_POST['service_locations']);
		$options['service_locations']['insert'] = !empty($data['insert']) ? $data['insert'] : false;

		return $options;
	}

	public function process_shortcode ($args=array(), $content='') {
		$service_id = !empty($args['service_id']) ? $args['service_id'] : false;
		if (!$service_id) {
			$post_id = get_queried_object_id();
			$service_id = $this->_map_description_post_to_service_id($post_id);
		}

		if (!$service_id) return $content;
		return $this->_get_service_location_markup($service_id, $content);
	}

	public function inject_location_markup ($markup, $service, $description) {
		if (!$service || empty($service->ID)) return $markup;
		$out = $this->_get_service_location_markup($service->ID, '', ('content' == $description));
		return ('before' == $this->_data['service_locations']['insert'])
			? $out . $markup
			: $markup . $out
		;
	}

	public function add_service_selection ($out, $service_id) {
		if (!class_exists('App_Locations_Model') || !$this->_locations) return $out;
		$locations = $this->_locations->get_all();
		$markup = '';

		$markup .= '' . __('Location:', 'appointments') . ' ';
		$markup .= '<select name="service_location[' . $service_id . ']"><option value=""></option>';
		foreach ($locations as $location) {
			$checked = $location->get_id() == self::service_to_location_id($service_id) ? 'selected="selected"' : '';
			$markup .= '<option value="' . $location->get_id() . '" ' . $checked . '>' . esc_html($location->get_admin_label()) . '</option>';
		}
		$markup .= '</select>';
		return $out . $markup;
	}

	public function save_service_location ($service_id) {
		if (!$service_id) return false;
		$key = self::STORAGE_PREFIX . $service_id;

		$old_location_id = self::service_to_location_id($service_id);
		$location_id = !empty($_POST['service_location'][$service_id]) ? $_POST['service_location'][$service_id] : false;

		if ($old_location_id != $location_id) $this->_update_appointment_locations($service_id, $old_location_id, $location_id);

		return update_option($key, $location_id);
	}

	public static function service_to_location_id ($service_id) {
		if (!$service_id) return false;
		$key = self::STORAGE_PREFIX . $service_id;

		return get_option($key, false);
	}

	private function _service_to_location ($service_id) {
		if (!$this->_locations) return false;
		$location_id = self::service_to_location_id($service_id);
		return $this->_locations->find_by('id', $location_id);
	}

	private function _update_appointment_locations ($service_id, $old_location_id, $location_id) {
		global $wpdb, $appointments;

		if ($old_location_id == $location_id) return false;

		$res = $wpdb->update(
			$appointments->app_table,
			array('location' => $location_id),
			array(
				'location' => $old_location_id,
				'service' => $service_id,
			), '%s', '%s'
		);
	}

	private function _get_service_location_markup ($service_id, $fallback='', $rich_content=true) {
		$location = $this->_service_to_location($service_id);
		if (!$location) return $fallback;
		return $this->_get_location_markup($location, $rich_content);
	}

	private function _get_location_markup ($location, $rich_content=true) {
		return '
get_id() . '">' .
			apply_filters('app-locations-location_output', $location->get_display_markup($rich_content), $service_id, $location) .
		'
';
	}

	private function _map_description_post_to_service_id ($post_id) {
		global $appointments, $wpdb;
		$sql = $wpdb->prepare("SELECT ID FROM {$appointments->services_table} WHERE page=%d", $post_id);
		return $wpdb->get_var($sql);
	}
}
App_Locations_ServiceLocations::serve();


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Standalone demo</title>
  <link href="cropper-demo.css" rel="stylesheet" />
  <link href="../dist/cropper.css" rel="stylesheet"/>

<form method="post" action="#" enctype="multipart/form-data">

    <button class="btn-upload btn-lg">Select</button>
    <input type="file" name="avatar" id="cropper-input"/>
    Support formats: JPG, PNG

Large

Medium

Small

  <input type="hidden" name="x" value="{{cropContext.left}}"/>
  <input type="hidden" name="y" value="{{cropContext.top}}"/>
  <input type="hidden" name="w" value="{{cropContext.width}}"/>
  <input type="hidden" name="h" value="{{cropContext.height}}"/>
</form>


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

#ifndef COMPONENTS_NTP_SNIPPETS_REMOTE_NTP_SNIPPETS_STATUS_SERVICE_H_
#define COMPONENTS_NTP_SNIPPETS_REMOTE_NTP_SNIPPETS_STATUS_SERVICE_H_

#include "base/callback.h"
#include "base/gtest_prod_util.h"
#include "base/scoped_observer.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/signin/core/browser/signin_manager.h"

class PrefRegistrySimple;
class PrefService;

namespace ntp_snippets {

enum class SnippetsStatus : int {
  // Snippets are enabled and the user is signed in.
  ENABLED_AND_SIGNED_IN,
  // Snippets are enabled and the user is signed out (sign in is not required).
  ENABLED_AND_SIGNED_OUT,
  // Snippets have been disabled as part of the service configuration.
  EXPLICITLY_DISABLED,
  // The user is not signed in, and the service requires it to be enabled.
  SIGNED_OUT_AND_DISABLED,
};

// Aggregates data from preferences and signin to notify the snippet service of
// relevant changes in their states.
class NTPSnippetsStatusService : public SigninManagerBase::Observer {
 public:
  using SnippetsStatusChangeCallback =
      base::Callback<void(SnippetsStatus /*old_status*/,
                          SnippetsStatus /*new_status*/)>;

  NTPSnippetsStatusService(SigninManagerBase* signin_manager,
                           PrefService* pref_service);

  ~NTPSnippetsStatusService() override;

  static void RegisterProfilePrefs(PrefRegistrySimple* registry);

  // Starts listening for changes from the dependencies. |callback| will be
  // called when a significant change in state is detected.
  void Init(const SnippetsStatusChangeCallback& callback);

 private:
  FRIEND_TEST_ALL_PREFIXES(NTPSnippetsStatusServiceTest, DisabledViaPref);

  // SigninManagerBase::Observer implementation
  void GoogleSigninSucceeded(const std::string& account_id,
                             const std::string& username,
                             const std::string& password) override;
  void GoogleSignedOut(const std::string& account_id,
                       const std::string& username) override;

  // Callback for the PrefChangeRegistrar.
  void OnSnippetsEnabledChanged();

  void OnStateChanged(SnippetsStatus new_snippets_status);

  bool IsSignedIn() const;

  SnippetsStatus GetSnippetsStatusFromDeps() const;

  SnippetsStatus snippets_status_;
  SnippetsStatusChangeCallback snippets_status_change_callback_;

  bool require_signin_;
  SigninManagerBase* signin_manager_;
  PrefService* pref_service_;

  PrefChangeRegistrar pref_change_registrar_;

  // The observer for the SigninManager.
  ScopedObserver<SigninManagerBase, SigninManagerBase::Observer>
      signin_observer_;

  DISALLOW_COPY_AND_ASSIGN(NTPSnippetsStatusService);
};

}  // namespace ntp_snippets

#endif  // COMPONENTS_NTP_SNIPPETS_REMOTE_NTP_SNIPPETS_STATUS_SERVICE_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syn. meth. fung. (Göttingen) 1: 155 (1801)

#### Original name
Scleroderma cepa var. cepa Pers.

### Remarks
null


text:
from django.test import TestCase

from block.models import ModerateState
from login.tests.factories import (
    TEST_PASSWORD,
    UserFactory,
)
from example_block.tests.factories import TitleFactory

class TestWorkflow(TestCase):

    def setUp(self):
        user = UserFactory(username='staff', is_staff=True)
        self.assertTrue(
            self.client.login(username=user.username, password=TEST_PASSWORD)
        )
        self.block = TitleFactory().block

    def _get_pending(self):
        return self.block.content.get(
            moderate_state=ModerateState.objects._pending()
        )

    def _get_published(self):
        return self.block.content.get(
            moderate_state=ModerateState.objects._published()
        )

    def _pending_count(self):
        return self.block.content.filter(
            moderate_state=ModerateState.objects._pending()
        ).count()

    def _publish_count(self):
        return self.block.content.filter(
            moderate_state=ModerateState.objects._published()
        ).count()

    def _remove_count(self):
        return self.block.content.filter(
            moderate_state__slug=ModerateState.REMOVED
        ).count()

    def test_pending(self):
        self.assertEqual(1, self._pending_count())
        self.assertEqual(0, self._publish_count())
        self.assertEqual(0, self._remove_count())

    def test_published(self):
        self.block.publish(UserFactory())
        self.assertEqual(1, self._pending_count())
        self.assertEqual(1, self._publish_count())
        self.assertEqual(0, self._remove_count())

    def test_remove_pending(self):
        self.block.remove(UserFactory())
        self.assertEqual(0, self._pending_count())
        self.assertEqual(0, self._publish_count())
        self.assertEqual(1, self._remove_count())

    def test_remove_published(self):
        self.block.publish(UserFactory())
        self.block.remove(UserFactory())
        self.assertEqual(0, self._pending_count())
        self.assertEqual(0, self._publish_count())
        self.assertEqual(1, self._remove_count())


text:
#ifndef POINT_H
#define POINT_H

#include <string>
#include <iostream>

namespace ocl
{

class Triangle;

///
/// \brief a point or vector in 3D space specified by its coordinates (x, y, z)
///
class Point {
    public:
        /// create a point at (0,0,0)
        Point();
        /// create a point at (x,y,z)
        Point(double x, double y, double z);
        /// create a point at (x,y,0)
        Point(double x, double y);
        /// create a point at p
        Point(const Point &p);
        /// destructor. empty.
        virtual ~Point() {};

        /// dot product
        double dot(const Point &p) const;

        /// cross product
        Point cross(const Point &p) const;

        /// norm of vector, or distance from (0,0,0) to *this
        double norm() const;

        /// scales vector so that norm()==1.0
        void normalize();

        /// distance from Point to another Point p in the XY plane
        double xyDistance(const Point &p) const;

        /// length of vector in the XY plane
        double xyNorm() const;

        /// normalize so that length xyNorm == 1.0
        void xyNormalize();

        /// return perpendicular in the xy plane, rotated 90 degree to the left
        Point xyPerp() const;

        /// move *this along z-axis so it lies on p1-p2 line-segment
        void z_projectOntoEdge(const Point& p1, const Point& p2);

        /// rotate point in the xy-plane by angle theta
        /// inputs are cos(theta) and sin(theta)
        void xyRotate(double cosa, double sina);
        /// rotate point in xy-plane bu angle theta (radians or degrees??)
        void xyRotate(double angle);

        /// rotate around x-axis
        void xRotate(double theta);
        /// rotate around y-axis
        void yRotate(double theta);
        /// rotate around z-axis
        void zRotate(double theta);
        void matrixRotate(double a,double b, double c,
                          double d,double e, double f,
                          double g,double h, double i);

        /// distance from Point to infinite line through p1 and p2. In the XY plane.
        double xyDistanceToLine(const Point &p1, const Point &p2) const;

        /// return closest Point to line through p1 and p2. in 3D.
        Point closestPoint(const Point &p1, const Point &p2) const;

        /// return closest Point to line through p1 and p2. Works in the XY plane.
        Point xyClosestPoint(const Point &p1, const Point &p2) const;

        /// returns true if point is right of line through p1 and p2 (works in the XY-plane)
        bool isRight(const Point &p1, const Point &p2) const;

        /// retruns true if Point *this is inside Triangle t
        bool isInside(const Triangle &t) const;
        /// retrun true if Point within line segment p1-p2
        bool isInside(const Point& p1, const Point& p2) const;

        /// return true if the x and y components are both zero.
        bool xParallel() const;
        /// return true if vector parallel to y-axis
        bool yParallel() const;
        /// return true if vector parallel to z-axis
        bool zParallel() const;

        /// assignment
        Point &operator=(const Point &p);
        /// addition
        Point &operator+=(const Point &p);
        /// subtraction
        Point &operator-=(const Point &p);
        /// addition
        const Point operator+(const Point &p)const;
        /// subtraction
        const Point operator-(const Point &p) const;

        /// scalar multiplication
        Point &operator*=(const double &a);  // scalar multiplication with Point *= scalar
        /// Point * scalar
        const Point operator*(const double &a)const;     // Point*scalar
        /// equality
        bool operator==(const Point &p) const;
        /// inequality
        bool operator!=(const Point &p) const;

        /// string repr
        friend std::ostream& operator<<(std::ostream &stream, const Point &p);
        /// string repr
        std::string str() const;

        /// X coordinate
        double x;
        /// Y coordinate
        double y;
        /// Z coordinate
        double z;
};

/// scalar multiplication   scalar*Point
const Point operator*(const double &a, const Point &p);

} // end namespace
#endif
// end file point.h


text:
==========================
Sample Configuration Files
==========================

.. toctree::
   :maxdepth: 1

   samples/neutron.rst

.. toctree::
   :maxdepth: 1

   samples/ml2-conf.rst
   samples/linuxbridge-agent.rst
   samples/macvtap-agent.rst
   samples/openvswitch-agent.rst
   samples/sriov-agent.rst
   samples/ovn.rst

.. toctree::
   :maxdepth: 1

   samples/dhcp-agent.rst
   samples/l3-agent.rst
   samples/metadata-agent.rst
   samples/metering-agent.rst


text:
%--- help for ts/transform ---
%
%  Apply different transformations following the definitions of Haver
%
%  ::
%
%     db = transform(db, type);
%
%  Args:
%     db (ts object): time series object
%     type: the type of the transformation. Available transformations are
%
%        - 1 or 'level': Untransformed data - level (default)
%        - 2 or 'pct_ch_ar': Percentage change at compound annual rate (% chg)
%        - 3 or 'pct_ch': Period to period percentage change (% change)
%        - 4 or 'yoy_pct_ch': Year over year percentage change (yr/yr % chg)
%        - 5 or 'diff': Period to period difference change
%        - 6 or 'yoy_diff': Year over Year difference change
%        - 7 or 'log_ch_ar': %Log Change - compound annual rate (ann l-chg)
%        - 8 or 'log_ch': %Log Change - period to period (log-change)
%        - 9 or 'yoy_log_ch': Year to year log change (yr-yr l-chg)
%
%  Returns:
%     :
%
%     - **db** (ts object): Transformed time series
%
%
%    Other functions named transform
%
%       abstvar/transform    sym/transform
%


text:
'use strict';

angular.module('cns.ui.dpl', [])
.controller('DplCtrl', ['$scope', '$element', '$sce', '$attrs', function($scope, $element, $sce, $attrs) {
    var md = {
        months: [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ],
        shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'],
        getNameOfMonth: function(month) {
            return this.months[month];
        },
        getShortNameOfMonth: function(month) {
                return this.shortMonths[month];
        }
    };
    $scope.arrow = angular.isDefined($attrs.arrow) ? $attrs.arrow : 18;
    var topPoints = '0,' + $scope.arrow + ' ' + ($scope.arrow / 2) + ',' + $scope.arrow / 2 + ' ' + $scope.arrow + ',' + $scope.arrow;
    $scope.arrowTop = $sce.trustAsHtml('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' + $scope.arrow + '" height="' + $scope.arrow + '">' +
    '<polygon class="cns-dpl-svg" points="' + topPoints + '" class="cns-grow-button" />' +
    '</svg>');
    var bottomPoints = '0,0 ' + $scope.arrow +',0 ' + $scope.arrow / 2 + ',' + $scope.arrow / 2;
    $scope.arrowBottom = $sce.trustAsHtml('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' + $scope.arrow+ '" height="' + $scope.arrow + '">' +
    '<polygon class="cns-dpl-svg" points="' + bottomPoints+ '" class="cns-grow-button" />' +
    '</svg>');
    var divDate = angular.element($element[0].querySelector('.cns-dpl'));
    var top = $element[0].offsetTop,
        left = $element[0].offsetLeft;
    var input = angular.element($element[0].querySelector('input'));
    var height = input[0].offsetHeight;
    input.on('focus', function() {
        divDate.css({top: top + height + 2 + 'px', left: left + 'px', display: 'block'});
    });

    var divM = angular.element($element[0].querySelector('#cns-dpl-month')),
        divD = angular.element($element[0].querySelector('#cns-dpl-date')),
        divY = angular.element($element[0].querySelector('#cns-dpl-year'));
    function addEvt (e, mousewheel) {
        if (e.addEventListener) {
            if ('onwheel' in document) {
                e.addEventListener ("wheel", mousewheel, false);
            } else if ('onmousewheel' in document) {
                e.addEventListener ("mousewheel", mousewheel, false);
            } else {
                e.addEventListener ("MozMousePixelScroll", mousewheel, false);
            }
        } else {
            e.attachEvent ("onmousewheel", mousewheel);
        }
    }
    function mousewheelMonth(event) {
        event.preventDefault();
        var delta = event.wheelDelta,
            dx = event.wheelDeltaX || event.deltaX,
            dy = event.wheelDeltaY || -event.deltaY || event.wheelDelta;
        if(dy < 0) {
            $scope.setMonth(1);
            $scope.$apply();
        }
        if(dy > 0) {
            $scope.setMonth(-1);
            $scope.$apply();
        }
    }
    function mousewheelDate(event) {
        event.preventDefault();
        var delta = event.wheelDelta,
            dx = event.wheelDeltaX || event.deltaX,
            dy = event.wheelDeltaY || -event.deltaY || event.wheelDelta;
        if(dy < 0) {
            $scope.setDate(1);
            $scope.$apply();
        }
        if(dy > 0) {
            $scope.setDate(-1);
            $scope.$apply();
        }
    }
    function mousewheelYear(event) {
        event.preventDefault();
        var delta = event.wheelDelta,
            dx = event.wheelDeltaX || event.deltaX,
            dy = event.wheelDeltaY || -event.deltaY || event.wheelDelta;
        if(dy < 0) {
            $scope.setYear(1);
            $scope.$apply();
        }
        if(dy > 0) {
            $scope.setYear(-1);
            $scope.$apply();
        }
    }
    addEvt(divM[0], mousewheelMonth);
    addEvt(divD[0], mousewheelDate);
    addEvt(divY[0], mousewheelYear);
    $scope.setNewDate = function() {
        $scope.dt.setFullYear($scope.date.year);
        $scope.dt.setMonth($scope.date.month);
        $scope.dt.setDate($scope.date.date);
        var s = $scope.ngModel.indexOf('-') > 0 ? '-' : '/';
        var m = $scope.date.month < 10 ? '0' + $scope.date.month : $scope.date.month;
        var d = $scope.date.date < 10 ? '0' + $scope.date.date : $scope.date.date;
        $scope.ngModel = m + s + d + s + $scope.date.year;
        divDate.css({display: 'none'});
    };
    $scope.cancel = function() {
        divDate.css({display: 'none'});
    };
    $scope.monthView = function(month) {
        switch ($scope.viewMonth) {
            case 'dig':
                return month < 10 ? '0' + month : month;
                break;
            default:
                return md.getShortNameOfMonth(month - 1);
                break;
        }
    };
    $scope.dateView = function(date) {
        return date < 10 ? '0' + date : date;
    };
    $scope.setMonth = function(delta) {
        if(delta < 0) {
            $scope.date.month = $scope.date.month == 1 ? 12 : $scope.date.month + delta;
            $scope.prevDate.month = $scope.date.month == 1 ? 12 : $scope.date.month - 1;
            $scope.nextDate.month = $scope.date.month == 12 ? 1 : $scope.date.month + 1;
        }
        if(delta > 0) {
            $scope.date.month = $scope.date.month == 12 ? 1 : $scope.date.month + delta;
            $scope.prevDate.month = $scope.date.month == 1 ? 12 : $scope.date.month - 1;
            $scope.nextDate.month = $scope.date.month == 12 ? 1 : $scope.date.month + 1;
        }
        var countDay = getLastDayOfMonth($scope.date.year, $scope.date.month - 1);
        if($scope.date.date > countDay) {
            $scope.date.date = countDay;
        }
        $scope.prevDate.date = $scope.date.date == 1 ? countDay : $scope.date.date - 1;
        $scope.nextDate.date = $scope.date.date == countDay ? 1 : $scope.date.date + 1;
    };
    $scope.setYear = function(delta) {
        if(delta < 0 && $scope.date.year > $scope.startYear) {
            $scope.prevDate.year--;
            $scope.date.year--;
            $scope.nextDate.year--;
        }
        if(delta > 0 && $scope.date.year < $scope.endYear) {
            $scope.prevDate.year++;
            $scope.date.year++;
            $scope.nextDate.year++;
        }
        if($scope.date.month == 2) {
            var countDay = getLastDayOfMonth($scope.date.year, $scope.date.month - 1);
            if($scope.date.date > countDay) {
                $scope.date.date = countDay;
            }
            $scope.prevDate.date = $scope.date.date == 1 ? countDay : $scope.date.date - 1;
            $scope.nextDate.date = $scope.date.date == countDay ? 1 : $scope.date.date + 1;
        }
    };
    $scope.setDate = function(delta) {
        var countDay = getLastDayOfMonth($scope.date.year, $scope.date.month - 1);
        if(delta < 0) {
            $scope.nextDate.date = $scope.date.date;
            $scope.date.date = $scope.prevDate.date;
            $scope.prevDate.date = $scope.prevDate.date == 1 ? countDay : $scope.prevDate.date + delta ;
        }
        if(delta > 0) {
            $scope.prevDate.date = $scope.date.date;
            $scope.date.date = $scope.nextDate.date;
            $scope.nextDate.date = $scope.nextDate.date == countDay ? 1 : $scope.nextDate.date + delta;
        }
    };
    $scope.$watch('ngModel', function() {
        $scope.dt = new Date($scope.ngModel);
        $scope.prevDate = getMDY(-1);
        $scope.date = getMDY(0);
        $scope.nextDate = getMDY(1);
    });
    function getMDY(delta) {
        var countDay = getLastDayOfMonth($scope.dt.getFullYear(), $scope.dt.getMonth()),
            countPrevDay = getLastDayOfMonth($scope.dt.getFullYear(), $scope.dt.getMonth() - 1);
        var d = $scope.dt.getDate() + delta,
            m = $scope.dt.getMonth() + delta + 1,
            y = $scope.dt.getFullYear() + delta;
        if(d == 0) {
            d = countPrevDay;
        } else if (d > countDay) {
            d = 1;
        }
        if(m < 1) {
            m = 12;
        } else if(m == 13) {
            m = 1;
        }
        return { month: m, date: d, year: y };
    }
    function getLastDayOfMonth(year, month) {
        var date = new Date(year, month + 1, 0);
        return date.getDate();
    }
    this.init = function() {

    };
}])
.directive('cnsDpl', [function() {
   return {
       controller: 'DplCtrl',
       link: function(scope, element, attributes, controllers) {
           scope.startYear = angular.isDefined(attributes.startYear) ? Number(attributes.startYear) : 1900;
           scope.endYear = angular.isDefined(attributes.endYear) ? Number(attributes.endYear) : 2099;
           scope.viewMonth = angular.isDefined(attributes.viewMonth) ? attributes.viewMonth : null;
           if(!scope.ngModel) {
               scope.dt = new Date();
           } else {
               var expr = /^[0,1][0-9][-,\/][0-3][0-9][-,\/][0-2]\d{3}/;
               if(scope.ngModel.match(expr)) {
                   scope.dt = new Date(scope.ngModel);
               } else {
                   scope.dt = new Date();
               }
           }
           var dplCtrl = controllers[0];
           if(!dplCtrl) {
               console.log('DplCtrl error');
           } else {
               dplCtrl.init();
           }
       },
       require: ['cnsDpl'],
       scope: {
           ngModel: '='
       },
       templateUrl: '../src/templates/directives/dpl.html'
    };
}]);


text:
namespace msgpack {

/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond

namespace adaptor {

template <typename T>
struct convert<boost::optional<T> > {
    msgpack::object const& operator()(msgpack::object const& o, boost::optional<T>& v) const {
        if(o.is_nil()) v = boost::none;
        else {
            T t;
            msgpack::adaptor::convert<T>()(o, t);
            v = t;
        }
        return o;
    }
};

template <typename T>
struct pack<boost::optional<T> > {
    template <typename Stream>
    msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const boost::optional<T>& v) const {
        if (v) o.pack(*v);
        else o.pack_nil();
        return o;
    }
};

template <typename T>
struct object<boost::optional<T> > {
    void operator()(msgpack::object& o, const boost::optional<T>& v) const {
        if (v) msgpack::adaptor::object<T>()(o, *v);
        else o.type = msgpack::type::NIL;
    }
};

template <typename T>
struct object_with_zone<boost::optional<T> > {
    void operator()(msgpack::object::with_zone& o, const boost::optional<T>& v) const {
        if (v) msgpack::adaptor::object_with_zone<T>()(o, *v);
        else o.type = msgpack::type::NIL;
    }
};

} // namespace adaptor

/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond

} // namespace msgpack

#endif // MSGPACK_TYPE_BOOST_OPTIONAL_HPP


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace HtcSharp.HttpModule.Core.Internal.Http2 {
    // SourceTools-Start
    // Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Http2\Http2Frame.Headers.cs
    // Start-At-Remote-Line 5
    // SourceTools-End
    /* https://tools.ietf.org/html/rfc7540#section-6.2
        +---------------+
        |Pad Length? (8)|
        +-+-------------+-----------------------------------------------+
        |E|                 Stream Dependency? (31)                     |
        +-+-------------+-----------------------------------------------+
        |  Weight? (8)  |
        +-+-------------+-----------------------------------------------+
        |                   Header Block Fragment (*)                 ...
        +---------------------------------------------------------------+
        |                           Padding (*)                       ...
        +---------------------------------------------------------------+
    */
    internal partial class Http2Frame {
        public Http2HeadersFrameFlags HeadersFlags {
            get => (Http2HeadersFrameFlags) Flags;
            set => Flags = (byte) value;
        }

        public bool HeadersEndHeaders => (HeadersFlags & Http2HeadersFrameFlags.END_HEADERS) == Http2HeadersFrameFlags.END_HEADERS;

        public bool HeadersEndStream => (HeadersFlags & Http2HeadersFrameFlags.END_STREAM) == Http2HeadersFrameFlags.END_STREAM;

        public bool HeadersHasPadding => (HeadersFlags & Http2HeadersFrameFlags.PADDED) == Http2HeadersFrameFlags.PADDED;

        public bool HeadersHasPriority => (HeadersFlags & Http2HeadersFrameFlags.PRIORITY) == Http2HeadersFrameFlags.PRIORITY;

        public byte HeadersPadLength { get; set; }

        public int HeadersStreamDependency { get; set; }

        public byte HeadersPriorityWeight { get; set; }

        private int HeadersPayloadOffset => (HeadersHasPadding ? 1 : 0) + (HeadersHasPriority ? 5 : 0);

        public int HeadersPayloadLength => PayloadLength - HeadersPayloadOffset - HeadersPadLength;

        public void PrepareHeaders(Http2HeadersFrameFlags flags, int streamId) {
            PayloadLength = 0;
            Type = Http2FrameType.HEADERS;
            HeadersFlags = flags;
            StreamId = streamId;
        }
    }
}


text:
import { Image } from 'test/common';

import { validateChannel } from '../channel';

describe('we check the validateChannel method', function () {
  it('check for a RGB image', function () {
    let image = new Image(2, 2, {
      kind: 'RGB',
    });

    expect(validateChannel(image, 'r')).toBe(0);
    expect(validateChannel(image, 'g')).toBe(1);
    expect(validateChannel(image, 'b')).toBe(2);
    expect(function () {
      validateChannel(image, 'a');
    }).toThrow(/does not contain alpha/);
    expect(function () {
      validateChannel(image);
    }).toThrow(/the channel has to be/);
    expect(function () {
      validateChannel(image, 3, false);
    }).toThrow(/the channel has to be/);
  });

  it('check for a RGBA image', function () {
    let image = new Image(2, 2, {
      kind: 'RGBA',
    });

    expect(validateChannel(image, 'r')).toBe(0);
    expect(validateChannel(image, 'g')).toBe(1);
    expect(validateChannel(image, 'b')).toBe(2);
    expect(validateChannel(image, 'a')).toBe(3);
    expect(function () {
      validateChannel(image);
    }).toThrow(/the channel has to be/);
    expect(function () {
      validateChannel(image, 3, false);
    }).toThrow(/alpha channel may not be/);
  });

  it('check for a GreyA image', function () {
    let image = new Image(2, 2, {
      kind: 'GREYA',
    });

    expect(validateChannel(image, 0)).toBe(0);
    expect(validateChannel(image, 1)).toBe(1);
    expect(validateChannel(image, 'a')).toBe(1);
    expect(validateChannel(image, 'a', true)).toBe(1);
    expect(function () {
      validateChannel(image, 'r');
    }).toThrow(/undefined channel/);
    expect(function () {
      validateChannel(image, 1, false);
    }).toThrow(/alpha channel may not/);
    expect(function () {
      validateChannel(image, 'a', false);
    }).toThrow(/alpha channel may not/);
  });
});


text:
<?php

namespace Ext;

use Core\Factory;
use Core\Lib\App;
use Core\Lib\IOUnit;

/**
 * Class libErrno
 *
 * @package Ext
 */
class libErrno extends Factory
{
    private array $msg_pool   = [];
    private bool  $multi_lang = false;

    /**
     * libErrno constructor.
     *
     * @param bool $multi_lang
     */
    public function __construct(bool $multi_lang = false)
    {
        $this->multi_lang = &$multi_lang;
        unset($multi_lang);
    }

    /**
     * Load error file (root based)
     *
     * @param string $file_name
     * @param string $root_path
     *
     * @return $this
     * @throws \Exception
     */
    public function load(string $file_name, string $root_path = ''): self
    {
        $app = App::new();

        $this->msg_pool = array_replace_recursive($this->msg_pool, $app->parseConf($app->getConfPath($file_name, $root_path), false));

        unset($file_name, $root_path, $app);
        return $this;
    }

    /**
     * Get standard error data
     *
     * @param int    $code
     * @param int    $errno
     * @param string $message
     *
     * @return array
     */
    public function get(int $code, int $errno = 0, string $message = ''): array
    {
        if ('' === $message) {
            $message = $this->msg_pool[$code] ?? 'Error message NOT found!';
        }

        return [
            'code'    => &$code,
            'errno'   => &$errno,
            'message' => $this->multi_lang ? gettext($message) : $message
        ];
    }

    /**
     * Set standard output error
     *
     * @param int    $code
     * @param int    $errno
     * @param string $message
     */
    public function set(int $code, int $errno = 0, string $message = ''): void
    {
        IOUnit::new()->setMsgCode(...array_values($this->get($code, $errno, $message)));
        unset($code, $errno, $message);
    }

    /**
     * Set standard output error in array format
     *
     * @param array $error_info
     */
    public function setArray(array $error_info): void
    {
        IOUnit::new()->setMsgCode(...$error_info);
        unset($error_info);
    }
}