text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

/* global window */
import type * as gax from 'google-gax';
import type {
  Callback,
  CallOptions,
  Descriptors,
  ClientOptions,
  LROperation,
  PaginationCallback,
  GaxCall,
} from 'google-gax';
import {Transform} from 'stream';
import * as protos from '../../protos/protos';
import jsonProtos = require('../../protos/protos.json');
/**
 * Client JSON configuration object, loaded from
 * `src/v1small/addresses_client_config.json`.
 * This file defines retry strategy and timeouts for all API methods in this library.
 */
import * as gapicConfig from './addresses_client_config.json';
const version = require('../../../package.json').version;

/**
 *
 *  Services
 *
 *  The Addresses API.
 * @class
 * @memberof v1small
 */
export class AddressesClient {
  private _terminated = false;
  private _opts: ClientOptions;
  private _providedCustomServicePath: boolean;
  private _gaxModule: typeof gax | typeof gax.fallback;
  private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient;
  private _protos: {};
  private _defaults: {[method: string]: gax.CallSettings};
  auth: gax.GoogleAuth;
  descriptors: Descriptors = {
    page: {},
    stream: {},
    longrunning: {},
    batching: {},
  };
  warn: (code: string, message: string, warnType?: string) => void;
  innerApiCalls: {[name: string]: Function};
  addressesStub?: Promise<{[name: string]: Function}>;

  /**
   * Construct an instance of AddressesClient.
   *
   * @param {object} [options] - The configuration object.
   * The options accepted by the constructor are described in detail
   * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance).
   * The common options are:
   * @param {object} [options.credentials] - Credentials object.
   * @param {string} [options.credentials.client_email]
   * @param {string} [options.credentials.private_key]
   * @param {string} [options.email] - Account email address. Required when
   *     using a .pem or .p12 keyFilename.
   * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
   *     .p12 key downloaded from the Google Developers Console. If you provide
   *     a path to a JSON file, the projectId option below is not necessary.
   *     NOTE: .pem and .p12 require you to specify options.email as well.
   * @param {number} [options.port] - The port on which to connect to
   *     the remote host.
   * @param {string} [options.projectId] - The project ID from the Google
   *     Developer's Console, e.g. 'grape-spaceship-123'. We will also check
   *     the environment variable GCLOUD_PROJECT for your project ID. If your
   *     app is running in an environment which supports
   *     {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
   *     your project ID will be detected automatically.
   * @param {string} [options.apiEndpoint] - The domain name of the
   *     API remote host.
   * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override.
   *     Follows the structure of {@link gapicConfig}.
   * @param {boolean | "rest"} [options.fallback] - Use HTTP fallback mode.
   *     Pass "rest" to use HTTP/1.1 REST API instead of gRPC.
   *     For more information, please check the
   *     {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}.
   * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you
   *     need to avoid loading the default gRPC version and want to use the fallback
   *     HTTP implementation. Load only fallback version and pass it to the constructor:
   *     ```
   *     const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC
   *     const client = new AddressesClient({fallback: 'rest'}, gax);
   *     ```
   */
  constructor(
    opts?: ClientOptions,
    gaxInstance?: typeof gax | typeof gax.fallback
  ) {
    // Ensure that options include all the required fields.
    const staticMembers = this.constructor as typeof AddressesClient;
    const servicePath =
      opts?.servicePath || opts?.apiEndpoint || staticMembers.servicePath;
    this._providedCustomServicePath = !!(
      opts?.servicePath || opts?.apiEndpoint
    );
    const port = opts?.port || staticMembers.port;
    const clientConfig = opts?.clientConfig ?? {};
    // Implicitely set 'rest' value for the apis use rest as transport (eg. googleapis-discovery apis).
    if (!opts) {
      opts = {fallback: 'rest'};
    } else {
      opts.fallback = opts.fallback ?? 'rest';
    }
    const fallback =
      opts?.fallback ??
      (typeof window !== 'undefined' && typeof window?.fetch === 'function');
    opts = Object.assign({servicePath, port, clientConfig, fallback}, opts);

    // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case.
    if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) {
      opts['scopes'] = staticMembers.scopes;
    }

    // Load google-gax module synchronously if needed
    if (!gaxInstance) {
      gaxInstance = require('google-gax') as typeof gax;
    }

    // Choose either gRPC or proto-over-HTTP implementation of google-gax.
    this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance;

    // Create a `gaxGrpc` object, with any grpc-specific options sent to the client.
    this._gaxGrpc = new this._gaxModule.GrpcClient(opts);

    // Save options to use in initialize() method.
    this._opts = opts;

    // Save the auth object to the client, for use by other methods.
    this.auth = this._gaxGrpc.auth as gax.GoogleAuth;

    // Set defaultServicePath on the auth object.
    this.auth.defaultServicePath = staticMembers.servicePath;

    // Set the default scopes in auth client if needed.
    if (servicePath === staticMembers.servicePath) {
      this.auth.defaultScopes = staticMembers.scopes;
    }

    // Determine the client header string.
    const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`];
    if (typeof process !== 'undefined' && 'versions' in process) {
      clientHeader.push(`gl-node/${process.versions.node}`);
    } else {
      clientHeader.push(`gl-web/${this._gaxModule.version}`);
    }
    if (!opts.fallback) {
      clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`);
    } else if (opts.fallback === 'rest') {
      clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`);
    }
    if (opts.libName && opts.libVersion) {
      clientHeader.push(`${opts.libName}/${opts.libVersion}`);
    }
    // Load the applicable protos.
    this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos);

    // Some of the methods on this service return "paged" results,
    // (e.g. 50 results at a time, with tokens to get subsequent
    // pages). Denote the keys used for pagination and results.
    this.descriptors.page = {
      aggregatedList: new this._gaxModule.PageDescriptor(
        'pageToken',
        'nextPageToken',
        'items'
      ),
      list: new this._gaxModule.PageDescriptor(
        'pageToken',
        'nextPageToken',
        'items'
      ),
    };

    // Put together the default options sent with requests.
    this._defaults = this._gaxGrpc.constructSettings(
      'google.cloud.compute.v1small.Addresses',
      gapicConfig as gax.ClientConfig,
      opts.clientConfig || {},
      {'x-goog-api-client': clientHeader.join(' ')}
    );

    // Set up a dictionary of "inner API calls"; the core implementation
    // of calling the API is handled in `google-gax`, with this code
    // merely providing the destination and request information.
    this.innerApiCalls = {};

    // Add a warn function to the client constructor so it can be easily tested.
    this.warn = this._gaxModule.warn;
  }

  /**
   * Initialize the client.
   * Performs asynchronous operations (such as authentication) and prepares the client.
   * This function will be called automatically when any class method is called for the
   * first time, but if you need to initialize it before calling an actual method,
   * feel free to call initialize() directly.
   *
   * You can await on this method if you want to make sure the client is initialized.
   *
   * @returns {Promise} A promise that resolves to an authenticated service stub.
   */
  initialize() {
    // If the client stub promise is already initialized, return immediately.
    if (this.addressesStub) {
      return this.addressesStub;
    }

    // Put together the "service stub" for
    // google.cloud.compute.v1small.Addresses.
    this.addressesStub = this._gaxGrpc.createStub(
      this._opts.fallback
        ? (this._protos as protobuf.Root).lookupService(
            'google.cloud.compute.v1small.Addresses'
          )
        : // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (this._protos as any).google.cloud.compute.v1small.Addresses,
      this._opts,
      this._providedCustomServicePath
    ) as Promise<{[method: string]: Function}>;

    // Iterate over each of the methods that the service provides
    // and create an API call method for each.
    const addressesStubMethods = ['aggregatedList', 'delete', 'insert', 'list'];
    for (const methodName of addressesStubMethods) {
      const callPromise = this.addressesStub.then(
        stub =>
          (...args: Array<{}>) => {
            if (this._terminated) {
              return Promise.reject('The client has already been closed.');
            }
            const func = stub[methodName];
            return func.apply(stub, args);
          },
        (err: Error | null | undefined) => () => {
          throw err;
        }
      );

      const descriptor = this.descriptors.page[methodName] || undefined;
      const apiCall = this._gaxModule.createApiCall(
        callPromise,
        this._defaults[methodName],
        descriptor,
        this._opts.fallback
      );

      this.innerApiCalls[methodName] = apiCall;
    }

    return this.addressesStub;
  }

  /**
   * The DNS address for this API service.
   * @returns {string} The DNS address for this service.
   */
  static get servicePath() {
    return 'compute.googleapis.com';
  }

  /**
   * The DNS address for this API service - same as servicePath(),
   * exists for compatibility reasons.
   * @returns {string} The DNS address for this service.
   */
  static get apiEndpoint() {
    return 'compute.googleapis.com';
  }

  /**
   * The port for this API service.
   * @returns {number} The default port for this service.
   */
  static get port() {
    return 443;
  }

  /**
   * The scopes needed to make gRPC calls for every method defined
   * in this service.
   * @returns {string[]} List of default scopes.
   */
  static get scopes() {
    return [
      'https://www.googleapis.com/auth/compute',
      'https://www.googleapis.com/auth/cloud-platform',
    ];
  }

  getProjectId(): Promise<string>;
  getProjectId(callback: Callback<string, undefined, undefined>): void;
  /**
   * Return the project ID used by this class.
   * @returns {Promise} A promise that resolves to string containing the project ID.
   */
  getProjectId(
    callback?: Callback<string, undefined, undefined>
  ): Promise<string> | void {
    if (callback) {
      this.auth.getProjectId(callback);
      return;
    }
    return this.auth.getProjectId();
  }

  // -------------------
  // -- Service calls --
  // -------------------
  /**
   * Deletes the specified address resource.
   *
   * @param {Object} request
   *   The request object that will be sent.
   * @param {string} request.address
   *   Name of the address resource to delete.
   * @param {string} request.project
   *   Project ID for this request.
   * @param {string} request.region
   *   Name of the region for this request.
   * @param {string} request.requestId
   *   An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
   *
   *   For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
   *
   *   The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
   * @param {object} [options]
   *   Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
   * @returns {Promise} - The promise which resolves to an array.
   *   The first element of the array is an object representing
   *   a long running operation.
   *   Please see the
   *   [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations)
   *   for more details and examples.
   *   This method is considered to be in beta. This means while
   *   stable it is still a work-in-progress and under active development,
   *   and might get backwards-incompatible changes at any time.
   *   `.promise()` is not supported yet.
   * @example
include:samples/generated/v1small/addresses.delete.js

   * region_tag:compute_v1small_generated_Addresses_Delete_async
   */
  delete(
    request?: protos.google.cloud.compute.v1small.IDeleteAddressRequest,
    options?: CallOptions
  ): Promise<
    [
      LROperation<protos.google.cloud.compute.v1small.IOperation, null>,
      protos.google.cloud.compute.v1small.IOperation | undefined,
      {} | undefined
    ]
  >;
  delete(
    request: protos.google.cloud.compute.v1small.IDeleteAddressRequest,
    options: CallOptions,
    callback: Callback<
      protos.google.cloud.compute.v1small.IOperation,
      | protos.google.cloud.compute.v1small.IDeleteAddressRequest
      | null
      | undefined,
      {} | null | undefined
    >
  ): void;
  delete(
    request: protos.google.cloud.compute.v1small.IDeleteAddressRequest,
    callback: Callback<
      protos.google.cloud.compute.v1small.IOperation,
      | protos.google.cloud.compute.v1small.IDeleteAddressRequest
      | null
      | undefined,
      {} | null | undefined
    >
  ): void;
  delete(
    request?: protos.google.cloud.compute.v1small.IDeleteAddressRequest,
    optionsOrCallback?:
      | CallOptions
      | Callback<
          protos.google.cloud.compute.v1small.IOperation,
          | protos.google.cloud.compute.v1small.IDeleteAddressRequest
          | null
          | undefined,
          {} | null | undefined
        >,
    callback?: Callback<
      protos.google.cloud.compute.v1small.IOperation,
      | protos.google.cloud.compute.v1small.IDeleteAddressRequest
      | null
      | undefined,
      {} | null | undefined
    >
  ): Promise<
    [
      LROperation<protos.google.cloud.compute.v1small.IOperation, null>,
      protos.google.cloud.compute.v1small.IOperation | undefined,
      {} | undefined
    ]
  > | void {
    request = request || {};
    let options: CallOptions;
    if (typeof optionsOrCallback === 'function' && callback === undefined) {
      callback = optionsOrCallback;
      options = {};
    } else {
      options = optionsOrCallback as CallOptions;
    }
    options = options || {};
    options.otherArgs = options.otherArgs || {};
    options.otherArgs.headers = options.otherArgs.headers || {};
    options.otherArgs.headers['x-goog-request-params'] =
      this._gaxModule.routingHeader.fromParams({
        project: request.project ?? '',
        region: request.region ?? '',
        address: request.address ?? '',
      });
    this.initialize();
    return this.innerApiCalls
      .delete(request, options, callback)
      .then(
        ([response, operation, rawResponse]: [
          protos.google.cloud.compute.v1.IOperation,
          protos.google.cloud.compute.v1.IOperation,
          protos.google.cloud.compute.v1.IOperation
        ]) => {
          return [
            {
              latestResponse: response,
              done: false,
              name: response.id,
              metadata: null,
              result: {},
            },
            operation,
            rawResponse,
          ];
        }
      );
  }
  /**
   * Creates an address resource in the specified project by using the data included in the request.
   *
   * @param {Object} request
   *   The request object that will be sent.
   * @param {google.cloud.compute.v1small.Address} request.addressResource
   *   The body resource for this request
   * @param {string} request.project
   *   Project ID for this request.
   * @param {string} request.region
   *   Name of the region for this request.
   * @param {string} request.requestId
   *   An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
   *
   *   For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
   *
   *   The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
   * @param {object} [options]
   *   Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
   * @returns {Promise} - The promise which resolves to an array.
   *   The first element of the array is an object representing
   *   a long running operation.
   *   Please see the
   *   [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations)
   *   for more details and examples.
   *   This method is considered to be in beta. This means while
   *   stable it is still a work-in-progress and under active development,
   *   and might get backwards-incompatible changes at any time.
   *   `.promise()` is not supported yet.
   * @example
include:samples/generated/v1small/addresses.insert.js

   * region_tag:compute_v1small_generated_Addresses_Insert_async
   */
  insert(
    request?: protos.google.cloud.compute.v1small.IInsertAddressRequest,
    options?: CallOptions
  ): Promise<
    [
      LROperation<protos.google.cloud.compute.v1small.IOperation, null>,
      protos.google.cloud.compute.v1small.IOperation | undefined,
      {} | undefined
    ]
  >;
  insert(
    request: protos.google.cloud.compute.v1small.IInsertAddressRequest,
    options: CallOptions,
    callback: Callback<
      protos.google.cloud.compute.v1small.IOperation,
      | protos.google.cloud.compute.v1small.IInsertAddressRequest
      | null
      | undefined,
      {} | null | undefined
    >
  ): void;
  insert(
    request: protos.google.cloud.compute.v1small.IInsertAddressRequest,
    callback: Callback<
      protos.google.cloud.compute.v1small.IOperation,
      | protos.google.cloud.compute.v1small.IInsertAddressRequest
      | null
      | undefined,
      {} | null | undefined
    >
  ): void;
  insert(
    request?: protos.google.cloud.compute.v1small.IInsertAddressRequest,
    optionsOrCallback?:
      | CallOptions
      | Callback<
          protos.google.cloud.compute.v1small.IOperation,
          | protos.google.cloud.compute.v1small.IInsertAddressRequest
          | null
          | undefined,
          {} | null | undefined
        >,
    callback?: Callback<
      protos.google.cloud.compute.v1small.IOperation,
      | protos.google.cloud.compute.v1small.IInsertAddressRequest
      | null
      | undefined,
      {} | null | undefined
    >
  ): Promise<
    [
      LROperation<protos.google.cloud.compute.v1small.IOperation, null>,
      protos.google.cloud.compute.v1small.IOperation | undefined,
      {} | undefined
    ]
  > | void {
    request = request || {};
    let options: CallOptions;
    if (typeof optionsOrCallback === 'function' && callback === undefined) {
      callback = optionsOrCallback;
      options = {};
    } else {
      options = optionsOrCallback as CallOptions;
    }
    options = options || {};
    options.otherArgs = options.otherArgs || {};
    options.otherArgs.headers = options.otherArgs.headers || {};
    options.otherArgs.headers['x-goog-request-params'] =
      this._gaxModule.routingHeader.fromParams({
        project: request.project ?? '',
        region: request.region ?? '',
      });
    this.initialize();
    return this.innerApiCalls
      .insert(request, options, callback)
      .then(
        ([response, operation, rawResponse]: [
          protos.google.cloud.compute.v1.IOperation,
          protos.google.cloud.compute.v1.IOperation,
          protos.google.cloud.compute.v1.IOperation
        ]) => {
          return [
            {
              latestResponse: response,
              done: false,
              name: response.id,
              metadata: null,
              result: {},
            },
            operation,
            rawResponse,
          ];
        }
      );
  }

  /**
   * Retrieves an aggregated list of addresses.
   *
   * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand.
   * @param {Object} request
   *   The request object that will be sent.
   * @param {string} request.filter
   *   A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
   *
   *   For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
   *
   *   You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
   *
   *   To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
   * @param {boolean} request.includeAllScopes
   *   Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included.
   * @param {number} request.maxResults
   *   The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
   * @param {string} request.orderBy
   *   Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
   *
   *   You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
   *
   *   Currently, only sorting by `name` or `creationTimestamp desc` is supported.
   * @param {string} request.pageToken
   *   Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
   * @param {string} request.project
   *   Project ID for this request.
   * @param {object} [options]
   *   Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
   * @returns {Object}
   *   An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
   *   When you iterate the returned iterable, each element will be an object representing
   *   as tuple [string, [AddressesScopedList]{@link google.cloud.compute.v1small.AddressesScopedList}]. The API will be called under the hood as needed, once per the page,
   *   so you can stop the iteration when you don't need more results.
   *   Please see the
   *   [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
   *   for more details and examples.
   * @example
include:samples/generated/v1small/addresses.aggregated_list.js

   * region_tag:compute_v1small_generated_Addresses_AggregatedList_async
   */
  aggregatedListAsync(
    request?: protos.google.cloud.compute.v1small.IAggregatedListAddressesRequest,
    options?: CallOptions
  ): AsyncIterable<
    [string, protos.google.cloud.compute.v1small.IAddressesScopedList]
  > {
    request = request || {};
    options = options || {};
    options.otherArgs = options.otherArgs || {};
    options.otherArgs.headers = options.otherArgs.headers || {};
    options.otherArgs.headers['x-goog-request-params'] =
      this._gaxModule.routingHeader.fromParams({
        project: request.project ?? '',
      });
    const defaultCallSettings = this._defaults['aggregatedList'];
    const callSettings = defaultCallSettings.merge(options);
    this.initialize();
    return this.descriptors.page.aggregatedList.asyncIterate(
      this.innerApiCalls['aggregatedList'] as GaxCall,
      request as {},
      callSettings
    ) as AsyncIterable<
      [string, protos.google.cloud.compute.v1small.IAddressesScopedList]
    >;
  }
  /**
   * Retrieves a list of addresses contained within the specified region.
   *
   * @param {Object} request
   *   The request object that will be sent.
   * @param {string} request.filter
   *   A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
   *
   *   For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
   *
   *   You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
   *
   *   To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
   * @param {number} request.maxResults
   *   The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
   * @param {string} request.orderBy
   *   Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
   *
   *   You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
   *
   *   Currently, only sorting by name or creationTimestamp desc is supported.
   * @param {string} request.pageToken
   *   Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
   * @param {string} request.project
   *   Project ID for this request.
   * @param {string} request.region
   *   Name of the region for this request.
   * @param {object} [options]
   *   Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
   * @returns {Promise} - The promise which resolves to an array.
   *   The first element of the array is Array of [Address]{@link google.cloud.compute.v1small.Address}.
   *   The client library will perform auto-pagination by default: it will call the API as many
   *   times as needed and will merge results from all the pages into this array.
   *   Note that it can affect your quota.
   *   We recommend using `listAsync()`
   *   method described below for async iteration which you can stop as needed.
   *   Please see the
   *   [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
   *   for more details and examples.
   */
  list(
    request?: protos.google.cloud.compute.v1small.IListAddressesRequest,
    options?: CallOptions
  ): Promise<
    [
      protos.google.cloud.compute.v1small.IAddress[],
      protos.google.cloud.compute.v1small.IListAddressesRequest | null,
      protos.google.cloud.compute.v1small.IAddressList
    ]
  >;
  list(
    request: protos.google.cloud.compute.v1small.IListAddressesRequest,
    options: CallOptions,
    callback: PaginationCallback<
      protos.google.cloud.compute.v1small.IListAddressesRequest,
      protos.google.cloud.compute.v1small.IAddressList | null | undefined,
      protos.google.cloud.compute.v1small.IAddress
    >
  ): void;
  list(
    request: protos.google.cloud.compute.v1small.IListAddressesRequest,
    callback: PaginationCallback<
      protos.google.cloud.compute.v1small.IListAddressesRequest,
      protos.google.cloud.compute.v1small.IAddressList | null | undefined,
      protos.google.cloud.compute.v1small.IAddress
    >
  ): void;
  list(
    request?: protos.google.cloud.compute.v1small.IListAddressesRequest,
    optionsOrCallback?:
      | CallOptions
      | PaginationCallback<
          protos.google.cloud.compute.v1small.IListAddressesRequest,
          protos.google.cloud.compute.v1small.IAddressList | null | undefined,
          protos.google.cloud.compute.v1small.IAddress
        >,
    callback?: PaginationCallback<
      protos.google.cloud.compute.v1small.IListAddressesRequest,
      protos.google.cloud.compute.v1small.IAddressList | null | undefined,
      protos.google.cloud.compute.v1small.IAddress
    >
  ): Promise<
    [
      protos.google.cloud.compute.v1small.IAddress[],
      protos.google.cloud.compute.v1small.IListAddressesRequest | null,
      protos.google.cloud.compute.v1small.IAddressList
    ]
  > | void {
    request = request || {};
    let options: CallOptions;
    if (typeof optionsOrCallback === 'function' && callback === undefined) {
      callback = optionsOrCallback;
      options = {};
    } else {
      options = optionsOrCallback as CallOptions;
    }
    options = options || {};
    options.otherArgs = options.otherArgs || {};
    options.otherArgs.headers = options.otherArgs.headers || {};
    options.otherArgs.headers['x-goog-request-params'] =
      this._gaxModule.routingHeader.fromParams({
        project: request.project ?? '',
        region: request.region ?? '',
      });
    this.initialize();
    return this.innerApiCalls.list(request, options, callback);
  }

  /**
   * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object.
   * @param {Object} request
   *   The request object that will be sent.
   * @param {string} request.filter
   *   A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
   *
   *   For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
   *
   *   You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
   *
   *   To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
   * @param {number} request.maxResults
   *   The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
   * @param {string} request.orderBy
   *   Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
   *
   *   You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
   *
   *   Currently, only sorting by name or creationTimestamp desc is supported.
   * @param {string} request.pageToken
   *   Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
   * @param {string} request.project
   *   Project ID for this request.
   * @param {string} request.region
   *   Name of the region for this request.
   * @param {object} [options]
   *   Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
   * @returns {Stream}
   *   An object stream which emits an object representing [Address]{@link google.cloud.compute.v1small.Address} on 'data' event.
   *   The client library will perform auto-pagination by default: it will call the API as many
   *   times as needed. Note that it can affect your quota.
   *   We recommend using `listAsync()`
   *   method described below for async iteration which you can stop as needed.
   *   Please see the
   *   [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
   *   for more details and examples.
   */
  listStream(
    request?: protos.google.cloud.compute.v1small.IListAddressesRequest,
    options?: CallOptions
  ): Transform {
    request = request || {};
    options = options || {};
    options.otherArgs = options.otherArgs || {};
    options.otherArgs.headers = options.otherArgs.headers || {};
    options.otherArgs.headers['x-goog-request-params'] =
      this._gaxModule.routingHeader.fromParams({
        project: request.project ?? '',
        region: request.region ?? '',
      });
    const defaultCallSettings = this._defaults['list'];
    const callSettings = defaultCallSettings.merge(options);
    this.initialize();
    return this.descriptors.page.list.createStream(
      this.innerApiCalls.list as GaxCall,
      request,
      callSettings
    );
  }

  /**
   * Equivalent to `list`, but returns an iterable object.
   *
   * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand.
   * @param {Object} request
   *   The request object that will be sent.
   * @param {string} request.filter
   *   A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
   *
   *   For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
   *
   *   You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
   *
   *   To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
   * @param {number} request.maxResults
   *   The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
   * @param {string} request.orderBy
   *   Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
   *
   *   You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
   *
   *   Currently, only sorting by name or creationTimestamp desc is supported.
   * @param {string} request.pageToken
   *   Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
   * @param {string} request.project
   *   Project ID for this request.
   * @param {string} request.region
   *   Name of the region for this request.
   * @param {object} [options]
   *   Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
   * @returns {Object}
   *   An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
   *   When you iterate the returned iterable, each element will be an object representing
   *   [Address]{@link google.cloud.compute.v1small.Address}. The API will be called under the hood as needed, once per the page,
   *   so you can stop the iteration when you don't need more results.
   *   Please see the
   *   [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
   *   for more details and examples.
   * @example
include:samples/generated/v1small/addresses.list.js

   * region_tag:compute_v1small_generated_Addresses_List_async
   */
  listAsync(
    request?: protos.google.cloud.compute.v1small.IListAddressesRequest,
    options?: CallOptions
  ): AsyncIterable<protos.google.cloud.compute.v1small.IAddress> {
    request = request || {};
    options = options || {};
    options.otherArgs = options.otherArgs || {};
    options.otherArgs.headers = options.otherArgs.headers || {};
    options.otherArgs.headers['x-goog-request-params'] =
      this._gaxModule.routingHeader.fromParams({
        project: request.project ?? '',
        region: request.region ?? '',
      });
    const defaultCallSettings = this._defaults['list'];
    const callSettings = defaultCallSettings.merge(options);
    this.initialize();
    return this.descriptors.page.list.asyncIterate(
      this.innerApiCalls['list'] as GaxCall,
      request as {},
      callSettings
    ) as AsyncIterable<protos.google.cloud.compute.v1small.IAddress>;
  }

  /**
   * Terminate the gRPC channel and close the client.
   *
   * The client will no longer be usable and all future behavior is undefined.
   * @returns {Promise} A promise that resolves when the client is closed.
   */
  close(): Promise<void> {
    if (this.addressesStub && !this._terminated) {
      return this.addressesStub.then(stub => {
        this._terminated = true;
        stub.close();
      });
    }
    return Promise.resolve();
  }
}


text:
using System;
using NakedFramework.Architecture.Facet;
using NakedFramework.Metamodel.Facet;

namespace NakedObjects.Reflector.Facet;

[Serializable]
public abstract class UpdatedCallbackFacetAbstract : CallbackFacetAbstract, IUpdatedCallbackFacet {
    public override Type FacetType => typeof(IUpdatedCallbackFacet);
}

// Copyright (c) Naked Objects Group Ltd.

redpajama_set_name: RedPajamaGithub


text:
var https = require("https");
var fs = require("fs");

var options = {
	hostname: "en.wikipedia.org",
	port: 443,
	path: "/wiki/George_Washington",
	method: "GET"
};

var req = https.request(options, function(response){
console.log("s");
	var responseBody = "";
	global.console.log("Response from server started.");
	global.console.log(`Server Status: ${response.statusCode}`);
	global.console.log("Respomse Headers: %j", response.headers);

	response.setEncoding("UTF-8");

	response.once("data", function(chunk){
		global.console.log(chunk);
	});

	response.on("data", function(chunk){
		global.console.log("--Chunk-- %j", chunk.length);
		responseBody += chunk;
	});

	response.on("end", function(){
		fs.writeFile("george-washington.html", responseBody, function(err){
			if(err){
				throw err;
			}

			global.console.log("File Downloaded");
			global.console.log(responseBody);
		});
	});
});

req.on("error", function(err){
	global.console.log("Problem with request: %j", err.message);
});

req.end();


text:
define(function(require, exports, module) {

	console.log('加载了 multiply 模块')

	var multiply = function(x, y) {
	    return x * y;
	};

    module.exports = {
        multiply: multiply
    };

});


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

<title>NoisyPacMan</title>
<meta name="date" content="2014-01-08">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

cpsr.environment.simulation.domains

Class NoisyPacMan

java.lang.Object

cpsr.environment.simulation.ASimulator

cpsr.environment.simulation.domains.PacMan

cpsr.environment.simulation.domains.NoisyPacMan

All Implemented Interfaces:

ISimulator

public class NoisyPacMan
extends PacMan

Field Summary

Fields

Modifier and Type
Field and Description

static double
NOISE

Fields inherited from class cpsr.environment.simulation.ASimulator

DEFAULT_RUN_LEN_LIMIT

Constructor Summary

Constructors

Constructor and Description

NoisyPacMan(long seed)

Method Summary

Methods

Modifier and Type
Method and Description

static void
main(java.lang.String[] args)

Methods inherited from class cpsr.environment.simulation.domains.PacMan

getName

Methods inherited from class cpsr.environment.simulation.ASimulator

getRandomPlanner, setMaxRunLength, simulateTestRuns, simulateTrainingRuns, simulateTrainingRuns

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

NOISE

public static double NOISE

Constructor Detail

NoisyPacMan

public NoisyPacMan(long seed)

Method Detail

main

public static void main(java.lang.String[] args)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


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

#if DOUBLE
#elif NETSTANDARD2_1
using Math = System.MathF;
#else
using Math = KelpNet.MathF;
#endif

namespace KelpNet
{
    [Serializable]
    [DebuggerDisplay("{Name + ToString(\"Size\")}", Type = "{\"NdArray\" + ToString(\"Size\")}")]
    public class NdArray<T> where T : unmanaged, IComparable<T>
    {
        public string Name = "NdArray";

        public T[] Data;

        [NonSerialized]
        public T[] Grad;

        //各関数内でまとめて実行されるバッチの数を示し、Loss関数内の割引で使用される
        public int BatchCount = 1;

        //このNdArrayの各次元のサイズ
        public int[] Shape;

        //Shapeから算出されるLengthで、DataのLengthとは異なる
        public int Length;

        //関数によって使用された回数をカウントしBackward動作のタイミングを図る
        [NonSerialized]
        public int UseCount;

        //自身が関数から生成された場合、その関数をここに保存する
        [NonSerialized]
        public IFunction<T> ParentFunc;

        //Updateを行わずに実行されたBackwardの回数をカウントし、Optimizer実行時に使用する
        [NonSerialized]
        public int TrainCount;

        public NdArray(Array array, bool asBatch = false, IFunction<T> parentFunc = null)
        {
            this.Data = array.FlattenEx<T>();

            //1次元目をバッチとして扱うか?
            if (asBatch)
            {
                this.BatchCount = array.Rank > 1 ? array.GetLength(0) : array.Length;
                int[] resultShape = array.Rank > 1 ? new int[array.Rank - 1] : new[] { 1 };

                if (array.Rank > 1)
                {
                    for (int i = 0; i < resultShape.Length; i++)
                    {
                        resultShape[i] = array.GetLength(i + 1);
                    }
                }

                this.Shape = resultShape;
                this.Length = NdArray.ShapeToLength(this.Shape);
            }
            else
            {
                int[] resultShape = new int[array.Rank];

                for (int i = 0; i < array.Rank; i++)
                {
                    resultShape[i] = array.GetLength(i);
                }

                this.Shape = resultShape;
                this.Length = Data.Length;
            }

            this.ParentFunc = parentFunc;
        }

        public NdArray(params int[] shape)
        {
            this.Data = new T[NdArray.ShapeToLength(shape)];
            this.Shape = shape.ToArray();
            this.Length = Data.Length;
        }

        public NdArray(T[] data, int[] shape, int batchCount = 1, IFunction<T> parentFunc = null)
        {
            this.Shape = shape.ToArray();
            this.Length = data.Length / batchCount;
            this.BatchCount = batchCount;
            this.Data = data.ToArray();
            this.ParentFunc = parentFunc;
        }

        public NdArray(int[] shape, int batchCount, IFunction<T> parentFunc = null)
        {
            this.Shape = shape.ToArray();
            this.Length = NdArray.ShapeToLength(this.Shape);
            this.BatchCount = batchCount;
            this.Data = new T[this.Length * batchCount];
            this.ParentFunc = parentFunc;
        }

        //インデクサはあまり早くないので頻繁にアクセスする場合は使用をオススメしません。デバッグ用途向けと割り切ってください。
        public T this[int batchcount, params int[] indices]
        {
            get
            {
                return this.Data[this.GetLocalIndex(batchcount, indices)];
            }
            set
            {
                this.Data[this.GetLocalIndex(batchcount, indices)] = value;
            }
        }

        public void Reshape(params int[] shape)
        {
            int val = 0;
            int dimension = Length;

            //-1指定を算出
            if (shape.Contains(-1))
            {
                int minusIndex = -1;

                for (int i = 0; i < shape.Length; i++)
                {
                    if (shape[i] != -1)
                    {
                        val += Length % shape[i];

                        if (val == 0)
                        {
                            dimension /= shape[i];
                        }
                        else
                        {
                            throw new Exception("要素の指定が間違っています");
                        }
                    }
                    else
                    {
                        if (minusIndex != -1)
                        {
                            throw new Exception("-1が二つ以上指定されています");
                        }

                        minusIndex = i;
                    }
                }

                shape[minusIndex] = dimension;
            }
#if DEBUG
            else if (Length != NdArray.ShapeToLength(shape)) throw new Exception("指定されたShapeのサイズが現在のData.Lengthと等しくありません");
#endif

            Shape = shape.ToArray();
        }

        //バッチでまとまっているアレイをバラバラにして排出する
        public NdArray<T>[] DivideArrays()
        {
            NdArray<T>[] result = new NdArray<T>[BatchCount];

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = GetSingleArray(i);
            }

            return result;
        }

        //バッチ番号に対応するアレイを排出する
        public NdArray<T> GetSingleArray(int i)
        {
            T[] data = new T[this.Length];
            Array.Copy(this.Data, i * this.Length, data, 0, this.Length);

            return new NdArray<T>(data, this.Shape);
        }

        public void CountUp()
        {
            TrainCount++;
        }

        //傾きの初期化
        public void InitGrad()
        {
            this.Grad = new T[this.Data.Length];
        }

        //傾きの初期化
        public void ClearGrad()
        {
            this.Grad = null;
        }

        public override string ToString()
        {
            return ToString(this.Data);
        }

        public string ToString(string format)
        {
            switch (format)
            {
                case "Data":
                    return ToString(this.Data);

                case "Grad":
                    return ToString(this.Grad);

                case "Shape":
                    return "[" + string.Join(",", Shape) + "]";

                case "Size":
                    return "[" + string.Join(",", Shape) + "]" +
                           (BatchCount > 1 ? "x" + BatchCount + "batch" : string.Empty);

                case "Name":
                    return Name;

                default:
                    return Name;
            }
        }

        public string ToString(T[] datas)
        {
#if DEBUG
            if (Shape.Length == 0 && datas.Length != 1) throw new Exception();
#endif
            //単品データ
            if (Shape.Length == 0 && datas.Length == 1)
            {
                return datas[0].ToString();
            }

            StringBuilder sb = new StringBuilder();

            int intMaxLength = 0; //整数部の最大値
            int realMaxLength = 0; //小数点以下の最大値
            bool isExponential = false; //指数表現にするか

            foreach (T data in datas)
            {
                string[] divStr = data.ToString().Split('.');
                intMaxLength = (int)Math.Max(intMaxLength, divStr[0].Length);

                if (divStr.Length > 1)
                {
                    isExponential |= divStr[1].Contains("E");
                }

                if (realMaxLength != 8 && divStr.Length == 2)
                {
                    realMaxLength = (int)Math.Max(realMaxLength, divStr[1].Length);

                    if (realMaxLength > 8)
                    {
                        realMaxLength = 8;
                    }
                }
            }

            //配列の約数を取得
            int[] commonDivisorList = new int[this.Shape.Length];

            //一個目は手動取得
            commonDivisorList[0] = this.Shape[this.Shape.Length - 1];

            for (int i = 1; i < this.Shape.Length; i++)
            {
                commonDivisorList[i] = commonDivisorList[i - 1] * this.Shape[this.Shape.Length - i - 1];
            }

            if (this.BatchCount > 1)
            {
                sb.Append("{");
            }

            for (int batch = 0; batch < this.BatchCount; batch++)
            {
                int indexOffset = batch * Length;
                //先頭の括弧
                for (int i = 0; i < this.Shape.Length; i++)
                {
                    sb.Append("[");
                }

                int closer = 0;
                for (int i = 0; i < Length; i++)
                {
                    string[] divStr;
                    if (isExponential)
                    {
                        divStr = string.Format("{0:0.00000000e+00}", datas[indexOffset + i]).Split('.');
                    }
                    else
                    {
                        divStr = datas[indexOffset + i].ToString().Split('.');
                    }

                    //最大文字数でインデントを揃える
                    for (int j = 0; j < intMaxLength - divStr[0].Length; j++)
                    {
                        sb.Append(" ");
                    }
                    sb.Append(divStr[0]);
                    if (realMaxLength != 0)
                    {
                        sb.Append(".");
                    }
                    if (divStr.Length == 2)
                    {
                        sb.Append(divStr[1].Length > 8 && !isExponential ? divStr[1].Substring(0, 8) : divStr[1]);
                        for (int j = 0; j < realMaxLength - divStr[1].Length; j++)
                        {
                            sb.Append(" ");
                        }
                    }
                    else
                    {
                        for (int j = 0; j < realMaxLength; j++)
                        {
                            sb.Append(" ");
                        }
                    }

                    //約数を調査してピッタリなら括弧を出力
                    if (i != Length - 1)
                    {
                        foreach (int commonDivisor in commonDivisorList)
                        {
                            if ((i + 1) % commonDivisor == 0)
                            {
                                sb.Append("]");
                                closer++;
                            }
                        }

                        sb.Append(" ");

                        if ((i + 1) % commonDivisorList[0] == 0)
                        {
                            //閉じ括弧分だけ改行を追加
                            for (int j = 0; j < closer; j++)
                            {
                                sb.Append("\n");
                            }
                            closer = 0;

                            if (BatchCount > 1) sb.Append(" ");

                            //括弧前のインデント
                            foreach (int commonDivisor in commonDivisorList)
                            {
                                if ((i + 1) % commonDivisor != 0)
                                {
                                    sb.Append(" ");
                                }
                            }
                        }

                        foreach (int commonDivisor in commonDivisorList)
                        {
                            if ((i + 1) % commonDivisor == 0)
                            {
                                sb.Append("[");
                            }
                        }
                    }
                }

                //後端の括弧
                for (int i = 0; i < this.Shape.Length; i++)
                {
                    sb.Append("]");
                }

                if (batch < this.BatchCount - 1)
                {
                    sb.Append("},\n{");
                }
            }

            if (this.BatchCount > 1)
            {
                sb.Append("}");
            }

            return sb.ToString();
        }

        public static NdArray<T> operator +(NdArray<T> a, NdArray<T> b)
        {
            return new Add<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator +(NdArray<T> a, T b)
        {
            return new AddConst<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator +(T a, NdArray<T> b)
        {
            return new ConstAdd<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator *(NdArray<T> a, NdArray<T> b)
        {
            return new Mul<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator *(NdArray<T> a, T b)
        {
            return new MulConst<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator *(T a, NdArray<T> b)
        {
            return new ConstMul<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator -(NdArray<T> a, NdArray<T> b)
        {
            return new Sub<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator -(NdArray<T> a, T b)
        {
            return new SubConst<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator -(T a, NdArray<T> b)
        {
            return new ConstSub<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator /(NdArray<T> a, NdArray<T> b)
        {
            return new Div<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator /(NdArray<T> a, T b)
        {
            return new DivConst<T>().Forward(a, b)[0];
        }

        public static NdArray<T> operator /(T a, NdArray<T> b)
        {
            return new ConstDiv<T>().Forward(a, b)[0];
        }

        public static implicit operator NdArray<T>(T[] a)
        {
            return new NdArray<T>(a);
        }

        public static implicit operator NdArray<T>(T a)
        {
            return new NdArray<T>(new[] { a });
        }

        //public static implicit operator NdArray<T>(long a)
        //{
        //    return new NdArray<T>(new[] { (T)a });
        //}

        //コピーを作成するメソッド
        public NdArray<T> Clone()
        {
            return new NdArray<T>(Data, Shape, BatchCount, ParentFunc)
            {
                Grad = Grad?.ToArray(),
                Name = Name,
                Length = Length,
                UseCount = UseCount,
                TrainCount = TrainCount
            };
        }

        public void Fill(T val)
        {
            for (int i = 0; i < Data.Length; i++)
            {
                Data[i] = val;
            }
        }

        public void FillGrad(T val)
        {
            for (int i = 0; i < Grad.Length; i++)
            {
                Grad[i] = val;
            }
        }

        public int[] GetDimensionsIndex(int index)
        {
            //バッチ分を補正
            int batchCount = index / this.Length;
            index -= this.Length * batchCount;

            int[] dimensionsIndex = new int[this.Shape.Length];

            for (int i = this.Shape.Length - 1; i >= 0; i--)
            {
                dimensionsIndex[i] = index % this.Shape[i];
                index /= this.Shape[i];
            }

            return dimensionsIndex;
        }

        public int GetLocalIndex(int batchIndex, params int[] indices)
        {
            int result = 0;
            int rankOffset = 1;

            for (int i = indices.Length - 1; i >= 0; i--)
            {
                result += indices[i] * rankOffset;
                rankOffset *= Shape[i];
            }

            return result + batchIndex * Length;
        }

    }

    public static class NdArray
    {
        public static int ShapeToLength(params int[] shapes)
        {
            int result = 1;

            foreach (int shape in shapes)
            {
                result *= shape;
            }

            return result;
        }

        //アレイ配列をバッチとして登録する
        public static NdArray<T> FromArrays<T>(T[][] arrays, IFunction<T> parentFunc = null) where T : unmanaged, IComparable<T>
        {
            int[] resultShape = new int[arrays[0].Rank];

            for (int i = 0; i < arrays[0].Rank; i++)
            {
                resultShape[i] = arrays[0].GetLength(i);
            }

            int length = arrays[0].Length;
            T[] result = new T[length * arrays.Length];

            for (int i = 0; i < arrays.Length; i++)
            {
                Array.Copy(arrays[i], 0, result, length * i, length);
            }

            return new NdArray<T>(result, resultShape, arrays.Length, parentFunc);
        }

        public static NdArray<T> FromArrays<T>(List<T[]> arrays, IFunction<T> parentFunc = null) where T : unmanaged, IComparable<T>
        {
            int[] resultShape = new int[arrays[0].Rank];

            for (int i = 0; i < arrays[0].Rank; i++)
            {
                resultShape[i] = arrays[0].GetLength(i);
            }

            int length = arrays[0].Length;
            T[] result = new T[length * arrays.Count];

            for (int i = 0; i < arrays.Count; i++)
            {
                Array.Copy(arrays[i], 0, result, length * i, length);
            }

            return new NdArray<T>(result, resultShape, arrays.Count, parentFunc);
        }

        public static NdArray<T> Convert<T>(T[] data, int[] shape, int batchCount, IFunction<T> parentFunc = null) where T : unmanaged, IComparable<T>
        {
            return new NdArray<T>(shape, batchCount, parentFunc) { Data = data };
        }

        public static NdArray<T> ZerosLike<T>(NdArray<T> baseArray) where T : unmanaged, IComparable<T>
        {
            return new NdArray<T>(baseArray.Shape, baseArray.BatchCount);
        }

        public static void Backward<T>(NdArray<T> y) where T : unmanaged, IComparable<T>
        {
            if (y.ParentFunc != null)
            {
                List<NdArray<T>[]> prevInputs = y.ParentFunc.PrevInputs;
                NdArray<T>[] xs = prevInputs[prevInputs.Count - 1];

                y.ParentFunc.Backward(y);

                for (int i = 0; i < xs.Length; i++)
                {
                    if (xs[i].UseCount == 0)
                    {
                        Backward(xs[i]);
                    }
                }
            }
        }

        public static NdArray<T>[] Split<T>(NdArray<T> array, int indices, int axis) where T : unmanaged, IComparable<T>
        {
            return Split(array, new[] { indices }, axis);
        }

        public static NdArray<T>[] Split<T>(NdArray<T> array, int[] indices, int axis) where T : unmanaged, IComparable<T>
        {
            int[] shapeOffets = new int[indices.Length + 1];        //入力されたindicesの先頭0を追加した配列
            int[] resultAxisShapes = new int[indices.Length + 1];   //分割後の指定軸のShape

            for (int i = 0; i < indices.Length; i++)
            {
                shapeOffets[i + 1] = indices[i];
                resultAxisShapes[i] = indices[i] - shapeOffets[i];
            }
            resultAxisShapes[indices.Length] = array.Shape[axis] - indices[indices.Length - 1];

            NdArray<T>[] resultArrays = new NdArray<T>[indices.Length + 1];

            for (int i = 0; i < resultArrays.Length; i++)
            {
                int[] resultShape = array.Shape.ToArray();
                resultShape[axis] = resultAxisShapes[i];
                resultArrays[i] = new NdArray<T>(resultShape, array.BatchCount);
                if (array.Grad != null) resultArrays[i].InitGrad();
            }

            for (int batchCount = 0; batchCount < array.BatchCount; batchCount++)
            {
                for (int i = 0; i < resultArrays.Length; i++)
                {
                    for (int j = 0; j < resultArrays[i].Length; j++)
                    {
                        int[] resultIndex = resultArrays[i].GetDimensionsIndex(j);
                        resultIndex[axis] += shapeOffets[i];
                        int localIndex = array.GetLocalIndex(batchCount, resultIndex);

                        resultArrays[i].Data[batchCount * resultArrays[i].Length + j] = array.Data[localIndex];
                        if (array.Grad != null) resultArrays[i].Grad[batchCount * resultArrays[i].Length + j] = array.Grad[localIndex];
                    }
                }
            }

            return resultArrays;
        }

        public static NdArray<T> Rollaxis<T>(NdArray<T> input, int axis, int start = 0) where T : unmanaged, IComparable<T>
        {
            int n = input.Shape.Length;
            if (axis < 0) axis += n;
            if (start < 0) start += n;

#if DEBUG
            string msg = "rollaxis: {0} ({1}) must be >=0 and < {2}";

            if (!(0 <= axis && axis < n)) throw new Exception(string.Format(msg, "axis", axis, n));
            if (!(0 <= start && start < n + 1)) throw new Exception(string.Format(msg, "start", start, n + 1));
#endif
            if (axis == start) return input;

            List<int> axes = new List<int>(Enumerable.Range(0, n).ToArray());
            axes.RemoveAt(axis);
            axes.Insert(start, axis);

            return Transpose(input, axes.ToArray());
        }

        public static NdArray<T> Transpose<T>(NdArray<T> input, params int[] dimensions) where T : unmanaged, IComparable<T>
        {
#if DEBUG
            if (input.Shape.Length != dimensions.Length)
            {
                throw new Exception("次元数がマッチしていません");
            }

            for (int i = 0; i < dimensions.Length; i++)
            {
                //自身の中にダブりがないか
                for (int j = i + 1; j < dimensions.Length; j++)
                {
                    if (dimensions[i] == dimensions[j]) throw new Exception("指定された要素がダブっています");
                }
                //範囲チェック
                if (dimensions[i] >= input.Shape.Length || dimensions[i] < 0) throw new Exception("指定された要素が範囲を超えています");
            }
#endif
            int[] transposedDimensions = new int[input.Shape.Length];

            for (int j = 0; j < input.Shape.Length; j++)
            {
                transposedDimensions[j] = input.Shape[dimensions[j]];
            }

            NdArray<T> resultMatrix = new NdArray<T>(transposedDimensions);

            for (int b = 0; b < input.BatchCount; b++)
            {
                for (int i = 0; i < input.Length; i++)
                {
                    int[] indecies = input.GetDimensionsIndex(i);
                    int[] transposedIndex = new int[input.Shape.Length];

                    for (int j = 0; j < input.Shape.Length; j++)
                    {
                        transposedIndex[j] = indecies[dimensions[j]];
                    }

                    resultMatrix.Data[resultMatrix.GetLocalIndex(b, transposedIndex)] = input.Data[input.GetLocalIndex(b, indecies)];
                }
            }

            return resultMatrix;
        }

        public static NdArray<T> Concatenate<T>(NdArray<T> a, NdArray<T> b, int axis) where T : unmanaged, IComparable<T>
        {
            int[] shapeList = a.Shape.ToArray();
            shapeList[axis] += b.Shape[axis];

#if DEBUG
            for (int i = 0; i < a.Shape.Length; i++)
            {
                if (i != axis && a.Shape[i] != b.Shape[i])
                {
                    throw new Exception("配列の大きさがマッチしていません");
                }
            }

            if (a.BatchCount != b.BatchCount)
            {
                throw new Exception("バッチの大きさがマッチしていません");
            }

            if((a.Grad != null) != (b.Grad != null))
            {
                throw new Exception("Grad値の有無が揃っていません");
            }
#endif

            NdArray<T> result = new NdArray<T>(shapeList, a.BatchCount);
            if (a.Grad != null || b.Grad != null)
            {
                result.InitGrad();
            }

            for (int batchCount = 0; batchCount < a.BatchCount; batchCount++)
            {
                int aInputBatchoffset = batchCount * a.Length;
                int bInputBatchoffset = batchCount * b.Length;

                for (int i = 0; i < a.Length; i++)
                {
                    int resultindex = result.GetLocalIndex(batchCount, a.GetDimensionsIndex(i));

                    result.Data[resultindex] = a.Data[i + aInputBatchoffset];
                    if (a.Grad != null) result.Grad[resultindex] = a.Grad[i + aInputBatchoffset];
                }

                for (int i = 0; i < b.Length; i++)
                {
                    int[] tmpIndex = b.GetDimensionsIndex(i);
                    tmpIndex[axis] += a.Shape[axis];

                    int resultIndex = result.GetLocalIndex(batchCount, tmpIndex);

                    result.Data[resultIndex] = b.Data[i + bInputBatchoffset];
                    if (b.Grad != null) result.Grad[resultIndex] = b.Grad[i + bInputBatchoffset];
                }
            }

            return result;
        }

    }
}


text:
package consts

// consts
const (
	HTTPAddr    = "127.0.0.1:8090"
	SOCKS5Addr  = "127.0.0.1:1080"
	PACTemplate = `// Generated by gfwlist2pac in precise mode
// https://github.com/clowwindy/gfwlist2pac

var proxy = "SOCKS5 127.0.0.1:1080; SOCKS 127.0.0.1:1080; DIRECT;";

var rules = __RULES__;

function createDict()
{
  var result = {};
  result.__proto__ = null;
  return result;
}

function getOwnPropertyDescriptor(obj, key)
{
  if (obj.hasOwnProperty(key))
  {
    return obj[key];
  }
  return null;
}

function extend(subclass, superclass, definition)
{
  if (Object.__proto__)
  {
    definition.__proto__ = superclass.prototype;
    subclass.prototype = definition;
  }
  else
  {
    var tmpclass = function(){}, ret;
    tmpclass.prototype = superclass.prototype;
    subclass.prototype = new tmpclass();
    subclass.prototype.constructor = superclass;
    for (var i in definition)
    {
      if (definition.hasOwnProperty(i))
      {
        subclass.prototype[i] = definition[i];
      }
    }
  }
}

function Filter(text)
{
  this.text = text;
  this.subscriptions = [];
}
Filter.prototype = {
text: null,
subscriptions: null,
toString: function()
  {
    return this.text;
  }
};
Filter.knownFilters = createDict();
Filter.elemhideRegExp = /^([^\/\*\|\@"!]*?)#(\@)?(?:([\w\-]+|\*)((?:\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\))*)|#([^{}]+))$/;
Filter.regexpRegExp = /^(@@)?\/.*\/(?:\$~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)?$/;
Filter.optionsRegExp = /\$(~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)$/;
Filter.fromText = function(text)
{
  if (text in Filter.knownFilters)
  {
    return Filter.knownFilters[text];
  }
  var ret;
  if (text[0] == "!")
  {
    ret = new CommentFilter(text);
  }
  else
  {
    ret = RegExpFilter.fromText(text);
  }
  Filter.knownFilters[ret.text] = ret;
  return ret;
};

function InvalidFilter(text, reason)
{
  Filter.call(this, text);
  this.reason = reason;
}
extend(InvalidFilter, Filter, {
       reason: null
       });

function CommentFilter(text)
{
  Filter.call(this, text);
}
extend(CommentFilter, Filter, {
       });

function ActiveFilter(text, domains)
{
  Filter.call(this, text);
  this.domainSource = domains;
}
extend(ActiveFilter, Filter, {
       domainSource: null,
       domainSeparator: null,
       ignoreTrailingDot: true,
       domainSourceIsUpperCase: false,
       getDomains: function()
       {
       var prop = getOwnPropertyDescriptor(this, "domains");
       if (prop)
       {
       return prop;
       }
       var domains = null;
       if (this.domainSource)
       {
       var source = this.domainSource;
       if (!this.domainSourceIsUpperCase)
       {
       source = source.toUpperCase();
       }
       var list = source.split(this.domainSeparator);
       if (list.length == 1 && list[0][0] != "~")
       {
       domains = createDict();
       domains[""] = false;
       if (this.ignoreTrailingDot)
       {
       list[0] = list[0].replace(/\.+$/, "");
       }
       domains[list[0]] = true;
       }
       else
       {
       var hasIncludes = false;
       for (var i = 0; i < list.length; i++)
       {
       var domain = list[i];
       if (this.ignoreTrailingDot)
       {
       domain = domain.replace(/\.+$/, "");
       }
       if (domain == "")
       {
       continue;
       }
       var include;
       if (domain[0] == "~")
       {
       include = false;
       domain = domain.substr(1);
       }
       else
       {
       include = true;
       hasIncludes = true;
       }
       if (!domains)
       {
       domains = createDict();
       }
       domains[domain] = include;
       }
       domains[""] = !hasIncludes;
       }
       this.domainSource = null;
       }
       return this.domains;
       },
       sitekeys: null,
       isActiveOnDomain: function(docDomain, sitekey)
       {
       if (this.getSitekeys() && (!sitekey || this.getSitekeys().indexOf(sitekey.toUpperCase()) < 0))
       {
       return false;
       }
       if (!this.getDomains())
       {
       return true;
       }
       if (!docDomain)
       {
       return this.getDomains()[""];
       }
       if (this.ignoreTrailingDot)
       {
       docDomain = docDomain.replace(/\.+$/, "");
       }
       docDomain = docDomain.toUpperCase();
       while (true)
       {
       if (docDomain in this.getDomains())
       {
       return this.domains[docDomain];
       }
       var nextDot = docDomain.indexOf(".");
       if (nextDot < 0)
       {
       break;
       }
       docDomain = docDomain.substr(nextDot + 1);
       }
       return this.domains[""];
       },
       isActiveOnlyOnDomain: function(docDomain)
       {
       if (!docDomain || !this.getDomains() || this.getDomains()[""])
       {
       return false;
       }
       if (this.ignoreTrailingDot)
       {
       docDomain = docDomain.replace(/\.+$/, "");
       }
       docDomain = docDomain.toUpperCase();
       for (var domain in this.getDomains())
       {
       if (this.domains[domain] && domain != docDomain && (domain.length <= docDomain.length || domain.indexOf("." + docDomain) != domain.length - docDomain.length - 1))
       {
       return false;
       }
       }
       return true;
       }
       });

function RegExpFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys)
{
  ActiveFilter.call(this, text, domains, sitekeys);
  if (contentType != null)
  {
    this.contentType = contentType;
  }
  if (matchCase)
  {
    this.matchCase = matchCase;
  }
  if (thirdParty != null)
  {
    this.thirdParty = thirdParty;
  }
  if (sitekeys != null)
  {
    this.sitekeySource = sitekeys;
  }
  if (regexpSource.length >= 2 && regexpSource[0] == "/" && regexpSource[regexpSource.length - 1] == "/")
  {
    var regexp = new RegExp(regexpSource.substr(1, regexpSource.length - 2), this.matchCase ? "" : "i");
    this.regexp = regexp;
  }
  else
  {
    this.regexpSource = regexpSource;
  }
}
extend(RegExpFilter, ActiveFilter, {
       domainSourceIsUpperCase: true,
       length: 1,
       domainSeparator: "|",
       regexpSource: null,
       getRegexp: function()
       {
       var prop = getOwnPropertyDescriptor(this, "regexp");
       if (prop)
       {
       return prop;
       }
       var source = this.regexpSource.replace(/\*+/g, "*").replace(/\^\|$/, "^").replace(/\W/g, "\\$&").replace(/\\\*/g, ".*").replace(/\\\^/g, "(?:[\\x00-\\x24\\x26-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\x7F]|$)").replace(/^\\\|\\\|/, "^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?").replace(/^\\\|/, "^").replace(/\\\|$/, "$").replace(/^(\.\*)/, "").replace(/(\.\*)$/, "");
       var regexp = new RegExp(source, this.matchCase ? "" : "i");
       this.regexp = regexp;
       return regexp;
       },
       contentType: 2147483647,
       matchCase: false,
       thirdParty: null,
       sitekeySource: null,
       getSitekeys: function()
       {
       var prop = getOwnPropertyDescriptor(this, "sitekeys");
       if (prop)
       {
       return prop;
       }
       var sitekeys = null;
       if (this.sitekeySource)
       {
       sitekeys = this.sitekeySource.split("|");
       this.sitekeySource = null;
       }
       this.sitekeys = sitekeys;
       return this.sitekeys;
       },
       matches: function(location, contentType, docDomain, thirdParty, sitekey)
       {
       if (this.getRegexp().test(location) && this.isActiveOnDomain(docDomain, sitekey))
       {
       return true;
       }
       return false;
       }
       });
RegExpFilter.prototype["0"] = "#this";
RegExpFilter.fromText = function(text)
{
  var blocking = true;
  var origText = text;
  if (text.indexOf("@@") == 0)
  {
    blocking = false;
    text = text.substr(2);
  }
  var contentType = null;
  var matchCase = null;
  var domains = null;
  var sitekeys = null;
  var thirdParty = null;
  var collapse = null;
  var options;
  var match = text.indexOf("$") >= 0 ? Filter.optionsRegExp.exec(text) : null;
  if (match)
  {
    options = match[1].toUpperCase().split(",");
    text = match.input.substr(0, match.index);
    for (var _loopIndex6 = 0; _loopIndex6 < options.length; ++_loopIndex6)
    {
      var option = options[_loopIndex6];
      var value = null;
      var separatorIndex = option.indexOf("=");
      if (separatorIndex >= 0)
      {
        value = option.substr(separatorIndex + 1);
        option = option.substr(0, separatorIndex);
      }
      option = option.replace(/-/, "_");
      if (option in RegExpFilter.typeMap)
      {
        if (contentType == null)
        {
          contentType = 0;
        }
        contentType |= RegExpFilter.typeMap[option];
      }
      else if (option[0] == "~" && option.substr(1) in RegExpFilter.typeMap)
      {
        if (contentType == null)
        {
          contentType = RegExpFilter.prototype.contentType;
        }
        contentType &= ~RegExpFilter.typeMap[option.substr(1)];
      }
      else if (option == "MATCH_CASE")
      {
        matchCase = true;
      }
      else if (option == "~MATCH_CASE")
      {
        matchCase = false;
      }
      else if (option == "DOMAIN" && typeof value != "undefined")
      {
        domains = value;
      }
      else if (option == "THIRD_PARTY")
      {
        thirdParty = true;
      }
      else if (option == "~THIRD_PARTY")
      {
        thirdParty = false;
      }
      else if (option == "COLLAPSE")
      {
        collapse = true;
      }
      else if (option == "~COLLAPSE")
      {
        collapse = false;
      }
      else if (option == "SITEKEY" && typeof value != "undefined")
      {
        sitekeys = value;
      }
      else
      {
        return new InvalidFilter(origText, "Unknown option " + option.toLowerCase());
      }
    }
  }
  if (!blocking && (contentType == null || contentType & RegExpFilter.typeMap.DOCUMENT) && (!options || options.indexOf("DOCUMENT") < 0) && !/^\|?[\w\-]+:/.test(text))
  {
    if (contentType == null)
    {
      contentType = RegExpFilter.prototype.contentType;
    }
    contentType &= ~RegExpFilter.typeMap.DOCUMENT;
  }
  try
  {
    if (blocking)
    {
      return new BlockingFilter(origText, text, contentType, matchCase, domains, thirdParty, sitekeys, collapse);
    }
    else
    {
      return new WhitelistFilter(origText, text, contentType, matchCase, domains, thirdParty, sitekeys);
    }
  }
  catch (e)
  {
    return new InvalidFilter(origText, e);
  }
};
RegExpFilter.typeMap = {
OTHER: 1,
SCRIPT: 2,
IMAGE: 4,
STYLESHEET: 8,
OBJECT: 16,
SUBDOCUMENT: 32,
DOCUMENT: 64,
XBL: 1,
PING: 1,
XMLHTTPREQUEST: 2048,
OBJECT_SUBREQUEST: 4096,
DTD: 1,
MEDIA: 16384,
FONT: 32768,
BACKGROUND: 4,
POPUP: 268435456,
ELEMHIDE: 1073741824
};
RegExpFilter.prototype.contentType &= ~ (RegExpFilter.typeMap.ELEMHIDE | RegExpFilter.typeMap.POPUP);

function BlockingFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys, collapse)
{
  RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys);
  this.collapse = collapse;
}
extend(BlockingFilter, RegExpFilter, {
       collapse: null
       });

function WhitelistFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys)
{
  RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys);
}
extend(WhitelistFilter, RegExpFilter, {
       });

function Matcher()
{
  this.clear();
}
Matcher.prototype = {
filterByKeyword: null,
keywordByFilter: null,
clear: function()
  {
    this.filterByKeyword = createDict();
    this.keywordByFilter = createDict();
  },
add: function(filter)
  {
    if (filter.text in this.keywordByFilter)
    {
      return;
    }
    var keyword = this.findKeyword(filter);
    var oldEntry = this.filterByKeyword[keyword];
    if (typeof oldEntry == "undefined")
    {
      this.filterByKeyword[keyword] = filter;
    }
    else if (oldEntry.length == 1)
    {
      this.filterByKeyword[keyword] = [oldEntry, filter];
    }
    else
    {
      oldEntry.push(filter);
    }
    this.keywordByFilter[filter.text] = keyword;
  },
remove: function(filter)
  {
    if (!(filter.text in this.keywordByFilter))
    {
      return;
    }
    var keyword = this.keywordByFilter[filter.text];
    var list = this.filterByKeyword[keyword];
    if (list.length <= 1)
    {
      delete this.filterByKeyword[keyword];
    }
    else
    {
      var index = list.indexOf(filter);
      if (index >= 0)
      {
        list.splice(index, 1);
        if (list.length == 1)
        {
          this.filterByKeyword[keyword] = list[0];
        }
      }
    }
    delete this.keywordByFilter[filter.text];
  },
findKeyword: function(filter)
  {
    var result = "";
    var text = filter.text;
    if (Filter.regexpRegExp.test(text))
    {
      return result;
    }
    var match = Filter.optionsRegExp.exec(text);
    if (match)
    {
      text = match.input.substr(0, match.index);
    }
    if (text.substr(0, 2) == "@@")
    {
      text = text.substr(2);
    }
    var candidates = text.toLowerCase().match(/[^a-z0-9%*][a-z0-9%]{3,}(?=[^a-z0-9%*])/g);
    if (!candidates)
    {
      return result;
    }
    var hash = this.filterByKeyword;
    var resultCount = 16777215;
    var resultLength = 0;
    for (var i = 0, l = candidates.length; i < l; i++)
    {
      var candidate = candidates[i].substr(1);
      var count = candidate in hash ? hash[candidate].length : 0;
      if (count < resultCount || count == resultCount && candidate.length > resultLength)
      {
        result = candidate;
        resultCount = count;
        resultLength = candidate.length;
      }
    }
    return result;
  },
hasFilter: function(filter)
  {
    return filter.text in this.keywordByFilter;
  },
getKeywordForFilter: function(filter)
  {
    if (filter.text in this.keywordByFilter)
    {
      return this.keywordByFilter[filter.text];
    }
    else
    {
      return null;
    }
  },
_checkEntryMatch: function(keyword, location, contentType, docDomain, thirdParty, sitekey)
  {
    var list = this.filterByKeyword[keyword];
    for (var i = 0; i < list.length; i++)
    {
      var filter = list[i];
      if (filter == "#this")
      {
        filter = list;
      }
      if (filter.matches(location, contentType, docDomain, thirdParty, sitekey))
      {
        return filter;
      }
    }
    return null;
  },
matchesAny: function(location, contentType, docDomain, thirdParty, sitekey)
  {
    var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);
    if (candidates === null)
    {
      candidates = [];
    }
    candidates.push("");
    for (var i = 0, l = candidates.length; i < l; i++)
    {
      var substr = candidates[i];
      if (substr in this.filterByKeyword)
      {
        var result = this._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);
        if (result)
        {
          return result;
        }
      }
    }
    return null;
  }
};

function CombinedMatcher()
{
  this.blacklist = new Matcher();
  this.whitelist = new Matcher();
  this.resultCache = createDict();
}
CombinedMatcher.maxCacheEntries = 1000;
CombinedMatcher.prototype = {
blacklist: null,
whitelist: null,
resultCache: null,
cacheEntries: 0,
clear: function()
  {
    this.blacklist.clear();
    this.whitelist.clear();
    this.resultCache = createDict();
    this.cacheEntries = 0;
  },
add: function(filter)
  {
    if (filter instanceof WhitelistFilter)
    {
      this.whitelist.add(filter);
    }
    else
    {
      this.blacklist.add(filter);
    }
    if (this.cacheEntries > 0)
    {
      this.resultCache = createDict();
      this.cacheEntries = 0;
    }
  },
remove: function(filter)
  {
    if (filter instanceof WhitelistFilter)
    {
      this.whitelist.remove(filter);
    }
    else
    {
      this.blacklist.remove(filter);
    }
    if (this.cacheEntries > 0)
    {
      this.resultCache = createDict();
      this.cacheEntries = 0;
    }
  },
findKeyword: function(filter)
  {
    if (filter instanceof WhitelistFilter)
    {
      return this.whitelist.findKeyword(filter);
    }
    else
    {
      return this.blacklist.findKeyword(filter);
    }
  },
hasFilter: function(filter)
  {
    if (filter instanceof WhitelistFilter)
    {
      return this.whitelist.hasFilter(filter);
    }
    else
    {
      return this.blacklist.hasFilter(filter);
    }
  },
getKeywordForFilter: function(filter)
  {
    if (filter instanceof WhitelistFilter)
    {
      return this.whitelist.getKeywordForFilter(filter);
    }
    else
    {
      return this.blacklist.getKeywordForFilter(filter);
    }
  },
isSlowFilter: function(filter)
  {
    var matcher = filter instanceof WhitelistFilter ? this.whitelist : this.blacklist;
    if (matcher.hasFilter(filter))
    {
      return !matcher.getKeywordForFilter(filter);
    }
    else
    {
      return !matcher.findKeyword(filter);
    }
  },
matchesAnyInternal: function(location, contentType, docDomain, thirdParty, sitekey)
  {
    var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);
    if (candidates === null)
    {
      candidates = [];
    }
    candidates.push("");
    var blacklistHit = null;
    for (var i = 0, l = candidates.length; i < l; i++)
    {
      var substr = candidates[i];
      if (substr in this.whitelist.filterByKeyword)
      {
        var result = this.whitelist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);
        if (result)
        {
          return result;
        }
      }
      if (substr in this.blacklist.filterByKeyword && blacklistHit === null)
      {
        blacklistHit = this.blacklist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);
      }
    }
    return blacklistHit;
  },
matchesAny: function(location, docDomain)
  {
    var key = location + " " + docDomain + " ";
    if (key in this.resultCache)
    {
      return this.resultCache[key];
    }
    var result = this.matchesAnyInternal(location, 0, docDomain, null, null);
    if (this.cacheEntries >= CombinedMatcher.maxCacheEntries)
    {
      this.resultCache = createDict();
      this.cacheEntries = 0;
    }
    this.resultCache[key] = result;
    this.cacheEntries++;
    return result;
  }
};
var defaultMatcher = new CombinedMatcher();

var direct = 'DIRECT;';

for (var i = 0; i < rules.length; i++) {
  defaultMatcher.add(Filter.fromText(rules[i]));
}

function FindProxyForURL(url, host) {
  if (defaultMatcher.matchesAny(url, host) instanceof BlockingFilter) {
    return proxy;
  }
  return direct;
}`
)


text:
<?php
/**
 * TOP API: tmall.wangwangfenliu.config.query request
 *
 * @author auto create
 * @since 1.0, 2013-12-10 16:57:25
 */
class TmallWangwangfenliuConfigQueryRequest
{

	private $apiParas = array();

	public function getApiMethodName()
	{
		return "tmall.wangwangfenliu.config.query";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.mapswithme.maps.widget.HeightLimitedFrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_height="match_parent"
  android:layout_width="match_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="@dimen/margin_base"
    android:layout_marginRight="@dimen/margin_base"
    android:layout_marginStart="@dimen/margin_base"
    android:layout_marginEnd="@dimen/margin_base">
    <LinearLayout
      android:id="@+id/update_widget"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:orientation="vertical"
      android:gravity="center">
      <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_base"
        android:layout_gravity="center_horizontal"
        android:tag="@string/tag_height_limited"
        android:src="@drawable/wn_autoupdate"/>
      <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_base"
        android:textAppearance="@style/MwmTextAppearance.Title"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:fontFamily="@string/robotoMedium"
        tools:text="@string/whats_new_auto_update_title"
        tools:targetApi="jelly_bean"/>
      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_base"
        android:textAppearance="@style/MwmTextAppearance.Body1.Secondary"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:text="@string/whats_new_auto_update_message"/>
    </LinearLayout>
    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/primary_button_min_height"
        android:layout_marginBottom="@dimen/margin_half"
        android:layout_gravity="center_horizontal">
        <TextView
          android:id="@+id/update_btn"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:textAppearance="@style/MwmTextAppearance.Button"
          android:textColor="?accentButtonTextColor"
          android:background="?accentButtonBackground"
          android:gravity="center"
          android:visibility="gone"
          tools:text="@string/whats_new_auto_update_button_size"
          tools:visibility="visible"/>
        <LinearLayout
          android:id="@+id/info"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="horizontal"
          android:layout_gravity="center"
          android:gravity="center"
          android:visibility="gone"
          tools:visibility="visible">
          <com.mapswithme.maps.widget.WheelProgressView
            android:id="@+id/progress"
            android:layout_width="@dimen/primary_button_min_height"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            app:wheelProgressColor="?colorAccent"
            app:wheelSecondaryColor="?dividerHorizontal"
            app:wheelThickness="@dimen/margin_eighth"
            android:visibility="gone"
            tools:visibility="visible"/>
          <TextView
            android:id="@+id/relative_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_half"
            android:layout_marginStart="@dimen/margin_half"
            android:layout_gravity="center_vertical"
            android:gravity="center"
            android:textAppearance="@style/MwmTextAppearance.Body1.Secondary"
            tools:text="@string/downloader_percent"/>
        </LinearLayout>
      </FrameLayout>
      <TextView
        android:id="@+id/later_btn"
        android:layout_width="match_parent"
        android:layout_height="@dimen/primary_button_min_height"
        android:layout_marginBottom="@dimen/margin_half"
        android:textAppearance="@style/MwmTextAppearance.Button"
        android:textColor="?buttonDialogTextColor"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:background="?clickableBackground"
        tools:text="@string/whats_new_auto_update_button_later"/>
    </LinearLayout>
  </LinearLayout>
</com.mapswithme.maps.widget.HeightLimitedFrameLayout>