text:
require "testing/routing_headers/routing_headers_pb"
require "google/cloud/location"

module Testing
  module RoutingHeaders
    module ServiceImplicitHeaders
      ##
      # Client for the ServiceImplicitHeaders service.
      #
      class Client
        # @private
        attr_reader :service_implicit_headers_stub

        ##
        # Configure the ServiceImplicitHeaders Client class.
        #
        # See {::Testing::RoutingHeaders::ServiceImplicitHeaders::Client::Configuration}
        # for a description of the configuration fields.
        #
        # @example
        #
        #   # Modify the configuration for all ServiceImplicitHeaders clients
        #   ::Testing::RoutingHeaders::ServiceImplicitHeaders::Client.configure do |config|
        #     config.timeout = 10.0
        #   end
        #
        # @yield [config] Configure the Client client.
        # @yieldparam config [Client::Configuration]
        #
        # @return [Client::Configuration]
        #
        def self.configure
          @configure ||= begin
            default_config = Client::Configuration.new

            default_config
          end
          yield @configure if block_given?
          @configure
        end

        ##
        # Configure the ServiceImplicitHeaders Client instance.
        #
        # The configuration is set to the derived mode, meaning that values can be changed,
        # but structural changes (adding new fields, etc.) are not allowed. Structural changes
        # should be made on {Client.configure}.
        #
        # See {::Testing::RoutingHeaders::ServiceImplicitHeaders::Client::Configuration}
        # for a description of the configuration fields.
        #
        # @yield [config] Configure the Client client.
        # @yieldparam config [Client::Configuration]
        #
        # @return [Client::Configuration]
        #
        def configure
          yield @config if block_given?
          @config
        end

        ##
        # Create a new ServiceImplicitHeaders client object.
        #
        # @example
        #
        #   # Create a client using the default configuration
        #   client = ::Testing::RoutingHeaders::ServiceImplicitHeaders::Client.new
        #
        #   # Create a client using a custom configuration
        #   client = ::Testing::RoutingHeaders::ServiceImplicitHeaders::Client.new do |config|
        #     config.timeout = 10.0
        #   end
        #
        # @yield [config] Configure the ServiceImplicitHeaders client.
        # @yieldparam config [Client::Configuration]
        #
        def initialize
          # These require statements are intentionally placed here to initialize
          # the gRPC module only when it's required.
          # See https://github.com/googleapis/toolkit/issues/446
          require "gapic/grpc"
          require "testing/routing_headers/routing_headers_services_pb"

          # Create the configuration object
          @config = Configuration.new Client.configure

          # Yield the configuration if needed
          yield @config if block_given?

          # Create credentials
          credentials = @config.credentials
          # Use self-signed JWT if the endpoint is unchanged from default,
          # but only if the default endpoint does not have a region prefix.
          enable_self_signed_jwt = @config.endpoint == Client.configure.endpoint &&
                                   !@config.endpoint.split(".").first.include?("-")
          credentials ||= Credentials.default scope: @config.scope,
                                              enable_self_signed_jwt: enable_self_signed_jwt
          if credentials.is_a?(::String) || credentials.is_a?(::Hash)
            credentials = Credentials.new credentials, scope: @config.scope
          end
          @quota_project_id = @config.quota_project
          @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id

          @location_client = Google::Cloud::Location::Locations::Client.new do |config|
            config.credentials = credentials
            config.quota_project = @quota_project_id
            config.endpoint = @config.endpoint
          end

          @service_implicit_headers_stub = ::Gapic::ServiceStub.new(
            ::Testing::RoutingHeaders::ServiceImplicitHeaders::Stub,
            credentials:  credentials,
            endpoint:     @config.endpoint,
            channel_args: @config.channel_args,
            interceptors: @config.interceptors
          )
        end

        ##
        # Get the associated client for mix-in of the Locations.
        #
        # @return [Google::Cloud::Location::Locations::Client]
        #
        attr_reader :location_client

        # Service calls

        ##
        # @overload plain(request, options = nil)
        #   Pass arguments to `plain` via a request object, either of type
        #   {::Testing::RoutingHeaders::Request} or an equivalent Hash.
        #
        #   @param request [::Testing::RoutingHeaders::Request, ::Hash]
        #     A request object representing the call parameters. Required. To specify no
        #     parameters, or to keep all the default parameter values, pass an empty Hash.
        #   @param options [::Gapic::CallOptions, ::Hash]
        #     Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
        #
        # @overload plain(table_name: nil, app_profile_id: nil, resource: nil)
        #   Pass arguments to `plain` via keyword arguments. Note that at
        #   least one keyword argument is required. To specify no parameters, or to keep all
        #   the default parameter values, pass an empty Hash as a request object (see above).
        #
        #   @param table_name [::String]
        #     The name of the Table
        #     Values can be of the following formats:
        #     - `projects/<project>/tables/<table>`
        #     - `projects/<project>/instances/<instance>/tables/<table>`
        #     - `region/<region>/zones/<zone>/tables/<table>`
        #   @param app_profile_id [::String]
        #     This value specifies routing for replication.
        #     It can be in the following formats:
        #     - profiles/<profile_id>
        #     - a legacy profile_id that can be any string
        #   @param resource [::Testing::RoutingHeaders::RequestResource, ::Hash]
        #
        # @yield [response, operation] Access the result along with the RPC operation
        # @yieldparam response [::Testing::RoutingHeaders::Response]
        # @yieldparam operation [::GRPC::ActiveCall::Operation]
        #
        # @return [::Testing::RoutingHeaders::Response]
        #
        # @raise [::GRPC::BadStatus] if the RPC is aborted.
        #
        # @example Basic example
        #   require "testing/routing_headers"
        #
        #   # Create a client object. The client can be reused for multiple calls.
        #   client = Testing::RoutingHeaders::ServiceImplicitHeaders::Client.new
        #
        #   # Create a request. To set request fields, pass in keyword arguments.
        #   request = Testing::RoutingHeaders::Request.new
        #
        #   # Call the plain method.
        #   result = client.plain request
        #
        #   # The returned object is of type Testing::RoutingHeaders::Response.
        #   p result
        #
        def plain request, options = nil
          raise ::ArgumentError, "request must be provided" if request.nil?

          request = ::Gapic::Protobuf.coerce request, to: ::Testing::RoutingHeaders::Request

          # Converts hash and nil to an options object
          options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h

          # Customize the options with defaults
          metadata = @config.rpcs.plain.metadata.to_h

          # Set x-goog-api-client and x-goog-user-project headers
          metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
            lib_name: @config.lib_name, lib_version: @config.lib_version,
            gapic_version: ::Testing::VERSION
          metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id

          header_params = {}
          if request.table_name
            header_params["table_name"] = request.table_name
          end

          request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
          metadata[:"x-goog-request-params"] ||= request_params_header

          options.apply_defaults timeout:      @config.rpcs.plain.timeout,
                                 metadata:     metadata,
                                 retry_policy: @config.rpcs.plain.retry_policy

          options.apply_defaults timeout:      @config.timeout,
                                 metadata:     @config.metadata,
                                 retry_policy: @config.retry_policy

          @service_implicit_headers_stub.call_rpc :plain, request, options: options do |response, operation|
            yield response, operation if block_given?
            return response
          end
        end

        ##
        # @overload with_sub_message(request, options = nil)
        #   Pass arguments to `with_sub_message` via a request object, either of type
        #   {::Testing::RoutingHeaders::Request} or an equivalent Hash.
        #
        #   @param request [::Testing::RoutingHeaders::Request, ::Hash]
        #     A request object representing the call parameters. Required. To specify no
        #     parameters, or to keep all the default parameter values, pass an empty Hash.
        #   @param options [::Gapic::CallOptions, ::Hash]
        #     Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
        #
        # @overload with_sub_message(table_name: nil, app_profile_id: nil, resource: nil)
        #   Pass arguments to `with_sub_message` via keyword arguments. Note that at
        #   least one keyword argument is required. To specify no parameters, or to keep all
        #   the default parameter values, pass an empty Hash as a request object (see above).
        #
        #   @param table_name [::String]
        #     The name of the Table
        #     Values can be of the following formats:
        #     - `projects/<project>/tables/<table>`
        #     - `projects/<project>/instances/<instance>/tables/<table>`
        #     - `region/<region>/zones/<zone>/tables/<table>`
        #   @param app_profile_id [::String]
        #     This value specifies routing for replication.
        #     It can be in the following formats:
        #     - profiles/<profile_id>
        #     - a legacy profile_id that can be any string
        #   @param resource [::Testing::RoutingHeaders::RequestResource, ::Hash]
        #
        # @yield [response, operation] Access the result along with the RPC operation
        # @yieldparam response [::Testing::RoutingHeaders::Response]
        # @yieldparam operation [::GRPC::ActiveCall::Operation]
        #
        # @return [::Testing::RoutingHeaders::Response]
        #
        # @raise [::GRPC::BadStatus] if the RPC is aborted.
        #
        # @example Basic example
        #   require "testing/routing_headers"
        #
        #   # Create a client object. The client can be reused for multiple calls.
        #   client = Testing::RoutingHeaders::ServiceImplicitHeaders::Client.new
        #
        #   # Create a request. To set request fields, pass in keyword arguments.
        #   request = Testing::RoutingHeaders::Request.new
        #
        #   # Call the with_sub_message method.
        #   result = client.with_sub_message request
        #
        #   # The returned object is of type Testing::RoutingHeaders::Response.
        #   p result
        #
        def with_sub_message request, options = nil
          raise ::ArgumentError, "request must be provided" if request.nil?

          request = ::Gapic::Protobuf.coerce request, to: ::Testing::RoutingHeaders::Request

          # Converts hash and nil to an options object
          options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h

          # Customize the options with defaults
          metadata = @config.rpcs.with_sub_message.metadata.to_h

          # Set x-goog-api-client and x-goog-user-project headers
          metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
            lib_name: @config.lib_name, lib_version: @config.lib_version,
            gapic_version: ::Testing::VERSION
          metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id

          header_params = {}
          if request.resource&.resource_name
            header_params["resource.resource_name"] = request.resource.resource_name
          end

          request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
          metadata[:"x-goog-request-params"] ||= request_params_header

          options.apply_defaults timeout:      @config.rpcs.with_sub_message.timeout,
                                 metadata:     metadata,
                                 retry_policy: @config.rpcs.with_sub_message.retry_policy

          options.apply_defaults timeout:      @config.timeout,
                                 metadata:     @config.metadata,
                                 retry_policy: @config.retry_policy

          @service_implicit_headers_stub.call_rpc :with_sub_message, request, options: options do |response, operation|
            yield response, operation if block_given?
            return response
          end
        end

        ##
        # @overload with_multiple_levels(request, options = nil)
        #   Pass arguments to `with_multiple_levels` via a request object, either of type
        #   {::Testing::RoutingHeaders::Request} or an equivalent Hash.
        #
        #   @param request [::Testing::RoutingHeaders::Request, ::Hash]
        #     A request object representing the call parameters. Required. To specify no
        #     parameters, or to keep all the default parameter values, pass an empty Hash.
        #   @param options [::Gapic::CallOptions, ::Hash]
        #     Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
        #
        # @overload with_multiple_levels(table_name: nil, app_profile_id: nil, resource: nil)
        #   Pass arguments to `with_multiple_levels` via keyword arguments. Note that at
        #   least one keyword argument is required. To specify no parameters, or to keep all
        #   the default parameter values, pass an empty Hash as a request object (see above).
        #
        #   @param table_name [::String]
        #     The name of the Table
        #     Values can be of the following formats:
        #     - `projects/<project>/tables/<table>`
        #     - `projects/<project>/instances/<instance>/tables/<table>`
        #     - `region/<region>/zones/<zone>/tables/<table>`
        #   @param app_profile_id [::String]
        #     This value specifies routing for replication.
        #     It can be in the following formats:
        #     - profiles/<profile_id>
        #     - a legacy profile_id that can be any string
        #   @param resource [::Testing::RoutingHeaders::RequestResource, ::Hash]
        #
        # @yield [response, operation] Access the result along with the RPC operation
        # @yieldparam response [::Testing::RoutingHeaders::Response]
        # @yieldparam operation [::GRPC::ActiveCall::Operation]
        #
        # @return [::Testing::RoutingHeaders::Response]
        #
        # @raise [::GRPC::BadStatus] if the RPC is aborted.
        #
        # @example Basic example
        #   require "testing/routing_headers"
        #
        #   # Create a client object. The client can be reused for multiple calls.
        #   client = Testing::RoutingHeaders::ServiceImplicitHeaders::Client.new
        #
        #   # Create a request. To set request fields, pass in keyword arguments.
        #   request = Testing::RoutingHeaders::Request.new
        #
        #   # Call the with_multiple_levels method.
        #   result = client.with_multiple_levels request
        #
        #   # The returned object is of type Testing::RoutingHeaders::Response.
        #   p result
        #
        def with_multiple_levels request, options = nil
          raise ::ArgumentError, "request must be provided" if request.nil?

          request = ::Gapic::Protobuf.coerce request, to: ::Testing::RoutingHeaders::Request

          # Converts hash and nil to an options object
          options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h

          # Customize the options with defaults
          metadata = @config.rpcs.with_multiple_levels.metadata.to_h

          # Set x-goog-api-client and x-goog-user-project headers
          metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
            lib_name: @config.lib_name, lib_version: @config.lib_version,
            gapic_version: ::Testing::VERSION
          metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id

          header_params = {}
          if request.resource&.inner&.inner_name
            header_params["resource.inner.inner_name"] = request.resource.inner.inner_name
          end

          request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
          metadata[:"x-goog-request-params"] ||= request_params_header

          options.apply_defaults timeout:      @config.rpcs.with_multiple_levels.timeout,
                                 metadata:     metadata,
                                 retry_policy: @config.rpcs.with_multiple_levels.retry_policy

          options.apply_defaults timeout:      @config.timeout,
                                 metadata:     @config.metadata,
                                 retry_policy: @config.retry_policy

          @service_implicit_headers_stub.call_rpc :with_multiple_levels, request,
                                                  options: options do |response, operation|
            yield response, operation if block_given?
            return response
          end
        end

        ##
        # Configuration class for the ServiceImplicitHeaders API.
        #
        # This class represents the configuration for ServiceImplicitHeaders,
        # providing control over timeouts, retry behavior, logging, transport
        # parameters, and other low-level controls. Certain parameters can also be
        # applied individually to specific RPCs. See
        # {::Testing::RoutingHeaders::ServiceImplicitHeaders::Client::Configuration::Rpcs}
        # for a list of RPCs that can be configured independently.
        #
        # Configuration can be applied globally to all clients, or to a single client
        # on construction.
        #
        # @example
        #
        #   # Modify the global config, setting the timeout for
        #   # plain to 20 seconds,
        #   # and all remaining timeouts to 10 seconds.
        #   ::Testing::RoutingHeaders::ServiceImplicitHeaders::Client.configure do |config|
        #     config.timeout = 10.0
        #     config.rpcs.plain.timeout = 20.0
        #   end
        #
        #   # Apply the above configuration only to a new client.
        #   client = ::Testing::RoutingHeaders::ServiceImplicitHeaders::Client.new do |config|
        #     config.timeout = 10.0
        #     config.rpcs.plain.timeout = 20.0
        #   end
        #
        # @!attribute [rw] endpoint
        #   The hostname or hostname:port of the service endpoint.
        #   Defaults to `"routingheaders.example.com"`.
        #   @return [::String]
        # @!attribute [rw] credentials
        #   Credentials to send with calls. You may provide any of the following types:
        #    *  (`String`) The path to a service account key file in JSON format
        #    *  (`Hash`) A service account key as a Hash
        #    *  (`Google::Auth::Credentials`) A googleauth credentials object
        #       (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
        #    *  (`Signet::OAuth2::Client`) A signet oauth2 client object
        #       (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
        #    *  (`GRPC::Core::Channel`) a gRPC channel with included credentials
        #    *  (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
        #    *  (`nil`) indicating no credentials
        #   @return [::Object]
        # @!attribute [rw] scope
        #   The OAuth scopes
        #   @return [::Array<::String>]
        # @!attribute [rw] lib_name
        #   The library name as recorded in instrumentation and logging
        #   @return [::String]
        # @!attribute [rw] lib_version
        #   The library version as recorded in instrumentation and logging
        #   @return [::String]
        # @!attribute [rw] channel_args
        #   Extra parameters passed to the gRPC channel. Note: this is ignored if a
        #   `GRPC::Core::Channel` object is provided as the credential.
        #   @return [::Hash]
        # @!attribute [rw] interceptors
        #   An array of interceptors that are run before calls are executed.
        #   @return [::Array<::GRPC::ClientInterceptor>]
        # @!attribute [rw] timeout
        #   The call timeout in seconds.
        #   @return [::Numeric]
        # @!attribute [rw] metadata
        #   Additional gRPC headers to be sent with the call.
        #   @return [::Hash{::Symbol=>::String}]
        # @!attribute [rw] retry_policy
        #   The retry policy. The value is a hash with the following keys:
        #    *  `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
        #    *  `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
        #    *  `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
        #    *  `:retry_codes` (*type:* `Array<String>`) - The error codes that should
        #       trigger a retry.
        #   @return [::Hash]
        # @!attribute [rw] quota_project
        #   A separate project against which to charge quota.
        #   @return [::String]
        #
        class Configuration
          extend ::Gapic::Config

          config_attr :endpoint,      "routingheaders.example.com", ::String
          config_attr :credentials,   nil do |value|
            allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
            allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
            allowed.any? { |klass| klass === value }
          end
          config_attr :scope,         nil, ::String, ::Array, nil
          config_attr :lib_name,      nil, ::String, nil
          config_attr :lib_version,   nil, ::String, nil
          config_attr(:channel_args,  { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
          config_attr :interceptors,  nil, ::Array, nil
          config_attr :timeout,       nil, ::Numeric, nil
          config_attr :metadata,      nil, ::Hash, nil
          config_attr :retry_policy,  nil, ::Hash, ::Proc, nil
          config_attr :quota_project, nil, ::String, nil

          # @private
          def initialize parent_config = nil
            @parent_config = parent_config unless parent_config.nil?

            yield self if block_given?
          end

          ##
          # Configurations for individual RPCs
          # @return [Rpcs]
          #
          def rpcs
            @rpcs ||= begin
              parent_rpcs = nil
              parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
              Rpcs.new parent_rpcs
            end
          end

          ##
          # Configuration RPC class for the ServiceImplicitHeaders API.
          #
          # Includes fields providing the configuration for each RPC in this service.
          # Each configuration object is of type `Gapic::Config::Method` and includes
          # the following configuration fields:
          #
          #  *  `timeout` (*type:* `Numeric`) - The call timeout in seconds
          #  *  `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
          #  *  `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
          #     include the following keys:
          #      *  `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
          #      *  `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
          #      *  `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
          #      *  `:retry_codes` (*type:* `Array<String>`) - The error codes that should
          #         trigger a retry.
          #
          class Rpcs
            ##
            # RPC-specific configuration for `plain`
            # @return [::Gapic::Config::Method]
            #
            attr_reader :plain
            ##
            # RPC-specific configuration for `with_sub_message`
            # @return [::Gapic::Config::Method]
            #
            attr_reader :with_sub_message
            ##
            # RPC-specific configuration for `with_multiple_levels`
            # @return [::Gapic::Config::Method]
            #
            attr_reader :with_multiple_levels

            # @private
            def initialize parent_rpcs = nil
              plain_config = parent_rpcs.plain if parent_rpcs.respond_to? :plain
              @plain = ::Gapic::Config::Method.new plain_config
              with_sub_message_config = parent_rpcs.with_sub_message if parent_rpcs.respond_to? :with_sub_message
              @with_sub_message = ::Gapic::Config::Method.new with_sub_message_config
              with_multiple_levels_config = parent_rpcs.with_multiple_levels if parent_rpcs.respond_to? :with_multiple_levels
              @with_multiple_levels = ::Gapic::Config::Method.new with_multiple_levels_config

              yield self if block_given?
            end
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<config>
    <sections>
        <iqnomy_extension translate="label" module="iqnomy_extension">
            IQNOMY Extension
            <tab>service</tab>
            <sort_order>200</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <versioninfo>
                    <frontend_model>iqnomy_extension/adminhtml_system_config_form_fieldset_versioninfo</frontend_model>
                    <sort_order>0</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                </versioninfo>
                <account translate="label">
                    IQNOMY Account
                    <sort_order>10</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>0</show_in_website>
                    <show_in_store>0</show_in_store>
                    <expanded>1</expanded>
                    <fields>

                        <tenant_id translate="label">
                            IQNOMY Account ID
                            <frontend_type>text</frontend_type>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </tenant_id>
                        <username translate="label comment">
                            Username
                            <comment>Usually your email address</comment>
                            <frontend_type>text</frontend_type>
                            <sort_order>30</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </username>
                        <api_key translate="label">
                            Webservice Key
                            <frontend_type>text</frontend_type>
                            <sort_order>40</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </api_key>
                        <enable_logging translate="label comment">
                            Enable Logging
                            <comment>Writes to: var/log/iqnomy.log</comment>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>50</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </enable_logging>
                        <tenant_script translate="label comment">
                            Enable tenant extra script
                            <comment>This option should only be set by an IQNOMY consultant.</comment>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>60</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </tenant_script>
                      	<custom_containers translate="label comment">
                            Enable custom containers
                            <comment>This option should only be set by an IQNOMY consultant.</comment>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>70</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </custom_containers>
                    </fields>
                </account>
                <dimensions translate="label comment">
                    Dimensions
                    <sort_order>20</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>0</show_in_website>
                    <show_in_store>0</show_in_store>
                    <expanded>1</expanded>
                    <fields>
                        <intro>
                            Intro
                            <frontend_model>iqnomy_extension/adminhtml_system_config_form_field_dimensions</frontend_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </intro>
                        <product translate="label">
                            Product Dimensions
                            <frontend_type>select</frontend_type>
                            <source_model>iqnomy_extension/adminhtml_system_config_source_dimensions</source_model>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </product>
                        <product_default translate="label">
                            Selected Product Dimensions
                            <sort_order>30</sort_order>
                            <frontend_model>iqnomy_extension/adminhtml_system_config_form_field_dimensions_product</frontend_model>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                            <depends>
                                <product>0</product>
                            </depends>
                        </product_default>
                        <product_custom translate="label comment">
                            Selected Product Dimensions
                            <comment>Use Ctrl+click to toggle individual items.</comment>
                            <frontend_type>multiselect</frontend_type>
                            <source_model>iqnomy_extension/adminhtml_system_config_source_dimensions_product</source_model>
                            <sort_order>40</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                            <depends>
                                <product>1</product>
                            </depends>
                        </product_custom>

                    </fields>
                </dimensions>

            </groups>
        </iqnomy_extension>
    </sections>
</config>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace TwbBundle\Options;

use Zend\Stdlib\AbstractOptions;

/**
 * Hold options for TwbBundle module
 */
class ModuleOptions extends AbstractOptions
{
    protected $ignoredViewHelpers;

    public function getIgnoredViewHelpers()
    {
        return $this->ignoredViewHelpers;
    }

    public function setIgnoredViewHelpers($ignoredViewHelpers)
    {
        $this->ignoredViewHelpers = $ignoredViewHelpers;
    }
}


text:
import sys
import os
os.chdir(os.path.dirname(sys.argv[0]))

from mule_local.JobMule import *
from itertools import product
from mule.exec_program import *

exec_program('mule.benchmark.cleanup_all', catch_output=False)

jg = JobGeneration()
jg.compile.unit_test = "test_sphere_coordinates"
jg.compile.sphere_spectral_space = "enable"
jg.runtime.verbosity = 5
jg.compile.mode = 'debug'

jg.gen_jobscript_directory()

exitcode = exec_program('mule.benchmark.jobs_run_directly', catch_output=False)
if exitcode != 0:
    sys.exit(exitcode)

print("Benchmarks successfully finished")

exec_program('mule.benchmark.cleanup_all', catch_output=False)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Jailer - Subset by Example</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Data Export Tool">
<link rel="shortcut icon" href="favicon.ico">
<meta name="keywords" content="data export referential integrity java jdbc dbms">
<link rel="stylesheet" type="text/css" href="exporting-data-Dateien/styles.css">

Database Subsetting Tool

  Home     Quick
Tour    Tutorial
   Data Browser
   FAQ
    Documentation
    Forum
Download

Basic

SQL
Export

XML
Export

Deleting
Data

Advanced

Subset By Example

Subset By
Example is an easy way to create extraction models.

Use the Data Browser to collect all the rows to be extracted and let
Jailer create a model for that subset.

Objective

<big style="font-style: italic;"><big><big>coming soon.</big></big></big>


text:
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using NServiceBus;
using SFA.DAS.CommitmentsV2.Application.Queries.GetDraftApprenticeshipCreatedEventsForCohort;
using SFA.DAS.CommitmentsV2.Messages.Events;

namespace SFA.DAS.CommitmentsV2.MessageHandlers.EventHandlers
{
    public class BulkUploadIntoCohortCompletedEventHandler : IHandleMessages<BulkUploadIntoCohortCompletedEvent>
    {
        private readonly IMediator _mediator;

        public BulkUploadIntoCohortCompletedEventHandler(IMediator mediator)
        {
            _mediator = mediator;
        }

        public async Task Handle(BulkUploadIntoCohortCompletedEvent message, IMessageHandlerContext context)
        {
            var response = await _mediator.Send(new GetDraftApprenticeshipCreatedEventsForCohortQuery(message.ProviderId, message.CohortId,
                message.NumberOfApprentices, message.UploadedOn));

            await Task.WhenAll(response.DraftApprenticeshipCreatedEvents.Select(context.Publish)).ConfigureAwait(false);
        }
    }
}


text:
import * as cors from 'cors';
import * as express from 'express';
import {
  getDistinctCategories,
  getProducts,
  getProductById,
  getProductsByCategory
} from './db-auction';

export const router = express.Router();

router.use(cors());

router.get('/products', async (req: express.Request, res: express.Response) => {
  res.json(await getProducts(req.query));
});

router.get('/products/:productId', async (req: express.Request, res: express.Response) => {
  const productId = parseInt(req.params.productId, 10) || -1;
  res.json(await getProductById(productId));
});

router.get('/categories', async (_, res: express.Response) => {
  res.json(await getDistinctCategories());
});

router.get('/categories/:category', async (req: express.Request, res: express.Response) => {
  res.json(await getProductsByCategory(req.params.category));
});


text:
package com.badlogic.gdx.graphics.g3d.particles;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetLoaderParameters;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData.AssetData;
import com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.reflect.ClassReflection;

/** This class can save and load a {@link ParticleEffect}. It should be added as {@link AsynchronousAssetLoader} to the
 * {@link AssetManager} so it will be able to load the effects. It's important to note that the two classes
 * {@link ParticleEffectLoadParameter} and {@link ParticleEffectSaveParameter} should be passed in whenever possible, because when
 * present the batches settings will be loaded automatically. When the load and save parameters are absent, once the effect will
 * be created, one will have to set the required batches manually otherwise the {@link ParticleController} instances contained
 * inside the effect will not be able to render themselves.
 * @author inferno */
public class ParticleEffectLoader extends
	AsynchronousAssetLoader<ParticleEffect, ParticleEffectLoader.ParticleEffectLoadParameter> {
	protected Array<ObjectMap.Entry<String, ResourceData<ParticleEffect>>> items = new Array<ObjectMap.Entry<String, ResourceData<ParticleEffect>>>();

	public ParticleEffectLoader (FileHandleResolver resolver) {
		super(resolver);
	}

	@Override
	public void loadAsync (AssetManager manager, String fileName, FileHandle file, ParticleEffectLoadParameter parameter) {
	}

	@Override
	public Array<AssetDescriptor> getDependencies (String fileName, FileHandle file, ParticleEffectLoadParameter parameter) {
		Json json = new Json();
		ResourceData<ParticleEffect> data = json.fromJson(ResourceData.class, file);
		Array<AssetData> assets = null;
		synchronized (items) {
			ObjectMap.Entry<String, ResourceData<ParticleEffect>> entry = new ObjectMap.Entry<String, ResourceData<ParticleEffect>>();
			entry.key = fileName;
			entry.value = data;
			items.add(entry);
			assets = data.getAssets();
		}

		Array<AssetDescriptor> descriptors = new Array<AssetDescriptor>();
		for (AssetData<?> assetData : assets) {

			// If the asset doesn't exist try to load it from loading effect directory
			if (!resolve(assetData.filename).exists()) {
				assetData.filename = file.parent().child(Gdx.files.internal(assetData.filename).name()).path();
			}

			if (assetData.type == ParticleEffect.class) {
				descriptors.add(new AssetDescriptor(assetData.filename, assetData.type, parameter));
			} else
				descriptors.add(new AssetDescriptor(assetData.filename, assetData.type));
		}

		return descriptors;

	}

	/** Saves the effect to the given file contained in the passed in parameter. */
	public void save (ParticleEffect effect, ParticleEffectSaveParameter parameter) throws IOException {
		ResourceData<ParticleEffect> data = new ResourceData<ParticleEffect>(effect);

		// effect assets
		effect.save(parameter.manager, data);

		// Batches configurations
		if (parameter.batches != null) {
			for (ParticleBatch<?> batch : parameter.batches) {
				boolean save = false;
				for (ParticleController controller : effect.getControllers()) {
					if (controller.renderer.isCompatible(batch)) {
						save = true;
						break;
					}
				}

				if (save) batch.save(parameter.manager, data);
			}
		}

		// save
		Json json = new Json();
		json.toJson(data, parameter.file);
	}

	@Override
	public ParticleEffect loadSync (AssetManager manager, String fileName, FileHandle file, ParticleEffectLoadParameter parameter) {
		ResourceData<ParticleEffect> effectData = null;
		synchronized (items) {
			for (int i = 0; i < items.size; ++i) {
				ObjectMap.Entry<String, ResourceData<ParticleEffect>> entry = items.get(i);
				if (entry.key.equals(fileName)) {
					effectData = entry.value;
					items.removeIndex(i);
					break;
				}
			}
		}

		effectData.resource.load(manager, effectData);
		if (parameter != null) {
			if (parameter.batches != null) {
				for (ParticleBatch<?> batch : parameter.batches) {
					batch.load(manager, effectData);
				}
			}
			effectData.resource.setBatch(parameter.batches);
		}
		return effectData.resource;
	}

	private <T> T find (Array<?> array, Class<T> type) {
		for (Object object : array) {
			if (ClassReflection.isAssignableFrom(type, object.getClass())) return (T)object;
		}
		return null;
	}

	public static class ParticleEffectLoadParameter extends AssetLoaderParameters<ParticleEffect> {
		Array<ParticleBatch<?>> batches;

		public ParticleEffectLoadParameter (Array<ParticleBatch<?>> batches) {
			this.batches = batches;
		}
	}

	public static class ParticleEffectSaveParameter extends AssetLoaderParameters<ParticleEffect> {
		/** Optional parameters, but should be present to correctly load the settings */
		Array<ParticleBatch<?>> batches;

		/** Required parameters */
		FileHandle file;
		AssetManager manager;

		public ParticleEffectSaveParameter (FileHandle file, AssetManager manager, Array<ParticleBatch<?>> batches) {
			this.batches = batches;
			this.file = file;
			this.manager = manager;
		}
	}

}


text:
<?php
$main = require dirname(__FILE__) . '/main.php';
return array_merge($main, array(
    // ...
));


text:
(function() {

  /**
   * @requires jsts/geom/Geometry.js
   */

  var Geometry = jsts.geom.Geometry;
  var TreeSet = javascript.util.TreeSet;
  var Arrays = javascript.util.Arrays;

  /**
   * @constructor
   * @extends jsts.geom.Geometry
   */
  jsts.geom.GeometryCollection = function(geometries, factory) {
    this.geometries = geometries || [];
    this.factory = factory;
  };

  jsts.geom.GeometryCollection.prototype = new Geometry();
  jsts.geom.GeometryCollection.constructor = jsts.geom.GeometryCollection;

  /**
   * @return {boolean}
   */
  jsts.geom.GeometryCollection.prototype.isEmpty = function() {
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      var geometry = this.getGeometryN(i);

      if (!geometry.isEmpty()) {
        return false;
      }
    }
    return true;
  };

  jsts.geom.Geometry.prototype.getArea = function() {
    var area = 0.0;

    for (var i = 0, len = this.geometries.length; i < len; i++) {
      area += this.getGeometryN(i).getArea();
    }

    return area;
  };

  jsts.geom.Geometry.prototype.getLength = function() {
    var length = 0.0;

    for (var i = 0, len = this.geometries.length; i < len; i++) {
      length += this.getGeometryN(i).getLength();
    }

    return length;
  };

  /**
   * @return {Coordinate}
   */
  jsts.geom.GeometryCollection.prototype.getCoordinate = function() {
    if (this.isEmpty())
      return null;

    return this.getGeometryN(0).getCoordinate();
  };

  /**
   * Collects all coordinates of all subgeometries into an Array.
   *
   * Note that while changes to the coordinate objects themselves may modify the
   * Geometries in place, the returned Array as such is only a temporary
   * container which is not synchronized back.
   *
   * @return {Coordinate[]} the collected coordinates.
   */
  jsts.geom.GeometryCollection.prototype.getCoordinates = function() {
    var coordinates = [];
    var k = -1;
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      var geometry = this.getGeometryN(i);

      var childCoordinates = geometry.getCoordinates();
      for (var j = 0; j < childCoordinates.length; j++) {
        k++;
        coordinates[k] = childCoordinates[j];
      }
    }
    return coordinates;
  };

  /**
   * @return {int}
   */
  jsts.geom.GeometryCollection.prototype.getNumGeometries = function() {
    return this.geometries.length;
  };

  /**
   * @param {int}
   *          n
   * @return {Geometry}
   */
  jsts.geom.GeometryCollection.prototype.getGeometryN = function(n) {
    var geometry = this.geometries[n];
    if (geometry instanceof jsts.geom.Coordinate) {
      geometry = new jsts.geom.Point(geometry);
    }
    return geometry;
  };

  /**
   * @param {Geometry}
   *          other
   * @param {double}
   *          tolerance
   * @return {boolean}
   */
  jsts.geom.GeometryCollection.prototype.equalsExact = function(other,
      tolerance) {
    if (!this.isEquivalentClass(other)) {
      return false;
    }
    if (this.geometries.length !== other.geometries.length) {
      return false;
    }
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      var geometry = this.getGeometryN(i);

      if (!geometry.equalsExact(other.getGeometryN(i), tolerance)) {
        return false;
      }
    }
    return true;
  };

  /**
   * Creates and returns a full copy of this {@link GeometryCollection} object.
   * (including all coordinates contained by it).
   *
   * @return a clone of this instance.
   */
  jsts.geom.GeometryCollection.prototype.clone = function() {
    var geometries = [];
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      geometries.push(this.geometries[i].clone());
    }
    return this.factory.createGeometryCollection(geometries);
  };

  jsts.geom.GeometryCollection.prototype.normalize = function() {
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      this.getGeometryN(i).normalize();
    }
    // TODO: might need to supply comparison function
    this.geometries.sort();
  };

  jsts.geom.GeometryCollection.prototype.compareToSameClass = function(o) {
    var theseElements = new TreeSet(Arrays.asList(this.geometries));
    var otherElements = new TreeSet(Arrays.asList(o.geometries));
    return this.compare(theseElements, otherElements);
  };

  jsts.geom.GeometryCollection.prototype.apply = function(filter) {
    if (filter instanceof jsts.geom.GeometryFilter ||
        filter instanceof jsts.geom.GeometryComponentFilter) {
      filter.filter(this);
      for (var i = 0, len = this.geometries.length; i < len; i++) {
        this.getGeometryN(i).apply(filter);
      }
    } else if (filter instanceof jsts.geom.CoordinateFilter) {
      for (var i = 0, len = this.geometries.length; i < len; i++) {
        this.getGeometryN(i).apply(filter);
      }
    } else if (filter instanceof jsts.geom.CoordinateSequenceFilter) {
      this.apply2.apply(this, arguments);
    }
  };

  jsts.geom.GeometryCollection.prototype.apply2 = function(filter) {
    if (this.geometries.length == 0)
      return;
    for (var i = 0; i < this.geometries.length; i++) {
      this.geometries[i].apply(filter);
      if (filter.isDone()) {
        break;
      }
    }
    if (filter.isGeometryChanged()) {
      // TODO: call this.geometryChanged(); when ported
    }
  };

  jsts.geom.GeometryCollection.prototype.getDimension = function() {
    var dimension = jsts.geom.Dimension.FALSE;
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      var geometry = this.getGeometryN(i);
      dimension = Math.max(dimension, geometry.getDimension());
    }
    return dimension;
  };

  /**
   * @protected
   */
  jsts.geom.GeometryCollection.prototype.computeEnvelopeInternal = function() {
    var envelope = new jsts.geom.Envelope();
    for (var i = 0, len = this.geometries.length; i < len; i++) {
      var geometry = this.getGeometryN(i);
      envelope.expandToInclude(geometry.getEnvelopeInternal());
    }
    return envelope;
  };

  jsts.geom.GeometryCollection.prototype.CLASS_NAME = 'jsts.geom.GeometryCollection';

})();

// TODO: port rest


text:
import pytest
from facts.grafts import user_grafts
from collections.abc import Mapping

@pytest.mark.asyncio
async def test_user():
    data = await user_grafts.user_data_info()
    assert isinstance(data.value, Mapping)


text:
package platform::VMS;

use strict;
use warnings;
use Carp;

use vars qw(@ISA);

require platform::BASE;
@ISA = qw(platform::BASE);

# Assume someone set @INC right before loading this module
use configdata;

# VMS has a cultural standard where all installed libraries are prefixed.
# For OpenSSL, the choice is 'ossl$' (this prefix was claimed in a
# conversation with VSI, Tuesday January 26 2016)
sub osslprefix          { 'OSSL$' }

sub binext              { '.EXE' }
sub dsoext              { '.EXE' }
sub shlibext            { '.EXE' }
sub libext              { '.OLB' }
sub defext              { '.OPT' }
sub objext              { '.OBJ' }
sub depext              { '.D' }
sub asmext              { '.ASM' }

# Other extra that aren't defined in platform::BASE
sub shlibvariant        { $target{shlib_variant} || '' }

sub optext              { '.OPT' }
sub optname             { return $_[1] }
sub opt                 { return $_[0]->optname($_[1]) . $_[0]->optext() }

# Other projects include the pointer size in the name of installed libraries,
# so we do too.
sub staticname {
    # Non-installed libraries are *always* static, and their names remain
    # the same, except for the mandatory extension
    my $in_libname = platform::BASE->staticname($_[1]);
    return $in_libname
        if $unified_info{attributes}->{libraries}->{$_[1]}->{noinst};

    return platform::BASE::__concat($_[0]->osslprefix(),
                                    platform::BASE->staticname($_[1]),
                                    $target{pointer_size});
}

# To enable installation of multiple major OpenSSL releases, we include the
# version number in installed shared library names.
my $sover_filename =
    join('', map { sprintf "%02d", $_ } split(m|\.|, $config{shlib_version}));
sub shlib_version_as_filename {
    return $sover_filename;
}
sub sharedname {
    return platform::BASE::__concat($_[0]->osslprefix(),
                                    platform::BASE->sharedname($_[1]),
                                    $_[0]->shlib_version_as_filename(),
                                    ($_[0]->shlibvariant() // ''),
                                    "_shr$target{pointer_size}");
}

1;


text:
layout: post
author: Justin Ball
title: Bringing the Web Back to the Blind with Ryan Florence
date: '2014-03-17T06:00:00Z'
tags:
  - "Mountain West Javascript"
  - "mwjs"
  - "Programming"
  - "accessibility"
templateKey: blog-post
path: "/bringing-the-web-back-to-the-blind-with-ryan-florence"
description: ''
---

Ryan Florence presenting "Bringing the Web Back to the Blind".

Probably the biggest accessiblity resource on the web: webaim.org.

Accessiblity

Accessiblity is more than just alt tags. You still want alt tags but there's more.

Use your headers for organization of content rather than for visual display. It helps blind users navigation through
the content based on its importance.

Landmarks

Use the role tag on elements. For example:

Adding 'role="main"' provides a 'landmark' in the page that a screen reader can find. A blind user can use these landmarks
to quickly navigate to specific sections of the page.

Html 5 includes a 'main' tag as well as others like 'article' that screen readers can use as landmarks.

Screen Reader Specific Content

Use css to hide text that is important for screen readers. Create a 'visually-hidden' css class then include
additional information to to describe the element. For example, developers frequently use an 'x' to close a modal
or other window. The screen reader will read this as 'times'. We can add additional information indicating that the
link/button will close the window.

Screen readers will execute Javascript!

ARIA

Add screen reader specific text with an attribute:

aria-label="A close button"

Tell the screen reader to ignore an element with:

aria-hidden="true"

WAI ARIA is a specification that defines how to make your website more accessible.

Aria attributes that can be used with tabs:

 - aria-selected
 - aria-controls
 - aria-expanded

However, if you don't know how to use 'aria' then don't. You'll probably make things worse.

We frequently think of Visual Interaction Design. Consider "Audible Interaction Design". Try out a screen reader and
see what it's like to use your website without the visual UI.


text:
package com.netflix.dyno.connectionpool.impl.hash;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import com.netflix.dyno.connectionpool.HashPartitioner;

/**
 * Utility class that maps a given token hashed from a key using a {@link HashPartitioner}
 * to a dynomite server on the dynomite topology ring.
 *
 * Note that as long as the Token T implements the comparable interface this class can be used
 * to perform the bin search on other homogeneous lists as well.
 *
 * Here are the imp details of the mapping algorithm
 *    1.  If a hashed token directly maps to a point on that ring, then that point is chosen.
 *    2.  If a hashed token maps between 2 points A and B where A > B then B is chosen as the owner of the token
 *    3.  All hashed tokens that go past the last point on the ring are mapped to the first point on the ring.
 *
 *    e.g
 *
 *    Consider the following points on the ring.
 *
 *    10, 20, 30, 40, 50, 60, 70, 80, 90, 100
 *
 *    Elements 0 .. 9 --> 10
 *    10 --> 10
 *    15 --> 20
 *    30 --> 30
 *    58 --> 60
 *    100 --> 100
 *    100 +  --> 10
 *
 * @author poberai
 *
 * @param <T>
 */
public class DynoBinarySearch<T extends Comparable<T>> {

	private final List<DynoTokenRange<T>> rangeList = new ArrayList<DynoTokenRange<T>>();

	private final AtomicBoolean listEmpty = new AtomicBoolean(false);

	public DynoBinarySearch(List<T> list) {

		if (list.isEmpty()) {
			listEmpty.set(true);
			return;
		}

		if (list.size() == 1) {
			rangeList.add(new DynoTokenRange<T>(null, list.get(0)));

		} else {
			// add the first range
			rangeList.add(new DynoTokenRange<T>(null, list.get(0)));
			// add rest of the tokens
			for (int i=1; i<(list.size()); i++) {
				rangeList.add(new DynoTokenRange<T>(list.get(i-1), list.get(i)));
			}

			rangeList.get(rangeList.size()-1).isLastRange = true;
		}
	}

	public T getTokenOwner(T token) {

		// Some quick boundary checks
		if (listEmpty.get()) {
			return null;
		}

		if (rangeList.size() == 1) {
			return rangeList.get(0).getTokenOwner();
		}

		DynoTokenRange<T> firstRange = rangeList.get(0);
		DynoTokenRange<T> lastRange = rangeList.get(rangeList.size()-1);

		if (firstRange.compareTo(token) == 0) {
			// Token is smaller than FIRST range, map to first range.
			return firstRange.getTokenOwner();
		}

		if (lastRange.compareTo(token) < 0) {
			// Token is greater than LAST range, map to first range.
			return firstRange.getTokenOwner();
		}

		int index = Collections.binarySearch(rangeList, token);

		if (index < 0) {
			throw new RuntimeException("Token not found!: " + token);
		}

		return rangeList.get(index).getTokenOwner();
	}

	public String toString() {

		StringBuilder sb = new StringBuilder("[DynoBinarySearch:\n");
		for (DynoTokenRange<T> r : rangeList) {
			sb.append(r.toString()).append("\n");
		}
		sb.append("]");
		return sb.toString();
	}

	static class DynoTokenRange<T extends Comparable<T>> implements Comparable<T> {

		final T start;
		final T end;
		boolean isFirstRange = false;
		boolean isLastRange = false;

		DynoTokenRange(T s, T e) {
			this.start = s;
			this.end = e;

			if (s == null) {
				isFirstRange = true;
			}

			if (isFirstRange) {
				if (end == null) {
					throw new RuntimeException("Bad Range: end must not be null");
				}
			} else if (!(lessThan(start, end))) {
				throw new RuntimeException("Bad Range: start must be less than end: " + this.toString());
			}
		}

		public T getTokenOwner() {
			return end;
		}

		public String toString() {
			if (isFirstRange) {
				return "(null," + end + "]";
			} else {
				return "(" + start + "," + end + "]";
			}
		}

		@Override
		public int compareTo(T key) {

			// Boundary checks, to be safe!

			if (isFirstRange) {

				if (lessThanEquals(key, end)) {
					return 0;  // This key is within this range
				} else {
					// else This range is smaller than this key
					return -1;
				}
			}

			// Functionality for any other range i.e in another position in the list except for the first
			if (lessThanEquals(key, start)) {
				// This range is greater than the key
				return 1;
			}

			if (lessThan(start, key) && lessThanEquals(key, end)) {
				// This key is within this range
				return 0;
			}

			if (lessThan(end, key)) {
				// This range is smaller than this key
				return -1;
			} else {
				throw new RuntimeException("Invalid key for bin search: " + key + ", this range: " + this.toString());
			}
		}

		private boolean lessThan(T left, T right) {
			return left.compareTo(right) < 0;
		}

		private boolean lessThanEquals(T left, T right) {
			return left.compareTo(right) <= 0;
		}
	}
}


text:
package cloudcallcenter

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Instance is a nested struct in cloudcallcenter response
type Instance struct {
	Name                      string                       `json:"Name" xml:"Name"`
	ModifyTime                int64                        `json:"ModifyTime" xml:"ModifyTime"`
	StorageBucket             string                       `json:"StorageBucket" xml:"StorageBucket"`
	InstanceDescription       string                       `json:"InstanceDescription" xml:"InstanceDescription"`
	CreatedTime               int64                        `json:"CreatedTime" xml:"CreatedTime"`
	InstanceId                string                       `json:"InstanceId" xml:"InstanceId"`
	Concurrency               int64                        `json:"Concurrency" xml:"Concurrency"`
	MaxOnlineAgents           int                          `json:"MaxOnlineAgents" xml:"MaxOnlineAgents"`
	MaxConcurrentConversation int                          `json:"MaxConcurrentConversation" xml:"MaxConcurrentConversation"`
	Description               string                       `json:"Description" xml:"Description"`
	TenantId                  string                       `json:"TenantId" xml:"TenantId"`
	DirectoryId               string                       `json:"DirectoryId" xml:"DirectoryId"`
	DomainName                string                       `json:"DomainName" xml:"DomainName"`
	InstanceName              string                       `json:"InstanceName" xml:"InstanceName"`
	ModifyUserName            string                       `json:"ModifyUserName" xml:"ModifyUserName"`
	Owner                     string                       `json:"Owner" xml:"Owner"`
	CreationTime              int64                        `json:"CreationTime" xml:"CreationTime"`
	CallCenterInstanceId      string                       `json:"CallCenterInstanceId" xml:"CallCenterInstanceId"`
	StorageMaxSize            int                          `json:"StorageMaxSize" xml:"StorageMaxSize"`
	StorageMaxDays            int                          `json:"StorageMaxDays" xml:"StorageMaxDays"`
	NluServiceType            string                       `json:"NluServiceType" xml:"NluServiceType"`
	ConsoleUrl                string                       `json:"ConsoleUrl" xml:"ConsoleUrl"`
	Status                    string                       `json:"Status" xml:"Status"`
	FailLoginNames            []string                     `json:"FailLoginNames" xml:"FailLoginNames"`
	FailPhoneNumbers          []string                     `json:"FailPhoneNumbers" xml:"FailPhoneNumbers"`
	SuccessLoginNames         []string                     `json:"SuccessLoginNames" xml:"SuccessLoginNames"`
	ApplicableOperations      []string                     `json:"ApplicableOperations" xml:"ApplicableOperations"`
	SuccessPhoneNumbers       []string                     `json:"SuccessPhoneNumbers" xml:"SuccessPhoneNumbers"`
	Admin                     AdminInCreateInstance        `json:"Admin" xml:"Admin"`
	PhoneNumbers              PhoneNumbersInCreateInstance `json:"PhoneNumbers" xml:"PhoneNumbers"`
}


text:
package com.hitme.omc.handler;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.hitme.omc.util.LogProxy;

public abstract class MessageHandler implements IMessageHandler {
	private static final LogProxy LOGGER = new LogProxy(MessageHandler.class);
	private String serverName;
	private int idleTimeOutInMilli;

	public int getIdleTimeOutInMilli() {
		return this.idleTimeOutInMilli;
	}

	public void setIdleTimeOutInMilli(int idleTimeOutInMilli) {
		this.idleTimeOutInMilli = idleTimeOutInMilli;
	}

	public String getServerName() {
		return this.serverName;
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}

	public void sessionOpened(IoSession session) {
		LOGGER.info("session opened, session=" + session);
	}

	public abstract void messageReceived(IoSession paramIoSession, Object paramObject);

	public void sessionClosed(IoSession session) {
		if (session != null) {
			session.closeNow();
		}
	}

	public void sessionIdle(IoSession session, IdleStatus status) {
		if (session == null) {
			return;
		}
		sessionClosed(session);
	}

	public boolean isConnected(String ipAddress) {
		return false;
	}

	public void exceptionCaught(IoSession session) {
		LOGGER.error("tcp exceptionCaught:" + session);
	}

	public abstract void sessionCreated(IoSession paramIoSession);
}


text:
class CreateStores < ActiveRecord::Migration
  def change
    create_table :stores do |t|
      t.string :name
      t.string :address

      t.timestamps
    end
  end
end


text:
[官方实例](https://android.googlesource.com/platform/development/+/master/samples/ToyVpn/src/com/example/android/toyvpn/ToyVpnConnection.java)

Android 上用来扩展实现 Vpn(Virtual Private Network) 方案的工具类

建立一个 Vpn 接口,可以配置地址和路由规则并返回一个文件描述符(实际为 ParcelFileDescriptor 类)

通过该文件描述符可以读取 Vpn 接口接受到远程服务器的 IP 数据包(FileOutputStream)和向远程服务器发送的 IP 数据包(FileInputStream)

**运行在 IP 协议之上**,应用程序可以通过 `tunnel` 和与远程服务器交换数据包

需要在 manitest 上注册

```java
<service android:name=".ExampleVpnService"
        android:permission="android.permission.BIND_VPN_SERVICE">
    <intent-filter>
        <action android:name="android.net.VpnService"/>
    </intent-filter>
</service>
```


text:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router) { }
  canActivate() {
    if (localStorage.getItem('currentUser')) {
      // logged in so return true
      return true;
    }
    // not logged in so redirect to login page
    this.router.navigate(['/login']);
    return false;
  }
}


text:
{-# LANGUAGE DeriveDataTypeable   #-}
{-# LANGUAGE EmptyDataDecls       #-}
{-# LANGUAGE TypeFamilies         #-}
{-# LANGUAGE TypeOperators        #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE PolyKinds            #-}

module Type.Operators where

import Data.Typeable
import Prelude
import GHC.Exts (Constraint)
import GHC.TypeLits
import Type.Bool
import Type.Container
import Type.Wrapped

-- | The `$$` operator is just like `$` one but with even lower precedence level.
--   Unlike value-level `$`, the type-level one has precedence level of `infixr 1`
--   in order to be used in function arguments, like `edge :: Node $ Source a -> Node $ Target a -> a`.
--   The `$$` operator has higher precedence than `->`, so the above expression would not be valid when using it.

infixr 0 $$
type f $$ a = f a

infixr 1 $
type f $ a = f a

infixl 1 &
type a & f = f a


text:
class Follow < ActiveRecord::Base
	belongs_to :user
end


text:
  local gen_code = require("Q/UTILS/lua/gen_code")
  local plpath = require "pl.path"
  local srcdir = "../gen_src/"
  local incdir = "../gen_inc/"
  if ( not plpath.isdir(srcdir) ) then plpath.mkdir(srcdir) end
  if ( not plpath.isdir(incdir) ) then plpath.mkdir(incdir) end

  local qtypes = { 'B1' }

  local num_produced = 0
  local sp_fn = assert(require("vnot_specialize"))

  local function generate_files(in_qtype, args)
    local status, subs, tmpl = pcall(sp_fn, in_qtype, args)
    if ( status ) then
      assert(type(subs) == "table")
      gen_code.doth(subs,tmpl, incdir)
      gen_code.dotc(subs, tmpl, srcdir)
      print("Produced ", subs.fn)
      num_produced = num_produced + 1
    else
      assert(nil, subs)
    end
    return true
  end

  for _, in_qtype in ipairs(qtypes) do
    status = pcall(generate_files, in_qtype)
    assert(status,
     "Failed to generate files for vnot")
  end
  assert(num_produced > 0)


text:
#ifndef __HELPER_CLIENT_H__
#define __HELPER_CLIENT_H__

#include <zlib.h>
#include <poller.h>
#include <timerlist.h>
#include <noncopyable.h>
#include <decode_unit.h>
#include <cache.h>
#include <memcheck.h>
#include <client_unit.h>
#include <vector>
using std::vector;
#include <game_unit.h>

#define MAX_HELPER_RECV_BUF 65536
using namespace comm::sockcommu;

extern CMemPool*	_helpMp;

HTTP_SVR_NS_BEGIN
class TPkgHeader;
class CHelperUnit : public CPollerObject,
					private CTimerObject,
					private noncopyable
{
public: //method
	CHelperUnit(CPollerUnit* unit);
	virtual ~CHelperUnit (void);

    int send_to_logic (CTimerList* lst);
    int append_pkg(const char* buf, unsigned int len);
	int connect (void);

	int send_to_logic();

  	inline void set_netfd (int fd)
	{
		netfd = fd;
	}

	inline int get_netfd (void)
	{
		return netfd;
	}
private:
	string IpMap(string& ip);

	CClientUnit* GetClientUintByUid(const int &uid, CDecoderUnit **pDecoder);
	CClientUnit* _get_client_by_id(const unsigned long& flow, CDecoderUnit** ppDecoder);

	int _worker_stat_chk(NETInputPacket* pack); 	/* Notify完成任务 */
	int _pay_res(NETInputPacket* pack); 	/* 返回支付请求结果 */

public:
	std::string addr;
	int			port;

private:
    virtual int InputNotify (void);
	virtual int OutputNotify (void);
	virtual int HangupNotify (void);
	virtual void TimerNotify (void);

	int reConnect(void);
    int send_to_cgi(void);
	int recv_from_cgi(void);
	int process_pkg(void);
	void update_timer(void);
	void reset_helper(void);
private:
	void SendClientClose(int uid);

private:
	CConnState      _stage;
	CTimerList*     _helperTimer;
    char            _curRecvBuf[MAX_HELPER_RECV_BUF];
	short 			_send_error_times;

	//��������: TCP_SOCKET\UDP_SOCKET\UNIX_SOCKET
	int         _type;
	//�Զ���Ϣ:
	CSocketAddr _addr;
	//������cache
	CRawCache   _r;
	//д�ظ�cache
	CRawCache   _w;
};

HTTP_SVR_NS_END
#endif


text:
namespace org.apache.lucene.analysis.hi
{

	using SetKeywordMarkerFilter = org.apache.lucene.analysis.miscellaneous.SetKeywordMarkerFilter; // javadoc @link
	using KeywordAttribute = org.apache.lucene.analysis.tokenattributes.KeywordAttribute;
	using CharTermAttribute = org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

	/// <summary>
	/// A <seealso cref="TokenFilter"/> that applies <seealso cref="HindiNormalizer"/> to normalize the
	/// orthography.
	/// <para>
	/// In some cases the normalization may cause unrelated terms to conflate, so
	/// to prevent terms from being normalized use an instance of
	/// <seealso cref="SetKeywordMarkerFilter"/> or a custom <seealso cref="TokenFilter"/> that sets
	/// the <seealso cref="KeywordAttribute"/> before this <seealso cref="TokenStream"/>.
	/// </para> </summary>
	/// <seealso cref= HindiNormalizer </seealso>
	public sealed class HindiNormalizationFilter : TokenFilter
	{

	  private readonly HindiNormalizer normalizer = new HindiNormalizer();
	  private readonly CharTermAttribute termAtt = addAttribute(typeof(CharTermAttribute));
	  private readonly KeywordAttribute keywordAtt = addAttribute(typeof(KeywordAttribute));

	  public HindiNormalizationFilter(TokenStream input) : base(input)
	  {
	  }

//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public boolean incrementToken() throws java.io.IOException
	  public override bool incrementToken()
	  {
		if (input.incrementToken())
		{
		  if (!keywordAtt.Keyword)
		  {
			termAtt.Length = normalizer.normalize(termAtt.buffer(), termAtt.length());
		  }
		  return true;
		}
		return false;
	  }
	}

}


text:
package org.apache.cassandra.service;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.db.ReadResponse;
import org.apache.cassandra.net.IAsyncCallback;
import org.apache.cassandra.net.MessageIn;
import org.apache.cassandra.utils.WrappedRunnable;

public class AsyncRepairCallback implements IAsyncCallback<ReadResponse>
{
    private final DataResolver repairResolver;
    private final int blockfor;
    protected final AtomicInteger received = new AtomicInteger(0);

    public AsyncRepairCallback(DataResolver repairResolver, int blockfor)
    {
        this.repairResolver = repairResolver;
        this.blockfor = blockfor;
    }

    public void response(MessageIn<ReadResponse> message)
    {
        repairResolver.preprocess(message);
        if (received.incrementAndGet() == blockfor)
        {
            StageManager.getStage(Stage.READ_REPAIR).execute(new WrappedRunnable()
            {
                protected void runMayThrow()
                {
                    repairResolver.resolve();
                }
            });
        }
    }

    public boolean isLatencyForSnitch()
    {
        return true;
    }
}


text:
from django.conf import settings
from django.conf.urls import patterns, include, url

urlpatterns = patterns('account.views',
  url(r'^sign-up/$', 'sign_up', name="sign-up"),
  url(r'^sign-up-success/$', 'sign_up_success', name="sign-up-success"),

  url(r'^brain-dead/$', 'password_reset', name="password-reset"),
  url(r'^brain-dead/sent/$', 'password_reset_sent', name="password-reset-sent"),
  url(r'^brain-dead/final/$', 'password_reset_final', name="password-reset-final"),
  url(r'^brain-dead/not-anymore/$', 'password_reset_success', name="password-reset-success"),

  url(r'^email-verify/$', 'email_verify', name="email-verify"),
)


text:
title: Create an AJAX-enabled SharePoint WebPart that uses the Telerik Controls
page_title: Create an AJAX-enabled SharePoint WebPart that uses the Telerik Controls | UI for ASP.NET AJAX Documentation
description: Create an AJAX-enabled SharePoint WebPart that uses the Telerik Controls
slug: sharepoint/2007/create-an-ajax-enabled-sharepoint-webpart-that-uses-the-telerik-controls
tags: create,an,ajax-enabled,sharepoint,webpart,that,uses,the,telerik,controls
published: True
position: 5
---

# Create an AJAX-enabled SharePoint WebPart that uses the Telerik Controls

This article shows how to create an AJAX-enabled SharePoint WebPart that uses Telerik controls.

* The article assumes that you already have ASP.NET AJAX installed and configured on the target MOSS installation. If haven't, you can follow [this excellent blog post by Mike Ammerlaan](http://sharepoint.microsoft.com/blogs/mike/Lists/Posts/Post.aspx?ID=3).

* The next step is to deploy Telerik UI for ASP.NET AJAX to the SharePoint server. You can find instructions at [Deploying Telerik UI for ASP.NET AJAX]({%slug sharepoint/2007/deploying-telerik-ui-for-asp.net-ajax%})

* To simplify creating, deploying and debugging the web part, we'll use the 'Visual Studio extensions for Windows SharePoint Services'. These extensions can be found at the following URLs:

	For Visual Studio 2005:[http://www.microsoft.com/downloads/details.aspx?FamilyID=3E1DCCCD-1CCA-433A-BB4D-97B96BF7AB63&displaylang=en](http://www.microsoft.com/downloads/details.aspx?FamilyID=3E1DCCCD-1CCA-433A-BB4D-97B96BF7AB63&displaylang=en)

	For Visual Studio 2008:[http://www.microsoft.com/downloads/details.aspx?familyid=7BF65B28-06E2-4E87-9BAD-086E32185E68&displaylang=en](http://www.microsoft.com/downloads/details.aspx?familyid=7BF65B28-06E2-4E87-9BAD-086E32185E68&displaylang=en)

* Create a new WebPart project in Visual Studio:

	![](images/Image1_NewProject.png)

* Add the following code:

	**C#**

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			Page.ClientScript.RegisterStartupScript(typeof(Web_Part1), this.ID, "_spOriginalFormAction = document.forms[0].action;_spSuppressFormOnSubmitWrapper=true;", true);
			if (this.Page.Form != null)
			{
				string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
				if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
				{
					this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
				}
			}
		}

	As explained in the linked blog post, we need this code to get ASP.NET AJAX working properly. You need to pass the typeof of the current WebPart to the RegisterStartupScript method.

* To use ASP.NET AJAX, you need a ScriptManager control on the page. The blog post explained how to add the ScriptManager to a SharePoint MasterPage. Alternatively, you can add the ScriptManager from the code of the WebPart itself as demonstrated here. Add the following to the OnInit method:

	**C#**

			ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
			if (scriptManager == null)
			{
				scriptManager = new RadScriptManager();
				this.Page.Form.Controls.AddAt(0, scriptManager);
			}

	It's important to note that the ScriptManager is created during the Init event. Creating it in the CreateChildControls method may cause problems as this method is sometimes called too late in the Page's lifecycle.We can use the RadScriptManager instead of the regular ScriptManager. You can read more about the RadScriptManager at [RadScriptManager]({%slug scriptmanager/overview%}).

* For the RadScriptManager to work, you need to register its HttpHandler. To do this, add the following in the `<httpHandlers>` section of SharePoint's web.config:

	**XML**

	    <add verb="*" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" />

* This is all the preparation you need to start using Telerik controls in your WebParts. Simply override the OnLoad method and add your controls there:

	**C#**

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			Panel panel = new Panel();
			panel.ID = "Panel1";
			this.Controls.Add(panel);
			RadTreeView treeView = new RadTreeView();
			treeView.ID = "RadTreeView1";
			treeView.Nodes.Add(new RadTreeNode("What's the time?"));
			treeView.NodeClick += new RadTreeViewEventHandler(treeView_NodeClick);
			panel.Controls.Add(treeView);
			label = new Label();
			label.Text = "This is a label";
			panel.Controls.Add(label);
			RadAjaxManager ajaxManager = RadAjaxManager.GetCurrent(this.Page);
			if (ajaxManager == null)
			{
				ajaxManager = new RadAjaxManager();
				ajaxManager.ID = "RadAjaxManager1";
				Controls.Add(ajaxManager);
				this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
			}
			ajaxManager.AjaxSettings.AddAjaxSetting(treeView, panel);
		}
		void treeView_NodeClick(object sender, RadTreeNodeEventArgs e)
		{
			label.Text = DateTime.Now.ToLongTimeString();
		}

	There is one difference from a non-SharePoint scenario. When you are using RadAjaxManager, you need to call the following code upon creating it:

	**C#**

			this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);

* You can now use the Deploy Web Part option in the Build menu to build and deploy the Web Part to SharePoint.You should now be able to add the Web Part to your pages:

	![](images/Image2_Deploy.png)

* Clicking the TreeView node will result in an AJAX update of the Label.

	![](images/Image3_Final_Result.png)


text:
#if NET
using System;
using System.Runtime.CompilerServices;
using System.Text;

namespace Secs4Net;

internal static class ModuleInitializer
{
    [ModuleInitializer]
    internal static void Initial()
    {
        if (!BitConverter.IsLittleEndian)
        {
            throw new PlatformNotSupportedException("This version is only work on little endian hardware.");
        }

        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    }
}
#endif


text:
#import "ZXParsedResult.h"

@interface ZXSMSParsedResult : ZXParsedResult

@property (nonatomic, strong, readonly) NSArray *numbers;
@property (nonatomic, strong, readonly) NSArray *vias;
@property (nonatomic, copy, readonly) NSString *subject;
@property (nonatomic, copy, readonly) NSString *body;

- (id)initWithNumber:(NSString *)number via:(NSString *)via subject:(NSString *)subject body:(NSString *)body;
- (id)initWithNumbers:(NSArray *)numbers vias:(NSArray *)vias subject:(NSString *)subject body:(NSString *)body;
+ (id)smsParsedResultWithNumber:(NSString *)number via:(NSString *)via subject:(NSString *)subject body:(NSString *)body;
+ (id)smsParsedResultWithNumbers:(NSArray *)numbers vias:(NSArray *)vias subject:(NSString *)subject body:(NSString *)body;
- (NSString *)sMSURI;

@end


text:
package com.nhl.link.rest.it.fixture.cayenne;

import com.nhl.link.rest.it.fixture.cayenne.auto._E3;

public class E3 extends _E3 {

	private static final long serialVersionUID = 1L;
}


text:
package ru.job4j.changetracker.internalclasses;

import java.util.List;

/**
 * Created on 01.09.2017.
 *
 * @author Aleks Sidorenko (alek.sidorenko1979@gmail.com).
 * @version $Id$.
 * @since 0.1.
 */
public class StubInput implements Input {

    /**
     * @param answers - array's param.
     */
    private List<String> answers;

    /**
     * @param position - param count position.
     */
    private int position = 0;

    /**
     * Constructor.
     * @param answers - array's param.
     */
    public StubInput(List<String> answers) {
        this.answers = answers;
    }

    /**
     * Method from interface.
     * @param question - param of method interface.
     * @return - string.
     */
    public String ask(String question) {
        return answers.get(position++);
    }
}


text:
<?php

/**
 * @file
 *
 * Definition of \Drupal\devel_generate\Routing\DevelGenerateRouteSubscriber.
 */
namespace Drupal\devel_generate\Routing;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Component\Plugin\PluginManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;

/**
 * Provides dynamic routes for devel_generate.
 */
class DevelGenerateRoutes implements ContainerInjectionInterface {

  /**
   * Constructs a new devel_generate route subscriber.
   *
   * @param \Drupal\Component\Plugin\PluginManagerInterface $devel_generate_manager
   *   The DevelGeneratePluginManager.
   */
  public function __construct(PluginManagerInterface $devel_generate_manager) {
    $this->DevelGenerateManager = $devel_generate_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('plugin.manager.develgenerate')
    );
  }

  public function routes() {
    $devel_generate_plugins = $this->DevelGenerateManager->getDefinitions();

    $routes = array();
    foreach ($devel_generate_plugins as $id => $plugin) {
      $label = $plugin['label'];
      $type_url_str = str_replace('_', '-', $plugin['url']);
      $routes["devel_generate.$id"] = new Route(
        "admin/config/development/generate/$type_url_str",
        array(
          '_form' => '\Drupal\devel_generate\Form\DevelGenerateForm',
          '_title' => "Generate $label",
          '_plugin_id' => $id,
        ),
        array(
          '_permission' => $plugin['permission'],
        )
      );
    }

    return $routes;
  }

}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TemplateHaskell   #-}
module Main ( main ) where

import           Control.Lens
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as BL8
import           Snap
import           Snap.Snaplet.SES

data App = App {
   _awsKeys :: Snaplet AWSKeys
}

makeLenses ''App

initApp :: SnapletInit App App
initApp = makeSnaplet "name" "description" Nothing $ do
            _awsKeys <- nestSnaplet "ses-html" awsKeys initAWSKeys
	    addRoutes [("/", handleKeys)]
	    return App {..}
  where
    handleKeys = method GET $ do
      with awsKeys $ withKeys $ liftIO . print
      result <- with awsKeys $ sendEmail ["david@solidtranslate.com"] "cookie-crisp" "
TEST
"
      liftIO $ print result
      writeBS "done"

main :: IO ()
main = do (_, app, _) <- runSnaplet Nothing initApp
          httpServe config app
  where
    config = setAccessLog ConfigNoLog $
             setErrorLog ConfigNoLog $
             defaultConfig