text:
module Google
  module Cloud
    module Bigquery
      class Dataset
        ##
        # # Dataset Access Control
        #
        # Represents the access control rules for a {Dataset}.
        #
        # @see https://cloud.google.com/bigquery/docs/access-control BigQuery
        #   Access Control
        #
        # @example
        #   require "google/cloud/bigquery"
        #
        #   bigquery = Google::Cloud::Bigquery.new
        #   dataset = bigquery.dataset "my_dataset"
        #
        #   dataset.access do |access|
        #     access.add_owner_group "owners@example.com"
        #     access.add_writer_user "writer@example.com"
        #     access.remove_writer_user "readers@example.com"
        #     access.add_reader_special :all_users
        #   end
        #
        class Access
          # @private
          ROLES = {
            "reader" => "READER",
            "writer" => "WRITER",
            "owner"  => "OWNER"
          }.freeze

          # @private
          SCOPES = {
            "domain"         => :domain,
            "group"          => :group_by_email,
            "group_by_email" => :group_by_email,
            "groupByEmail"   => :group_by_email,
            "iam_member"     => :iam_member,
            "iamMember"      => :iam_member,
            "routine"        => :routine,
            "special"        => :special_group,
            "special_group"  => :special_group,
            "specialGroup"   => :special_group,
            "user"           => :user_by_email,
            "user_by_email"  => :user_by_email,
            "userByEmail"    => :user_by_email,
            "view"           => :view
          }.freeze

          # @private
          GROUPS = {
            "owners"                  => "projectOwners",
            "project_owners"          => "projectOwners",
            "projectOwners"           => "projectOwners",
            "readers"                 => "projectReaders",
            "project_readers"         => "projectReaders",
            "projectReaders"          => "projectReaders",
            "writers"                 => "projectWriters",
            "project_writers"         => "projectWriters",
            "projectWriters"          => "projectWriters",
            "all"                     => "allAuthenticatedUsers",
            "all_authenticated_users" => "allAuthenticatedUsers",
            "allAuthenticatedUsers"   => "allAuthenticatedUsers",
            "all_users"               => "allUsers",
            "allUsers"                => "allUsers"
          }.freeze

          ##
          # @private
          # Initialized a new Access object.
          # Must provide a valid Google::Apis::BigqueryV2::Dataset object.
          # Access will mutate the gapi object.
          def initialize
            @rules = [] # easiest to do this in the constructor
            @original_rules_hashes = @rules.map(&:to_h)
          end

          # @private
          def changed?
            @original_rules_hashes != @rules.map(&:to_h)
          end

          # @private
          def empty?
            @rules.empty?
          end

          # @private
          def freeze
            @rules = @rules.map(&:dup).map(&:freeze)
            @rules.freeze
            super
          end

          ##
          # @private View the access rules as an array of hashes.
          def to_a
            @rules.map(&:to_h)
          end

          ##
          # Add reader access to a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_reader_user "entity@example.com"
          #   end
          #
          def add_reader_user email
            add_access_role_scope_value :reader, :user, email
          end

          ##
          # Add reader access to a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_reader_group "entity@example.com"
          #   end
          #
          def add_reader_group email
            add_access_role_scope_value :reader, :group, email
          end

          ##
          # Add reader access to some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_reader_iam_member "entity@example.com"
          #   end
          #
          def add_reader_iam_member identity
            add_access_role_scope_value :reader, :iam_member, identity
          end

          ##
          # Add reader access to a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_reader_domain "example.com"
          #   end
          #
          def add_reader_domain domain
            add_access_role_scope_value :reader, :domain, domain
          end

          ##
          # Add reader access to a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_reader_special :all_users
          #   end
          #
          def add_reader_special group
            add_access_role_scope_value :reader, :special, group
          end

          ##
          # Add access to a routine from a different dataset. Queries executed
          # against that routine will have read access to views/tables/routines
          # in this dataset. Only UDF is supported for now. The role field is
          # not required when this field is set. If that routine is updated by
          # any user, access to the routine needs to be granted again via an
          # update operation.
          #
          # @param [Google::Cloud::Bigquery::Routine] routine A routine object.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #   other_dataset = bigquery.dataset "my_other_dataset", skip_lookup: true
          #
          #   routine = other_dataset.routine "my_routine"
          #
          #   dataset.access do |access|
          #     access.add_reader_routine routine
          #   end
          #
          def add_reader_routine routine
            add_access_routine routine
          end

          ##
          # Add reader access to a view.
          #
          # @param [Google::Cloud::Bigquery::Table, String] view A table object,
          #   or a string identifier as specified by the [Standard SQL Query
          #   Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
          #   (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
          #   Reference](https://cloud.google.com/bigquery/query-reference#from)
          #   (`project-name:dataset_id.table_id`).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #   other_dataset = bigquery.dataset "my_other_dataset", skip_lookup: true
          #
          #   view = other_dataset.table "my_view", skip_lookup: true
          #
          #   dataset.access do |access|
          #     access.add_reader_view view
          #   end
          #
          def add_reader_view view
            add_access_view view
          end

          ##
          # Add writer access to a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_writer_user "entity@example.com"
          #   end
          #
          def add_writer_user email
            add_access_role_scope_value :writer, :user, email
          end

          ##
          # Add writer access to a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_writer_group "entity@example.com"
          #   end
          #
          def add_writer_group email
            add_access_role_scope_value :writer, :group, email
          end

          ##
          # Add writer access to some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_writer_iam_member "entity@example.com"
          #   end
          #
          def add_writer_iam_member identity
            add_access_role_scope_value :writer, :iam_member, identity
          end

          ##
          # Add writer access to a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_writer_domain "example.com"
          #   end
          #
          def add_writer_domain domain
            add_access_role_scope_value :writer, :domain, domain
          end

          ##
          # Add writer access to a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_writer_special :all_users
          #   end
          #
          def add_writer_special group
            add_access_role_scope_value :writer, :special, group
          end

          ##
          # Add owner access to a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_owner_user "entity@example.com"
          #   end
          #
          def add_owner_user email
            add_access_role_scope_value :owner, :user, email
          end

          ##
          # Add owner access to a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_owner_group "entity@example.com"
          #   end
          #
          def add_owner_group email
            add_access_role_scope_value :owner, :group, email
          end

          ##
          # Add owner access to some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_owner_iam_member "entity@example.com"
          #   end
          #
          def add_owner_iam_member identity
            add_access_role_scope_value :owner, :iam_member, identity
          end

          ##
          # Add owner access to a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_owner_domain "example.com"
          #   end
          #
          def add_owner_domain domain
            add_access_role_scope_value :owner, :domain, domain
          end

          ##
          # Add owner access to a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.add_owner_special :all_users
          #   end
          #
          def add_owner_special group
            add_access_role_scope_value :owner, :special, group
          end

          ##
          # Remove reader access from a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_reader_user "entity@example.com"
          #   end
          #
          def remove_reader_user email
            remove_access_role_scope_value :reader, :user, email
          end

          ##
          # Remove reader access from a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_reader_group "entity@example.com"
          #   end
          #
          def remove_reader_group email
            remove_access_role_scope_value :reader, :group, email
          end

          ##
          # Remove reader access from some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_reader_iam_member "entity@example.com"
          #   end
          #
          def remove_reader_iam_member identity
            remove_access_role_scope_value :reader, :iam_member, identity
          end

          ##
          # Remove reader access from a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_reader_domain "example.com"
          #   end
          #
          def remove_reader_domain domain
            remove_access_role_scope_value :reader, :domain, domain
          end

          ##
          # Remove reader access from a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_reader_special :all_users
          #   end
          #
          def remove_reader_special group
            remove_access_role_scope_value :reader, :special, group
          end

          ##
          # Remove reader access from a routine from a different dataset.
          #
          # @param [Google::Cloud::Bigquery::Routine] routine A routine object.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #   other_dataset = bigquery.dataset "my_other_dataset", skip_lookup: true
          #
          #   routine = other_dataset.routine "my_routine", skip_lookup: true
          #
          #   dataset.access do |access|
          #     access.remove_reader_routine routine
          #   end
          #
          def remove_reader_routine routine
            remove_access_routine routine
          end

          ##
          # Remove reader access from a view.
          #
          # @param [Google::Cloud::Bigquery::Table, String] view A table object,
          #   or a string identifier as specified by the [Standard SQL Query
          #   Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
          #   (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
          #   Reference](https://cloud.google.com/bigquery/query-reference#from)
          #   (`project-name:dataset_id.table_id`).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #   other_dataset = bigquery.dataset "my_other_dataset", skip_lookup: true
          #
          #   view = other_dataset.table "my_view", skip_lookup: true
          #
          #   dataset.access do |access|
          #     access.remove_reader_view view
          #   end
          #
          def remove_reader_view view
            remove_access_view view
          end

          ##
          # Remove writer access from a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_writer_user "entity@example.com"
          #   end
          #
          def remove_writer_user email
            remove_access_role_scope_value :writer, :user, email
          end

          ##
          # Remove writer access from a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_writer_group "entity@example.com"
          #   end
          #
          def remove_writer_group email
            remove_access_role_scope_value :writer, :group, email
          end

          ##
          # Remove writer access from some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_writer_iam_member "entity@example.com"
          #   end
          #
          def remove_writer_iam_member identity
            remove_access_role_scope_value :writer, :iam_member, identity
          end

          ##
          # Remove writer access from a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_writer_domain "example.com"
          #   end
          #
          def remove_writer_domain domain
            remove_access_role_scope_value :writer, :domain, domain
          end

          ##
          # Remove writer access from a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_writer_special :all_users
          #   end
          #
          def remove_writer_special group
            remove_access_role_scope_value :writer, :special, group
          end

          ##
          # Remove owner access from a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_owner_user "entity@example.com"
          #   end
          #
          def remove_owner_user email
            remove_access_role_scope_value :owner, :user, email
          end

          ##
          # Remove owner access from a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_owner_group "entity@example.com"
          #   end
          #
          def remove_owner_group email
            remove_access_role_scope_value :owner, :group, email
          end

          ##
          # Remove owner access from some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_owner_iam_member "entity@example.com"
          #   end
          #
          def remove_owner_iam_member identity
            remove_access_role_scope_value :owner, :iam_member, identity
          end

          ##
          # Remove owner access from a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_owner_domain "example.com"
          #   end
          #
          def remove_owner_domain domain
            remove_access_role_scope_value :owner, :domain, domain
          end

          ##
          # Remove owner access from a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   dataset.access do |access|
          #     access.remove_owner_special :all_users
          #   end
          #
          def remove_owner_special group
            remove_access_role_scope_value :owner, :special, group
          end

          ##
          # Checks reader access for a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.reader_user? "entity@example.com" #=> false
          #
          def reader_user? email
            lookup_access_role_scope_value :reader, :user, email
          end

          ##
          # Checks reader access for a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.reader_group? "entity@example.com" #=> false
          #
          def reader_group? email
            lookup_access_role_scope_value :reader, :group, email
          end

          ##
          # Checks reader access for some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.reader_iam_member? "entity@example.com" #=> false
          #
          def reader_iam_member? identity
            lookup_access_role_scope_value :reader, :iam_member, identity
          end

          ##
          # Checks reader access for a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.reader_domain? "example.com" #=> false
          #
          def reader_domain? domain
            lookup_access_role_scope_value :reader, :domain, domain
          end

          ##
          # Checks reader access for a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.reader_special? :all_users #=> false
          #
          def reader_special? group
            lookup_access_role_scope_value :reader, :special, group
          end

          ##
          # Checks access for a routine from a different dataset. Queries executed
          # against that routine will have read access to views/tables/routines
          # in this dataset. Only UDF is supported for now. The role field is
          # not required when this field is set. If that routine is updated by
          # any user, access to the routine needs to be granted again via an
          # update operation.
          #
          # @param [Google::Cloud::Bigquery::Routine] routine A routine object.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #   other_dataset = bigquery.dataset "my_other_dataset", skip_lookup: true
          #
          #   routine = other_dataset.routine "my_routine", skip_lookup: true
          #
          #   access = dataset.access
          #   access.reader_routine? routine #=> false
          #
          def reader_routine? routine
            lookup_access_routine routine
          end

          ##
          # Checks reader access for a view.
          #
          # @param [Google::Cloud::Bigquery::Table, String] view A table object,
          #   or a string identifier as specified by the [Standard SQL Query
          #   Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
          #   (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
          #   Reference](https://cloud.google.com/bigquery/query-reference#from)
          #   (`project-name:dataset_id.table_id`).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #   other_dataset = bigquery.dataset "my_other_dataset", skip_lookup: true
          #
          #   view = other_dataset.table "my_view", skip_lookup: true
          #
          #   access = dataset.access
          #   access.reader_view? view #=> false
          #
          def reader_view? view
            lookup_access_view view
          end

          ##
          # Checks writer access for a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.writer_user? "entity@example.com" #=> false
          #
          def writer_user? email
            lookup_access_role_scope_value :writer, :user, email
          end

          ##
          # Checks writer access for a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.writer_group? "entity@example.com" #=> false
          #
          def writer_group? email
            lookup_access_role_scope_value :writer, :group, email
          end

          ##
          # Checks writer access for some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.writer_iam_member? "entity@example.com" #=> false
          #
          def writer_iam_member? identity
            lookup_access_role_scope_value :writer, :iam_member, identity
          end

          ##
          # Checks writer access for a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.writer_domain? "example.com" #=> false
          #
          def writer_domain? domain
            lookup_access_role_scope_value :writer, :domain, domain
          end

          ##
          # Checks writer access for a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.writer_special? :all_users #=> false
          #
          def writer_special? group
            lookup_access_role_scope_value :writer, :special, group
          end

          ##
          # Checks owner access for a user.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.owner_user? "entity@example.com" #=> false
          #
          def owner_user? email
            lookup_access_role_scope_value :owner, :user, email
          end

          ##
          # Checks owner access for a group.
          #
          # @param [String] email The email address for the entity.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.owner_group? "entity@example.com" #=> false
          #
          def owner_group? email
            lookup_access_role_scope_value :owner, :group, email
          end

          ##
          # Checks owner access for some other type of member that appears in the IAM
          # Policy but isn't a user, group, domain, or special group.
          #
          # @param [String] identity The identity reference.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.owner_iam_member? "entity@example.com" #=> false
          #
          def owner_iam_member? identity
            lookup_access_role_scope_value :owner, :iam_member, identity
          end

          ##
          # Checks owner access for a domain.
          #
          # @param [String] domain A [Cloud Identity
          #   domain](https://cloud.google.com/iam/docs/overview#cloudid_name_domain).
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.owner_domain? "example.com" #=> false
          #
          def owner_domain? domain
            lookup_access_role_scope_value :owner, :domain, domain
          end

          ##
          # Checks owner access for a special group.
          #
          # @param [String] group Accepted values are `owners`, `writers`,
          #   `readers`, `all_authenticated_users`, and `all_users`.
          #
          # @example
          #   require "google/cloud/bigquery"
          #
          #   bigquery = Google::Cloud::Bigquery.new
          #   dataset = bigquery.dataset "my_dataset"
          #
          #   access = dataset.access
          #   access.owner_special? :all_users #=> false
          #
          def owner_special? group
            lookup_access_role_scope_value :owner, :special, group
          end

          # @private
          def self.from_gapi gapi
            rules = Array gapi.access
            new.tap do |s|
              s.instance_variable_set :@rules, rules
              s.instance_variable_set :@original_rules_hashes, rules.map(&:to_h)
              s.instance_variable_set :@dataset_reference, gapi.dataset_reference
            end
          end

          # @private
          def to_gapi
            @rules
          end

          protected

          # @private
          def validate_role role
            good_role = ROLES[role.to_s]
            raise ArgumentError "Unable to determine role for #{role}" if good_role.nil?
            good_role
          end

          # @private
          def validate_scope scope
            good_scope = SCOPES[scope.to_s]
            raise ArgumentError "Unable to determine scope for #{scope}" if good_scope.nil?
            good_scope
          end

          # @private
          def validate_special_group value
            good_value = GROUPS[value.to_s]
            return good_value unless good_value.nil?
            value
          end

          # @private
          def validate_view view
            if view.respond_to? :table_ref
              view.table_ref
            else
              Service.table_ref_from_s view, default_ref: @dataset_reference
            end
          end

          # @private
          def add_access_role_scope_value role, scope, value
            role = validate_role role
            scope = validate_scope scope
            # If scope is special group, make sure value is in the list
            value = validate_special_group value if scope == :special_group
            # Remove any rules of this scope and value
            @rules.reject!(&find_by_scope_and_value(scope, value))
            # Add new rule for this role, scope, and value
            opts = { role: role, scope => value }
            @rules << Google::Apis::BigqueryV2::Dataset::Access.new(**opts)
          end

          # @private
          def add_access_routine routine
            value = routine.routine_ref
            # Remove existing routine rule, if any
            @rules.reject!(&find_by_scope_and_resource_ref(:routine, value))
            # Add new rule for this role, scope, and value
            opts = { routine: value }
            @rules << Google::Apis::BigqueryV2::Dataset::Access.new(**opts)
          end

          # @private
          def add_access_view value
            # scope is view, make sure value is in the right format
            value = validate_view value
            # Remove existing view rule, if any
            @rules.reject!(&find_by_scope_and_resource_ref(:view, value))
            # Add new rule for this role, scope, and value
            opts = { view: value }
            @rules << Google::Apis::BigqueryV2::Dataset::Access.new(**opts)
          end

          # @private
          def remove_access_role_scope_value role, scope, value
            role = validate_role role
            scope = validate_scope scope
            # If scope is special group, make sure value is in the list
            value = validate_special_group value if scope == :special_group
            # Remove any rules of this role, scope, and value
            @rules.reject!(
              &find_by_role_and_scope_and_value(role, scope, value)
            )
          end

          # @private
          def remove_access_routine routine
            # Remove existing routine rule, if any
            @rules.reject!(&find_by_scope_and_resource_ref(:routine, routine.routine_ref))
          end

          # @private
          def remove_access_view value
            # scope is view, make sure value is in the right format
            value = validate_view value
            # Remove existing view rule, if any
            @rules.reject!(&find_by_scope_and_resource_ref(:view, value))
          end

          # @private
          def lookup_access_role_scope_value role, scope, value
            role = validate_role role
            scope = validate_scope scope
            # If scope is special group, make sure value is in the list
            value = validate_special_group value if scope == :special_group
            # Detect any rules of this role, scope, and value
            !(!@rules.detect(&find_by_role_and_scope_and_value(role, scope, value)))
          end

          # @private
          def lookup_access_routine routine
            # Detect routine rule, if any
            !(!@rules.detect(&find_by_scope_and_resource_ref(:routine, routine.routine_ref)))
          end

          # @private
          def lookup_access_view value
            # scope is view, make sure value is in the right format
            value = validate_view value
            # Detect view rule, if any
            !(!@rules.detect(&find_by_scope_and_resource_ref(:view, value)))
          end

          # @private
          def find_by_role_and_scope_and_value role, scope, value
            lambda do |a|
              h = a.to_h
              h[:role] == role && h[scope] == value
            end
          end

          # @private
          def find_by_scope_and_value scope, value
            lambda do |a|
              h = a.to_h
              h[scope] == value
            end
          end

          # @private Compare hash representations to find table_ref, routine_ref.
          def find_by_scope_and_resource_ref scope, value
            lambda do |a|
              h = a.to_h
              h[scope].to_h == value.to_h
            end
          end
        end
      end
    end
  end
end


text:
function exit() {
  process.exit();
}

function stop(e) {
  if (e) {
    console.log(e);
  }
  sparkSession.stop().then(exit).catch(exit);
}

function run(sparkSession, spark) {
  return new Promise(function(resolve, reject) {

    // Load training data
    var data = sparkSession.read().format("libsvm")
      .load(__dirname+"/../mllib/data/sample_libsvm_data.txt");

    // Prepare training and test data.
    data.randomSplit([0.6, 0.4], 1234).then(function(splits) {
      var train = splits[0];
      var test = splits[1];

      // create the trainer and set its parameters
      var nb = new spark.ml.classification.NaiveBayes();
      // train the model
      var model = nb.fit(train);
      // compute precision on the test set
      var result = model.transform(test);
      var predictionAndLabels = result.select("prediction", "label");
      var evaluator = new spark.ml.evaluation.MulticlassClassificationEvaluator()
        .setMetricName("accuracy");

      evaluator.evaluate(predictionAndLabels).then(resolve).catch(reject);
    }).catch(reject)
  });
}

if (global.SC) {
  // we are being run as part of a test
  module.exports = run;
} else {
  var eclairjs = require('../../lib/index.js');
  var spark = new eclairjs();
  var sparkSession = spark.sql.SparkSession
            .builder()
            .appName("Naive Bayes")
            .getOrCreate();

  run(sparkSession, spark).then(function(results) {
    console.log("Precision:", results);
    stop();
  }).catch(stop);
}

redpajama_set_name: RedPajamaGithub


text:
package dlp

import (
	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
	dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2beta1"
)

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"strings"
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"golang.org/x/net/context"
	"google.golang.org/api/option"
	status "google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	gstatus "google.golang.org/grpc/status"
)

var _ = io.EOF
var _ = ptypes.MarshalAny
var _ status.Status

type mockDlpServer struct {
	// Embed for forward compatibility.
	// Tests will keep working if more methods are added
	// in the future.
	dlppb.DlpServiceServer

	reqs []proto.Message

	// If set, all calls return this error.
	err error

	// responses to return if err == nil
	resps []proto.Message
}

func (s *mockDlpServer) InspectContent(ctx context.Context, req *dlppb.InspectContentRequest) (*dlppb.InspectContentResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*dlppb.InspectContentResponse), nil
}

func (s *mockDlpServer) RedactContent(ctx context.Context, req *dlppb.RedactContentRequest) (*dlppb.RedactContentResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*dlppb.RedactContentResponse), nil
}

func (s *mockDlpServer) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyContentRequest) (*dlppb.DeidentifyContentResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*dlppb.DeidentifyContentResponse), nil
}

func (s *mockDlpServer) CreateInspectOperation(ctx context.Context, req *dlppb.CreateInspectOperationRequest) (*longrunningpb.Operation, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*longrunningpb.Operation), nil
}

func (s *mockDlpServer) AnalyzeDataSourceRisk(ctx context.Context, req *dlppb.AnalyzeDataSourceRiskRequest) (*longrunningpb.Operation, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*longrunningpb.Operation), nil
}

func (s *mockDlpServer) ListInspectFindings(ctx context.Context, req *dlppb.ListInspectFindingsRequest) (*dlppb.ListInspectFindingsResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*dlppb.ListInspectFindingsResponse), nil
}

func (s *mockDlpServer) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequest) (*dlppb.ListInfoTypesResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*dlppb.ListInfoTypesResponse), nil
}

func (s *mockDlpServer) ListRootCategories(ctx context.Context, req *dlppb.ListRootCategoriesRequest) (*dlppb.ListRootCategoriesResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*dlppb.ListRootCategoriesResponse), nil
}

// clientOpt is the option tests should use to connect to the test server.
// It is initialized by TestMain.
var clientOpt option.ClientOption

var (
	mockDlp mockDlpServer
)

func TestMain(m *testing.M) {
	flag.Parse()

	serv := grpc.NewServer()
	dlppb.RegisterDlpServiceServer(serv, &mockDlp)

	lis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		log.Fatal(err)
	}
	go serv.Serve(lis)

	conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	clientOpt = option.WithGRPCConn(conn)

	os.Exit(m.Run())
}

func TestDlpServiceInspectContent(t *testing.T) {
	var expectedResponse *dlppb.InspectContentResponse = &dlppb.InspectContentResponse{}

	mockDlp.err = nil
	mockDlp.reqs = nil

	mockDlp.resps = append(mockDlp.resps[:0], expectedResponse)

	var name string = "EMAIL_ADDRESS"
	var infoTypesElement = &dlppb.InfoType{
		Name: name,
	}
	var infoTypes = []*dlppb.InfoType{infoTypesElement}
	var inspectConfig = &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}
	var type_ string = "text/plain"
	var value string = "My email is example@example.com."
	var itemsElement = &dlppb.ContentItem{
		Type: type_,
		DataItem: &dlppb.ContentItem_Value{
			Value: value,
		},
	}
	var items = []*dlppb.ContentItem{itemsElement}
	var request = &dlppb.InspectContentRequest{
		InspectConfig: inspectConfig,
		Items:         items,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.InspectContent(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceInspectContentError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = gstatus.Error(errCode, "test error")

	var name string = "EMAIL_ADDRESS"
	var infoTypesElement = &dlppb.InfoType{
		Name: name,
	}
	var infoTypes = []*dlppb.InfoType{infoTypesElement}
	var inspectConfig = &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}
	var type_ string = "text/plain"
	var value string = "My email is example@example.com."
	var itemsElement = &dlppb.ContentItem{
		Type: type_,
		DataItem: &dlppb.ContentItem_Value{
			Value: value,
		},
	}
	var items = []*dlppb.ContentItem{itemsElement}
	var request = &dlppb.InspectContentRequest{
		InspectConfig: inspectConfig,
		Items:         items,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.InspectContent(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceRedactContent(t *testing.T) {
	var expectedResponse *dlppb.RedactContentResponse = &dlppb.RedactContentResponse{}

	mockDlp.err = nil
	mockDlp.reqs = nil

	mockDlp.resps = append(mockDlp.resps[:0], expectedResponse)

	var name string = "EMAIL_ADDRESS"
	var infoTypesElement = &dlppb.InfoType{
		Name: name,
	}
	var infoTypes = []*dlppb.InfoType{infoTypesElement}
	var inspectConfig = &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}
	var type_ string = "text/plain"
	var value string = "My email is example@example.com."
	var itemsElement = &dlppb.ContentItem{
		Type: type_,
		DataItem: &dlppb.ContentItem_Value{
			Value: value,
		},
	}
	var items = []*dlppb.ContentItem{itemsElement}
	var request = &dlppb.RedactContentRequest{
		InspectConfig: inspectConfig,
		Items:         items,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.RedactContent(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceRedactContentError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = gstatus.Error(errCode, "test error")

	var name string = "EMAIL_ADDRESS"
	var infoTypesElement = &dlppb.InfoType{
		Name: name,
	}
	var infoTypes = []*dlppb.InfoType{infoTypesElement}
	var inspectConfig = &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}
	var type_ string = "text/plain"
	var value string = "My email is example@example.com."
	var itemsElement = &dlppb.ContentItem{
		Type: type_,
		DataItem: &dlppb.ContentItem_Value{
			Value: value,
		},
	}
	var items = []*dlppb.ContentItem{itemsElement}
	var request = &dlppb.RedactContentRequest{
		InspectConfig: inspectConfig,
		Items:         items,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.RedactContent(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceDeidentifyContent(t *testing.T) {
	var expectedResponse *dlppb.DeidentifyContentResponse = &dlppb.DeidentifyContentResponse{}

	mockDlp.err = nil
	mockDlp.reqs = nil

	mockDlp.resps = append(mockDlp.resps[:0], expectedResponse)

	var deidentifyConfig *dlppb.DeidentifyConfig = &dlppb.DeidentifyConfig{}
	var inspectConfig *dlppb.InspectConfig = &dlppb.InspectConfig{}
	var items []*dlppb.ContentItem = nil
	var request = &dlppb.DeidentifyContentRequest{
		DeidentifyConfig: deidentifyConfig,
		InspectConfig:    inspectConfig,
		Items:            items,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.DeidentifyContent(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceDeidentifyContentError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = gstatus.Error(errCode, "test error")

	var deidentifyConfig *dlppb.DeidentifyConfig = &dlppb.DeidentifyConfig{}
	var inspectConfig *dlppb.InspectConfig = &dlppb.InspectConfig{}
	var items []*dlppb.ContentItem = nil
	var request = &dlppb.DeidentifyContentRequest{
		DeidentifyConfig: deidentifyConfig,
		InspectConfig:    inspectConfig,
		Items:            items,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.DeidentifyContent(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceAnalyzeDataSourceRisk(t *testing.T) {
	var expectedResponse *dlppb.RiskAnalysisOperationResult = &dlppb.RiskAnalysisOperationResult{}

	mockDlp.err = nil
	mockDlp.reqs = nil

	any, err := ptypes.MarshalAny(expectedResponse)
	if err != nil {
		t.Fatal(err)
	}
	mockDlp.resps = append(mockDlp.resps[:0], &longrunningpb.Operation{
		Name:   "longrunning-test",
		Done:   true,
		Result: &longrunningpb.Operation_Response{Response: any},
	})

	var privacyMetric *dlppb.PrivacyMetric = &dlppb.PrivacyMetric{}
	var sourceTable *dlppb.BigQueryTable = &dlppb.BigQueryTable{}
	var request = &dlppb.AnalyzeDataSourceRiskRequest{
		PrivacyMetric: privacyMetric,
		SourceTable:   sourceTable,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	respLRO, err := c.AnalyzeDataSourceRisk(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}
	resp, err := respLRO.Wait(context.Background())

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceAnalyzeDataSourceRiskError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = nil
	mockDlp.resps = append(mockDlp.resps[:0], &longrunningpb.Operation{
		Name: "longrunning-test",
		Done: true,
		Result: &longrunningpb.Operation_Error{
			Error: &status.Status{
				Code:    int32(errCode),
				Message: "test error",
			},
		},
	})

	var privacyMetric *dlppb.PrivacyMetric = &dlppb.PrivacyMetric{}
	var sourceTable *dlppb.BigQueryTable = &dlppb.BigQueryTable{}
	var request = &dlppb.AnalyzeDataSourceRiskRequest{
		PrivacyMetric: privacyMetric,
		SourceTable:   sourceTable,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	respLRO, err := c.AnalyzeDataSourceRisk(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}
	resp, err := respLRO.Wait(context.Background())

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceCreateInspectOperation(t *testing.T) {
	var name2 string = "name2-1052831874"
	var expectedResponse = &dlppb.InspectOperationResult{
		Name: name2,
	}

	mockDlp.err = nil
	mockDlp.reqs = nil

	any, err := ptypes.MarshalAny(expectedResponse)
	if err != nil {
		t.Fatal(err)
	}
	mockDlp.resps = append(mockDlp.resps[:0], &longrunningpb.Operation{
		Name:   "longrunning-test",
		Done:   true,
		Result: &longrunningpb.Operation_Response{Response: any},
	})

	var name string = "EMAIL_ADDRESS"
	var infoTypesElement = &dlppb.InfoType{
		Name: name,
	}
	var infoTypes = []*dlppb.InfoType{infoTypesElement}
	var inspectConfig = &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}
	var url string = "gs://example_bucket/example_file.png"
	var fileSet = &dlppb.CloudStorageOptions_FileSet{
		Url: url,
	}
	var cloudStorageOptions = &dlppb.CloudStorageOptions{
		FileSet: fileSet,
	}
	var storageConfig = &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_CloudStorageOptions{
			CloudStorageOptions: cloudStorageOptions,
		},
	}
	var outputConfig *dlppb.OutputStorageConfig = &dlppb.OutputStorageConfig{}
	var request = &dlppb.CreateInspectOperationRequest{
		InspectConfig: inspectConfig,
		StorageConfig: storageConfig,
		OutputConfig:  outputConfig,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	respLRO, err := c.CreateInspectOperation(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}
	resp, err := respLRO.Wait(context.Background())

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceCreateInspectOperationError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = nil
	mockDlp.resps = append(mockDlp.resps[:0], &longrunningpb.Operation{
		Name: "longrunning-test",
		Done: true,
		Result: &longrunningpb.Operation_Error{
			Error: &status.Status{
				Code:    int32(errCode),
				Message: "test error",
			},
		},
	})

	var name string = "EMAIL_ADDRESS"
	var infoTypesElement = &dlppb.InfoType{
		Name: name,
	}
	var infoTypes = []*dlppb.InfoType{infoTypesElement}
	var inspectConfig = &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}
	var url string = "gs://example_bucket/example_file.png"
	var fileSet = &dlppb.CloudStorageOptions_FileSet{
		Url: url,
	}
	var cloudStorageOptions = &dlppb.CloudStorageOptions{
		FileSet: fileSet,
	}
	var storageConfig = &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_CloudStorageOptions{
			CloudStorageOptions: cloudStorageOptions,
		},
	}
	var outputConfig *dlppb.OutputStorageConfig = &dlppb.OutputStorageConfig{}
	var request = &dlppb.CreateInspectOperationRequest{
		InspectConfig: inspectConfig,
		StorageConfig: storageConfig,
		OutputConfig:  outputConfig,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	respLRO, err := c.CreateInspectOperation(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}
	resp, err := respLRO.Wait(context.Background())

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceListInspectFindings(t *testing.T) {
	var nextPageToken string = "nextPageToken-1530815211"
	var expectedResponse = &dlppb.ListInspectFindingsResponse{
		NextPageToken: nextPageToken,
	}

	mockDlp.err = nil
	mockDlp.reqs = nil

	mockDlp.resps = append(mockDlp.resps[:0], expectedResponse)

	var formattedName string = ResultPath("[RESULT]")
	var request = &dlppb.ListInspectFindingsRequest{
		Name: formattedName,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.ListInspectFindings(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceListInspectFindingsError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = gstatus.Error(errCode, "test error")

	var formattedName string = ResultPath("[RESULT]")
	var request = &dlppb.ListInspectFindingsRequest{
		Name: formattedName,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.ListInspectFindings(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceListInfoTypes(t *testing.T) {
	var expectedResponse *dlppb.ListInfoTypesResponse = &dlppb.ListInfoTypesResponse{}

	mockDlp.err = nil
	mockDlp.reqs = nil

	mockDlp.resps = append(mockDlp.resps[:0], expectedResponse)

	var category string = "PII"
	var languageCode string = "en"
	var request = &dlppb.ListInfoTypesRequest{
		Category:     category,
		LanguageCode: languageCode,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.ListInfoTypes(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceListInfoTypesError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = gstatus.Error(errCode, "test error")

	var category string = "PII"
	var languageCode string = "en"
	var request = &dlppb.ListInfoTypesRequest{
		Category:     category,
		LanguageCode: languageCode,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.ListInfoTypes(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestDlpServiceListRootCategories(t *testing.T) {
	var expectedResponse *dlppb.ListRootCategoriesResponse = &dlppb.ListRootCategoriesResponse{}

	mockDlp.err = nil
	mockDlp.reqs = nil

	mockDlp.resps = append(mockDlp.resps[:0], expectedResponse)

	var languageCode string = "en"
	var request = &dlppb.ListRootCategoriesRequest{
		LanguageCode: languageCode,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.ListRootCategories(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockDlp.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestDlpServiceListRootCategoriesError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockDlp.err = gstatus.Error(errCode, "test error")

	var languageCode string = "en"
	var request = &dlppb.ListRootCategoriesRequest{
		LanguageCode: languageCode,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.ListRootCategories(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}


text:
<?php
namespace App\Gitter\Models;

/**
 * Class Achieve
 * @package App\Gitter\Models
 *
 * @property string $title
 * @property string $description
 * @property string $image
 * @property \App\User $user
 */
class Achieve extends Model
{
    // http://docs.rudev.org/stream/a265faa4be6dbd24f957db97b89c4e51
    public function __toString()
    {
        $strings = [
            sprintf('> # [%s](%s)', $this->title, $this->image),
            sprintf('> *%s*', $this->description),
            sprintf('> *Achievement unlocked for @%s*', $this->user->login),
            sprintf('> ![%s](%s)', $this->title, $this->image)
        ];

        return implode("\n", $strings);
    }
}


text:
goog.require('goog.dom');
goog.require('goog.editor.Command');
goog.require('goog.editor.SeamlessField');
goog.require('goog.editor.plugins.BasicTextFormatter');
goog.require('goog.editor.plugins.EnterHandler');
goog.require('goog.editor.plugins.HeaderFormatter');
//goog.require('goog.editor.plugins.LinkDialogPlugin');
goog.require('goog.editor.plugins.ListTabHandler');
//goog.require('goog.editor.plugins.LoremIpsum');
goog.require('goog.editor.plugins.RemoveFormatting');
goog.require('goog.editor.plugins.SpacesTabHandler');
goog.require('goog.editor.plugins.UndoRedo');

goog.exportSymbol('goog.editor.Field.EventType.COMMAND_VALUE_CHANGE', goog.editor.Field.EventType.COMMAND_VALUE_CHANGE);
goog.exportSymbol('goog.editor.Field.EventType.DELAYEDCHANGE', goog.editor.Field.EventType.DELAYEDCHANGE);
goog.exportSymbol('goog.editor.Field.EventType.SELECTIONCHANGE', goog.editor.Field.EventType.SELECTIONCHANGE);

goog.exportSymbol('goog.editor.Field.DELAYED_CHANGE_FREQUENCY', goog.editor.Field.DELAYED_CHANGE_FREQUENCY);

goog.exportSymbol('goog.editor.SeamlessField', goog.editor.SeamlessField);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'executeCommand', goog.editor.SeamlessField.prototype.executeCommand);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'focus', goog.editor.SeamlessField.prototype.focus);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'focusAndPlaceCursorAtStart', goog.editor.SeamlessField.prototype.focusAndPlaceCursorAtStart);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'getAppWindow', goog.editor.SeamlessField.prototype.getAppWindow);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'getCleanContents', goog.editor.SeamlessField.prototype.getCleanContents);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'getElement', goog.editor.SeamlessField.prototype.getElement);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'getPluginByClassId', goog.editor.SeamlessField.prototype.getPluginByClassId);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'isUneditable', goog.editor.SeamlessField.prototype.isUneditable);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'makeEditable', goog.editor.SeamlessField.prototype.makeEditable);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'makeUneditable', goog.editor.SeamlessField.prototype.makeUneditable);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'queryCommandValue', goog.editor.SeamlessField.prototype.queryCommandValue);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'registerPlugin', goog.editor.SeamlessField.prototype.registerPlugin);
goog.exportProperty(goog.editor.SeamlessField.prototype, 'setHtml', goog.editor.SeamlessField.prototype.setHtml);

goog.exportSymbol('goog.editor.Command', goog.editor.Command);
goog.exportProperty(goog.editor.Command, 'UNDO', goog.editor.Command.UNDO);
goog.exportProperty(goog.editor.Command, 'REDO', goog.editor.Command.REDO);
goog.exportProperty(goog.editor.Command, 'LINK', goog.editor.Command.LINK);
goog.exportProperty(goog.editor.Command, 'FORMAT_BLOCK', goog.editor.Command.FORMAT_BLOCK);
goog.exportProperty(goog.editor.Command, 'INDENT', goog.editor.Command.INDENT);
goog.exportProperty(goog.editor.Command, 'OUTDENT', goog.editor.Command.OUTDENT);
goog.exportProperty(goog.editor.Command, 'REMOVE_FORMAT', goog.editor.Command.REMOVE_FORMAT);
goog.exportProperty(goog.editor.Command, 'STRIKE_THROUGH', goog.editor.Command.STRIKE_THROUGH);
goog.exportProperty(goog.editor.Command, 'HORIZONTAL_RULE', goog.editor.Command.HORIZONTAL_RULE);
goog.exportProperty(goog.editor.Command, 'SUBSCRIPT', goog.editor.Command.SUBSCRIPT);
goog.exportProperty(goog.editor.Command, 'SUPERSCRIPT', goog.editor.Command.SUPERSCRIPT);
goog.exportProperty(goog.editor.Command, 'UNDERLINE', goog.editor.Command.UNDERLINE);
goog.exportProperty(goog.editor.Command, 'BOLD', goog.editor.Command.BOLD);
goog.exportProperty(goog.editor.Command, 'ITALIC', goog.editor.Command.ITALIC);
goog.exportProperty(goog.editor.Command, 'FONT_SIZE', goog.editor.Command.FONT_SIZE);
goog.exportProperty(goog.editor.Command, 'FONT_FACE', goog.editor.Command.FONT_FACE);
goog.exportProperty(goog.editor.Command, 'FONT_COLOR', goog.editor.Command.FONT_COLOR);
// goog.exportProperty(goog.editor.Command, 'EMOTICON', goog.editor.Command.EMOTICON);
goog.exportProperty(goog.editor.Command, 'BACKGROUND_COLOR', goog.editor.Command.BACKGROUND_COLOR);
goog.exportProperty(goog.editor.Command, 'ORDERED_LIST', goog.editor.Command.ORDERED_LIST);
goog.exportProperty(goog.editor.Command, 'UNORDERED_LIST', goog.editor.Command.UNORDERED_LIST);
goog.exportProperty(goog.editor.Command, 'TABLE', goog.editor.Command.TABLE);
goog.exportProperty(goog.editor.Command, 'JUSTIFY_CENTER', goog.editor.Command.JUSTIFY_CENTER);
goog.exportProperty(goog.editor.Command, 'JUSTIFY_FULL', goog.editor.Command.JUSTIFY_FULL);
goog.exportProperty(goog.editor.Command, 'JUSTIFY_RIGHT', goog.editor.Command.JUSTIFY_RIGHT);
goog.exportProperty(goog.editor.Command, 'JUSTIFY_LEFT', goog.editor.Command.JUSTIFY_LEFT);
goog.exportProperty(goog.editor.Command, 'BLOCKQUOTE', goog.editor.Command.BLOCKQUOTE);
// goog.exportProperty(goog.editor.Command, 'DIR_LTR', goog.editor.Command.DIR_LTR);
// goog.exportProperty(goog.editor.Command, 'DIR_RTL', goog.editor.Command.DIR_RTL);
// goog.exportProperty(goog.editor.Command, 'IMAGE', goog.editor.Command.IMAGE);
// goog.exportProperty(goog.editor.Command, 'EDIT_HTML', goog.editor.Command.EDIT_HTML);
// goog.exportProperty(goog.editor.Command, 'DEFAULT_TAG', goog.editor.Command.DEFAULT_TAG);

goog.exportSymbol('goog.events.listen', goog.events.listen);
goog.exportSymbol('goog.editor.plugins.BasicTextFormatter', goog.editor.plugins.BasicTextFormatter);
goog.exportSymbol('goog.editor.plugins.EnterHandler', goog.editor.plugins.EnterHandler);
goog.exportSymbol('goog.editor.plugins.HeaderFormatter', goog.editor.plugins.HeaderFormatter);
goog.exportSymbol('goog.editor.plugins.ListTabHandler', goog.editor.plugins.ListTabHandler);
goog.exportSymbol('goog.editor.plugins.RemoveFormatting', goog.editor.plugins.RemoveFormatting);
goog.exportSymbol('goog.editor.plugins.SpacesTabHandler', goog.editor.plugins.SpacesTabHandler);
goog.exportSymbol('goog.editor.plugins.UndoRedo', goog.editor.plugins.UndoRedo);
goog.exportSymbol('goog.editor.plugins.UndoRedoManager', goog.editor.plugins.UndoRedoManager);

goog.exportProperty(goog.editor.plugins.UndoRedo.prototype, 'disable', goog.editor.plugins.UndoRedo.prototype.disable);
goog.exportProperty(goog.editor.plugins.UndoRedo.prototype, 'enable', goog.editor.plugins.UndoRedo.prototype.enable);
goog.exportProperty(goog.editor.plugins.UndoRedo.prototype, 'setUndoRedoManager', goog.editor.plugins.UndoRedo.prototype.setUndoRedoManager);


text:
#ifndef _VIEW_H_
#define _VIEW_H_

/*********************************************/

#include <SDL.h>
#include <vector>
#include <string>
#include "../structures.h"
#include "../ResourceManager.h"
#include "../Graphics/Graphics.h"
#include "../ScreenSystem/InputState.h"

/*********************************************/

class Screen;

/*********************************************/

#define SIZE_WRAP_CONTENT -1
#define SIZE_FILL_PARENT -2

/*********************************************/

/*
Calling order:
1. ctor
2. Properties
3. Initialize
4. SetSize
*/

/*********************************************/

class View
{
private:
	void DrawBackground(Position offset);
	void DrawDebugViewBounds(Rectangle viewBounds);
	Rectangle CalculateViewBounds(Position offset, Rectangle parentViewBounds);
	bool isInitialized;
protected:
	Screen* context;
	std::string id;
	std::string name;
	std::vector<std::string> tags;
	View* parent;
	std::vector<View*> children;
	bool visible;
	Position relativePosition;
	Position absolutePosition;
	Size size;
	Size calculatedSize;
	Size contentSize;
	Box layoutMargin;
	int layoutGravity;
	int gravity;
	Color background;
	View* itemTemplate;
	std::string action;
	std::vector<std::string> actionArgs;

	View* CopyBase(View* view);
	virtual void DrawChildren(Position offset, Rectangle viewBounds);
	std::string FindAndReplace(std::string origString, std::map<std::string, std::string>& values);
public:
	View();
	virtual ~View();
	void Initialize(Screen* context);
	virtual void OnInitialize();
	void InitializeAll(Screen* context);
	bool IsInitialized();
	void Update();
	virtual void OnUpdate();
	virtual void Draw(Position offset = Position(0, 0), Rectangle parentViewBounds = Rectangle(-1, -1, -1, -1));
	virtual void OnDraw(Graphics& graphics, Position offset);
	std::string GetId();
	void SetId(std::string id);
	std::string GetName();
	void SetName(std::string name);
	std::vector<std::string> GetTags();
	void AddTag(std::string tag);
	View* GetParentView();
	void SetParentView(View* parent);
	View* GetChildViewById(std::string id);
	View* GetFirstChildViewByTag(std::string tag);
	virtual void AddChildView(View* view);
	void DeleteChildView(int i);
	void DeleteChildView(View* view);
	void DeleteChildView(std::string id);
	int GetNumberOfChildren();
	View* GetChildView(int i);
	void SortChildren(bool(*comparer)(View* v1, View* v2));
	bool IsVisible();
	void SetVisible(bool visible);
	Position GetRelativePosition();
	void SetRelativePosition(Position position);
	void SetRelativePosition(int x, int y);
	Position GetAbsolutePosition();
	Size GetSize();
	void SetSize(Size size);
	void SetSize(int width, int height);
	Size GetCalculatedSize();
	Size GetContentSize();
	Rectangle GetViewBounds();
	Box GetLayoutMargin();
	void SetLayoutMargin(Box margin);
	int GetLayoutGravity();
	void SetLayoutGravity(int gravity);
	int GetGravity();
	void SetGravity(int gravity);
	Color GetBackground();
	void SetBackground(Color background);
	std::string GetAction();
	void SetAction(std::string action);
	std::vector<std::string> GetActionArgs();
	void SetActionArgs(std::vector<std::string> actionArgs);
	Size CalculateLayout(Size sizeAvailable);
	void RecalculateLayout();
	void CalculateAbsolutePosition(Position parentPosition);
	virtual void OnLayoutChange();
	virtual bool SetProperty(std::string name, std::string value);
	virtual View* Copy() = 0;
	View* GetItemTemplate();
	void SetItemTemplate(View* itemTemplate);
	virtual void FillData(std::map<std::string, std::string>& data);
	void FillDataAll(std::map<std::string, std::string>& data);
	void PropagateStateChange(std::string stateName, std::string stateValue);
	virtual void OnStateChange(std::string stateName, std::string stateValue);
	/*virtual void SetTransition(TransitionEffect effect, double value) = 0;
	virtual void ClearTransitions();*/
};

/*********************************************/

#endif


text:
package im.actor.sdk.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;

import im.actor.sdk.ActorSDK;
import im.actor.sdk.R;

public class DividerView extends View {

    public DividerView(Context context) {
        super(context);
        initStyles();
    }

    public DividerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initStyles();
    }

    public DividerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initStyles();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public DividerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initStyles();
    }

    private void initStyles() {
        setBackgroundColor(ActorSDK.sharedActor().style.getDividerColor());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getResources().getDimensionPixelSize(R.dimen.div_size));
    }
}


text:
<!DOCTYPE HTML>

<title>Uses of Class com.bitpay.sdk.model.Wallet.Currencies (BitPay 8.6.2 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-11-21">
<meta name="description" content="use: package: com.bitpay.sdk.model.Wallet, class: Currencies">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

<button id="navbar-toggle-button" aria-controls="navbar-top" aria-expanded="false" aria-label="Toggle navigation links"></button>

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search-input" disabled placeholder="Search">
<input type="reset" id="reset-button" disabled value="reset">

Uses of Class
com.bitpay.sdk.model.Wallet.Currencies

Packages that use Currencies

Package

Description

com.bitpay.sdk.model.Wallet

BitPay SDK Wallet.

Uses of Currencies in com.bitpay.sdk.model.Wallet

Methods in com.bitpay.sdk.model.Wallet that return types with arguments of type Currencies

Modifier and Type

Method

Description

ArrayList<Currencies>

Wallet.getCurrencies()

Gets currencies.

Method parameters in com.bitpay.sdk.model.Wallet with type arguments of type Currencies

Modifier and Type

Method

Description

void

Wallet.setCurrencies<wbr>(ArrayList<Currencies> currencies)

Sets currencies.

Copyright © 2022 BitPay. All rights reserved.


text:
from portality.util import url_for

from portality.events.consumer import EventConsumer
from portality import constants
from portality import models
from portality.bll import DOAJ
from portality.bll import exceptions

class ApplicationEditorGroupAssignedNotify(EventConsumer):
    ID = "application:editor_group:assigned:notify"

    @classmethod
    def consumes(cls, event):
        return event.id == constants.EVENT_APPLICATION_EDITOR_GROUP_ASSIGNED and \
               event.context.get("application") is not None

    @classmethod
    def consume(cls, event):
        app_source = event.context.get("application")

        try:
            application = models.Application(**app_source)
        except Exception as e:
            raise exceptions.NoSuchObjectException("Unable to construct Application from supplied source - data structure validation error, {x}".format(x=e))

        if not application.editor_group:
            return

        editor_group = models.EditorGroup.pull_by_key("name", application.editor_group)

        if not editor_group.editor:
            raise exceptions.NoSuchPropertyException("Editor Group {x} does not have property `editor`".format(x=editor_group.id))

        svc = DOAJ.notificationsService()

        notification = models.Notification()
        notification.who = editor_group.editor
        notification.created_by = cls.ID
        notification.classification = constants.NOTIFICATION_CLASSIFICATION_ASSIGN

        notification.long = svc.long_notification(cls.ID).format(
            journal_name=application.bibjson().title
        )
        notification.short = svc.short_notification(cls.ID)

        notification.action = url_for("editor.application", application_id=application.id)

        svc.notify(notification)


text:
package org.arquillian.cube.docker.impl.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Logger;
import org.arquillian.cube.HostIpContext;
import org.arquillian.cube.docker.impl.client.config.CubeContainer;
import org.arquillian.cube.docker.impl.client.config.DockerCompositions;
import org.arquillian.cube.docker.impl.client.config.Link;
import org.arquillian.cube.docker.impl.client.config.PortBinding;
import org.arquillian.cube.docker.impl.client.config.StarOperator;
import org.arquillian.cube.docker.impl.util.Boot2Docker;
import org.arquillian.cube.docker.impl.util.DockerMachine;
import org.arquillian.cube.docker.impl.util.OperatingSystemFamily;
import org.arquillian.cube.docker.impl.util.OperatingSystemResolver;
import org.arquillian.cube.docker.impl.util.Top;
import org.arquillian.cube.spi.CubeConfiguration;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;

public class CubeDockerConfigurator {

    public static final String DOCKER_HOST = "DOCKER_HOST";
    private static final String EXTENSION_NAME = "docker";
    private static Random random = new Random();
    private static Logger log = Logger.getLogger(CubeDockerConfigurator.class.getName());
    @Inject
    @ApplicationScoped
    private InstanceProducer<CubeDockerConfiguration> configurationProducer;

    @Inject
    @ApplicationScoped
    private InstanceProducer<HostIpContext> hostUriContextInstanceProducer;

    @Inject
    private Instance<Boot2Docker> boot2DockerInstance;

    @Inject
    private Instance<DockerMachine> dockerMachineInstance;

    @Inject
    private Instance<Top> topInstance;

    @Inject
    private Instance<Injector> injectorInstance;

    @Inject
    @ApplicationScoped
    private InstanceProducer<OperatingSystemFamily> operatingSystemFamilyInstanceProducer;

    public void configure(@Observes CubeConfiguration event, ArquillianDescriptor arquillianDescriptor) {
        configure(arquillianDescriptor);
    }

    private void configure(ArquillianDescriptor arquillianDescriptor) {
        operatingSystemFamilyInstanceProducer.set(new OperatingSystemResolver().currentOperatingSystem().getFamily());
        Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();
        CubeDockerConfigurationResolver resolver = new CubeDockerConfigurationResolver(topInstance.get(),
            dockerMachineInstance.get(),
            boot2DockerInstance.get(),
            operatingSystemFamilyInstanceProducer.get());
        resolver.resolve(config);
        CubeDockerConfiguration cubeConfiguration = CubeDockerConfiguration.fromMap(config, injectorInstance.get());
        cubeConfiguration = resolveDynamicNames(cubeConfiguration);
        System.out.println(cubeConfiguration);
        hostUriContextInstanceProducer.set(new HostIpContext(cubeConfiguration.getDockerServerIp()));
        configurationProducer.set(cubeConfiguration);
    }

    CubeDockerConfiguration resolveDynamicNames(CubeDockerConfiguration cubeConfiguration) {

        final Map<String, CubeContainer> resolvedContainers = new HashMap<>();

        final DockerCompositions dockerContainersContent = cubeConfiguration.getDockerContainersContent();
        final Map<String, CubeContainer> containers = dockerContainersContent.getContainers();

        final UUID uuid = UUID.randomUUID();

        for (Map.Entry<String, CubeContainer> container : containers.entrySet()) {

            // If it is a dynamic definition
            final String containerId = container.getKey();
            if (containerId.endsWith("*")) {
                String templateName = containerId.substring(0, containerId.lastIndexOf('*'));

                CubeContainer cubeContainer = container.getValue();

                StarOperator.adaptPortBindingToParallelRun(cubeContainer);
                StarOperator.adaptLinksToParallelRun(uuid, cubeContainer);
                StarOperator.adaptDependenciesToParallelRun(uuid, cubeContainer);

                String newId = StarOperator.generateNewName(templateName, uuid);
                resolvedContainers.put(newId, cubeContainer);
            } else {
                resolvedContainers.put(containerId, container.getValue());
            }
        }

        dockerContainersContent.setContainers(resolvedContainers);
        return cubeConfiguration;
    }

}


text:
/*  Extensible Array Definitions */

/*  Copyright (c) 1994 Stanford University

    All rights reserved.

    This software is provided under the terms described in
    the "suif_copyright.h" include file. */

#include <suif_copyright.h>

#ifndef XARRAY_H
#define XARRAY_H

#pragma interface

RCS_HEADER(xarray_h,
    "$Id: xarray.h,v 1.2 1999/08/25 03:29:20 brm Exp $")

/*
 *  An x_array is an extensible array of void* objects.  An initial size is
 *  specified when the array is created, but the array elements cannot be
 *  referenced until they are initialized using the "extend" method.  In this
 *  way an x_array behaves like a list -- the array elements must be appended
 *  (with "extend") to the end of the array before they can be used.  If the
 *  number of elements exceed the initial size additional chunks of data are
 *  automatically allocated.  The "ub" method returns the number of elements
 *  that are currently in the array.
 */

class x_array {
private:
    /* We make explicit copy constructor and assignment operator and
     * make them private to foil C++'s automatic default versions. */
    x_array(const x_array &);
    x_array &operator=(const x_array &);

    int size;
    int hi;
    void **data;
    x_array *next;

public:
    x_array(int sz);
    ~x_array();

    void *& operator[](int i);
    int extend(void *e);
    int ub();
};

/*
 *  The following macro definition is used to automatically generate
 *  subclasses of x_array that contain pointers to various data types.
 *  This is similar to the macros for declaring new list classes.
 */

#define DECLARE_X_ARRAY(CLASS, PTRTYPE, DEFAULT_SIZE)			      \
class CLASS: public x_array						      \
{									      \
public:									      \
    CLASS(int sz=DEFAULT_SIZE) : x_array(sz) { }			      \
    ~CLASS() { }							      \
    PTRTYPE *&operator[](int i)						      \
      { return (PTRTYPE *&)(x_array::operator[](i)); }			      \
}

#endif /* XARRAY_H */


text:
//
//  UIView+FrameAdditions.h
//
//	Copyright (c) 2010 Paddy Keane
//	All rights reserved.
//
//	This software is released under the terms of the MIT licence
//	http://www.opensource.org/licenses/mit-license.html
//
//	Permission is hereby granted, free of charge, to any person
//	obtaining a copy of this software and associated documentation
//	files (the "Software"), to deal in the Software without
//	restriction, including without limitation the rights to use,
//	copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the
//	Software is furnished to do so, subject to the following
//	conditions:
//
//	The above copyright notice and this permission notice shall be
//	included in all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//	OTHER DEALINGS IN THE SOFTWARE.
//

#import <UIKit/UIKit.h>

@interface UIView (PKFrameAdditions)

/*!
 @property      frameX
 @discussion    Shorthand for setting a frame's x value
 */
@property(assign) CGFloat frameX;

/*!
 @property      frameY
 @discussion    Shorthand for setting/getting a frame's y value
 */
@property(assign) CGFloat frameY;

/*!
 @property      frameWidth
 @discussion    Shorthand for setting/getting a frame's width value
 */
@property(assign) CGFloat frameWidth;

/*!
 @property      frameHeight
 @discussion    Shorthand for setting/getting a frame's height value
 */
@property(assign) CGFloat frameHeight;

/*!
 @property      frameSize
 @discussion    Shorthand for setting/getting a frame's width and height together

 @param         size        new width and height values.
*/
@property(assign) CGSize frameSize;

/*!
 @property      frameOrigin
 @discussion    Shorthand for setting/getting a frame's x and y together

 @param         origin        new x and y values.

 */
@property(assign) CGPoint frameOrigin;

@end