hexsha
stringlengths
40
40
size
int64
2
1.01M
content
stringlengths
2
1.01M
avg_line_length
float64
1.5
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
1
1a2e531e0b0bc67dff2d3bce67a5ea0f7c69acaf
1,204
require 'spec_helper' require 'pp' require 'fakefs/safe' module RailsEventStoreActiveRecord RSpec.describe AddValidAtGenerator do around(:each) do |example| current_stdout = $stdout $stdout = StringIO.new example.call $stdout = current_stdout end specify do FakeFS.with_fresh do FakeFS::FileSystem.clone(File.expand_path('../../', __FILE__)) stub_const("Rails::VERSION::STRING", "4.2.8") generator = AddValidAtGenerator.new allow(Time).to receive(:now).and_return(Time.new(2016,8,9,22,22,22)) generator.create_migration expect(File.read("db/migrate/20160809222222_add_valid_at.rb")).to match(/ActiveRecord::Migration$/) end end specify do FakeFS.with_fresh do FakeFS::FileSystem.clone(File.expand_path('../../', __FILE__)) stub_const("Rails::VERSION::STRING", "5.0.0") generator = AddValidAtGenerator.new allow(Time).to receive(:now).and_return(Time.new(2016,8,9,22,22,22)) generator.create_migration expect(File.read("db/migrate/20160809222222_add_valid_at.rb")).to match(/ActiveRecord::Migration\[4\.2\]$/) end end end end
29.365854
115
0.66196
5dd166c9908469db84b5bffad8201256b4977716
1,649
class FixAzureStackAzFlavorStiClass < ActiveRecord::Migration[6.0] class ExtManagementSystem < ActiveRecord::Base include ActiveRecord::IdRegions self.inheritance_column = :_type_disabled end class AvailabilityZone < ActiveRecord::Base include ActiveRecord::IdRegions self.inheritance_column = :_type_disabled belongs_to :ext_management_system, :foreign_key => :ems_id, :class_name => "FixAzureStackAzFlavorStiClass::ExtManagementSystem" end class Flavor < ActiveRecord::Base include ActiveRecord::IdRegions self.inheritance_column = :_type_disabled belongs_to :ext_management_system, :foreign_key => :ems_id, :class_name => "FixAzureStackAzFlavorStiClass::ExtManagementSystem" end def up say_with_time("Fixing AzureStack AZ/Flavor STI class") do azure_klass = "ManageIQ::Providers::AzureStack::CloudManager" managers = ExtManagementSystem.in_my_region.where(:type => azure_klass) AvailabilityZone.in_my_region.where(:ext_management_system => managers).update_all(:type => "#{azure_klass}::AvailabilityZone") Flavor.in_my_region.where(:ext_management_system => managers).update_all(:type => "#{azure_klass}::Flavor") end end def down say_with_time("Resetting AzureStack AZ/Flavor STI class") do azure_klass = "ManageIQ::Providers::AzureStack::CloudManager" managers = ExtManagementSystem.in_my_region.where(:type => azure_klass) AvailabilityZone.in_my_region.where(:ext_management_system => managers).update_all(:type => nil) Flavor.in_my_region.where(:ext_management_system => managers).update_all(:type => nil) end end end
40.219512
133
0.758035
6a91b8d0b86746eb0401771ebf1d6ed053248fdc
16,734
# Author:: Tor Magnus Rakvåg ([email protected]) # Author:: John McCrae ([email protected]) # Copyright:: 2018, Intility AS # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative "../resource" class Chef class Resource class PowershellPackageSource < Chef::Resource unified_mode true provides :powershell_package_source description "Use the **powershell_package_source** resource to register a PowerShell Repository or other Package Source type with. There are 2 distinct objects we care about here. The first is a Package Source like a PowerShell Repository or a Nuget Source. The second object is a provider that PowerShell uses to get to that source with, like PowerShellGet, Nuget, Chocolatey, etc. " introduced "14.3" examples <<~DOC **Add a new PSRepository that is not trusted and which requires credentials to connect to**: ```ruby powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted false user_name "[email protected]" user_pass "my_password" provider_name "PSRepository" action :register end ``` **Add a new Package Source that uses Chocolatey as the Package Provider**: ```ruby powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true provider_name "chocolatey" action :register end ``` **Add a new PowerShell Script source that is trusted**: ```ruby powershell_package_source 'MyDodgyScript' do source_name "MyDodgyScript" script_source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" script_publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true action :register end ``` **Update my existing PSRepository to make it Trusted after all**: ```ruby powershell_package_source 'MyPSModule' do source_name "MyPSModule" trusted true action :set end ``` **Update a Nuget package source with a new name and make it trusted**: ```ruby powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" provider_name "Nuget" trusted true action :set end ``` **Update a Nuget package source with a new name when the source is secured with a username and password**: ```ruby powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" trusted true user_name "[email protected]" user_pass "some_secret_password" action :set end ``` **Unregister a package source**: ```ruby powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" action :unregister end ``` DOC property :source_name, String, description: "A label that names your package source.", name_property: true property :new_name, String, description: "Used when updating the name of a NON-PSRepository" property :source_location, String, description: "The URL to the location to retrieve modules from." alias :url :source_location property :publish_location, String, description: "The URL where modules will be published to. Only valid if the provider is `PowerShellGet`." property :script_source_location, String, description: "The URL where scripts are located for this source. Only valid if the provider is `PowerShellGet`." property :script_publish_location, String, description: "The location where scripts will be published to for this source. Only valid if the provider is `PowerShellGet`." property :trusted, [TrueClass, FalseClass], description: "Whether or not to trust packages from this source. Used when creating a NON-PSRepository Package Source", default: false property :user_name, String, description: "A username that, as part of a credential object, is used to register a repository or other package source with." property :user_pass, String, description: "A password that, as part of a credential object, is used to register a repository or other package source with." property :provider_name, String, equal_to: %w{ Programs msi NuGet msu PowerShellGet psl chocolatey winget }, validation_message: "The following providers are supported: 'Programs', 'msi', 'NuGet', 'msu', 'PowerShellGet', 'psl', 'chocolatey' or 'winget'", description: "The package management provider for the package source. The default is PowerShellGet and this option need only be set otherwise in specific use cases.", default: "NuGet" load_current_value do cmd = load_resource_state_script(source_name) repo = powershell_exec!(cmd) if repo.result.empty? current_value_does_not_exist! else status = repo.result end source_name status["source_name"] new_name status["new_name"] source_location status["source_location"] trusted status["trusted"] provider_name status["provider_name"] publish_location status["publish_location"] script_source_location status["script_source_location"] script_publish_location status["script_publish_location"] end # Notes: # There are 2 objects we care about with this code. 1) The Package Provider which can be Nuget, PowerShellGet, Chocolatey, et al. 2) The PackageSource where the files we want access to live. The Package Provider gets us access to the Package Source. # Per the Microsoft docs you can only have one provider for one source. Enter the PSRepository. It is a sub-type of Package Source. # If you register a new PSRepository you get both a PSRepository object AND a Package Source object which are distinct. If you call "Get-PSRepository -Name 'PSGallery'" from powershell, notice that the Packageprovider is Nuget # now go execute "Get-PackageSource -Name 'PSGallery'" and notice that the PackageProvider is PowerShellGet. If you set a new PSRepository without specifying a PackageProvider ("Register-PSRepository -Name 'foo' -source...") the command will create both # a PackageSource and a PSRepository with different providers. # Unregistering a PackageSource (unregister-packagesource -name 'foo') where that source is also a PSRepository also causes that object to delete as well. This makes sense as PSRepository is a sub-type of packagesource. # All PSRepositories are PackageSources, and all PackageSources with Provider PowerShellGet are PSRepositories. They are 2 different views of the same object. action :register, description: "Registers a PowerShell package source." do package_details = get_package_source_details output = package_details.result if output == "PSRepository" || output == "PackageSource" action_set elsif new_resource.provider_name.downcase.strip == "powershellget" converge_by("register source: #{new_resource.source_name}") do register_cmd = build_ps_repository_command("Register", new_resource) res = powershell_exec(register_cmd) raise "Failed to register #{new_resource.source_name}: #{res.errors}" if res.error? end else converge_by("register source: #{new_resource.source_name}") do register_cmd = build_package_source_command("Register", new_resource) res = powershell_exec(register_cmd) raise "Failed to register #{new_resource.source_name}: #{res.errors}" if res.error? end end end action :set, description: "Updates an existing PSRepository or Package Source" do package_details = get_package_source_details output = package_details.result if output == "PSRepository" converge_if_changed :source_location, :trusted, :publish_location, :script_source_location, :script_publish_location, :source_name do set_cmd = build_ps_repository_command("Set", new_resource) res = powershell_exec(set_cmd) raise "Failed to Update #{new_resource.source_name}: #{res.errors}" if res.error? end elsif output == "PackageSource" converge_if_changed :source_location, :trusted, :new_name, :provider_name do set_cmd = build_package_source_command("Set", new_resource) res = powershell_exec(set_cmd) raise "Failed to Update #{new_resource.source_name}: #{res.errors}" if res.error? end end end action :unregister, description: "Unregisters the PowerShell package source." do package_details = get_package_source_details output = package_details.result if output == "PackageSource" || output == "PSRepository" unregister_cmd = "Unregister-PackageSource -Name '#{new_resource.source_name}'" converge_by("unregister source: #{new_resource.source_name}") do res = powershell_exec!(unregister_cmd) raise "Failed to unregister #{new_resource.source_name}: #{res.errors}" if res.error? end else logger.warn("*****************************************") logger.warn("Failed to unregister #{new_resource.source_name}: Package Source does not exist") logger.warn("*****************************************") end end action_class do def get_package_source_details powershell_exec! <<~EOH $package_details = Get-PackageSource -Name '#{new_resource.source_name}' -ErrorAction SilentlyContinue if ($package_details.ProviderName -match "PowerShellGet"){ return "PSRepository" } elseif ($package_details.ProviderName ) { return "PackageSource" } elseif ($null -eq $package_details) { return "Unregistered" } EOH end def build_ps_repository_command(cmdlet_type, new_resource) if new_resource.trusted == true install_policy = "Trusted" else install_policy = "Untrusted" end if new_resource.user_name && new_resource.user_pass cmd = "$user = '#{new_resource.user_name}';" cmd << "[securestring]$secure_password = Convertto-SecureString -String '#{new_resource.user_pass}' -AsPlainText -Force;" cmd << "$Credentials = New-Object System.Management.Automation.PSCredential -Argumentlist ($user, $secure_password);" cmd << "#{cmdlet_type}-PSRepository -Name '#{new_resource.source_name}'" cmd << " -SourceLocation '#{new_resource.source_location}'" if new_resource.source_location cmd << " -InstallationPolicy '#{install_policy}'" cmd << " -PublishLocation '#{new_resource.publish_location}'" if new_resource.publish_location cmd << " -ScriptSourceLocation '#{new_resource.script_source_location}'" if new_resource.script_source_location cmd << " -ScriptPublishLocation '#{new_resource.script_publish_location}'" if new_resource.script_publish_location cmd << " -Credential $Credentials" cmd << " | Out-Null" else cmd = "#{cmdlet_type}-PSRepository -Name '#{new_resource.source_name}'" cmd << " -SourceLocation '#{new_resource.source_location}'" if new_resource.source_location cmd << " -InstallationPolicy '#{install_policy}'" cmd << " -PublishLocation '#{new_resource.publish_location}'" if new_resource.publish_location cmd << " -ScriptSourceLocation '#{new_resource.script_source_location}'" if new_resource.script_source_location cmd << " -ScriptPublishLocation '#{new_resource.script_publish_location}'" if new_resource.script_publish_location cmd << " | Out-Null" end cmd end def build_package_source_command(cmdlet_type, new_resource) if new_resource.user_name && new_resource.user_pass cmd = "$user = '#{new_resource.user_name}';" cmd << "[securestring]$secure_password = Convertto-SecureString -String '#{new_resource.user_pass}' -AsPlainText -Force;" cmd << "$Credentials = New-Object System.Management.Automation.PSCredential -Argumentlist ($user, $secure_password);" cmd << "#{cmdlet_type}-PackageSource -Name '#{new_resource.source_name}'" cmd << " -Location '#{new_resource.source_location}'" if new_resource.source_location cmd << " -Trusted" if new_resource.trusted cmd << " -ProviderName '#{new_resource.provider_name}'" if new_resource.provider_name cmd << " -Credential $credentials" cmd << " | Out-Null" cmd else cmd = "#{cmdlet_type}-PackageSource -Name '#{new_resource.source_name}'" cmd << " -NewName '#{new_resource.new_name}'" if new_resource.new_name cmd << " -Location '#{new_resource.source_location}'" if new_resource.source_location cmd << " -Trusted" if new_resource.trusted cmd << " -ProviderName '#{new_resource.provider_name}'" if new_resource.provider_name cmd << " | Out-Null" cmd end end end end private def load_resource_state_script(source_name) <<-EOH $PSDefaultParameterValues = @{ "*:WarningAction" = "SilentlyContinue" } if(Get-PackageSource -Name '#{source_name}' -ErrorAction SilentlyContinue) { if ((Get-PackageSource -Name '#{source_name}').ProviderName -eq 'PowerShellGet') { (Get-PSRepository -Name '#{source_name}') | Select @{n='source_name';e={$_.Name}}, @{n='source_location';e={$_.SourceLocation}}, @{n='trusted';e={$_.Trusted}}, @{n='provider_name';e={$_.PackageManagementProvider}}, @{n='publish_location';e={$_.PublishLocation}}, @{n='script_source_location';e={$_.ScriptSourceLocation}}, @{n='script_publish_location';e={$_.ScriptPublishLocation}} } else { (Get-PackageSource -Name '#{source_name}') | Select @{n='source_name';e={$_.Name}}, @{n='new_name';e={$_.Name}}, @{n='source_location';e={$_.Location}}, @{n='provider_name';e={$_.ProviderName}}, @{n='trusted';e={$_.IsTrusted}}, @{n='publish_location';e={$_.PublishLocation}} } } EOH end end end
50.709091
390
0.633501
28ed000c505da18b7efa5b49e95c38d5e6b7dfe7
170
namespace :asset do desc 'Display asset path' task paths: :environment do Rails.application.config.assets.paths.each do |path| puts path end end end
17
56
0.694118
5df36a711bf085b611d55f0794332a40c168a2b8
1,908
class OrderWalkthrough def self.up_to(state) # A payment method must exist for an order to proceed through the Address state unless Spree::PaymentMethod.exists? FactoryGirl.create(:check_payment_method) end # Need to create a valid zone too... zone = FactoryGirl.create(:zone) country = FactoryGirl.create(:country) zone.members << Spree::ZoneMember.create(:zoneable => country) country.states << FactoryGirl.create(:state, :country => country) # A shipping method must exist for rates to be displayed on checkout page unless Spree::ShippingMethod.exists? FactoryGirl.create(:shipping_method).tap do |sm| sm.calculator.preferred_amount = 10 sm.calculator.preferred_currency = Spree::Config[:currency] sm.calculator.save end end order = Spree::Order.create!(:email => "[email protected]") add_line_item!(order) order.next! end_state_position = states.index(state.to_sym) states[0..end_state_position].each do |state| send(state, order) end order end private def self.add_line_item!(order) FactoryGirl.create(:line_item, order: order) order.reload end def self.address(order) order.bill_address = FactoryGirl.create(:address, :country_id => Spree::Zone.global.members.first.zoneable.id) order.ship_address = FactoryGirl.create(:address, :country_id => Spree::Zone.global.members.first.zoneable.id) order.next! end def self.delivery(order) order.next! end def self.payment(order) order.payments.create!(:payment_method => Spree::PaymentMethod.first, :amount => order.total) # TODO: maybe look at some way of making this payment_state change automatic order.payment_state = 'paid' order.next! end def self.complete(order) #noop? end def self.states [:address, :delivery, :payment, :complete] end end
27.652174
114
0.698113
f77d9a689b2382e85f9faed949219abfb6e8b591
5,137
class DnscryptProxy < Formula desc "Secure communications between a client and a DNS resolver" homepage "https://dnscrypt.org" url "https://github.com/jedisct1/dnscrypt-proxy/archive/1.9.5.tar.gz" sha256 "947000568f79ab4d036b259d9cf3fe6fdf8419860d9ad18004ac767db0dbd5ac" revision 1 head "https://github.com/jedisct1/dnscrypt-proxy.git" bottle do sha256 "2fd6cc2b0ec7730290eafb55560b95c8bbc42df874ef03fe4c7b1faab49619fc" => :high_sierra sha256 "ef7459f7e9ba0e1d0f88e91d51309d93faaf5c4778d87098dea0509536467158" => :sierra sha256 "6a278225af005fbf91a401c7b8f4f277b2d714a83c7621c51937825af4991f0e" => :el_capitan end option "without-plugins", "Disable support for plugins" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "pkg-config" => :build depends_on "libtool" => :run depends_on "libsodium" depends_on "minisign" => :recommended if MacOS.version >= :el_capitan depends_on "ldns" => :recommended def install # Modify hard-coded path to resolver list & run as unprivileged user. inreplace "dnscrypt-proxy.conf" do |s| s.gsub! "# ResolversList /usr/local/share/dnscrypt-proxy/dnscrypt-resolvers.csv", "ResolversList #{opt_pkgshare}/dnscrypt-resolvers.csv" s.gsub! "# User _dnscrypt-proxy", "User nobody" end system "./autogen.sh" args = %W[ --disable-dependency-tracking --prefix=#{prefix} --sysconfdir=#{etc} ] if build.with? "plugins" args << "--enable-plugins" args << "--enable-relaxed-plugins-permissions" args << "--enable-plugins-root" end system "./configure", *args system "make", "install" pkgshare.install Dir["contrib/*"] - Dir["contrib/Makefile*"] if build.with? "minisign" (bin/"dnscrypt-update-resolvers").write <<-EOS.undent #!/bin/sh RESOLVERS_UPDATES_BASE_URL=https://download.dnscrypt.org/dnscrypt-proxy RESOLVERS_LIST_BASE_DIR=#{pkgshare} RESOLVERS_LIST_PUBLIC_KEY="RWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3" curl -L --max-redirs 5 -4 -m 30 --connect-timeout 30 -s \ "${RESOLVERS_UPDATES_BASE_URL}/dnscrypt-resolvers.csv" > \ "${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.tmp" && \ curl -L --max-redirs 5 -4 -m 30 --connect-timeout 30 -s \ "${RESOLVERS_UPDATES_BASE_URL}/dnscrypt-resolvers.csv.minisig" > \ "${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.minisig" && \ minisign -Vm ${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.tmp \ -x "${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.minisig" \ -P "$RESOLVERS_LIST_PUBLIC_KEY" -q && \ mv -f ${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.tmp \ ${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv EOS chmod 0775, bin/"dnscrypt-update-resolvers" end end def post_install return if build.without? "minisign" system bin/"dnscrypt-update-resolvers" end def caveats s = <<-EOS.undent After starting dnscrypt-proxy, you will need to point your local DNS server to 127.0.0.1. You can do this by going to System Preferences > "Network" and clicking the "Advanced..." button for your interface. You will see a "DNS" tab where you can click "+" and enter 127.0.0.1 in the "DNS Servers" section. By default, dnscrypt-proxy runs on localhost (127.0.0.1), port 53, and under the "nobody" user using a random resolver. If you would like to change these settings, you will have to edit the configuration file: #{etc}/dnscrypt-proxy.conf (e.g., ResolverName, etc.) To check that dnscrypt-proxy is working correctly, open Terminal and enter the following command. Replace en1 with whatever network interface you're using: sudo tcpdump -i en1 -vvv 'port 443' You should see a line in the result that looks like this: resolver2.dnscrypt.eu.https EOS if build.with? "minisign" s += <<-EOS.undent If at some point the resolver file gets outdated, it can be updated to the latest version by running: #{opt_bin}/dnscrypt-update-resolvers EOS end s end plist_options :startup => true def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-/Apple/DTD PLIST 1.0/EN" "http:/www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>KeepAlive</key> <true/> <key>RunAtLoad</key> <true/> <key>ProgramArguments</key> <array> <string>#{opt_sbin}/dnscrypt-proxy</string> <string>#{etc}/dnscrypt-proxy.conf</string> </array> <key>UserName</key> <string>root</string> <key>StandardErrorPath</key> <string>/dev/null</string> <key>StandardOutPath</key> <string>/dev/null</string> </dict> </plist> EOS end test do system "#{sbin}/dnscrypt-proxy", "--version" end end
34.709459
102
0.662644
916c313884213349db73cf3925174209fe3c7484
113,459
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module JobsV3 # Application related details of a job posting. class ApplicationInfo include Google::Apis::Core::Hashable # Optional but at least one of uris, # emails or instruction must be # specified. # Use this field to specify email address(es) to which resumes or # applications can be sent. # The maximum number of allowed characters for each entry is 255. # Corresponds to the JSON property `emails` # @return [Array<String>] attr_accessor :emails # Optional but at least one of uris, # emails or instruction must be # specified. # Use this field to provide instructions, such as "Mail your application # to ...", that a candidate can follow to apply for the job. # This field accepts and sanitizes HTML input, and also accepts # bold, italic, ordered list, and unordered list markup tags. # The maximum number of allowed characters is 3,000. # Corresponds to the JSON property `instruction` # @return [String] attr_accessor :instruction # Optional but at least one of uris, # emails or instruction must be # specified. # Use this URI field to direct an applicant to a website, for example to # link to an online application form. # The maximum number of allowed characters for each entry is 2,000. # Corresponds to the JSON property `uris` # @return [Array<String>] attr_accessor :uris def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @emails = args[:emails] if args.key?(:emails) @instruction = args[:instruction] if args.key?(:instruction) @uris = args[:uris] if args.key?(:uris) end end # Input only. # Batch delete jobs request. class BatchDeleteJobsRequest include Google::Apis::Core::Hashable # Required. # The filter string specifies the jobs to be deleted. # Supported operator: =, AND # The fields eligible for filtering are: # * `companyName` (Required) # * `requisitionId` (Required) # Sample Query: companyName = "projects/api-test-project/companies/123" AND # requisitionId = "req-1" # Corresponds to the JSON property `filter` # @return [String] attr_accessor :filter def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @filter = args[:filter] if args.key?(:filter) end end # Represents starting and ending value of a range in double. class BucketRange include Google::Apis::Core::Hashable # Starting value of the bucket range. # Corresponds to the JSON property `from` # @return [Float] attr_accessor :from # Ending value of the bucket range. # Corresponds to the JSON property `to` # @return [Float] attr_accessor :to def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @from = args[:from] if args.key?(:from) @to = args[:to] if args.key?(:to) end end # Represents count of jobs within one bucket. class BucketizedCount include Google::Apis::Core::Hashable # Number of jobs whose numeric field value fall into `range`. # Corresponds to the JSON property `count` # @return [Fixnum] attr_accessor :count # Represents starting and ending value of a range in double. # Corresponds to the JSON property `range` # @return [Google::Apis::JobsV3::BucketRange] attr_accessor :range def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @count = args[:count] if args.key?(:count) @range = args[:range] if args.key?(:range) end end # Input only. # Parameters needed for commute search. class CommuteFilter include Google::Apis::Core::Hashable # Optional. # If `true`, jobs without street level addresses may also be returned. # For city level addresses, the city center is used. For state and coarser # level addresses, text matching is used. # If this field is set to `false` or is not specified, only jobs that include # street level addresses will be returned by commute search. # Corresponds to the JSON property `allowImpreciseAddresses` # @return [Boolean] attr_accessor :allow_imprecise_addresses alias_method :allow_imprecise_addresses?, :allow_imprecise_addresses # Required. # The method of transportation for which to calculate the commute time. # Corresponds to the JSON property `commuteMethod` # @return [String] attr_accessor :commute_method # Represents a time of day. The date and time zone are either not significant # or are specified elsewhere. An API may choose to allow leap seconds. Related # types are google.type.Date and `google.protobuf.Timestamp`. # Corresponds to the JSON property `departureTime` # @return [Google::Apis::JobsV3::TimeOfDay] attr_accessor :departure_time # Optional. # Specifies the traffic density to use when calculating commute time. # Corresponds to the JSON property `roadTraffic` # @return [String] attr_accessor :road_traffic # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Corresponds to the JSON property `startCoordinates` # @return [Google::Apis::JobsV3::LatLng] attr_accessor :start_coordinates # Required. # The maximum travel time in seconds. The maximum allowed value is `3600s` # (one hour). Format is `123s`. # Corresponds to the JSON property `travelDuration` # @return [String] attr_accessor :travel_duration def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @allow_imprecise_addresses = args[:allow_imprecise_addresses] if args.key?(:allow_imprecise_addresses) @commute_method = args[:commute_method] if args.key?(:commute_method) @departure_time = args[:departure_time] if args.key?(:departure_time) @road_traffic = args[:road_traffic] if args.key?(:road_traffic) @start_coordinates = args[:start_coordinates] if args.key?(:start_coordinates) @travel_duration = args[:travel_duration] if args.key?(:travel_duration) end end # Output only. # Commute details related to this job. class CommuteInfo include Google::Apis::Core::Hashable # Output only. # A resource that represents a location with full geographic information. # Corresponds to the JSON property `jobLocation` # @return [Google::Apis::JobsV3::Location] attr_accessor :job_location # The number of seconds required to travel to the job location from the # query location. A duration of 0 seconds indicates that the job is not # reachable within the requested duration, but was returned as part of an # expanded query. # Corresponds to the JSON property `travelDuration` # @return [String] attr_accessor :travel_duration def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @job_location = args[:job_location] if args.key?(:job_location) @travel_duration = args[:travel_duration] if args.key?(:travel_duration) end end # A Company resource represents a company in the service. A company is the # entity that owns job postings, that is, the hiring entity responsible for # employing applicants for the job position. class Company include Google::Apis::Core::Hashable # Optional. # The URI to employer's career site or careers page on the employer's web # site, for example, "https://careers.google.com". # Corresponds to the JSON property `careerSiteUri` # @return [String] attr_accessor :career_site_uri # Derived details about the company. # Corresponds to the JSON property `derivedInfo` # @return [Google::Apis::JobsV3::CompanyDerivedInfo] attr_accessor :derived_info # Required. # The display name of the company, for example, "Google, LLC". # Corresponds to the JSON property `displayName` # @return [String] attr_accessor :display_name # Optional. # Equal Employment Opportunity legal disclaimer text to be # associated with all jobs, and typically to be displayed in all # roles. # The maximum number of allowed characters is 500. # Corresponds to the JSON property `eeoText` # @return [String] attr_accessor :eeo_text # Required. # Client side company identifier, used to uniquely identify the # company. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `externalId` # @return [String] attr_accessor :external_id # Optional. # The street address of the company's main headquarters, which may be # different from the job location. The service attempts # to geolocate the provided address, and populates a more specific # location wherever possible in DerivedInfo.headquarters_location. # Corresponds to the JSON property `headquartersAddress` # @return [String] attr_accessor :headquarters_address # Optional. # Set to true if it is the hiring agency that post jobs for other # employers. # Defaults to false if not provided. # Corresponds to the JSON property `hiringAgency` # @return [Boolean] attr_accessor :hiring_agency alias_method :hiring_agency?, :hiring_agency # Optional. # A URI that hosts the employer's company logo. # Corresponds to the JSON property `imageUri` # @return [String] attr_accessor :image_uri # Optional. # A list of keys of filterable Job.custom_attributes, whose # corresponding `string_values` are used in keyword search. Jobs with # `string_values` under these specified field keys are returned if any # of the values matches the search keyword. Custom field values with # parenthesis, brackets and special symbols won't be properly searchable, # and those keyword queries need to be surrounded by quotes. # Corresponds to the JSON property `keywordSearchableJobCustomAttributes` # @return [Array<String>] attr_accessor :keyword_searchable_job_custom_attributes # Required during company update. # The resource name for a company. This is generated by the service when a # company is created. # The format is "projects/`project_id`/companies/`company_id`", for example, # "projects/api-test-project/companies/foo". # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Optional. # The employer's company size. # Corresponds to the JSON property `size` # @return [String] attr_accessor :size # Output only. Indicates whether a company is flagged to be suspended from # public availability by the service when job content appears suspicious, # abusive, or spammy. # Corresponds to the JSON property `suspended` # @return [Boolean] attr_accessor :suspended alias_method :suspended?, :suspended # Optional. # The URI representing the company's primary web site or home page, # for example, "https://www.google.com". # The maximum number of allowed characters is 255. # Corresponds to the JSON property `websiteUri` # @return [String] attr_accessor :website_uri def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @career_site_uri = args[:career_site_uri] if args.key?(:career_site_uri) @derived_info = args[:derived_info] if args.key?(:derived_info) @display_name = args[:display_name] if args.key?(:display_name) @eeo_text = args[:eeo_text] if args.key?(:eeo_text) @external_id = args[:external_id] if args.key?(:external_id) @headquarters_address = args[:headquarters_address] if args.key?(:headquarters_address) @hiring_agency = args[:hiring_agency] if args.key?(:hiring_agency) @image_uri = args[:image_uri] if args.key?(:image_uri) @keyword_searchable_job_custom_attributes = args[:keyword_searchable_job_custom_attributes] if args.key?(:keyword_searchable_job_custom_attributes) @name = args[:name] if args.key?(:name) @size = args[:size] if args.key?(:size) @suspended = args[:suspended] if args.key?(:suspended) @website_uri = args[:website_uri] if args.key?(:website_uri) end end # Derived details about the company. class CompanyDerivedInfo include Google::Apis::Core::Hashable # Output only. # A resource that represents a location with full geographic information. # Corresponds to the JSON property `headquartersLocation` # @return [Google::Apis::JobsV3::Location] attr_accessor :headquarters_location def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @headquarters_location = args[:headquarters_location] if args.key?(:headquarters_location) end end # A compensation entry that represents one component of compensation, such # as base pay, bonus, or other compensation type. # Annualization: One compensation entry can be annualized if # - it contains valid amount or range. # - and its expected_units_per_year is set or can be derived. # Its annualized range is determined as (amount or range) times # expected_units_per_year. class CompensationEntry include Google::Apis::Core::Hashable # Represents an amount of money with its currency type. # Corresponds to the JSON property `amount` # @return [Google::Apis::JobsV3::Money] attr_accessor :amount # Optional. # Compensation description. For example, could # indicate equity terms or provide additional context to an estimated # bonus. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # Optional. # Expected number of units paid each year. If not specified, when # Job.employment_types is FULLTIME, a default value is inferred # based on unit. Default values: # - HOURLY: 2080 # - DAILY: 260 # - WEEKLY: 52 # - MONTHLY: 12 # - ANNUAL: 1 # Corresponds to the JSON property `expectedUnitsPerYear` # @return [Float] attr_accessor :expected_units_per_year # Compensation range. # Corresponds to the JSON property `range` # @return [Google::Apis::JobsV3::CompensationRange] attr_accessor :range # Optional. # Compensation type. # Default is CompensationUnit.OTHER_COMPENSATION_TYPE. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type # Optional. # Frequency of the specified amount. # Default is CompensationUnit.OTHER_COMPENSATION_UNIT. # Corresponds to the JSON property `unit` # @return [String] attr_accessor :unit def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @amount = args[:amount] if args.key?(:amount) @description = args[:description] if args.key?(:description) @expected_units_per_year = args[:expected_units_per_year] if args.key?(:expected_units_per_year) @range = args[:range] if args.key?(:range) @type = args[:type] if args.key?(:type) @unit = args[:unit] if args.key?(:unit) end end # Input only. # Filter on job compensation type and amount. class CompensationFilter include Google::Apis::Core::Hashable # Optional. # Whether to include jobs whose compensation range is unspecified. # Corresponds to the JSON property `includeJobsWithUnspecifiedCompensationRange` # @return [Boolean] attr_accessor :include_jobs_with_unspecified_compensation_range alias_method :include_jobs_with_unspecified_compensation_range?, :include_jobs_with_unspecified_compensation_range # Compensation range. # Corresponds to the JSON property `range` # @return [Google::Apis::JobsV3::CompensationRange] attr_accessor :range # Required. # Type of filter. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type # Required. # Specify desired `base compensation entry's` # CompensationInfo.CompensationUnit. # Corresponds to the JSON property `units` # @return [Array<String>] attr_accessor :units def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @include_jobs_with_unspecified_compensation_range = args[:include_jobs_with_unspecified_compensation_range] if args.key?(:include_jobs_with_unspecified_compensation_range) @range = args[:range] if args.key?(:range) @type = args[:type] if args.key?(:type) @units = args[:units] if args.key?(:units) end end # Input only. # Compensation based histogram request. class CompensationHistogramRequest include Google::Apis::Core::Hashable # Input only. # Use this field to specify bucketing option for the histogram search response. # Corresponds to the JSON property `bucketingOption` # @return [Google::Apis::JobsV3::NumericBucketingOption] attr_accessor :bucketing_option # Required. # Type of the request, representing which field the histogramming should be # performed over. A single request can only specify one histogram of each # `CompensationHistogramRequestType`. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @bucketing_option = args[:bucketing_option] if args.key?(:bucketing_option) @type = args[:type] if args.key?(:type) end end # Output only. # Compensation based histogram result. class CompensationHistogramResult include Google::Apis::Core::Hashable # Output only. # Custom numeric bucketing result. # Corresponds to the JSON property `result` # @return [Google::Apis::JobsV3::NumericBucketingResult] attr_accessor :result # Type of the request, corresponding to # CompensationHistogramRequest.type. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @result = args[:result] if args.key?(:result) @type = args[:type] if args.key?(:type) end end # Job compensation details. class CompensationInfo include Google::Apis::Core::Hashable # Compensation range. # Corresponds to the JSON property `annualizedBaseCompensationRange` # @return [Google::Apis::JobsV3::CompensationRange] attr_accessor :annualized_base_compensation_range # Compensation range. # Corresponds to the JSON property `annualizedTotalCompensationRange` # @return [Google::Apis::JobsV3::CompensationRange] attr_accessor :annualized_total_compensation_range # Optional. # Job compensation information. # At most one entry can be of type # CompensationInfo.CompensationType.BASE, which is # referred as ** base compensation entry ** for the job. # Corresponds to the JSON property `entries` # @return [Array<Google::Apis::JobsV3::CompensationEntry>] attr_accessor :entries def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @annualized_base_compensation_range = args[:annualized_base_compensation_range] if args.key?(:annualized_base_compensation_range) @annualized_total_compensation_range = args[:annualized_total_compensation_range] if args.key?(:annualized_total_compensation_range) @entries = args[:entries] if args.key?(:entries) end end # Compensation range. class CompensationRange include Google::Apis::Core::Hashable # Represents an amount of money with its currency type. # Corresponds to the JSON property `maxCompensation` # @return [Google::Apis::JobsV3::Money] attr_accessor :max_compensation # Represents an amount of money with its currency type. # Corresponds to the JSON property `minCompensation` # @return [Google::Apis::JobsV3::Money] attr_accessor :min_compensation def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @max_compensation = args[:max_compensation] if args.key?(:max_compensation) @min_compensation = args[:min_compensation] if args.key?(:min_compensation) end end # Output only. # Response of auto-complete query. class CompleteQueryResponse include Google::Apis::Core::Hashable # Results of the matching job/company candidates. # Corresponds to the JSON property `completionResults` # @return [Array<Google::Apis::JobsV3::CompletionResult>] attr_accessor :completion_results # Output only. # Additional information returned to client, such as debugging information. # Corresponds to the JSON property `metadata` # @return [Google::Apis::JobsV3::ResponseMetadata] attr_accessor :metadata def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @completion_results = args[:completion_results] if args.key?(:completion_results) @metadata = args[:metadata] if args.key?(:metadata) end end # Output only. # Resource that represents completion results. class CompletionResult include Google::Apis::Core::Hashable # The URI of the company image for CompletionType.COMPANY_NAME. # Corresponds to the JSON property `imageUri` # @return [String] attr_accessor :image_uri # The suggestion for the query. # Corresponds to the JSON property `suggestion` # @return [String] attr_accessor :suggestion # The completion topic. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @image_uri = args[:image_uri] if args.key?(:image_uri) @suggestion = args[:suggestion] if args.key?(:suggestion) @type = args[:type] if args.key?(:type) end end # Input only. # The Request of the CreateCompany method. class CreateCompanyRequest include Google::Apis::Core::Hashable # A Company resource represents a company in the service. A company is the # entity that owns job postings, that is, the hiring entity responsible for # employing applicants for the job position. # Corresponds to the JSON property `company` # @return [Google::Apis::JobsV3::Company] attr_accessor :company def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @company = args[:company] if args.key?(:company) end end # Input only. # Create job request. class CreateJobRequest include Google::Apis::Core::Hashable # A Job resource represents a job posting (also referred to as a "job listing" # or "job requisition"). A job belongs to a Company, which is the hiring # entity responsible for the job. # Corresponds to the JSON property `job` # @return [Google::Apis::JobsV3::Job] attr_accessor :job def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @job = args[:job] if args.key?(:job) end end # Custom attribute values that are either filterable or non-filterable. class CustomAttribute include Google::Apis::Core::Hashable # Optional. # If the `filterable` flag is true, custom field values are searchable. # If false, values are not searchable. # Default is false. # Corresponds to the JSON property `filterable` # @return [Boolean] attr_accessor :filterable alias_method :filterable?, :filterable # Optional but exactly one of string_values or long_values must # be specified. # This field is used to perform number range search. # (`EQ`, `GT`, `GE`, `LE`, `LT`) over filterable `long_value`. # Currently at most 1 long_values is supported. # Corresponds to the JSON property `longValues` # @return [Array<Fixnum>] attr_accessor :long_values # Optional but exactly one of string_values or long_values must # be specified. # This field is used to perform a string match (`CASE_SENSITIVE_MATCH` or # `CASE_INSENSITIVE_MATCH`) search. # For filterable `string_value`s, a maximum total number of 200 values # is allowed, with each `string_value` has a byte size of no more than # 255B. For unfilterable `string_values`, the maximum total byte size of # unfilterable `string_values` is 50KB. # Empty string is not allowed. # Corresponds to the JSON property `stringValues` # @return [Array<String>] attr_accessor :string_values def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @filterable = args[:filterable] if args.key?(:filterable) @long_values = args[:long_values] if args.key?(:long_values) @string_values = args[:string_values] if args.key?(:string_values) end end # Custom attributes histogram request. An error is thrown if neither # string_value_histogram or long_value_histogram_bucketing_option has # been defined. class CustomAttributeHistogramRequest include Google::Apis::Core::Hashable # Required. # Specifies the custom field key to perform a histogram on. If specified # without `long_value_histogram_bucketing_option`, histogram on string values # of the given `key` is triggered, otherwise histogram is performed on long # values. # Corresponds to the JSON property `key` # @return [String] attr_accessor :key # Input only. # Use this field to specify bucketing option for the histogram search response. # Corresponds to the JSON property `longValueHistogramBucketingOption` # @return [Google::Apis::JobsV3::NumericBucketingOption] attr_accessor :long_value_histogram_bucketing_option # Optional. If set to true, the response includes the histogram value for # each key as a string. # Corresponds to the JSON property `stringValueHistogram` # @return [Boolean] attr_accessor :string_value_histogram alias_method :string_value_histogram?, :string_value_histogram def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @key = args[:key] if args.key?(:key) @long_value_histogram_bucketing_option = args[:long_value_histogram_bucketing_option] if args.key?(:long_value_histogram_bucketing_option) @string_value_histogram = args[:string_value_histogram] if args.key?(:string_value_histogram) end end # Output only. # Custom attribute histogram result. class CustomAttributeHistogramResult include Google::Apis::Core::Hashable # Stores the key of custom attribute the histogram is performed on. # Corresponds to the JSON property `key` # @return [String] attr_accessor :key # Output only. # Custom numeric bucketing result. # Corresponds to the JSON property `longValueHistogramResult` # @return [Google::Apis::JobsV3::NumericBucketingResult] attr_accessor :long_value_histogram_result # Stores a map from the values of string custom field associated # with `key` to the number of jobs with that value in this histogram result. # Corresponds to the JSON property `stringValueHistogramResult` # @return [Hash<String,Fixnum>] attr_accessor :string_value_histogram_result def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @key = args[:key] if args.key?(:key) @long_value_histogram_result = args[:long_value_histogram_result] if args.key?(:long_value_histogram_result) @string_value_histogram_result = args[:string_value_histogram_result] if args.key?(:string_value_histogram_result) end end # Device information collected from the job seeker, candidate, or # other entity conducting the job search. Providing this information improves # the quality of the search results across devices. class DeviceInfo include Google::Apis::Core::Hashable # Optional. # Type of the device. # Corresponds to the JSON property `deviceType` # @return [String] attr_accessor :device_type # Optional. # A device-specific ID. The ID must be a unique identifier that # distinguishes the device from other devices. # Corresponds to the JSON property `id` # @return [String] attr_accessor :id def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @device_type = args[:device_type] if args.key?(:device_type) @id = args[:id] if args.key?(:id) end end # A generic empty message that you can re-use to avoid defining duplicated # empty messages in your APIs. A typical example is to use it as the request # or the response type of an API method. For instance: # service Foo ` # rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); # ` # The JSON representation for `Empty` is empty JSON object ````. class Empty include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # Input only. # Histogram facets to be specified in SearchJobsRequest. class HistogramFacets include Google::Apis::Core::Hashable # Optional. # Specifies compensation field-based histogram requests. # Duplicate values of CompensationHistogramRequest.type are not allowed. # Corresponds to the JSON property `compensationHistogramFacets` # @return [Array<Google::Apis::JobsV3::CompensationHistogramRequest>] attr_accessor :compensation_histogram_facets # Optional. # Specifies the custom attributes histogram requests. # Duplicate values of CustomAttributeHistogramRequest.key are not # allowed. # Corresponds to the JSON property `customAttributeHistogramFacets` # @return [Array<Google::Apis::JobsV3::CustomAttributeHistogramRequest>] attr_accessor :custom_attribute_histogram_facets # Optional. # Specifies the simple type of histogram facets, for example, # `COMPANY_SIZE`, `EMPLOYMENT_TYPE` etc. # Corresponds to the JSON property `simpleHistogramFacets` # @return [Array<String>] attr_accessor :simple_histogram_facets def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @compensation_histogram_facets = args[:compensation_histogram_facets] if args.key?(:compensation_histogram_facets) @custom_attribute_histogram_facets = args[:custom_attribute_histogram_facets] if args.key?(:custom_attribute_histogram_facets) @simple_histogram_facets = args[:simple_histogram_facets] if args.key?(:simple_histogram_facets) end end # Output only. # Result of a histogram call. The response contains the histogram map for the # search type specified by HistogramResult.field. # The response is a map of each filter value to the corresponding count of # jobs for that filter. class HistogramResult include Google::Apis::Core::Hashable # The Histogram search filters. # Corresponds to the JSON property `searchType` # @return [String] attr_accessor :search_type # A map from the values of field to the number of jobs with that value # in this search result. # Key: search type (filter names, such as the companyName). # Values: the count of jobs that match the filter for this search. # Corresponds to the JSON property `values` # @return [Hash<String,Fixnum>] attr_accessor :values def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @search_type = args[:search_type] if args.key?(:search_type) @values = args[:values] if args.key?(:values) end end # Output only. # Histogram results that match HistogramFacets specified in # SearchJobsRequest. class HistogramResults include Google::Apis::Core::Hashable # Specifies compensation field-based histogram results that match # HistogramFacets.compensation_histogram_requests. # Corresponds to the JSON property `compensationHistogramResults` # @return [Array<Google::Apis::JobsV3::CompensationHistogramResult>] attr_accessor :compensation_histogram_results # Specifies histogram results for custom attributes that match # HistogramFacets.custom_attribute_histogram_facets. # Corresponds to the JSON property `customAttributeHistogramResults` # @return [Array<Google::Apis::JobsV3::CustomAttributeHistogramResult>] attr_accessor :custom_attribute_histogram_results # Specifies histogram results that matches # HistogramFacets.simple_histogram_facets. # Corresponds to the JSON property `simpleHistogramResults` # @return [Array<Google::Apis::JobsV3::HistogramResult>] attr_accessor :simple_histogram_results def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @compensation_histogram_results = args[:compensation_histogram_results] if args.key?(:compensation_histogram_results) @custom_attribute_histogram_results = args[:custom_attribute_histogram_results] if args.key?(:custom_attribute_histogram_results) @simple_histogram_results = args[:simple_histogram_results] if args.key?(:simple_histogram_results) end end # A Job resource represents a job posting (also referred to as a "job listing" # or "job requisition"). A job belongs to a Company, which is the hiring # entity responsible for the job. class Job include Google::Apis::Core::Hashable # Optional but strongly recommended for the best service experience. # Location(s) where the employer is looking to hire for this job posting. # Specifying the full street address(es) of the hiring location enables # better API results, especially job searches by commute time. # At most 50 locations are allowed for best search performance. If a job has # more locations, it is suggested to split it into multiple jobs with unique # requisition_ids (e.g. 'ReqA' becomes 'ReqA-1', 'ReqA-2', etc.) as # multiple jobs with the same company_name, language_code and # requisition_id are not allowed. If the original requisition_id must # be preserved, a custom field should be used for storage. It is also # suggested to group the locations that close to each other in the same job # for better search experience. # The maximum number of allowed characters is 500. # Corresponds to the JSON property `addresses` # @return [Array<String>] attr_accessor :addresses # Application related details of a job posting. # Corresponds to the JSON property `applicationInfo` # @return [Google::Apis::JobsV3::ApplicationInfo] attr_accessor :application_info # Output only. Display name of the company listing the job. # Corresponds to the JSON property `companyDisplayName` # @return [String] attr_accessor :company_display_name # Required. # The resource name of the company listing the job, such as # "projects/api-test-project/companies/foo". # Corresponds to the JSON property `companyName` # @return [String] attr_accessor :company_name # Job compensation details. # Corresponds to the JSON property `compensationInfo` # @return [Google::Apis::JobsV3::CompensationInfo] attr_accessor :compensation_info # Optional. # A map of fields to hold both filterable and non-filterable custom job # attributes that are not covered by the provided structured fields. # The keys of the map are strings up to 64 bytes and must match the # pattern: a-zA-Z*. For example, key0LikeThis or # KEY_1_LIKE_THIS. # At most 100 filterable and at most 100 unfilterable keys are supported. # For filterable `string_values`, across all keys at most 200 values are # allowed, with each string no more than 255 characters. For unfilterable # `string_values`, the maximum total size of `string_values` across all keys # is 50KB. # Corresponds to the JSON property `customAttributes` # @return [Hash<String,Google::Apis::JobsV3::CustomAttribute>] attr_accessor :custom_attributes # Optional. # The desired education degrees for the job, such as Bachelors, Masters. # Corresponds to the JSON property `degreeTypes` # @return [Array<String>] attr_accessor :degree_types # Optional. # The department or functional area within the company with the open # position. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `department` # @return [String] attr_accessor :department # Output only. # Derived details about the job posting. # Corresponds to the JSON property `derivedInfo` # @return [Google::Apis::JobsV3::JobDerivedInfo] attr_accessor :derived_info # Required. # The description of the job, which typically includes a multi-paragraph # description of the company and related information. Separate fields are # provided on the job object for responsibilities, # qualifications, and other job characteristics. Use of # these separate job fields is recommended. # This field accepts and sanitizes HTML input, and also accepts # bold, italic, ordered list, and unordered list markup tags. # The maximum number of allowed characters is 100,000. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # Optional. # The employment type(s) of a job, for example, # full time or # part time. # Corresponds to the JSON property `employmentTypes` # @return [Array<String>] attr_accessor :employment_types # Optional. # A description of bonus, commission, and other compensation # incentives associated with the job not including salary or pay. # The maximum number of allowed characters is 10,000. # Corresponds to the JSON property `incentives` # @return [String] attr_accessor :incentives # Optional. # The benefits included with the job. # Corresponds to the JSON property `jobBenefits` # @return [Array<String>] attr_accessor :job_benefits # Optional. # The end timestamp of the job. Typically this field is used for contracting # engagements. Invalid timestamps are ignored. # Corresponds to the JSON property `jobEndTime` # @return [String] attr_accessor :job_end_time # Optional. # The experience level associated with the job, such as "Entry Level". # Corresponds to the JSON property `jobLevel` # @return [String] attr_accessor :job_level # Optional. # The start timestamp of the job in UTC time zone. Typically this field # is used for contracting engagements. Invalid timestamps are ignored. # Corresponds to the JSON property `jobStartTime` # @return [String] attr_accessor :job_start_time # Optional. # The language of the posting. This field is distinct from # any requirements for fluency that are associated with the job. # Language codes must be in BCP-47 format, such as "en-US" or "sr-Latn". # For more information, see # [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47)`: # class="external" target="_blank" `. # If this field is unspecified and Job.description is present, detected # language code based on Job.description is assigned, otherwise # defaults to 'en_US'. # Corresponds to the JSON property `languageCode` # @return [String] attr_accessor :language_code # Required during job update. # The resource name for the job. This is generated by the service when a # job is created. # The format is "projects/`project_id`/jobs/`job_id`", # for example, "projects/api-test-project/jobs/1234". # Use of this field in job queries and API calls is preferred over the use of # requisition_id since this value is unique. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Output only. The timestamp when this job posting was created. # Corresponds to the JSON property `postingCreateTime` # @return [String] attr_accessor :posting_create_time # Optional but strongly recommended for the best service # experience. # The expiration timestamp of the job. After this timestamp, the # job is marked as expired, and it no longer appears in search results. The # expired job can't be deleted or listed by the DeleteJob and # ListJobs APIs, but it can be retrieved with the GetJob API or # updated with the UpdateJob API. An expired job can be updated and # opened again by using a future expiration timestamp. Updating an expired # job fails if there is another existing open job with same company_name, # language_code and requisition_id. # The expired jobs are retained in our system for 90 days. However, the # overall expired job count cannot exceed 3 times the maximum of open jobs # count over the past week, otherwise jobs with earlier expire time are # cleaned first. Expired jobs are no longer accessible after they are cleaned # out. # Invalid timestamps are ignored, and treated as expire time not provided. # Timestamp before the instant request is made is considered valid, the job # will be treated as expired immediately. # If this value is not provided at the time of job creation or is invalid, # the job posting expires after 30 days from the job's creation time. For # example, if the job was created on 2017/01/01 13:00AM UTC with an # unspecified expiration date, the job expires after 2017/01/31 13:00AM UTC. # If this value is not provided on job update, it depends on the field masks # set by UpdateJobRequest.update_mask. If the field masks include # expiry_time, or the masks are empty meaning that every field is # updated, the job posting expires after 30 days from the job's last # update time. Otherwise the expiration date isn't updated. # Corresponds to the JSON property `postingExpireTime` # @return [String] attr_accessor :posting_expire_time # Optional. # The timestamp this job posting was most recently published. The default # value is the time the request arrives at the server. Invalid timestamps are # ignored. # Corresponds to the JSON property `postingPublishTime` # @return [String] attr_accessor :posting_publish_time # Optional. # The job PostingRegion (for example, state, country) throughout which # the job is available. If this field is set, a # LocationFilter in a search query within the job region # finds this job posting if an exact location match is not specified. # If this field is set to PostingRegion.NATION_WIDE or # [PostingRegion.ADMINISTRATIVE_AREA], setting job addresses # to the same location level as this field is strongly recommended. # Corresponds to the JSON property `postingRegion` # @return [String] attr_accessor :posting_region # Output only. The timestamp when this job posting was last updated. # Corresponds to the JSON property `postingUpdateTime` # @return [String] attr_accessor :posting_update_time # Input only. # Options for job processing. # Corresponds to the JSON property `processingOptions` # @return [Google::Apis::JobsV3::ProcessingOptions] attr_accessor :processing_options # Optional. # A promotion value of the job, as determined by the client. # The value determines the sort order of the jobs returned when searching for # jobs using the featured jobs search call, with higher promotional values # being returned first and ties being resolved by relevance sort. Only the # jobs with a promotionValue >0 are returned in a FEATURED_JOB_SEARCH. # Default value is 0, and negative values are treated as 0. # Corresponds to the JSON property `promotionValue` # @return [Fixnum] attr_accessor :promotion_value # Optional. # A description of the qualifications required to perform the # job. The use of this field is recommended # as an alternative to using the more general description field. # This field accepts and sanitizes HTML input, and also accepts # bold, italic, ordered list, and unordered list markup tags. # The maximum number of allowed characters is 10,000. # Corresponds to the JSON property `qualifications` # @return [String] attr_accessor :qualifications # Required. # The requisition ID, also referred to as the posting ID, assigned by the # client to identify a job. This field is intended to be used by clients # for client identification and tracking of postings. A job is not allowed # to be created if there is another job with the same [company_name], # language_code and requisition_id. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `requisitionId` # @return [String] attr_accessor :requisition_id # Optional. # A description of job responsibilities. The use of this field is # recommended as an alternative to using the more general description # field. # This field accepts and sanitizes HTML input, and also accepts # bold, italic, ordered list, and unordered list markup tags. # The maximum number of allowed characters is 10,000. # Corresponds to the JSON property `responsibilities` # @return [String] attr_accessor :responsibilities # Required. # The title of the job, such as "Software Engineer" # The maximum number of allowed characters is 500. # Corresponds to the JSON property `title` # @return [String] attr_accessor :title # Optional. # The visibility of the job. # Defaults to Visibility.ACCOUNT_ONLY if not specified. # Corresponds to the JSON property `visibility` # @return [String] attr_accessor :visibility def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @addresses = args[:addresses] if args.key?(:addresses) @application_info = args[:application_info] if args.key?(:application_info) @company_display_name = args[:company_display_name] if args.key?(:company_display_name) @company_name = args[:company_name] if args.key?(:company_name) @compensation_info = args[:compensation_info] if args.key?(:compensation_info) @custom_attributes = args[:custom_attributes] if args.key?(:custom_attributes) @degree_types = args[:degree_types] if args.key?(:degree_types) @department = args[:department] if args.key?(:department) @derived_info = args[:derived_info] if args.key?(:derived_info) @description = args[:description] if args.key?(:description) @employment_types = args[:employment_types] if args.key?(:employment_types) @incentives = args[:incentives] if args.key?(:incentives) @job_benefits = args[:job_benefits] if args.key?(:job_benefits) @job_end_time = args[:job_end_time] if args.key?(:job_end_time) @job_level = args[:job_level] if args.key?(:job_level) @job_start_time = args[:job_start_time] if args.key?(:job_start_time) @language_code = args[:language_code] if args.key?(:language_code) @name = args[:name] if args.key?(:name) @posting_create_time = args[:posting_create_time] if args.key?(:posting_create_time) @posting_expire_time = args[:posting_expire_time] if args.key?(:posting_expire_time) @posting_publish_time = args[:posting_publish_time] if args.key?(:posting_publish_time) @posting_region = args[:posting_region] if args.key?(:posting_region) @posting_update_time = args[:posting_update_time] if args.key?(:posting_update_time) @processing_options = args[:processing_options] if args.key?(:processing_options) @promotion_value = args[:promotion_value] if args.key?(:promotion_value) @qualifications = args[:qualifications] if args.key?(:qualifications) @requisition_id = args[:requisition_id] if args.key?(:requisition_id) @responsibilities = args[:responsibilities] if args.key?(:responsibilities) @title = args[:title] if args.key?(:title) @visibility = args[:visibility] if args.key?(:visibility) end end # Output only. # Derived details about the job posting. class JobDerivedInfo include Google::Apis::Core::Hashable # Job categories derived from Job.title and Job.description. # Corresponds to the JSON property `jobCategories` # @return [Array<String>] attr_accessor :job_categories # Structured locations of the job, resolved from Job.addresses. # locations are exactly matched to Job.addresses in the same # order. # Corresponds to the JSON property `locations` # @return [Array<Google::Apis::JobsV3::Location>] attr_accessor :locations def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @job_categories = args[:job_categories] if args.key?(:job_categories) @locations = args[:locations] if args.key?(:locations) end end # Input only. # The query required to perform a search query. class JobQuery include Google::Apis::Core::Hashable # Input only. # Parameters needed for commute search. # Corresponds to the JSON property `commuteFilter` # @return [Google::Apis::JobsV3::CommuteFilter] attr_accessor :commute_filter # Optional. # This filter specifies the exact company display # name of the jobs to search against. # If a value isn't specified, jobs within the search results are # associated with any company. # If multiple values are specified, jobs within the search results may be # associated with any of the specified companies. # At most 20 company display name filters are allowed. # Corresponds to the JSON property `companyDisplayNames` # @return [Array<String>] attr_accessor :company_display_names # Optional. # This filter specifies the company entities to search against. # If a value isn't specified, jobs are searched for against all # companies. # If multiple values are specified, jobs are searched against the # companies specified. # The format is "projects/`project_id`/companies/`company_id`", for example, # "projects/api-test-project/companies/foo". # At most 20 company filters are allowed. # Corresponds to the JSON property `companyNames` # @return [Array<String>] attr_accessor :company_names # Input only. # Filter on job compensation type and amount. # Corresponds to the JSON property `compensationFilter` # @return [Google::Apis::JobsV3::CompensationFilter] attr_accessor :compensation_filter # Optional. # This filter specifies a structured syntax to match against the # Job.custom_attributes marked as `filterable`. # The syntax for this expression is a subset of SQL syntax. # Supported operators are: `=`, `!=`, `<`, `<=`, `>`, and `>=` where the # left of the operator is a custom field key and the right of the operator # is a number or a quoted string. You must escape backslash (\\) and # quote (\") characters. # Supported functions are `LOWER([field_name])` to # perform a case insensitive match and `EMPTY([field_name])` to filter on the # existence of a key. # Boolean expressions (AND/OR/NOT) are supported up to 3 levels of # nesting (for example, "((A AND B AND C) OR NOT D) AND E"), a maximum of 100 # comparisons or functions are allowed in the expression. The expression # must be < 3000 bytes in length. # Sample Query: # `(LOWER(driving_license)="class \"a\"" OR EMPTY(driving_license)) AND # driving_years > 10` # Corresponds to the JSON property `customAttributeFilter` # @return [String] attr_accessor :custom_attribute_filter # Optional. # This flag controls the spell-check feature. If false, the # service attempts to correct a misspelled query, # for example, "enginee" is corrected to "engineer". # Defaults to false: a spell check is performed. # Corresponds to the JSON property `disableSpellCheck` # @return [Boolean] attr_accessor :disable_spell_check alias_method :disable_spell_check?, :disable_spell_check # Optional. # The employment type filter specifies the employment type of jobs to # search against, such as EmploymentType.FULL_TIME. # If a value is not specified, jobs in the search results includes any # employment type. # If multiple values are specified, jobs in the search results include # any of the specified employment types. # Corresponds to the JSON property `employmentTypes` # @return [Array<String>] attr_accessor :employment_types # Optional. # The category filter specifies the categories of jobs to search against. # See Category for more information. # If a value is not specified, jobs from any category are searched against. # If multiple values are specified, jobs from any of the specified # categories are searched against. # Corresponds to the JSON property `jobCategories` # @return [Array<String>] attr_accessor :job_categories # Optional. # This filter specifies the locale of jobs to search against, # for example, "en-US". # If a value isn't specified, the search results can contain jobs in any # locale. # Language codes should be in BCP-47 format, such as "en-US" or "sr-Latn". # For more information, see # [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). # At most 10 language code filters are allowed. # Corresponds to the JSON property `languageCodes` # @return [Array<String>] attr_accessor :language_codes # Optional. # The location filter specifies geo-regions containing the jobs to # search against. See LocationFilter for more information. # If a location value isn't specified, jobs fitting the other search # criteria are retrieved regardless of where they're located. # If multiple values are specified, jobs are retrieved from any of the # specified locations. If different values are specified for the # LocationFilter.distance_in_miles parameter, the maximum provided # distance is used for all locations. # At most 5 location filters are allowed. # Corresponds to the JSON property `locationFilters` # @return [Array<Google::Apis::JobsV3::LocationFilter>] attr_accessor :location_filters # Message representing a period of time between two timestamps. # Corresponds to the JSON property `publishTimeRange` # @return [Google::Apis::JobsV3::TimestampRange] attr_accessor :publish_time_range # Optional. # The query string that matches against the job title, description, and # location fields. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `query` # @return [String] attr_accessor :query def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @commute_filter = args[:commute_filter] if args.key?(:commute_filter) @company_display_names = args[:company_display_names] if args.key?(:company_display_names) @company_names = args[:company_names] if args.key?(:company_names) @compensation_filter = args[:compensation_filter] if args.key?(:compensation_filter) @custom_attribute_filter = args[:custom_attribute_filter] if args.key?(:custom_attribute_filter) @disable_spell_check = args[:disable_spell_check] if args.key?(:disable_spell_check) @employment_types = args[:employment_types] if args.key?(:employment_types) @job_categories = args[:job_categories] if args.key?(:job_categories) @language_codes = args[:language_codes] if args.key?(:language_codes) @location_filters = args[:location_filters] if args.key?(:location_filters) @publish_time_range = args[:publish_time_range] if args.key?(:publish_time_range) @query = args[:query] if args.key?(:query) end end # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. class LatLng include Google::Apis::Core::Hashable # The latitude in degrees. It must be in the range [-90.0, +90.0]. # Corresponds to the JSON property `latitude` # @return [Float] attr_accessor :latitude # The longitude in degrees. It must be in the range [-180.0, +180.0]. # Corresponds to the JSON property `longitude` # @return [Float] attr_accessor :longitude def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @latitude = args[:latitude] if args.key?(:latitude) @longitude = args[:longitude] if args.key?(:longitude) end end # Output only. # The List companies response object. class ListCompaniesResponse include Google::Apis::Core::Hashable # Companies for the current client. # Corresponds to the JSON property `companies` # @return [Array<Google::Apis::JobsV3::Company>] attr_accessor :companies # Output only. # Additional information returned to client, such as debugging information. # Corresponds to the JSON property `metadata` # @return [Google::Apis::JobsV3::ResponseMetadata] attr_accessor :metadata # A token to retrieve the next page of results. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @companies = args[:companies] if args.key?(:companies) @metadata = args[:metadata] if args.key?(:metadata) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) end end # Output only. # List jobs response. class ListJobsResponse include Google::Apis::Core::Hashable # The Jobs for a given company. # The maximum number of items returned is based on the limit field # provided in the request. # Corresponds to the JSON property `jobs` # @return [Array<Google::Apis::JobsV3::Job>] attr_accessor :jobs # Output only. # Additional information returned to client, such as debugging information. # Corresponds to the JSON property `metadata` # @return [Google::Apis::JobsV3::ResponseMetadata] attr_accessor :metadata # A token to retrieve the next page of results. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @jobs = args[:jobs] if args.key?(:jobs) @metadata = args[:metadata] if args.key?(:metadata) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) end end # Output only. # A resource that represents a location with full geographic information. class Location include Google::Apis::Core::Hashable # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Corresponds to the JSON property `latLng` # @return [Google::Apis::JobsV3::LatLng] attr_accessor :lat_lng # The type of a location, which corresponds to the address lines field of # PostalAddress. For example, "Downtown, Atlanta, GA, USA" has a type of # LocationType#NEIGHBORHOOD, and "Kansas City, KS, USA" has a type of # LocationType#LOCALITY. # Corresponds to the JSON property `locationType` # @return [String] attr_accessor :location_type # Represents a postal address, e.g. for postal delivery or payments addresses. # Given a postal address, a postal service can deliver items to a premise, P.O. # Box or similar. # It is not intended to model geographical locations (roads, towns, # mountains). # In typical usage an address would be created via user input or from importing # existing data, depending on the type of process. # Advice on address input / editing: # - Use an i18n-ready address widget such as # https://github.com/googlei18n/libaddressinput) # - Users should not be presented with UI elements for input or editing of # fields outside countries where that field is used. # For more guidance on how to use this schema, please see: # https://support.google.com/business/answer/6397478 # Corresponds to the JSON property `postalAddress` # @return [Google::Apis::JobsV3::PostalAddress] attr_accessor :postal_address # Radius in miles of the job location. This value is derived from the # location bounding box in which a circle with the specified radius # centered from LatLng covers the area associated with the job location. # For example, currently, "Mountain View, CA, USA" has a radius of # 6.17 miles. # Corresponds to the JSON property `radiusInMiles` # @return [Float] attr_accessor :radius_in_miles def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @lat_lng = args[:lat_lng] if args.key?(:lat_lng) @location_type = args[:location_type] if args.key?(:location_type) @postal_address = args[:postal_address] if args.key?(:postal_address) @radius_in_miles = args[:radius_in_miles] if args.key?(:radius_in_miles) end end # Input only. # Geographic region of the search. class LocationFilter include Google::Apis::Core::Hashable # Optional. # The address name, such as "Mountain View" or "Bay Area". # Corresponds to the JSON property `address` # @return [String] attr_accessor :address # Optional. # The distance_in_miles is applied when the location being searched for is # identified as a city or smaller. When the location being searched for is a # state or larger, this field is ignored. # Corresponds to the JSON property `distanceInMiles` # @return [Float] attr_accessor :distance_in_miles # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Corresponds to the JSON property `latLng` # @return [Google::Apis::JobsV3::LatLng] attr_accessor :lat_lng # Optional. # CLDR region code of the country/region of the address. This is used # to address ambiguity of the user-input location, for example, "Liverpool" # against "Liverpool, NY, US" or "Liverpool, UK". # Set this field if all the jobs to search against are from a same region, # or jobs are world-wide, but the job seeker is from a specific region. # See http://cldr.unicode.org/ and # http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html # for details. Example: "CH" for Switzerland. # Corresponds to the JSON property `regionCode` # @return [String] attr_accessor :region_code # Optional. # Allows the client to return jobs without a # set location, specifically, telecommuting jobs (telecomuting is considered # by the service as a special location. # Job.posting_region indicates if a job permits telecommuting. # If this field is set to TelecommutePreference.TELECOMMUTE_ALLOWED, # telecommuting jobs are searched, and address and lat_lng are # ignored. If not set or set to # TelecommutePreference.TELECOMMUTE_EXCLUDED, telecommute job are not # searched. # This filter can be used by itself to search exclusively for telecommuting # jobs, or it can be combined with another location # filter to search for a combination of job locations, # such as "Mountain View" or "telecommuting" jobs. However, when used in # combination with other location filters, telecommuting jobs can be # treated as less relevant than other jobs in the search response. # Corresponds to the JSON property `telecommutePreference` # @return [String] attr_accessor :telecommute_preference def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @address = args[:address] if args.key?(:address) @distance_in_miles = args[:distance_in_miles] if args.key?(:distance_in_miles) @lat_lng = args[:lat_lng] if args.key?(:lat_lng) @region_code = args[:region_code] if args.key?(:region_code) @telecommute_preference = args[:telecommute_preference] if args.key?(:telecommute_preference) end end # Output only. # Job entry with metadata inside SearchJobsResponse. class MatchingJob include Google::Apis::Core::Hashable # Output only. # Commute details related to this job. # Corresponds to the JSON property `commuteInfo` # @return [Google::Apis::JobsV3::CommuteInfo] attr_accessor :commute_info # A Job resource represents a job posting (also referred to as a "job listing" # or "job requisition"). A job belongs to a Company, which is the hiring # entity responsible for the job. # Corresponds to the JSON property `job` # @return [Google::Apis::JobsV3::Job] attr_accessor :job # A summary of the job with core information that's displayed on the search # results listing page. # Corresponds to the JSON property `jobSummary` # @return [String] attr_accessor :job_summary # Contains snippets of text from the Job.job_title field most # closely matching a search query's keywords, if available. The matching # query keywords are enclosed in HTML bold tags. # Corresponds to the JSON property `jobTitleSnippet` # @return [String] attr_accessor :job_title_snippet # Contains snippets of text from the Job.description and similar # fields that most closely match a search query's keywords, if available. # All HTML tags in the original fields are stripped when returned in this # field, and matching query keywords are enclosed in HTML bold tags. # Corresponds to the JSON property `searchTextSnippet` # @return [String] attr_accessor :search_text_snippet def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @commute_info = args[:commute_info] if args.key?(:commute_info) @job = args[:job] if args.key?(:job) @job_summary = args[:job_summary] if args.key?(:job_summary) @job_title_snippet = args[:job_title_snippet] if args.key?(:job_title_snippet) @search_text_snippet = args[:search_text_snippet] if args.key?(:search_text_snippet) end end # Represents an amount of money with its currency type. class Money include Google::Apis::Core::Hashable # The 3-letter currency code defined in ISO 4217. # Corresponds to the JSON property `currencyCode` # @return [String] attr_accessor :currency_code # Number of nano (10^-9) units of the amount. # The value must be between -999,999,999 and +999,999,999 inclusive. # If `units` is positive, `nanos` must be positive or zero. # If `units` is zero, `nanos` can be positive, zero, or negative. # If `units` is negative, `nanos` must be negative or zero. # For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. # Corresponds to the JSON property `nanos` # @return [Fixnum] attr_accessor :nanos # The whole units of the amount. # For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. # Corresponds to the JSON property `units` # @return [Fixnum] attr_accessor :units def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @currency_code = args[:currency_code] if args.key?(:currency_code) @nanos = args[:nanos] if args.key?(:nanos) @units = args[:units] if args.key?(:units) end end # Input only. # Use this field to specify bucketing option for the histogram search response. class NumericBucketingOption include Google::Apis::Core::Hashable # Required. # Two adjacent values form a histogram bucket. Values should be in # ascending order. For example, if [5, 10, 15] are provided, four buckets are # created: (-inf, 5), 5, 10), [10, 15), [15, inf). At most 20 # [buckets_bound is supported. # Corresponds to the JSON property `bucketBounds` # @return [Array<Float>] attr_accessor :bucket_bounds # Optional. # If set to true, the histogram result includes minimum/maximum # value of the numeric field. # Corresponds to the JSON property `requiresMinMax` # @return [Boolean] attr_accessor :requires_min_max alias_method :requires_min_max?, :requires_min_max def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @bucket_bounds = args[:bucket_bounds] if args.key?(:bucket_bounds) @requires_min_max = args[:requires_min_max] if args.key?(:requires_min_max) end end # Output only. # Custom numeric bucketing result. class NumericBucketingResult include Google::Apis::Core::Hashable # Count within each bucket. Its size is the length of # NumericBucketingOption.bucket_bounds plus 1. # Corresponds to the JSON property `counts` # @return [Array<Google::Apis::JobsV3::BucketizedCount>] attr_accessor :counts # Stores the maximum value of the numeric field. Is populated only if # [NumericBucketingOption.requires_min_max] is set to true. # Corresponds to the JSON property `maxValue` # @return [Float] attr_accessor :max_value # Stores the minimum value of the numeric field. Will be populated only if # [NumericBucketingOption.requires_min_max] is set to true. # Corresponds to the JSON property `minValue` # @return [Float] attr_accessor :min_value def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @counts = args[:counts] if args.key?(:counts) @max_value = args[:max_value] if args.key?(:max_value) @min_value = args[:min_value] if args.key?(:min_value) end end # Represents a postal address, e.g. for postal delivery or payments addresses. # Given a postal address, a postal service can deliver items to a premise, P.O. # Box or similar. # It is not intended to model geographical locations (roads, towns, # mountains). # In typical usage an address would be created via user input or from importing # existing data, depending on the type of process. # Advice on address input / editing: # - Use an i18n-ready address widget such as # https://github.com/googlei18n/libaddressinput) # - Users should not be presented with UI elements for input or editing of # fields outside countries where that field is used. # For more guidance on how to use this schema, please see: # https://support.google.com/business/answer/6397478 class PostalAddress include Google::Apis::Core::Hashable # Unstructured address lines describing the lower levels of an address. # Because values in address_lines do not have type information and may # sometimes contain multiple values in a single field (e.g. # "Austin, TX"), it is important that the line order is clear. The order of # address lines should be "envelope order" for the country/region of the # address. In places where this can vary (e.g. Japan), address_language is # used to make it explicit (e.g. "ja" for large-to-small ordering and # "ja-Latn" or "en" for small-to-large). This way, the most specific line of # an address can be selected based on the language. # The minimum permitted structural representation of an address consists # of a region_code with all remaining information placed in the # address_lines. It would be possible to format such an address very # approximately without geocoding, but no semantic reasoning could be # made about any of the address components until it was at least # partially resolved. # Creating an address only containing a region_code and address_lines, and # then geocoding is the recommended way to handle completely unstructured # addresses (as opposed to guessing which parts of the address should be # localities or administrative areas). # Corresponds to the JSON property `addressLines` # @return [Array<String>] attr_accessor :address_lines # Optional. Highest administrative subdivision which is used for postal # addresses of a country or region. # For example, this can be a state, a province, an oblast, or a prefecture. # Specifically, for Spain this is the province and not the autonomous # community (e.g. "Barcelona" and not "Catalonia"). # Many countries don't use an administrative area in postal addresses. E.g. # in Switzerland this should be left unpopulated. # Corresponds to the JSON property `administrativeArea` # @return [String] attr_accessor :administrative_area # Optional. BCP-47 language code of the contents of this address (if # known). This is often the UI language of the input form or is expected # to match one of the languages used in the address' country/region, or their # transliterated equivalents. # This can affect formatting in certain countries, but is not critical # to the correctness of the data and will never affect any validation or # other non-formatting related operations. # If this value is not known, it should be omitted (rather than specifying a # possibly incorrect default). # Examples: "zh-Hant", "ja", "ja-Latn", "en". # Corresponds to the JSON property `languageCode` # @return [String] attr_accessor :language_code # Optional. Generally refers to the city/town portion of the address. # Examples: US city, IT comune, UK post town. # In regions of the world where localities are not well defined or do not fit # into this structure well, leave locality empty and use address_lines. # Corresponds to the JSON property `locality` # @return [String] attr_accessor :locality # Optional. The name of the organization at the address. # Corresponds to the JSON property `organization` # @return [String] attr_accessor :organization # Optional. Postal code of the address. Not all countries use or require # postal codes to be present, but where they are used, they may trigger # additional validation with other parts of the address (e.g. state/zip # validation in the U.S.A.). # Corresponds to the JSON property `postalCode` # @return [String] attr_accessor :postal_code # Optional. The recipient at the address. # This field may, under certain circumstances, contain multiline information. # For example, it might contain "care of" information. # Corresponds to the JSON property `recipients` # @return [Array<String>] attr_accessor :recipients # Required. CLDR region code of the country/region of the address. This # is never inferred and it is up to the user to ensure the value is # correct. See http://cldr.unicode.org/ and # http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html # for details. Example: "CH" for Switzerland. # Corresponds to the JSON property `regionCode` # @return [String] attr_accessor :region_code # The schema revision of the `PostalAddress`. This must be set to 0, which is # the latest revision. # All new revisions **must** be backward compatible with old revisions. # Corresponds to the JSON property `revision` # @return [Fixnum] attr_accessor :revision # Optional. Additional, country-specific, sorting code. This is not used # in most regions. Where it is used, the value is either a string like # "CEDEX", optionally followed by a number (e.g. "CEDEX 7"), or just a number # alone, representing the "sector code" (Jamaica), "delivery area indicator" # (Malawi) or "post office indicator" (e.g. Côte d'Ivoire). # Corresponds to the JSON property `sortingCode` # @return [String] attr_accessor :sorting_code # Optional. Sublocality of the address. # For example, this can be neighborhoods, boroughs, districts. # Corresponds to the JSON property `sublocality` # @return [String] attr_accessor :sublocality def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @address_lines = args[:address_lines] if args.key?(:address_lines) @administrative_area = args[:administrative_area] if args.key?(:administrative_area) @language_code = args[:language_code] if args.key?(:language_code) @locality = args[:locality] if args.key?(:locality) @organization = args[:organization] if args.key?(:organization) @postal_code = args[:postal_code] if args.key?(:postal_code) @recipients = args[:recipients] if args.key?(:recipients) @region_code = args[:region_code] if args.key?(:region_code) @revision = args[:revision] if args.key?(:revision) @sorting_code = args[:sorting_code] if args.key?(:sorting_code) @sublocality = args[:sublocality] if args.key?(:sublocality) end end # Input only. # Options for job processing. class ProcessingOptions include Google::Apis::Core::Hashable # Optional. # If set to `true`, the service does not attempt to resolve a # more precise address for the job. # Corresponds to the JSON property `disableStreetAddressResolution` # @return [Boolean] attr_accessor :disable_street_address_resolution alias_method :disable_street_address_resolution?, :disable_street_address_resolution # Optional. # Option for job HTML content sanitization. Applied fields are: # * description # * applicationInfo.instruction # * incentives # * qualifications # * responsibilities # HTML tags in these fields may be stripped if sanitiazation is not # disabled. # Defaults to HtmlSanitization.SIMPLE_FORMATTING_ONLY. # Corresponds to the JSON property `htmlSanitization` # @return [String] attr_accessor :html_sanitization def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @disable_street_address_resolution = args[:disable_street_address_resolution] if args.key?(:disable_street_address_resolution) @html_sanitization = args[:html_sanitization] if args.key?(:html_sanitization) end end # Input only. # Meta information related to the job searcher or entity # conducting the job search. This information is used to improve the # performance of the service. class RequestMetadata include Google::Apis::Core::Hashable # Device information collected from the job seeker, candidate, or # other entity conducting the job search. Providing this information improves # the quality of the search results across devices. # Corresponds to the JSON property `deviceInfo` # @return [Google::Apis::JobsV3::DeviceInfo] attr_accessor :device_info # Required. # The client-defined scope or source of the service call, which typically # is the domain on # which the service has been implemented and is currently being run. # For example, if the service is being run by client <em>Foo, Inc.</em>, on # job board www.foo.com and career site www.bar.com, then this field is # set to "foo.com" for use on the job board, and "bar.com" for use on the # career site. # If this field isn't available for some reason, send "UNKNOWN". # Any improvements to the model for a particular tenant site rely on this # field being set correctly to a domain. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `domain` # @return [String] attr_accessor :domain # Required. # A unique session identification string. A session is defined as the # duration of an end user's interaction with the service over a certain # period. # Obfuscate this field for privacy concerns before # providing it to the service. # If this field is not available for some reason, send "UNKNOWN". Note # that any improvements to the model for a particular tenant # site, rely on this field being set correctly to some unique session_id. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `sessionId` # @return [String] attr_accessor :session_id # Required. # A unique user identification string, as determined by the client. # To have the strongest positive impact on search quality # make sure the client-level is unique. # Obfuscate this field for privacy concerns before # providing it to the service. # If this field is not available for some reason, send "UNKNOWN". Note # that any improvements to the model for a particular tenant # site, rely on this field being set correctly to a unique user_id. # The maximum number of allowed characters is 255. # Corresponds to the JSON property `userId` # @return [String] attr_accessor :user_id def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @device_info = args[:device_info] if args.key?(:device_info) @domain = args[:domain] if args.key?(:domain) @session_id = args[:session_id] if args.key?(:session_id) @user_id = args[:user_id] if args.key?(:user_id) end end # Output only. # Additional information returned to client, such as debugging information. class ResponseMetadata include Google::Apis::Core::Hashable # A unique id associated with this call. # This id is logged for tracking purposes. # Corresponds to the JSON property `requestId` # @return [String] attr_accessor :request_id def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @request_id = args[:request_id] if args.key?(:request_id) end end # Input only. # The Request body of the `SearchJobs` call. class SearchJobsRequest include Google::Apis::Core::Hashable # Optional. # Controls whether to disable exact keyword match on Job.job_title, # Job.description, Job.company_display_name, Job.locations, # Job.qualifications. When disable keyword match is turned off, a # keyword match returns jobs that do not match given category filters when # there are matching keywords. For example, the query "program manager," a # result is returned even if the job posting has the title "software # developer," which does not fall into "program manager" ontology, but does # have "program manager" appearing in its description. # For queries like "cloud" that does not contain title or # location specific ontology, jobs with "cloud" keyword matches are returned # regardless of this flag's value. # Please use Company.keyword_searchable_custom_fields or # Company.keyword_searchable_custom_attributes if company specific # globally matched custom field/attribute string values is needed. Enabling # keyword match improves recall of subsequent search requests. # Defaults to false. # Corresponds to the JSON property `disableKeywordMatch` # @return [Boolean] attr_accessor :disable_keyword_match alias_method :disable_keyword_match?, :disable_keyword_match # Optional. # Controls whether highly similar jobs are returned next to each other in # the search results. Jobs are identified as highly similar based on # their titles, job categories, and locations. Highly similar results are # clustered so that only one representative job of the cluster is # displayed to the job seeker higher up in the results, with the other jobs # being displayed lower down in the results. # Defaults to DiversificationLevel.SIMPLE if no value # is specified. # Corresponds to the JSON property `diversificationLevel` # @return [String] attr_accessor :diversification_level # Optional. # Controls whether to broaden the search when it produces sparse results. # Broadened queries append results to the end of the matching results # list. # Defaults to false. # Corresponds to the JSON property `enableBroadening` # @return [Boolean] attr_accessor :enable_broadening alias_method :enable_broadening?, :enable_broadening # Input only. # Histogram facets to be specified in SearchJobsRequest. # Corresponds to the JSON property `histogramFacets` # @return [Google::Apis::JobsV3::HistogramFacets] attr_accessor :histogram_facets # Input only. # The query required to perform a search query. # Corresponds to the JSON property `jobQuery` # @return [Google::Apis::JobsV3::JobQuery] attr_accessor :job_query # Optional. # The desired job attributes returned for jobs in the # search response. Defaults to JobView.SMALL if no value is specified. # Corresponds to the JSON property `jobView` # @return [String] attr_accessor :job_view # Optional. # An integer that specifies the current offset (that is, starting result # location, amongst the jobs deemed by the API as relevant) in search # results. This field is only considered if page_token is unset. # For example, 0 means to return results starting from the first matching # job, and 10 means to return from the 11th job. This can be used for # pagination, (for example, pageSize = 10 and offset = 10 means to return # from the second page). # Corresponds to the JSON property `offset` # @return [Fixnum] attr_accessor :offset # Optional. # The criteria determining how search results are sorted. Default is # "relevance desc". # Supported options are: # * "relevance desc": By relevance descending, as determined by the API # algorithms. Relevance thresholding of query results is only available # with this ordering. # * "posting`_`publish`_`time desc": By Job.posting_publish_time descending. # * "posting`_`update`_`time desc": By Job.posting_update_time descending. # * "title": By Job.title ascending. # * "title desc": By Job.title descending. # * "annualized`_`base`_`compensation": By job's # CompensationInfo.annualized_base_compensation_range ascending. Jobs # whose annualized base compensation is unspecified are put at the end of # search results. # * "annualized`_`base`_`compensation desc": By job's # CompensationInfo.annualized_base_compensation_range descending. Jobs # whose annualized base compensation is unspecified are put at the end of # search results. # * "annualized`_`total`_`compensation": By job's # CompensationInfo.annualized_total_compensation_range ascending. Jobs # whose annualized base compensation is unspecified are put at the end of # search results. # * "annualized`_`total`_`compensation desc": By job's # CompensationInfo.annualized_total_compensation_range descending. Jobs # whose annualized base compensation is unspecified are put at the end of # search results. # Corresponds to the JSON property `orderBy` # @return [String] attr_accessor :order_by # Optional. # A limit on the number of jobs returned in the search results. # Increasing this value above the default value of 10 can increase search # response time. The value can be between 1 and 100. # Corresponds to the JSON property `pageSize` # @return [Fixnum] attr_accessor :page_size # Optional. # The token specifying the current offset within # search results. See SearchJobsResponse.next_page_token for # an explanation of how to obtain the next set of query results. # Corresponds to the JSON property `pageToken` # @return [String] attr_accessor :page_token # Input only. # Meta information related to the job searcher or entity # conducting the job search. This information is used to improve the # performance of the service. # Corresponds to the JSON property `requestMetadata` # @return [Google::Apis::JobsV3::RequestMetadata] attr_accessor :request_metadata # Optional. # Controls if the search job request requires the return of a precise # count of the first 300 results. Setting this to `true` ensures # consistency in the number of results per page. Best practice is to set this # value to true if a client allows users to jump directly to a # non-sequential search results page. # Enabling this flag may adversely impact performance. # Defaults to false. # Corresponds to the JSON property `requirePreciseResultSize` # @return [Boolean] attr_accessor :require_precise_result_size alias_method :require_precise_result_size?, :require_precise_result_size # Optional. # Mode of a search. # Defaults to SearchMode.JOB_SEARCH. # Corresponds to the JSON property `searchMode` # @return [String] attr_accessor :search_mode def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @disable_keyword_match = args[:disable_keyword_match] if args.key?(:disable_keyword_match) @diversification_level = args[:diversification_level] if args.key?(:diversification_level) @enable_broadening = args[:enable_broadening] if args.key?(:enable_broadening) @histogram_facets = args[:histogram_facets] if args.key?(:histogram_facets) @job_query = args[:job_query] if args.key?(:job_query) @job_view = args[:job_view] if args.key?(:job_view) @offset = args[:offset] if args.key?(:offset) @order_by = args[:order_by] if args.key?(:order_by) @page_size = args[:page_size] if args.key?(:page_size) @page_token = args[:page_token] if args.key?(:page_token) @request_metadata = args[:request_metadata] if args.key?(:request_metadata) @require_precise_result_size = args[:require_precise_result_size] if args.key?(:require_precise_result_size) @search_mode = args[:search_mode] if args.key?(:search_mode) end end # Output only. # Response for SearchJob method. class SearchJobsResponse include Google::Apis::Core::Hashable # If query broadening is enabled, we may append additional results from the # broadened query. This number indicates how many of the jobs returned in the # jobs field are from the broadened query. These results are always at the # end of the jobs list. In particular, a value of 0, or if the field isn't # set, all the jobs in the jobs list are from the original # (without broadening) query. If this field is non-zero, subsequent requests # with offset after this result set should contain all broadened results. # Corresponds to the JSON property `broadenedQueryJobsCount` # @return [Fixnum] attr_accessor :broadened_query_jobs_count # An estimation of the number of jobs that match the specified query. # This number is not guaranteed to be accurate. For accurate results, # see enable_precise_result_size. # Corresponds to the JSON property `estimatedTotalSize` # @return [Fixnum] attr_accessor :estimated_total_size # Output only. # Histogram results that match HistogramFacets specified in # SearchJobsRequest. # Corresponds to the JSON property `histogramResults` # @return [Google::Apis::JobsV3::HistogramResults] attr_accessor :histogram_results # The location filters that the service applied to the specified query. If # any filters are lat-lng based, the JobLocation.location_type is # JobLocation.LocationType#LOCATION_TYPE_UNSPECIFIED. # Corresponds to the JSON property `locationFilters` # @return [Array<Google::Apis::JobsV3::Location>] attr_accessor :location_filters # The Job entities that match the specified SearchJobsRequest. # Corresponds to the JSON property `matchingJobs` # @return [Array<Google::Apis::JobsV3::MatchingJob>] attr_accessor :matching_jobs # Output only. # Additional information returned to client, such as debugging information. # Corresponds to the JSON property `metadata` # @return [Google::Apis::JobsV3::ResponseMetadata] attr_accessor :metadata # The token that specifies the starting position of the next page of results. # This field is empty if there are no more results. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # Output only. # Spell check result. # Corresponds to the JSON property `spellCorrection` # @return [Google::Apis::JobsV3::SpellingCorrection] attr_accessor :spell_correction # The precise result count, which is available only if the client set # enable_precise_result_size to `true`, or if the response # is the last page of results. Otherwise, the value is `-1`. # Corresponds to the JSON property `totalSize` # @return [Fixnum] attr_accessor :total_size def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @broadened_query_jobs_count = args[:broadened_query_jobs_count] if args.key?(:broadened_query_jobs_count) @estimated_total_size = args[:estimated_total_size] if args.key?(:estimated_total_size) @histogram_results = args[:histogram_results] if args.key?(:histogram_results) @location_filters = args[:location_filters] if args.key?(:location_filters) @matching_jobs = args[:matching_jobs] if args.key?(:matching_jobs) @metadata = args[:metadata] if args.key?(:metadata) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @spell_correction = args[:spell_correction] if args.key?(:spell_correction) @total_size = args[:total_size] if args.key?(:total_size) end end # Output only. # Spell check result. class SpellingCorrection include Google::Apis::Core::Hashable # Indicates if the query was corrected by the spell checker. # Corresponds to the JSON property `corrected` # @return [Boolean] attr_accessor :corrected alias_method :corrected?, :corrected # Correction output consisting of the corrected keyword string. # Corresponds to the JSON property `correctedText` # @return [String] attr_accessor :corrected_text def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @corrected = args[:corrected] if args.key?(:corrected) @corrected_text = args[:corrected_text] if args.key?(:corrected_text) end end # Represents a time of day. The date and time zone are either not significant # or are specified elsewhere. An API may choose to allow leap seconds. Related # types are google.type.Date and `google.protobuf.Timestamp`. class TimeOfDay include Google::Apis::Core::Hashable # Hours of day in 24 hour format. Should be from 0 to 23. An API may choose # to allow the value "24:00:00" for scenarios like business closing time. # Corresponds to the JSON property `hours` # @return [Fixnum] attr_accessor :hours # Minutes of hour of day. Must be from 0 to 59. # Corresponds to the JSON property `minutes` # @return [Fixnum] attr_accessor :minutes # Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999. # Corresponds to the JSON property `nanos` # @return [Fixnum] attr_accessor :nanos # Seconds of minutes of the time. Must normally be from 0 to 59. An API may # allow the value 60 if it allows leap-seconds. # Corresponds to the JSON property `seconds` # @return [Fixnum] attr_accessor :seconds def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @hours = args[:hours] if args.key?(:hours) @minutes = args[:minutes] if args.key?(:minutes) @nanos = args[:nanos] if args.key?(:nanos) @seconds = args[:seconds] if args.key?(:seconds) end end # Message representing a period of time between two timestamps. class TimestampRange include Google::Apis::Core::Hashable # End of the period. # Corresponds to the JSON property `endTime` # @return [String] attr_accessor :end_time # Begin of the period. # Corresponds to the JSON property `startTime` # @return [String] attr_accessor :start_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @end_time = args[:end_time] if args.key?(:end_time) @start_time = args[:start_time] if args.key?(:start_time) end end # Input only. # Request for updating a specified company. class UpdateCompanyRequest include Google::Apis::Core::Hashable # A Company resource represents a company in the service. A company is the # entity that owns job postings, that is, the hiring entity responsible for # employing applicants for the job position. # Corresponds to the JSON property `company` # @return [Google::Apis::JobsV3::Company] attr_accessor :company # Optional but strongly recommended for the best service # experience. # If update_mask is provided, only the specified fields in # company are updated. Otherwise all the fields are updated. # A field mask to specify the company fields to be updated. Only # top level fields of Company are supported. # Corresponds to the JSON property `updateMask` # @return [String] attr_accessor :update_mask def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @company = args[:company] if args.key?(:company) @update_mask = args[:update_mask] if args.key?(:update_mask) end end # Input only. # Update job request. class UpdateJobRequest include Google::Apis::Core::Hashable # A Job resource represents a job posting (also referred to as a "job listing" # or "job requisition"). A job belongs to a Company, which is the hiring # entity responsible for the job. # Corresponds to the JSON property `job` # @return [Google::Apis::JobsV3::Job] attr_accessor :job # Optional but strongly recommended to be provided for the best service # experience. # If update_mask is provided, only the specified fields in # job are updated. Otherwise all the fields are updated. # A field mask to restrict the fields that are updated. Only # top level fields of Job are supported. # Corresponds to the JSON property `updateMask` # @return [String] attr_accessor :update_mask def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @job = args[:job] if args.key?(:job) @update_mask = args[:update_mask] if args.key?(:update_mask) end end end end end
43.571045
181
0.6389
289e745ffc71ab56730807285bc719dbdce4068d
2,479
# ActsAsVirtualAttribute module Sixty4Bit module Acts module VirtualAttribute def self.included(base) base.extend(ClassMethods) end module ClassMethods def acts_as_virtual_attribute(*args, &proc) property = args[0] property_class_name = self.reflections[property].class_name class_eval <<-EOT after_update :save_#{property} def new_#{property}_attributes=(attrs) attrs.each { |a| #{property}.build(a) } end def existing_#{property}_attributes=(attrs) #{property}.reject(&:new_record?).each do |a| attributes = attrs[a.id.to_s] if attributes a.attributes = attributes end end end def save_#{property} #{property}.each do |p| if p.should_destroy? p.destroy else p.save end end end EOT destroy_method = <<REMOVE_CODE attr_accessor :should_destroy def should_destroy? should_destroy.to_i == 1 end REMOVE_CODE property_class_name.constantize.class_eval(destroy_method) helper_method = <<HELPER_CODE def fields_for_#{property.to_s.singularize}(virt, &block) prefix = virt.new_record? ? 'new' : 'existing' fields_for("#{self.name.downcase}[#\{prefix\}_#{property}_attributes][]", virt, &block) end def link_to_remove_#{property.to_s.singularize}(name, container, form, &block) if form.object.new_record? link_to_function(name, "$(this).up('#\{container\}').remove()") else link_to_function(name, "$(this).up('#\{container\}').hide(); $(this).next('.should_destroy').value = 1") + form.hidden_field(:should_destroy, :value => 0, :class => 'should_destroy') end end HELPER_CODE helper_name = self.class_name.pluralize + "Helper" helper_name.constantize.class_eval(helper_method) include Sixty4Bit::Acts::VirtualAttribute::InstanceMethods extend Sixty4Bit::Acts::VirtualAttribute::SingletonMethods end end module InstanceMethods end module SingletonMethods end end end end ActiveRecord::Base.send(:include, Sixty4Bit::Acts::VirtualAttribute)
28.825581
120
0.578056
e95a7548973217bcfe5b1f9d00882df97b099b7d
2,481
require 'test/minirunit' is_windows = RUBY_PLATFORM =~ /mswin/i || (RUBY_PLATFORM =~ /java/i && ENV_JAVA['os.name'] =~ /windows/i) #test_check('test_bracket') test_equal(nil, ENV['test']) test_equal(nil, ENV['TEST']) ENV['test'] = 'foo' test_equal('foo', ENV['test']) test_equal(is_windows ? 'foo' : nil, ENV['TEST']) ENV['TEST'] = 'bar' test_equal('bar', ENV['TEST']) test_equal(is_windows ? 'bar' : 'foo', ENV['test']) test_exception(TypeError) { tmp = ENV[1] } test_exception(TypeError) { ENV[1] = 'foo' } test_exception(TypeError) { ENV['test'] = 0 } #test_check('has_value') val = 'a' val.succ! while ENV.has_value?(val) && ENV.has_value?(val.upcase) ENV['test'] = val[0...-1] test_equal(false, ENV.has_value?(val)) test_equal(false, ENV.has_value?(val.upcase)) ENV['test'] = val test_equal(true, ENV.has_value?(val)) test_equal(false, ENV.has_value?(val.upcase)) ENV['test'] = val.upcase test_equal(false, ENV.has_value?(val)) test_equal(true, ENV.has_value?(val.upcase)) #test_check('index') val = 'a' val.succ! while ENV.has_value?(val) && ENV.has_value?(val.upcase) ENV['test'] = val[0...-1] test_equal(nil, ENV.index(val)) test_equal(nil, ENV.index(val.upcase)) ENV['test'] = val test_equal('test', ENV.index(val)) test_equal(nil, ENV.index(val.upcase)) ENV['test'] = val.upcase test_equal(nil, ENV.index(val)) test_equal('test', ENV.index(val.upcase)) #nil values are ok (corresponding key will be deleted) #nil keys are not ok test_exception(TypeError) {ENV[nil]} test_exception(TypeError) {ENV[nil] = "foo"} ENV['test'] = nil test_equal(nil, ENV['test']) test_equal(false, ENV.has_key?('test')) name = (ENV['OS'] =~ /\AWin/i ? '%__JRUBY_T1%' : '$__JRUBY_T1') expected = (ENV['OS'] =~ /\AWin/i ? '%__JRUBY_T1%' : '') v = `echo #{name}`.chomp test_equal expected,v ENV['__JRUBY_T1'] = "abc" v = `echo #{name}`.chomp test_equal "abc",v # See JRUBY-3097 # try setting up PATH in such a way that doesn't find 'jruby' # but 'java' is available jruby_exe = File.join(File.dirname(__FILE__), '..', 'bin', 'jruby') old_path = ENV['PATH'] our_path = [] old_path.split(File::PATH_SEPARATOR).each do |dir| our_path << dir unless File.exist? File.join(dir, 'jruby') end unless our_path.select {|dir| File.exist? File.join(dir, 'java')}.empty? test_equal "abc", `PATH=#{our_path.join(File::PATH_SEPARATOR)} #{jruby_exe} -e "puts ENV[%{__JRUBY_T1}]"`.chomp end ENV['PATH'] = old_path # JRUBY-2393 test_ok(ENV.object_id != ENV.to_hash.object_id)
25.57732
115
0.677952
e90d05576c614318462143183407cce6607c0ee2
2,500
# -*- encoding: utf-8 -*- # stub: ffi 1.12.2 ruby lib # stub: ext/ffi_c/extconf.rb Gem::Specification.new do |s| s.name = "ffi".freeze s.version = "1.12.2" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "bug_tracker_uri" => "https://github.com/ffi/ffi/issues", "changelog_uri" => "https://github.com/ffi/ffi/blob/master/CHANGELOG.md", "documentation_uri" => "https://github.com/ffi/ffi/wiki", "mailing_list_uri" => "http://groups.google.com/group/ruby-ffi", "source_code_uri" => "https://github.com/ffi/ffi/", "wiki_uri" => "https://github.com/ffi/ffi/wiki" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Wayne Meissner".freeze] s.date = "2020-02-01" s.description = "Ruby FFI library".freeze s.email = "[email protected]".freeze s.extensions = ["ext/ffi_c/extconf.rb".freeze] s.files = ["ext/ffi_c/extconf.rb".freeze] s.homepage = "https://github.com/ffi/ffi/wiki".freeze s.licenses = ["BSD-3-Clause".freeze] s.rdoc_options = ["--exclude=ext/ffi_c/.*\\.o$".freeze, "--exclude=ffi_c\\.(bundle|so)$".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze) s.rubygems_version = "2.7.6.2".freeze s.summary = "Ruby FFI".freeze s.installed_by_version = "2.7.6.2" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rake>.freeze, ["~> 13.0"]) s.add_development_dependency(%q<rake-compiler>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<rake-compiler-dock>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 2.14.1"]) s.add_development_dependency(%q<rubygems-tasks>.freeze, ["~> 0.2.4"]) else s.add_dependency(%q<rake>.freeze, ["~> 13.0"]) s.add_dependency(%q<rake-compiler>.freeze, ["~> 1.0"]) s.add_dependency(%q<rake-compiler-dock>.freeze, ["~> 1.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 2.14.1"]) s.add_dependency(%q<rubygems-tasks>.freeze, ["~> 0.2.4"]) end else s.add_dependency(%q<rake>.freeze, ["~> 13.0"]) s.add_dependency(%q<rake-compiler>.freeze, ["~> 1.0"]) s.add_dependency(%q<rake-compiler-dock>.freeze, ["~> 1.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 2.14.1"]) s.add_dependency(%q<rubygems-tasks>.freeze, ["~> 0.2.4"]) end end
49.019608
401
0.6548
918e20858fe677f08a05f00ccb37c2fe851c2742
4,997
$LOAD_PATH.delete_if { |path| path[/gems\/vanity-\d/] } $LOAD_PATH.unshift File.expand_path("../lib", File.dirname(__FILE__)) RAILS_ROOT = File.expand_path("..") require "test/unit" require "mocha" require "action_controller" require "action_controller/test_case" require "active_record" require "initializer" Rails.configuration = Rails::Configuration.new require "phusion_passenger/events" require "lib/vanity" require "timecop" require "webmock/test_unit" if $VERBOSE $logger = Logger.new(STDOUT) $logger.level = Logger::DEBUG end class Test::Unit::TestCase include WebMock def setup FileUtils.mkpath "tmp/experiments/metrics" new_playground #WebMock.after_request do |request_signature, response| # puts "Request #{request_signature} was made and #{response} was returned" #end end # Call this on teardown. It wipes put the playground and any state held in it # (mostly experiments), resets vanity ID, and clears database of all experiments. def nuke_playground Vanity.playground.connection.flushdb new_playground end # Call this if you need a new playground, e.g. to re-define the same experiment, # or reload an experiment (saved by the previous playground). def new_playground adapter = ENV["ADAPTER"] || "redis" # We go destructive on the database at the end of each run, so make sure we # don't use databases you care about. For Redis, we pick database 15 # (default is 0). spec = { "redis"=>"redis://localhost/15", "mongodb"=>"mongodb://localhost/vanity-test", "mock"=>"mock:/" }[adapter] raise "No support yet for #{adapter}" unless spec Vanity.playground = Vanity::Playground.new(:logger=>$logger, :load_path=>"tmp/experiments") Vanity.playground.establish_connection spec end # Defines the specified metrics (one or more names). Returns metric, or array # of metric (if more than one argument). def metric(*names) metrics = names.map do |name| id = name.to_s.downcase.gsub(/\W+/, '_').to_sym Vanity.playground.metrics[id] ||= Vanity::Metric.new(Vanity.playground, name) end names.size == 1 ? metrics.first : metrics end # Defines an A/B experiment. def new_ab_test(name, &block) id = name.to_s.downcase.gsub(/\W/, "_").to_sym experiment = Vanity::Experiment::AbTest.new(Vanity.playground, id, name) experiment.instance_eval &block experiment.save Vanity.playground.experiments[id] = experiment end # Returns named experiment. def experiment(name) Vanity.playground.experiment(name) end def today @today ||= Date.today end def not_collecting! Vanity.playground.collecting = false Vanity.playground.stubs(:connection).returns(stub(:flushdb=>nil)) end def teardown Vanity.context = nil FileUtils.rm_rf "tmp" Vanity.playground.connection.flushdb if Vanity.playground.connected? WebMock.reset_webmock end end ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end ActiveRecord::Base.logger = $logger ActiveRecord::Base.establish_connection :adapter=>"sqlite3", :database=>File.expand_path("database.sqlite") # Call this to define aggregate functions not available in SQlite. class ActiveRecord::Base def self.aggregates connection.raw_connection.create_aggregate("minimum", 1) do step do |func, value| func[:minimum] = value.to_i unless func[:minimum] && func[:minimum].to_i < value.to_i end finalize { |func| func.result = func[:minimum] } end connection.raw_connection.create_aggregate("maximum", 1) do step do |func, value| func[:maximum] = value.to_i unless func[:maximum] && func[:maximum].to_i > value.to_i end finalize { |func| func.result = func[:maximum] } end connection.raw_connection.create_aggregate("average", 1) do step do |func, value| func[:total] = func[:total].to_i + value.to_i func[:count] = func[:count].to_i + 1 end finalize { |func| func.result = func[:total].to_i / func[:count].to_i } end end end class Array # Not in Ruby 1.8.6. unless method_defined?(:shuffle) def shuffle copy = clone Array.new(size) { copy.delete_at(Kernel.rand(copy.size)) } end end end # Source: http://gist.github.com/25455 def context(*args, &block) return super unless (name = args.first) && block parent = Class === self ? self : (defined?(ActiveSupport::TestCase) ? ActiveSupport::TestCase : Test::Unit::TestCase) klass = Class.new(parent) do def self.test(name, &block) define_method("test_#{name.gsub(/\W/,'_')}", &block) if block end def self.xtest(*args) end def self.setup(&block) define_method(:setup) { super() ; instance_eval &block } end def self.teardown(&block) define_method(:teardown) { super() ; instance_eval &block } end end parent.const_set name.split(/\W+/).map(&:capitalize).join, klass klass.class_eval &block end
31.626582
119
0.693816
f7c17df0fc38b9edcb4073d32ca92a251dd908de
234
class Donation < ApplicationRecord belongs_to :user belongs_to :organization validates :amount, presence: true scope :recent, -> { order(date: :desc) } accepts_nested_attributes_for :organization, reject_if: :all_blank end
26
68
0.764957
5dfb6d687bfb105da6ec1dd1b0d7ae7637b05700
114
require "daisybill_api/data/url" require "daisybill_api/data/client" module DaisybillApi module Data end end
14.25
35
0.798246
e27ba2db8741a2c2912c86a2c86122a3122799c0
321
require 'nokogiri' require 'redcarpet' require "redcarpet_markdown_to_prismjs/version" require "redcarpet_markdown_to_prismjs/content_constructor" require "redcarpet_markdown_to_prismjs/parser" module RedcarpetMarkdownToPrismjs def prism_html(string) RedcarpetMarkdownToPrismjs::Parser.new(string).parse end end
26.75
59
0.853583
f8376e17751a59fe6e70f4ca82de6f625114c120
442
RSpec.describe ModsulatorSheet do describe "#rows" do subject { ModsulatorSheet.new File.join(FIXTURES_DIR, "test_002.csv"), "test_002.csv" } it "should use the right header row" do expect(subject.headers).to include "druid", "sourceId" end it "should present each row as a hash" do row = subject.rows.first expect(row["druid"]).to be_nil expect(row["sourceId"]).to eq "test:002" end end end
27.625
91
0.667421
21e7b07d80028e947740593bcc43bd02263f2f51
422
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'entries/show', type: :view do before(:each) do view.extend TextHelper user = FactoryGirl.create(:user) @journal = FactoryGirl.create(:journal, user: user) @entry = FactoryGirl.create(:entry, journal: @journal, user: user) end it 'renders attributes in <p>' do render expect(rendered).to match(/Best day ever/) end end
23.444444
70
0.696682
0126ac6d7af450e2b373fc1d9532b12773078ed6
493
module Okubo module DeckMethods def deck d = Okubo::Deck.where(:user_id => self.id, :user_type => self.class.name).first_or_create d.source_class.module_eval do def stats Okubo::Item.first(:conditions => {:source_id => self.id, :source_type => self.class.name}) end end d end def remove_deck deck = Okubo::Deck.first(:conditions => {:user_id => self.id, :user_type => self.class.name}) deck.destroy end end end
27.388889
99
0.616633
f798eb22563bcbda10ca60bdee9529df8dd6fb29
73,502
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'seahorse/client/plugins/content_length.rb' require 'aws-sdk-core/plugins/credentials_configuration.rb' require 'aws-sdk-core/plugins/logging.rb' require 'aws-sdk-core/plugins/param_converter.rb' require 'aws-sdk-core/plugins/param_validator.rb' require 'aws-sdk-core/plugins/user_agent.rb' require 'aws-sdk-core/plugins/helpful_socket_errors.rb' require 'aws-sdk-core/plugins/retry_errors.rb' require 'aws-sdk-core/plugins/global_configuration.rb' require 'aws-sdk-core/plugins/regional_endpoint.rb' require 'aws-sdk-core/plugins/endpoint_discovery.rb' require 'aws-sdk-core/plugins/endpoint_pattern.rb' require 'aws-sdk-core/plugins/response_paging.rb' require 'aws-sdk-core/plugins/stub_responses.rb' require 'aws-sdk-core/plugins/idempotency_token.rb' require 'aws-sdk-core/plugins/jsonvalue_converter.rb' require 'aws-sdk-core/plugins/client_metrics_plugin.rb' require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb' require 'aws-sdk-core/plugins/signature_v4.rb' require 'aws-sdk-core/plugins/protocols/rest_json.rb' Aws::Plugins::GlobalConfiguration.add_identifier(:connect) module Aws::Connect class Client < Seahorse::Client::Base include Aws::ClientStubs @identifier = :connect set_api(ClientApi::API) add_plugin(Seahorse::Client::Plugins::ContentLength) add_plugin(Aws::Plugins::CredentialsConfiguration) add_plugin(Aws::Plugins::Logging) add_plugin(Aws::Plugins::ParamConverter) add_plugin(Aws::Plugins::ParamValidator) add_plugin(Aws::Plugins::UserAgent) add_plugin(Aws::Plugins::HelpfulSocketErrors) add_plugin(Aws::Plugins::RetryErrors) add_plugin(Aws::Plugins::GlobalConfiguration) add_plugin(Aws::Plugins::RegionalEndpoint) add_plugin(Aws::Plugins::EndpointDiscovery) add_plugin(Aws::Plugins::EndpointPattern) add_plugin(Aws::Plugins::ResponsePaging) add_plugin(Aws::Plugins::StubResponses) add_plugin(Aws::Plugins::IdempotencyToken) add_plugin(Aws::Plugins::JsonvalueConverter) add_plugin(Aws::Plugins::ClientMetricsPlugin) add_plugin(Aws::Plugins::ClientMetricsSendPlugin) add_plugin(Aws::Plugins::SignatureV4) add_plugin(Aws::Plugins::Protocols::RestJson) # @overload initialize(options) # @param [Hash] options # @option options [required, Aws::CredentialProvider] :credentials # Your AWS credentials. This can be an instance of any one of the # following classes: # # * `Aws::Credentials` - Used for configuring static, non-refreshing # credentials. # # * `Aws::InstanceProfileCredentials` - Used for loading credentials # from an EC2 IMDS on an EC2 instance. # # * `Aws::SharedCredentials` - Used for loading credentials from a # shared file, such as `~/.aws/config`. # # * `Aws::AssumeRoleCredentials` - Used when you need to assume a role. # # When `:credentials` are not configured directly, the following # locations will be searched for credentials: # # * `Aws.config[:credentials]` # * The `:access_key_id`, `:secret_access_key`, and `:session_token` options. # * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] # * `~/.aws/credentials` # * `~/.aws/config` # * EC2 IMDS instance profile - When used by default, the timeouts are # very aggressive. Construct and pass an instance of # `Aws::InstanceProfileCredentails` to enable retries and extended # timeouts. # # @option options [required, String] :region # The AWS region to connect to. The configured `:region` is # used to determine the service `:endpoint`. When not passed, # a default `:region` is search for in the following locations: # # * `Aws.config[:region]` # * `ENV['AWS_REGION']` # * `ENV['AMAZON_REGION']` # * `ENV['AWS_DEFAULT_REGION']` # * `~/.aws/credentials` # * `~/.aws/config` # # @option options [String] :access_key_id # # @option options [Boolean] :active_endpoint_cache (false) # When set to `true`, a thread polling for endpoints will be running in # the background every 60 secs (default). Defaults to `false`. # # @option options [Boolean] :client_side_monitoring (false) # When `true`, client-side metrics will be collected for all API requests from # this client. # # @option options [String] :client_side_monitoring_client_id ("") # Allows you to provide an identifier for this client which will be attached to # all generated client side metrics. Defaults to an empty string. # # @option options [Integer] :client_side_monitoring_port (31000) # Required for publishing client metrics. The port that the client side monitoring # agent is running on, where client metrics will be published via UDP. # # @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher) # Allows you to provide a custom client-side monitoring publisher class. By default, # will use the Client Side Monitoring Agent Publisher. # # @option options [Boolean] :convert_params (true) # When `true`, an attempt is made to coerce request parameters into # the required types. # # @option options [Boolean] :disable_host_prefix_injection (false) # Set to true to disable SDK automatically adding host prefix # to default service endpoint when available. # # @option options [String] :endpoint # The client endpoint is normally constructed from the `:region` # option. You should only configure an `:endpoint` when connecting # to test endpoints. This should be avalid HTTP(S) URI. # # @option options [Integer] :endpoint_cache_max_entries (1000) # Used for the maximum size limit of the LRU cache storing endpoints data # for endpoint discovery enabled operations. Defaults to 1000. # # @option options [Integer] :endpoint_cache_max_threads (10) # Used for the maximum threads in use for polling endpoints to be cached, defaults to 10. # # @option options [Integer] :endpoint_cache_poll_interval (60) # When :endpoint_discovery and :active_endpoint_cache is enabled, # Use this option to config the time interval in seconds for making # requests fetching endpoints information. Defaults to 60 sec. # # @option options [Boolean] :endpoint_discovery (false) # When set to `true`, endpoint discovery will be enabled for operations when available. Defaults to `false`. # # @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default) # The log formatter. # # @option options [Symbol] :log_level (:info) # The log level to send messages to the `:logger` at. # # @option options [Logger] :logger # The Logger instance to send log messages to. If this option # is not set, logging will be disabled. # # @option options [String] :profile ("default") # Used when loading credentials from the shared credentials file # at HOME/.aws/credentials. When not specified, 'default' is used. # # @option options [Float] :retry_base_delay (0.3) # The base delay in seconds used by the default backoff function. # # @option options [Symbol] :retry_jitter (:none) # A delay randomiser function used by the default backoff function. Some predefined functions can be referenced by name - :none, :equal, :full, otherwise a Proc that takes and returns a number. # # @see https://www.awsarchitectureblog.com/2015/03/backoff.html # # @option options [Integer] :retry_limit (3) # The maximum number of times to retry failed requests. Only # ~ 500 level server errors and certain ~ 400 level client errors # are retried. Generally, these are throttling errors, data # checksum errors, networking errors, timeout errors and auth # errors from expired credentials. # # @option options [Integer] :retry_max_delay (0) # The maximum number of seconds to delay between retries (0 for no limit) used by the default backoff function. # # @option options [String] :secret_access_key # # @option options [String] :session_token # # @option options [Boolean] :stub_responses (false) # Causes the client to return stubbed responses. By default # fake responses are generated and returned. You can specify # the response data to return or errors to raise by calling # {ClientStubs#stub_responses}. See {ClientStubs} for more information. # # ** Please note ** When response stubbing is enabled, no HTTP # requests are made, and retries are disabled. # # @option options [Boolean] :validate_params (true) # When `true`, request parameters are validated before # sending the request. # # @option options [URI::HTTP,String] :http_proxy A proxy to send # requests through. Formatted like 'http://proxy.com:123'. # # @option options [Float] :http_open_timeout (15) The number of # seconds to wait when opening a HTTP session before rasing a # `Timeout::Error`. # # @option options [Integer] :http_read_timeout (60) The default # number of seconds to wait for response data. This value can # safely be set # per-request on the session yeidled by {#session_for}. # # @option options [Float] :http_idle_timeout (5) The number of # seconds a connection is allowed to sit idble before it is # considered stale. Stale connections are closed and removed # from the pool before making a request. # # @option options [Float] :http_continue_timeout (1) The number of # seconds to wait for a 100-continue response before sending the # request body. This option has no effect unless the request has # "Expect" header set to "100-continue". Defaults to `nil` which # disables this behaviour. This value can safely be set per # request on the session yeidled by {#session_for}. # # @option options [Boolean] :http_wire_trace (false) When `true`, # HTTP debug output will be sent to the `:logger`. # # @option options [Boolean] :ssl_verify_peer (true) When `true`, # SSL peer certificates are verified when establishing a # connection. # # @option options [String] :ssl_ca_bundle Full path to the SSL # certificate authority bundle file that should be used when # verifying peer certificates. If you do not pass # `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default # will be used if available. # # @option options [String] :ssl_ca_directory Full path of the # directory that contains the unbundled SSL certificate # authority files for verifying peer certificates. If you do # not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the # system default will be used if available. # def initialize(*args) super end # @!group API Operations # Creates a new user account in your Amazon Connect instance. # # @option params [required, String] :username # The user name in Amazon Connect for the account to create. If you are # using SAML for identity management in your Amazon Connect, the value # for `Username` can include up to 64 characters from # \[a-zA-Z0-9\_-.\\@\]+. # # @option params [String] :password # The password for the user account to create. This is required if you # are using Amazon Connect for identity management. If you are using # SAML for identity management and include this parameter, an # `InvalidRequestException` is returned. # # @option params [Types::UserIdentityInfo] :identity_info # Information about the user, including email address, first name, and # last name. # # @option params [required, Types::UserPhoneConfig] :phone_config # Specifies the phone settings for the user, including # `AfterContactWorkTimeLimit`, `AutoAccept`, `DeskPhoneNumber`, and # `PhoneType`. # # @option params [String] :directory_user_id # The unique identifier for the user account in the directory service # directory used for identity management. If Amazon Connect is unable to # access the existing directory, you can use the `DirectoryUserId` to # authenticate users. If you include the parameter, it is assumed that # Amazon Connect cannot access the directory. If the parameter is not # included, the `UserIdentityInfo` is used to authenticate users from # your existing directory. # # This parameter is required if you are using an existing directory for # identity management in Amazon Connect when Amazon Connect cannot # access your directory to authenticate users. If you are using SAML for # identity management and include this parameter, an # `InvalidRequestException` is returned. # # @option params [required, Array<String>] :security_profile_ids # The unique identifier of the security profile to assign to the user # created. # # @option params [required, String] :routing_profile_id # The unique identifier for the routing profile to assign to the user # created. # # @option params [String] :hierarchy_group_id # The unique identifier for the hierarchy group to assign to the user # created. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Types::CreateUserResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::CreateUserResponse#user_id #user_id} => String # * {Types::CreateUserResponse#user_arn #user_arn} => String # # @example Request syntax with placeholder values # # resp = client.create_user({ # username: "AgentUsername", # required # password: "Password", # identity_info: { # first_name: "AgentFirstName", # last_name: "AgentLastName", # email: "Email", # }, # phone_config: { # required # phone_type: "SOFT_PHONE", # required, accepts SOFT_PHONE, DESK_PHONE # auto_accept: false, # after_contact_work_time_limit: 1, # desk_phone_number: "PhoneNumber", # }, # directory_user_id: "DirectoryUserId", # security_profile_ids: ["SecurityProfileId"], # required # routing_profile_id: "RoutingProfileId", # required # hierarchy_group_id: "HierarchyGroupId", # instance_id: "InstanceId", # required # }) # # @example Response structure # # resp.user_id #=> String # resp.user_arn #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/CreateUser AWS API Documentation # # @overload create_user(params = {}) # @param [Hash] params ({}) def create_user(params = {}, options = {}) req = build_request(:create_user, params) req.send_request(options) end # Deletes a user account from Amazon Connect. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [required, String] :user_id # The unique identifier of the user to delete. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.delete_user({ # instance_id: "InstanceId", # required # user_id: "UserId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/DeleteUser AWS API Documentation # # @overload delete_user(params = {}) # @param [Hash] params ({}) def delete_user(params = {}, options = {}) req = build_request(:delete_user, params) req.send_request(options) end # Returns a `User` object that contains information about the user # account specified by the `UserId`. # # @option params [required, String] :user_id # Unique identifier for the user account to return. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Types::DescribeUserResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeUserResponse#user #user} => Types::User # # @example Request syntax with placeholder values # # resp = client.describe_user({ # user_id: "UserId", # required # instance_id: "InstanceId", # required # }) # # @example Response structure # # resp.user.id #=> String # resp.user.arn #=> String # resp.user.username #=> String # resp.user.identity_info.first_name #=> String # resp.user.identity_info.last_name #=> String # resp.user.identity_info.email #=> String # resp.user.phone_config.phone_type #=> String, one of "SOFT_PHONE", "DESK_PHONE" # resp.user.phone_config.auto_accept #=> Boolean # resp.user.phone_config.after_contact_work_time_limit #=> Integer # resp.user.phone_config.desk_phone_number #=> String # resp.user.directory_user_id #=> String # resp.user.security_profile_ids #=> Array # resp.user.security_profile_ids[0] #=> String # resp.user.routing_profile_id #=> String # resp.user.hierarchy_group_id #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/DescribeUser AWS API Documentation # # @overload describe_user(params = {}) # @param [Hash] params ({}) def describe_user(params = {}, options = {}) req = build_request(:describe_user, params) req.send_request(options) end # Returns a `HierarchyGroup` object that includes information about a # hierarchy group in your instance. # # @option params [required, String] :hierarchy_group_id # The identifier for the hierarchy group to return. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Types::DescribeUserHierarchyGroupResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeUserHierarchyGroupResponse#hierarchy_group #hierarchy_group} => Types::HierarchyGroup # # @example Request syntax with placeholder values # # resp = client.describe_user_hierarchy_group({ # hierarchy_group_id: "HierarchyGroupId", # required # instance_id: "InstanceId", # required # }) # # @example Response structure # # resp.hierarchy_group.id #=> String # resp.hierarchy_group.arn #=> String # resp.hierarchy_group.name #=> String # resp.hierarchy_group.level_id #=> String # resp.hierarchy_group.hierarchy_path.level_one.id #=> String # resp.hierarchy_group.hierarchy_path.level_one.arn #=> String # resp.hierarchy_group.hierarchy_path.level_one.name #=> String # resp.hierarchy_group.hierarchy_path.level_two.id #=> String # resp.hierarchy_group.hierarchy_path.level_two.arn #=> String # resp.hierarchy_group.hierarchy_path.level_two.name #=> String # resp.hierarchy_group.hierarchy_path.level_three.id #=> String # resp.hierarchy_group.hierarchy_path.level_three.arn #=> String # resp.hierarchy_group.hierarchy_path.level_three.name #=> String # resp.hierarchy_group.hierarchy_path.level_four.id #=> String # resp.hierarchy_group.hierarchy_path.level_four.arn #=> String # resp.hierarchy_group.hierarchy_path.level_four.name #=> String # resp.hierarchy_group.hierarchy_path.level_five.id #=> String # resp.hierarchy_group.hierarchy_path.level_five.arn #=> String # resp.hierarchy_group.hierarchy_path.level_five.name #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/DescribeUserHierarchyGroup AWS API Documentation # # @overload describe_user_hierarchy_group(params = {}) # @param [Hash] params ({}) def describe_user_hierarchy_group(params = {}, options = {}) req = build_request(:describe_user_hierarchy_group, params) req.send_request(options) end # Returns a `HiearchyGroupStructure` object, which contains data about # the levels in the agent hierarchy. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Types::DescribeUserHierarchyStructureResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeUserHierarchyStructureResponse#hierarchy_structure #hierarchy_structure} => Types::HierarchyStructure # # @example Request syntax with placeholder values # # resp = client.describe_user_hierarchy_structure({ # instance_id: "InstanceId", # required # }) # # @example Response structure # # resp.hierarchy_structure.level_one.id #=> String # resp.hierarchy_structure.level_one.arn #=> String # resp.hierarchy_structure.level_one.name #=> String # resp.hierarchy_structure.level_two.id #=> String # resp.hierarchy_structure.level_two.arn #=> String # resp.hierarchy_structure.level_two.name #=> String # resp.hierarchy_structure.level_three.id #=> String # resp.hierarchy_structure.level_three.arn #=> String # resp.hierarchy_structure.level_three.name #=> String # resp.hierarchy_structure.level_four.id #=> String # resp.hierarchy_structure.level_four.arn #=> String # resp.hierarchy_structure.level_four.name #=> String # resp.hierarchy_structure.level_five.id #=> String # resp.hierarchy_structure.level_five.arn #=> String # resp.hierarchy_structure.level_five.name #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/DescribeUserHierarchyStructure AWS API Documentation # # @overload describe_user_hierarchy_structure(params = {}) # @param [Hash] params ({}) def describe_user_hierarchy_structure(params = {}, options = {}) req = build_request(:describe_user_hierarchy_structure, params) req.send_request(options) end # Retrieves the contact attributes associated with a contact. # # @option params [required, String] :instance_id # The instance ID for the instance from which to retrieve contact # attributes. # # @option params [required, String] :initial_contact_id # The ID for the initial contact in Amazon Connect associated with the # attributes to update. # # @return [Types::GetContactAttributesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetContactAttributesResponse#attributes #attributes} => Hash&lt;String,String&gt; # # @example Request syntax with placeholder values # # resp = client.get_contact_attributes({ # instance_id: "InstanceId", # required # initial_contact_id: "ContactId", # required # }) # # @example Response structure # # resp.attributes #=> Hash # resp.attributes["AttributeName"] #=> <Hash,Array,String,Numeric,Boolean,IO,Set,nil> # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/GetContactAttributes AWS API Documentation # # @overload get_contact_attributes(params = {}) # @param [Hash] params ({}) def get_contact_attributes(params = {}, options = {}) req = build_request(:get_contact_attributes, params) req.send_request(options) end # The `GetCurrentMetricData` operation retrieves current metric data # from your Amazon Connect instance. # # If you are using an IAM account, it must have permission to the # `connect:GetCurrentMetricData` action. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [required, Types::Filters] :filters # A `Filters` object that contains a list of queue IDs or queue ARNs, up # to 100, or list of Channels to use to filter the metrics returned in # the response. Metric data is retrieved only for the resources # associated with the queue IDs, ARNs, or Channels included in the # filter. You can include both IDs and ARNs in the same request. To # retrieve metrics for all queues, add the queue ID or ARN for each # queue in your instance. Only VOICE is supported for Channels. # # To find the ARN for a queue, open the queue you want to use in the # Amazon Connect Queue editor. The ARN for the queue is displayed in the # address bar as part of the URL. For example, the queue ARN is the set # of characters at the end of the URL, after 'id=' such as # `arn:aws:connect:us-east-1:270923740243:instance/78fb859d-1b7d-44b1-8aa3-12f0835c5855/queue/1d1a4575-9618-40ab-bbeb-81e45795fe61`. # The queue ID is also included in the URL, and is the string after # 'queue/'. # # @option params [Array<String>] :groupings # The grouping applied to the metrics returned. For example, when # grouped by QUEUE, the metrics returned apply to each queue rather than # aggregated for all queues. If you group by CHANNEL, you should include # a Channels filter. The only supported channel is VOICE. # # If no `Grouping` is included in the request, a summary of # `CurrentMetrics` is returned. # # @option params [required, Array<Types::CurrentMetric>] :current_metrics # A list of `CurrentMetric` objects for the metrics to retrieve. Each # `CurrentMetric` includes a name of a metric to retrieve and the unit # to use for it. You must list each metric to retrieve data for in the # request. # # The following metrics are available: # # AGENTS\_AVAILABLE # # : Unit: COUNT # # AGENTS\_ONLINE # # : Unit: COUNT # # AGENTS\_ON\_CALL # # : Unit: COUNT # # AGENTS\_STAFFED # # : Unit: COUNT # # AGENTS\_AFTER\_CONTACT\_WORK # # : Unit: COUNT # # AGENTS\_NON\_PRODUCTIVE # # : Unit: COUNT # # AGENTS\_ERROR # # : Unit: COUNT # # CONTACTS\_IN\_QUEUE # # : Unit: COUNT # # OLDEST\_CONTACT\_AGE # # : Unit: SECONDS # # CONTACTS\_SCHEDULED # # : Unit: COUNT # # @option params [String] :next_token # The token for the next set of results. Use the value returned in the # previous response in the next request to retrieve the next set of # results. # # The token expires after 5 minutes from the time it is created. # Subsequent requests that use the [NextToken]() must use the same # request parameters as the request that generated the token. # # @option params [Integer] :max_results # `MaxResults` indicates the maximum number of results to return per # page in the response, between 1 and 100. # # @return [Types::GetCurrentMetricDataResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetCurrentMetricDataResponse#next_token #next_token} => String # * {Types::GetCurrentMetricDataResponse#metric_results #metric_results} => Array&lt;Types::CurrentMetricResult&gt; # * {Types::GetCurrentMetricDataResponse#data_snapshot_time #data_snapshot_time} => Time # # @example Request syntax with placeholder values # # resp = client.get_current_metric_data({ # instance_id: "InstanceId", # required # filters: { # required # queues: ["QueueId"], # channels: ["VOICE"], # accepts VOICE # }, # groupings: ["QUEUE"], # accepts QUEUE, CHANNEL # current_metrics: [ # required # { # name: "AGENTS_ONLINE", # accepts AGENTS_ONLINE, AGENTS_AVAILABLE, AGENTS_ON_CALL, AGENTS_NON_PRODUCTIVE, AGENTS_AFTER_CONTACT_WORK, AGENTS_ERROR, AGENTS_STAFFED, CONTACTS_IN_QUEUE, OLDEST_CONTACT_AGE, CONTACTS_SCHEDULED # unit: "SECONDS", # accepts SECONDS, COUNT, PERCENT # }, # ], # next_token: "NextToken", # max_results: 1, # }) # # @example Response structure # # resp.next_token #=> String # resp.metric_results #=> Array # resp.metric_results[0].dimensions.queue.id #=> String # resp.metric_results[0].dimensions.queue.arn #=> String # resp.metric_results[0].dimensions.channel #=> String, one of "VOICE" # resp.metric_results[0].collections #=> Array # resp.metric_results[0].collections[0].metric.name #=> String, one of "AGENTS_ONLINE", "AGENTS_AVAILABLE", "AGENTS_ON_CALL", "AGENTS_NON_PRODUCTIVE", "AGENTS_AFTER_CONTACT_WORK", "AGENTS_ERROR", "AGENTS_STAFFED", "CONTACTS_IN_QUEUE", "OLDEST_CONTACT_AGE", "CONTACTS_SCHEDULED" # resp.metric_results[0].collections[0].metric.unit #=> String, one of "SECONDS", "COUNT", "PERCENT" # resp.metric_results[0].collections[0].value #=> Float # resp.data_snapshot_time #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/GetCurrentMetricData AWS API Documentation # # @overload get_current_metric_data(params = {}) # @param [Hash] params ({}) def get_current_metric_data(params = {}, options = {}) req = build_request(:get_current_metric_data, params) req.send_request(options) end # Retrieves a token for federation. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Types::GetFederationTokenResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetFederationTokenResponse#credentials #credentials} => Types::Credentials # # @example Request syntax with placeholder values # # resp = client.get_federation_token({ # instance_id: "InstanceId", # required # }) # # @example Response structure # # resp.credentials.access_token #=> String # resp.credentials.access_token_expiration #=> Time # resp.credentials.refresh_token #=> String # resp.credentials.refresh_token_expiration #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/GetFederationToken AWS API Documentation # # @overload get_federation_token(params = {}) # @param [Hash] params ({}) def get_federation_token(params = {}, options = {}) req = build_request(:get_federation_token, params) req.send_request(options) end # The `GetMetricData` operation retrieves historical metrics data from # your Amazon Connect instance. # # If you are using an IAM account, it must have permission to the # `connect:GetMetricData` action. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [required, Time,DateTime,Date,Integer,String] :start_time # The timestamp, in UNIX Epoch time format, at which to start the # reporting interval for the retrieval of historical metrics data. The # time must be specified using a multiple of 5 minutes, such as 10:05, # 10:10, 10:15. # # `StartTime` cannot be earlier than 24 hours before the time of the # request. Historical metrics are available in Amazon Connect only for # 24 hours. # # @option params [required, Time,DateTime,Date,Integer,String] :end_time # The timestamp, in UNIX Epoch time format, at which to end the # reporting interval for the retrieval of historical metrics data. The # time must be specified using an interval of 5 minutes, such as 11:00, # 11:05, 11:10, and must be later than the `StartTime` timestamp. # # The time range between `StartTime` and `EndTime` must be less than 24 # hours. # # @option params [required, Types::Filters] :filters # A `Filters` object that contains a list of queue IDs or queue ARNs, up # to 100, or a list of Channels to use to filter the metrics returned in # the response. Metric data is retrieved only for the resources # associated with the IDs, ARNs, or Channels included in the filter. You # can use both IDs and ARNs together in a request. Only VOICE is # supported for Channel. # # To find the ARN for a queue, open the queue you want to use in the # Amazon Connect Queue editor. The ARN for the queue is displayed in the # address bar as part of the URL. For example, the queue ARN is the set # of characters at the end of the URL, after 'id=' such as # `arn:aws:connect:us-east-1:270923740243:instance/78fb859d-1b7d-44b1-8aa3-12f0835c5855/queue/1d1a4575-9618-40ab-bbeb-81e45795fe61`. # The queue ID is also included in the URL, and is the string after # 'queue/'. # # @option params [Array<String>] :groupings # The grouping applied to the metrics returned. For example, when # results are grouped by queueId, the metrics returned are grouped by # queue. The values returned apply to the metrics for each queue rather # than aggregated for all queues. # # The current version supports grouping by Queue # # If no `Grouping` is included in the request, a summary of # `HistoricalMetrics` for all queues is returned. # # @option params [required, Array<Types::HistoricalMetric>] :historical_metrics # A list of `HistoricalMetric` objects that contain the metrics to # retrieve with the request. # # A `HistoricalMetric` object contains: `HistoricalMetricName`, # `Statistic`, `Threshold`, and `Unit`. # # You must list each metric to retrieve data for in the request. For # each historical metric you include in the request, you must include a # `Unit` and a `Statistic`. # # The following historical metrics are available: # # CONTACTS\_QUEUED # # : Unit: COUNT # # Statistic: SUM # # CONTACTS\_HANDLED # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_ABANDONED # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_CONSULTED # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_AGENT\_HUNG\_UP\_FIRST # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_HANDLED\_INCOMING # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_HANDLED\_OUTBOUND # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_HOLD\_ABANDONS # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_TRANSFERRED\_IN # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_TRANSFERRED\_OUT # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_TRANSFERRED\_IN\_FROM\_QUEUE # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_TRANSFERRED\_OUT\_FROM\_QUEUE # # : Unit: COUNT # # Statistics: SUM # # CALLBACK\_CONTACTS\_HANDLED # # : Unit: COUNT # # Statistics: SUM # # CALLBACK\_CONTACTS\_HANDLED # # : Unit: COUNT # # Statistics: SUM # # API\_CONTACTS\_HANDLED # # : Unit: COUNT # # Statistics: SUM # # CONTACTS\_MISSED # # : Unit: COUNT # # Statistics: SUM # # OCCUPANCY # # : Unit: PERCENT # # Statistics: AVG # # HANDLE\_TIME # # : Unit: SECONDS # # Statistics: AVG # # AFTER\_CONTACT\_WORK\_TIME # # : Unit: SECONDS # # Statistics: AVG # # QUEUED\_TIME # # : Unit: SECONDS # # Statistics: MAX # # ABANDON\_TIME # # : Unit: COUNT # # Statistics: SUM # # QUEUE\_ANSWER\_TIME # # : Unit: SECONDS # # Statistics: AVG # # HOLD\_TIME # # : Unit: SECONDS # # Statistics: AVG # # INTERACTION\_TIME # # : Unit: SECONDS # # Statistics: AVG # # INTERACTION\_AND\_HOLD\_TIME # # : Unit: SECONDS # # Statistics: AVG # # SERVICE\_LEVEL # # : Unit: PERCENT # # Statistics: AVG # # Threshold: Only "Less than" comparisons are supported, with the # following service level thresholds: 15, 20, 25, 30, 45, 60, 90, 120, # 180, 240, 300, 600 # # @option params [String] :next_token # The token for the next set of results. Use the value returned in the # previous response in the next request to retrieve the next set of # results. # # @option params [Integer] :max_results # Indicates the maximum number of results to return per page in the # response, between 1-100. # # @return [Types::GetMetricDataResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetMetricDataResponse#next_token #next_token} => String # * {Types::GetMetricDataResponse#metric_results #metric_results} => Array&lt;Types::HistoricalMetricResult&gt; # # @example Request syntax with placeholder values # # resp = client.get_metric_data({ # instance_id: "InstanceId", # required # start_time: Time.now, # required # end_time: Time.now, # required # filters: { # required # queues: ["QueueId"], # channels: ["VOICE"], # accepts VOICE # }, # groupings: ["QUEUE"], # accepts QUEUE, CHANNEL # historical_metrics: [ # required # { # name: "CONTACTS_QUEUED", # accepts CONTACTS_QUEUED, CONTACTS_HANDLED, CONTACTS_ABANDONED, CONTACTS_CONSULTED, CONTACTS_AGENT_HUNG_UP_FIRST, CONTACTS_HANDLED_INCOMING, CONTACTS_HANDLED_OUTBOUND, CONTACTS_HOLD_ABANDONS, CONTACTS_TRANSFERRED_IN, CONTACTS_TRANSFERRED_OUT, CONTACTS_TRANSFERRED_IN_FROM_QUEUE, CONTACTS_TRANSFERRED_OUT_FROM_QUEUE, CONTACTS_MISSED, CALLBACK_CONTACTS_HANDLED, API_CONTACTS_HANDLED, OCCUPANCY, HANDLE_TIME, AFTER_CONTACT_WORK_TIME, QUEUED_TIME, ABANDON_TIME, QUEUE_ANSWER_TIME, HOLD_TIME, INTERACTION_TIME, INTERACTION_AND_HOLD_TIME, SERVICE_LEVEL # threshold: { # comparison: "LT", # accepts LT # threshold_value: 1.0, # }, # statistic: "SUM", # accepts SUM, MAX, AVG # unit: "SECONDS", # accepts SECONDS, COUNT, PERCENT # }, # ], # next_token: "NextToken", # max_results: 1, # }) # # @example Response structure # # resp.next_token #=> String # resp.metric_results #=> Array # resp.metric_results[0].dimensions.queue.id #=> String # resp.metric_results[0].dimensions.queue.arn #=> String # resp.metric_results[0].dimensions.channel #=> String, one of "VOICE" # resp.metric_results[0].collections #=> Array # resp.metric_results[0].collections[0].metric.name #=> String, one of "CONTACTS_QUEUED", "CONTACTS_HANDLED", "CONTACTS_ABANDONED", "CONTACTS_CONSULTED", "CONTACTS_AGENT_HUNG_UP_FIRST", "CONTACTS_HANDLED_INCOMING", "CONTACTS_HANDLED_OUTBOUND", "CONTACTS_HOLD_ABANDONS", "CONTACTS_TRANSFERRED_IN", "CONTACTS_TRANSFERRED_OUT", "CONTACTS_TRANSFERRED_IN_FROM_QUEUE", "CONTACTS_TRANSFERRED_OUT_FROM_QUEUE", "CONTACTS_MISSED", "CALLBACK_CONTACTS_HANDLED", "API_CONTACTS_HANDLED", "OCCUPANCY", "HANDLE_TIME", "AFTER_CONTACT_WORK_TIME", "QUEUED_TIME", "ABANDON_TIME", "QUEUE_ANSWER_TIME", "HOLD_TIME", "INTERACTION_TIME", "INTERACTION_AND_HOLD_TIME", "SERVICE_LEVEL" # resp.metric_results[0].collections[0].metric.threshold.comparison #=> String, one of "LT" # resp.metric_results[0].collections[0].metric.threshold.threshold_value #=> Float # resp.metric_results[0].collections[0].metric.statistic #=> String, one of "SUM", "MAX", "AVG" # resp.metric_results[0].collections[0].metric.unit #=> String, one of "SECONDS", "COUNT", "PERCENT" # resp.metric_results[0].collections[0].value #=> Float # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/GetMetricData AWS API Documentation # # @overload get_metric_data(params = {}) # @param [Hash] params ({}) def get_metric_data(params = {}, options = {}) req = build_request(:get_metric_data, params) req.send_request(options) end # Returns an array of `RoutingProfileSummary` objects that includes # information about the routing profiles in your instance. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [String] :next_token # The token for the next set of results. Use the value returned in the # previous response in the next request to retrieve the next set of # results. # # @option params [Integer] :max_results # The maximum number of routing profiles to return in the response. # # @return [Types::ListRoutingProfilesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListRoutingProfilesResponse#routing_profile_summary_list #routing_profile_summary_list} => Array&lt;Types::RoutingProfileSummary&gt; # * {Types::ListRoutingProfilesResponse#next_token #next_token} => String # # @example Request syntax with placeholder values # # resp = client.list_routing_profiles({ # instance_id: "InstanceId", # required # next_token: "NextToken", # max_results: 1, # }) # # @example Response structure # # resp.routing_profile_summary_list #=> Array # resp.routing_profile_summary_list[0].id #=> String # resp.routing_profile_summary_list[0].arn #=> String # resp.routing_profile_summary_list[0].name #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/ListRoutingProfiles AWS API Documentation # # @overload list_routing_profiles(params = {}) # @param [Hash] params ({}) def list_routing_profiles(params = {}, options = {}) req = build_request(:list_routing_profiles, params) req.send_request(options) end # Returns an array of SecurityProfileSummary objects that contain # information about the security profiles in your instance, including # the ARN, Id, and Name of the security profile. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [String] :next_token # The token for the next set of results. Use the value returned in the # previous response in the next request to retrieve the next set of # results. # # @option params [Integer] :max_results # The maximum number of security profiles to return. # # @return [Types::ListSecurityProfilesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListSecurityProfilesResponse#security_profile_summary_list #security_profile_summary_list} => Array&lt;Types::SecurityProfileSummary&gt; # * {Types::ListSecurityProfilesResponse#next_token #next_token} => String # # @example Request syntax with placeholder values # # resp = client.list_security_profiles({ # instance_id: "InstanceId", # required # next_token: "NextToken", # max_results: 1, # }) # # @example Response structure # # resp.security_profile_summary_list #=> Array # resp.security_profile_summary_list[0].id #=> String # resp.security_profile_summary_list[0].arn #=> String # resp.security_profile_summary_list[0].name #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/ListSecurityProfiles AWS API Documentation # # @overload list_security_profiles(params = {}) # @param [Hash] params ({}) def list_security_profiles(params = {}, options = {}) req = build_request(:list_security_profiles, params) req.send_request(options) end # Returns a `UserHierarchyGroupSummaryList`, which is an array of # `HierarchyGroupSummary` objects that contain information about the # hierarchy groups in your instance. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [String] :next_token # The token for the next set of results. Use the value returned in the # previous response in the next request to retrieve the next set of # results. # # @option params [Integer] :max_results # The maximum number of hierarchy groups to return. # # @return [Types::ListUserHierarchyGroupsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListUserHierarchyGroupsResponse#user_hierarchy_group_summary_list #user_hierarchy_group_summary_list} => Array&lt;Types::HierarchyGroupSummary&gt; # * {Types::ListUserHierarchyGroupsResponse#next_token #next_token} => String # # @example Request syntax with placeholder values # # resp = client.list_user_hierarchy_groups({ # instance_id: "InstanceId", # required # next_token: "NextToken", # max_results: 1, # }) # # @example Response structure # # resp.user_hierarchy_group_summary_list #=> Array # resp.user_hierarchy_group_summary_list[0].id #=> String # resp.user_hierarchy_group_summary_list[0].arn #=> String # resp.user_hierarchy_group_summary_list[0].name #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/ListUserHierarchyGroups AWS API Documentation # # @overload list_user_hierarchy_groups(params = {}) # @param [Hash] params ({}) def list_user_hierarchy_groups(params = {}, options = {}) req = build_request(:list_user_hierarchy_groups, params) req.send_request(options) end # Returns a `UserSummaryList`, which is an array of `UserSummary` # objects. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [String] :next_token # The token for the next set of results. Use the value returned in the # previous response in the next request to retrieve the next set of # results. # # @option params [Integer] :max_results # The maximum number of results to return in the response. # # @return [Types::ListUsersResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListUsersResponse#user_summary_list #user_summary_list} => Array&lt;Types::UserSummary&gt; # * {Types::ListUsersResponse#next_token #next_token} => String # # @example Request syntax with placeholder values # # resp = client.list_users({ # instance_id: "InstanceId", # required # next_token: "NextToken", # max_results: 1, # }) # # @example Response structure # # resp.user_summary_list #=> Array # resp.user_summary_list[0].id #=> String # resp.user_summary_list[0].arn #=> String # resp.user_summary_list[0].username #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/ListUsers AWS API Documentation # # @overload list_users(params = {}) # @param [Hash] params ({}) def list_users(params = {}, options = {}) req = build_request(:list_users, params) req.send_request(options) end # The `StartOutboundVoiceContact` operation initiates a contact flow to # place an outbound call to a customer. # # If you are using an IAM account, it must have permission to the # `connect:StartOutboundVoiceContact` action. # # There is a 60 second dialing timeout for this operation. If the call # is not connected after 60 seconds, the call fails. # # @option params [required, String] :destination_phone_number # The phone number of the customer in E.164 format. # # @option params [required, String] :contact_flow_id # The identifier for the contact flow to connect the outbound call to. # # To find the `ContactFlowId`, open the contact flow you want to use in # the Amazon Connect contact flow editor. The ID for the contact flow is # displayed in the address bar as part of the URL. For example, the # contact flow ID is the set of characters at the end of the URL, after # 'contact-flow/' such as `78ea8fd5-2659-4f2b-b528-699760ccfc1b`. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [String] :client_token # A unique, case-sensitive identifier that you provide to ensure the # idempotency of the request. The token is valid for 7 days after # creation. If a contact is already started, the contact ID is returned. # If the contact is disconnected, a new contact is started. # # **A suitable default value is auto-generated.** You should normally # not need to pass this option.** # # @option params [String] :source_phone_number # The phone number, in E.164 format, associated with your Amazon Connect # instance to use for the outbound call. # # @option params [String] :queue_id # The queue to add the call to. If you specify a queue, the phone # displayed for caller ID is the phone number specified in the queue. If # you do not specify a queue, the queue used will be the queue defined # in the contact flow. # # To find the `QueueId`, open the queue you want to use in the Amazon # Connect Queue editor. The ID for the queue is displayed in the address # bar as part of the URL. For example, the queue ID is the set of # characters at the end of the URL, after 'queue/' such as # `queue/aeg40574-2d01-51c3-73d6-bf8624d2168c`. # # @option params [Hash<String,String>] :attributes # Specify a custom key-value pair using an attribute map. The attributes # are standard Amazon Connect attributes, and can be accessed in contact # flows just like any other contact attributes. # # There can be up to 32,768 UTF-8 bytes across all key-value pairs per # contact. Attribute keys can include only alphanumeric, dash, and # underscore characters. # # For example, if you want play a greeting when the customer answers the # call, you can pass the customer name in attributes similar to the # following: # # @return [Types::StartOutboundVoiceContactResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::StartOutboundVoiceContactResponse#contact_id #contact_id} => String # # @example Request syntax with placeholder values # # resp = client.start_outbound_voice_contact({ # destination_phone_number: "PhoneNumber", # required # contact_flow_id: "ContactFlowId", # required # instance_id: "InstanceId", # required # client_token: "ClientToken", # source_phone_number: "PhoneNumber", # queue_id: "QueueId", # attributes: { # "AttributeName" => "AttributeValue", # }, # }) # # @example Response structure # # resp.contact_id #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/StartOutboundVoiceContact AWS API Documentation # # @overload start_outbound_voice_contact(params = {}) # @param [Hash] params ({}) def start_outbound_voice_contact(params = {}, options = {}) req = build_request(:start_outbound_voice_contact, params) req.send_request(options) end # Ends the contact initiated by the `StartOutboundVoiceContact` # operation. # # If you are using an IAM account, it must have permission to the # `connect:StopContact` action. # # @option params [required, String] :contact_id # The unique identifier of the contact to end. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.stop_contact({ # contact_id: "ContactId", # required # instance_id: "InstanceId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/StopContact AWS API Documentation # # @overload stop_contact(params = {}) # @param [Hash] params ({}) def stop_contact(params = {}, options = {}) req = build_request(:stop_contact, params) req.send_request(options) end # The `UpdateContactAttributes` operation lets you programmatically # create new, or update existing, contact attributes associated with a # contact. You can use the operation to add or update attributes for # both ongoing and completed contacts. For example, you can update the # customer's name or the reason the customer called while the call is # active, or add notes about steps that the agent took during the call # that are displayed to the next agent that takes the call. You can also # use the `UpdateContactAttributes` operation to update attributes for a # contact using data from your CRM application and save the data with # the contact in Amazon Connect. You could also flag calls for # additional analysis, such as legal review or identifying abusive # callers. # # Contact attributes are available in Amazon Connect for 24 months, and # are then deleted. # # *Important:* # # You cannot use the operation to update attributes for contacts that # occurred prior to the release of the API, September 12, 2018. You can # update attributes only for contacts that started after the release of # the API. If you attempt to update attributes for a contact that # occurred prior to the release of the API, a 400 error is returned. # This applies also to queued callbacks that were initiated prior to the # release of the API but are still active in your instance. # # @option params [required, String] :initial_contact_id # The unique identifier of the contact for which to update attributes. # This is the identifier for the contact associated with the first # interaction with the contact center. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @option params [required, Hash<String,String>] :attributes # Specify a custom key-value pair using an attribute map. The attributes # are standard Amazon Connect attributes, and can be accessed in contact # flows just like any other contact attributes. # # There can be up to 32,768 UTF-8 bytes across all key-value pairs per # contact. Attribute keys can include only alphanumeric, dash, and # underscore characters. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_contact_attributes({ # initial_contact_id: "ContactId", # required # instance_id: "InstanceId", # required # attributes: { # required # "AttributeName" => "AttributeValue", # }, # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/UpdateContactAttributes AWS API Documentation # # @overload update_contact_attributes(params = {}) # @param [Hash] params ({}) def update_contact_attributes(params = {}, options = {}) req = build_request(:update_contact_attributes, params) req.send_request(options) end # Assigns the specified hierarchy group to the user. # # @option params [String] :hierarchy_group_id # The identifier for the hierarchy group to assign to the user. # # @option params [required, String] :user_id # The identifier of the user account to assign the hierarchy group to. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_user_hierarchy({ # hierarchy_group_id: "HierarchyGroupId", # user_id: "UserId", # required # instance_id: "InstanceId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/UpdateUserHierarchy AWS API Documentation # # @overload update_user_hierarchy(params = {}) # @param [Hash] params ({}) def update_user_hierarchy(params = {}, options = {}) req = build_request(:update_user_hierarchy, params) req.send_request(options) end # Updates the identity information for the specified user in a # `UserIdentityInfo` object, including email, first name, and last name. # # @option params [required, Types::UserIdentityInfo] :identity_info # A `UserIdentityInfo` object. # # @option params [required, String] :user_id # The identifier for the user account to update identity information # for. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_user_identity_info({ # identity_info: { # required # first_name: "AgentFirstName", # last_name: "AgentLastName", # email: "Email", # }, # user_id: "UserId", # required # instance_id: "InstanceId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/UpdateUserIdentityInfo AWS API Documentation # # @overload update_user_identity_info(params = {}) # @param [Hash] params ({}) def update_user_identity_info(params = {}, options = {}) req = build_request(:update_user_identity_info, params) req.send_request(options) end # Updates the phone configuration settings in the `UserPhoneConfig` # object for the specified user. # # @option params [required, Types::UserPhoneConfig] :phone_config # A `UserPhoneConfig` object that contains settings for # `AfterContactWorkTimeLimit`, `AutoAccept`, `DeskPhoneNumber`, and # `PhoneType` to assign to the user. # # @option params [required, String] :user_id # The identifier for the user account to change phone settings for. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_user_phone_config({ # phone_config: { # required # phone_type: "SOFT_PHONE", # required, accepts SOFT_PHONE, DESK_PHONE # auto_accept: false, # after_contact_work_time_limit: 1, # desk_phone_number: "PhoneNumber", # }, # user_id: "UserId", # required # instance_id: "InstanceId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/UpdateUserPhoneConfig AWS API Documentation # # @overload update_user_phone_config(params = {}) # @param [Hash] params ({}) def update_user_phone_config(params = {}, options = {}) req = build_request(:update_user_phone_config, params) req.send_request(options) end # Assigns the specified routing profile to a user. # # @option params [required, String] :routing_profile_id # The identifier of the routing profile to assign to the user. # # @option params [required, String] :user_id # The identifier for the user account to assign the routing profile to. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_user_routing_profile({ # routing_profile_id: "RoutingProfileId", # required # user_id: "UserId", # required # instance_id: "InstanceId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/UpdateUserRoutingProfile AWS API Documentation # # @overload update_user_routing_profile(params = {}) # @param [Hash] params ({}) def update_user_routing_profile(params = {}, options = {}) req = build_request(:update_user_routing_profile, params) req.send_request(options) end # Updates the security profiles assigned to the user. # # @option params [required, Array<String>] :security_profile_ids # The identifiers for the security profiles to assign to the user. # # @option params [required, String] :user_id # The identifier of the user account to assign the security profiles. # # @option params [required, String] :instance_id # The identifier for your Amazon Connect instance. To find the ID of # your instance, open the AWS console and select Amazon Connect. Select # the alias of the instance in the Instance alias column. The instance # ID is displayed in the Overview section of your instance settings. For # example, the instance ID is the set of characters at the end of the # instance ARN, after instance/, such as # 10a4c4eb-f57e-4d4c-b602-bf39176ced07. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_user_security_profiles({ # security_profile_ids: ["SecurityProfileId"], # required # user_id: "UserId", # required # instance_id: "InstanceId", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/UpdateUserSecurityProfiles AWS API Documentation # # @overload update_user_security_profiles(params = {}) # @param [Hash] params ({}) def update_user_security_profiles(params = {}, options = {}) req = build_request(:update_user_security_profiles, params) req.send_request(options) end # @!endgroup # @param params ({}) # @api private def build_request(operation_name, params = {}) handlers = @handlers.for(operation_name) context = Seahorse::Client::RequestContext.new( operation_name: operation_name, operation: config.api.operation(operation_name), client: self, params: params, config: config) context[:gem_name] = 'aws-sdk-connect' context[:gem_version] = '1.13.0' Seahorse::Client::Request.new(handlers, context) end # @api private # @deprecated def waiter_names [] end class << self # @api private attr_reader :identifier # @api private def errors_module Errors end end end end
43.261919
664
0.667927
b9fe6055568e4e829a400c9e7ae5d54871c64147
835
# frozen_string_literal: true require 'apia/dsl' require 'apia/helpers' require 'apia/errors/scope_not_granted_error' module Apia module DSLs class Authenticator < DSL def type(type) @definition.type = type end def potential_error(klass, &block) if block_given? && klass.is_a?(String) id = "#{@definition.id}/#{Helpers.camelize(klass)}" klass = Apia::Error.create(id, &block) end @definition.potential_errors << klass end def action(&block) @definition.action = block end def scope_validator(&block) unless @definition.potential_errors.include?(Apia::ScopeNotGrantedError) potential_error Apia::ScopeNotGrantedError end @definition.scope_validator = block end end end end
21.410256
80
0.637126
5d9f7f87f43a4d653ea83cb0eeb66d3420d6b431
1,106
class SalesInvoice < ActiveRecord::Base before_create :update_sequences ## CONSTANTS ## SEQUENCE_TYPE = 'LI' def self.create_invoice(provider_id, provider_type, order_id, item_qty, net_amount) invoice = self.where(:provider_id => provider_id.to_i,:provider_type => provider_type, :order_id => order_id).first_or_initialize invoice.invoice_number = "#{SalesInvoice::SEQUENCE_TYPE}#{order_id}" + generate_invoice_number.to_s.rjust(8,'0') invoice.invoice_date = Time.now invoice.item_qty = item_qty invoice.net_amount = net_amount if invoice.new_record? invoice.save else invoice.touch end end private def update_sequences seq = Sequence.find_or_initialize_by(:seq_type => SEQUENCE_TYPE) seq_number = seq.seq_number.present? ? seq.seq_number : 0 seq.update_attributes(:seq_number => seq_number + 1) end def self.generate_invoice_number sequence = Sequence.where(:seq_type => LabOrder::SEQUENCE_TYPE).first last_transaction_number = sequence.present? ? (sequence.seq_number + 1) : 1 last_transaction_number end end
30.722222
133
0.73689
79837e3d4579bf48b021a11a206e19717c049d34
283
class Oca::FileConverter def initialize(options = {}) @name = options[:name] @content = options[:content] @format = options[:format] || 'pdf' end def convert File.open("#{@name}.#{@format}", 'wb') { |file| file.write(Base64.decode64(@content)) } end end
23.583333
91
0.607774
210b1679a07bbd65fccff1f583ea862ee7960fcb
885
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require_relative '../../api600/synergy/logical_enclosure' module OneviewSDK module API800 module Synergy # Logical Enclosure resource implementation on API800 Synergy class LogicalEnclosure < OneviewSDK::API600::Synergy::LogicalEnclosure end end end end
38.478261
85
0.767232
7a58fe920bc0d7255bd56dc4539c9f1293ad64b1
31
module UsersSessionsHelper end
10.333333
26
0.903226
28431e93da2155ceeb313c50e0b1a571c873f0d7
5,278
################################################################################ # (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ require 'spec_helper' require_relative '../../support/fake_response' require_relative '../../shared_context' provider_class = Puppet::Type.type(:oneview_logical_interconnect_group).provider(:c7000) api_version = login[:api_version] || 200 resource_type ||= OneviewSDK.resource_named(:LogicalInterconnectGroup, api_version, :C7000) ethtype ||= OneviewSDK.resource_named(:EthernetNetwork, api_version, :C7000) interconnect_type ||= OneviewSDK.resource_named(:Interconnect, api_version, :C7000) describe provider_class, unit: true do include_context 'shared context' let(:resource) do Puppet::Type.type(:oneview_logical_interconnect_group).new( name: 'LIG', ensure: 'present', data: { 'name' => 'PUPPET_TEST_LIG', 'type' => 'logical-interconnect-groupV300', 'enclosureType' => 'C7000', 'state' => 'Active' }, provider: 'c7000' ) end let(:provider) { resource.provider } let(:instance) { provider.class.instances.first } let(:test) { resource_type.new(@client, resource['data']) } context 'given the min parameters' do before(:each) do allow(resource_type).to receive(:find_by).and_return([test]) provider.exists? end it 'should be an instance of the provider c7000' do expect(provider).to be_an_instance_of Puppet::Type.type(:oneview_logical_interconnect_group).provider(:c7000) end it 'return false when the resource does not exists' do allow(resource_type).to receive(:find_by).and_return([]) expect(provider.exists?).to eq(false) end it 'should be able to get the default settings' do provider.exists? allow(resource_type).to receive(:get_default_settings).and_return('Test') expect(provider.get_default_settings).to be end it 'should be able to get the settings' do allow_any_instance_of(resource_type).to receive(:get_settings).and_return('Test') expect(provider.get_settings).to be end it 'should be able to find the resource' do expect(provider.found).to be end it 'deletes the resource' do expect_any_instance_of(resource_type).to receive(:delete).and_return([]) expect(provider.destroy).to be end end context 'given the #uplink sets and interconnects parameters' do let(:resource) do Puppet::Type.type(:oneview_logical_interconnect_group).new( name: 'LIG', ensure: 'present', data: { 'name' => 'PUPPET_TEST_LIG', 'type' => 'logical-interconnect-groupV300', 'enclosureType' => 'C7000', 'state' => 'Active', 'uplinkSets' => [ { 'name' => 'TUNNEL_ETH_UP_01', 'ethernetNetworkType' => 'Tunnel', 'networkType' => 'Ethernet', 'lacpTimer' => 'Short', 'mode' => 'Auto', 'uplink_ports' => [{ 'bay' => 1, 'port' => 'X5' }, { 'bay' => 1, 'port' => 'X6' }, { 'bay' => 2, 'port' => 'X7' }, { 'bay' => 2, 'port' => 'X8' }], 'networkUris' => [ { name: 'test_network' } ] } ], 'interconnects' => [ { 'bay' => 1, 'type' => 'HP VC FlexFabric 10Gb/24-Port Module' }, { 'bay' => 2, 'type' => 'HP VC FlexFabric 10Gb/24-Port Module' } ], 'internalNetworkUris' => ['test'] }, provider: 'c7000' ) end before(:each) do allow(resource_type).to receive(:find_by).and_return([test]) allow(ethtype).to receive(:find_by).and_return([ethtype.new(@client, name: 'fake_eth', uri: '/rest/fake_uri')]) allow(interconnect_type).to receive(:get_type).and_return('uri' => '/fake/interconnect_type_uri') provider.exists? end it 'runs through the create method' do allow(resource_type).to receive(:find_by).and_return([]) allow_any_instance_of(resource_type).to receive(:create).and_return(test) provider.exists? expect(provider.create).to be end end end
36.4
117
0.565555
625dc757c491cbdc635fbf7b1e775659cf84afd8
894
# # Configuration object for storing some parameters required for making transactions # module Dagjeweg::Config class << self # @return [String] Your Dagjeweg API Key # @note The is a required parameter. attr_accessor :api_key # Set's the default value's to nil and false # @return [Hash] configuration options def init! @defaults = { :@api_key => nil, } end # Resets the value's to there previous value (instance_variable) # @return [Hash] configuration options def reset! @defaults.each { |key, value| instance_variable_set(key, value) } end # Set's the new value's as instance variables # @return [Hash] configuration options def update! @defaults.each do |key, value| instance_variable_set(key, value) unless instance_variable_defined?(key) end end end init! reset! end
24.833333
83
0.661074
62a4430138884745333865db8483efef003e7e66
712
# -*- coding: binary -*- require 'msf/core' module Msf::Payload::Python # # Encode the given python command in base64 and wrap it with a stub # that will decode and execute it on the fly. The code will be condensed to # one line and compatible with all Python versions supported by the Python # Meterpreter stage. # # @param cmd [String] The python code to execute. # @return [String] Full python stub to execute the command. # def py_create_exec_stub(cmd) # Base64 encoding is required in order to handle Python's formatting b64_stub = "exec(__import__('base64').b64decode(__import__('codecs').getencoder('utf-8')('#{Rex::Text.encode_base64(cmd)}')[0]))" b64_stub end end
29.666667
133
0.706461
5d66cf70ad19a2a7ef1769df88639b51a3f1556c
182
require_relative 'observer_set_shared' module Concurrent module Collection RSpec.describe CopyOnNotifyObserverSet do it_behaves_like 'an observer set' end end end
18.2
45
0.78022
f8b210fe637e826edefed5c64a88ebdfe8b189c4
770
Rails.application.routes.draw do get 'password_resets/new' get 'password_resets/edit' root 'static_pages#home' get '/help', to: 'static_pages#help' get '/about', to: 'static_pages#about' get '/contact', to: 'static_pages#contact' get '/signup', to: 'users#new' post '/signup', to: 'users#create' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' resources :users do member do get :following, :followers end end resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :microposts, only: [:create, :destroy] resources :relationships, only: [:create, :destroy] end
33.478261
67
0.653247
8764e3a3c88ccdb6ee27c74d55bfa84289e74310
3,622
class User < ApplicationRecord has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower has_many :microposts, dependent: :destroy attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true # Returns the hash digest of the given string. def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # Returns a random token. def User.new_token SecureRandom.urlsafe_base64 end # Remembers a user in the database for use in persistent sessions. def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # Returns true if the given token matches the digest. def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end # Forgets a user. def forget update_attribute(:remember_digest, nil) end # Activates an account. def activate update_attribute(:activated, true) update_attribute(:activated_at, Time.zone.now) end # Sends activation email. def send_activation_email UserMailer.account_activation(self).deliver_now end # Sets the password reset attributes. def create_reset_digest self.reset_token = User.new_token update_columns(:reset_digest, User.digest(reset_token)) update_columns(:reset_sent_at, Time.zone.now) end # Sends password reset email. def send_password_reset_email UserMailer.password_reset(self).deliver_now end # Returns true if a password reset has expired. def password_reset_expired? reset_sent_at < 2.hours.ago end # Returns a user's status feed. def feed following_ids = "SELECT followed_id FROM relationships WHERE follower_id = :user_id" Micropost.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id) end # Follows a user. def follow(other_user) following << other_user end # Unfollows a user. def unfollow(other_user) following.delete(other_user) end # Returns true if the current user is following the other user. def following?(other_user) following.include?(other_user) end private # Converts email to all lower-case. def downcase_email self.email = email.downcase end # Creates and assigns the activation token and digest. def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
29.933884
78
0.680011
5d80523bcdacd81b89420efa2cd2cffbe973bb51
62
class Passport < ActiveRecord::Base belongs_to :company end
15.5
35
0.790323
187b365f41a9be96a10c14bfd13514d1995ad7df
806
# encoding: utf-8 $:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'apitome/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'apitome' s.version = Apitome::VERSION s.authors = ['jejacks0n'] s.email = ['[email protected]'] s.homepage = 'https://github.com/modeset/apitome' s.summary = 'Apitome: /iˈpitəmē/ An API documentation reader RSpec API Documentation' s.description = 'API documentation renderer for Rails using RSpec API Documentation JSON output' s.files = Dir['{app,config,lib,vendor}/**/*'] + ['MIT.LICENSE', 'README.md'] s.test_files = Dir['{spec}/**/*'] s.add_dependency 'railties', ['>= 3.2.5', '< 7'] s.add_dependency 'rspec_api_documentation' end
35.043478
98
0.663772
ed16cb0ad2c907087afeb67a3484df5126f32915
126
FactoryBot.define do factory :user do nickname { 'MyString' } email { 'MyString' } uid { 'MyString' } end end
15.75
27
0.611111
91cb4834668acc28034db2244f35e83ad2172009
1,933
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ContainerRegistry::Mgmt::V2017_10_01 module Models # # A request to check whether a container registry name is available. # class RegistryNameCheckRequest include MsRestAzure # @return [String] The name of the container registry. attr_accessor :name # @return [String] The resource type of the container registry. This # field must be set to 'Microsoft.ContainerRegistry/registries'. Default # value: 'Microsoft.ContainerRegistry/registries' . attr_accessor :type # # Mapper for RegistryNameCheckRequest class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'RegistryNameCheckRequest', type: { name: 'Composite', class_name: 'RegistryNameCheckRequest', model_properties: { name: { client_side_validation: true, required: true, serialized_name: 'name', constraints: { MaxLength: 50, MinLength: 5, Pattern: '^[a-zA-Z0-9]*$' }, type: { name: 'String' } }, type: { client_side_validation: true, required: true, is_constant: true, serialized_name: 'type', default_value: 'Microsoft.ContainerRegistry/registries', type: { name: 'String' } } } } } end end end end
28.850746
78
0.533885
2807beb85e8ba00f6a0e231b8b7f8659841c4879
8,381
=begin PureCloud Platform API With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more. OpenAPI spec version: v2 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git License: UNLICENSED https://help.mypurecloud.com/articles/terms-and-conditions/ Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/ =end require 'date' module PureCloud # Activity Code class CreateActivityCodeRequest # The name of the activity code attr_accessor :name # The activity code's category attr_accessor :category # The default length of the activity in minutes attr_accessor :length_in_minutes # Whether an agent is paid while performing this activity attr_accessor :counts_as_paid_time # Indicates whether or not the activity should be counted as work time attr_accessor :counts_as_work_time # Whether an agent can select this activity code when creating or editing a time off request attr_accessor :agent_time_off_selectable # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'name' => :'name', :'category' => :'category', :'length_in_minutes' => :'lengthInMinutes', :'counts_as_paid_time' => :'countsAsPaidTime', :'counts_as_work_time' => :'countsAsWorkTime', :'agent_time_off_selectable' => :'agentTimeOffSelectable' } end # Attribute type mapping. def self.swagger_types { :'name' => :'String', :'category' => :'String', :'length_in_minutes' => :'Integer', :'counts_as_paid_time' => :'BOOLEAN', :'counts_as_work_time' => :'BOOLEAN', :'agent_time_off_selectable' => :'BOOLEAN' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'name') self.name = attributes[:'name'] end if attributes.has_key?(:'category') self.category = attributes[:'category'] end if attributes.has_key?(:'lengthInMinutes') self.length_in_minutes = attributes[:'lengthInMinutes'] end if attributes.has_key?(:'countsAsPaidTime') self.counts_as_paid_time = attributes[:'countsAsPaidTime'] end if attributes.has_key?(:'countsAsWorkTime') self.counts_as_work_time = attributes[:'countsAsWorkTime'] end if attributes.has_key?(:'agentTimeOffSelectable') self.agent_time_off_selectable = attributes[:'agentTimeOffSelectable'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? if @name.nil? return false end if @category.nil? return false end allowed_values = ["OnQueueWork", "Break", "Meal", "Meeting", "OffQueueWork", "TimeOff", "Training", "Unavailable", "Unscheduled"] if @category && !allowed_values.include?(@category) return false end end # Custom attribute writer method checking allowed values (enum). # @param [Object] category Object to be assigned def category=(category) allowed_values = ["OnQueueWork", "Break", "Meal", "Meeting", "OffQueueWork", "TimeOff", "Training", "Unavailable", "Unscheduled"] if category && !allowed_values.include?(category) fail ArgumentError, "invalid value for 'category', must be one of #{allowed_values}." end @category = category end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && name == o.name && category == o.category && length_in_minutes == o.length_in_minutes && counts_as_paid_time == o.counts_as_paid_time && counts_as_work_time == o.counts_as_work_time && agent_time_off_selectable == o.agent_time_off_selectable end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [name, category, length_in_minutes, counts_as_paid_time, counts_as_work_time, agent_time_off_selectable].hash end # build the object from hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) else #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) else # data not found in attributes(hash), not an issue as the data can be optional end end self end def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /^(true|t|yes|y|1)$/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model _model = Object.const_get("PureCloud").const_get(type).new _model.build_from_hash(value) end end def to_s to_hash.to_s end # to_body is an alias to to_body (backward compatibility)) def to_body to_hash end # return the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Method to output non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
23.410615
177
0.579167
015cd15c414b6da939aaedc9ba9f8a4e543fdada
5,833
# frozen_string_literal: true # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'test_help' class TestProtocol < Test::Unit::TestCase class ExampleProtocol attr_reader :protocol_string, :valid, :name attr_accessor :comment def initialize(protocol_string, name=nil, comment='') @protocol_string = protocol_string @name = name || protocol_string # default to schema_string for name @comment = comment end end # # Example Protocols # EXAMPLES = [ ExampleProtocol.new(<<-EOS, true), { "namespace": "com.acme", "protocol": "HelloWorld", "types": [ {"name": "Greeting", "type": "record", "fields": [ {"name": "message", "type": "string"}]}, {"name": "Curse", "type": "error", "fields": [ {"name": "message", "type": "string"}]} ], "messages": { "hello": { "request": [{"name": "greeting", "type": "Greeting" }], "response": "Greeting", "errors": ["Curse"] } } } EOS ExampleProtocol.new(<<-EOS, true), {"namespace": "org.apache.aingle.test", "protocol": "Simple", "types": [ {"name": "Kind", "type": "enum", "symbols": ["FOO","BAR","BAZ"]}, {"name": "MD5", "type": "fixed", "size": 16}, {"name": "TestRecord", "type": "record", "fields": [ {"name": "name", "type": "string", "order": "ignore"}, {"name": "kind", "type": "Kind", "order": "descending"}, {"name": "hash", "type": "MD5"} ] }, {"name": "TestError", "type": "error", "fields": [ {"name": "message", "type": "string"} ] } ], "messages": { "hello": { "request": [{"name": "greeting", "type": "string"}], "response": "string" }, "echo": { "request": [{"name": "record", "type": "TestRecord"}], "response": "TestRecord" }, "add": { "request": [{"name": "arg1", "type": "int"}, {"name": "arg2", "type": "int"}], "response": "int" }, "echoBytes": { "request": [{"name": "data", "type": "bytes"}], "response": "bytes" }, "error": { "request": [], "response": "null", "errors": ["TestError"] } } } EOS ExampleProtocol.new(<<-EOS, true), {"namespace": "org.apache.aingle.test.namespace", "protocol": "TestNamespace", "types": [ {"name": "org.apache.aingle.test.util.MD5", "type": "fixed", "size": 16}, {"name": "TestRecord", "type": "record", "fields": [ {"name": "hash", "type": "org.apache.aingle.test.util.MD5"} ] }, {"name": "TestError", "namespace": "org.apache.aingle.test.errors", "type": "error", "fields": [ {"name": "message", "type": "string"} ] } ], "messages": { "echo": { "request": [{"name": "record", "type": "TestRecord"}], "response": "TestRecord" }, "error": { "request": [], "response": "null", "errors": ["org.apache.aingle.test.errors.TestError"] } } } EOS ExampleProtocol.new(<<-EOS, true), {"namespace": "org.apache.aingle.test", "protocol": "BulkData", "types": [], "messages": { "read": { "request": [], "response": "bytes" }, "write": { "request": [ {"name": "data", "type": "bytes"} ], "response": "null" } } } EOS ExampleProtocol.new(<<-EOS, true), { "namespace": "com.acme", "protocol": "HelloWorld", "doc": "protocol_documentation", "types": [ {"name": "Greeting", "type": "record", "fields": [ {"name": "message", "type": "string"}]}, {"name": "Curse", "type": "error", "fields": [ {"name": "message", "type": "string"}]} ], "messages": { "hello": { "doc": "message_documentation", "request": [{"name": "greeting", "type": "Greeting" }], "response": "Greeting", "errors": ["Curse"] } } } EOS ].freeze Protocol = AIngle::Protocol def test_parse EXAMPLES.each do |example| assert_nothing_raised("should be valid: #{example.protocol_string}") { Protocol.parse(example.protocol_string) } end end def test_valid_cast_to_string_after_parse EXAMPLES.each do |example| assert_nothing_raised("round tripped okay #{example.protocol_string}") { foo = Protocol.parse(example.protocol_string).to_s Protocol.parse(foo) } end end def test_equivalence_after_round_trip EXAMPLES.each do |example| original = Protocol.parse(example.protocol_string) round_trip = Protocol.parse(original.to_s) assert_equal original, round_trip end end def test_namespaces protocol = Protocol.parse(EXAMPLES.first.protocol_string) protocol.types.each do |type| assert_equal type.namespace, 'com.acme' end end def test_protocol_doc_attribute original = Protocol.parse(EXAMPLES.last.protocol_string) assert_equal 'protocol_documentation', original.doc end def test_protocol_message_doc_attribute original = Protocol.parse(EXAMPLES.last.protocol_string) assert_equal 'message_documentation', original.messages['hello'].doc end end
24.92735
87
0.584776
ffc84b5f251453d998b6b939c01d009e19fb7eb9
624
require 'byebug' require 'JSON' def eliminate_red_hashes(data) return if data.is_a?(String) || data.is_a?(Fixnum) if data.is_a?(Hash) && (data.keys.include?('red') || data.values.include?('red')) sum = data.to_s.scan(/-?\d+/).inject(0) { |sum, num| sum += num.to_i } add_to_subtractor(sum) return end data.each do |datum| eliminate_red_hashes(datum) end end @subtractor = 0 def add_to_subtractor(sum) @subtractor += sum end file_str = File.open('12_input.json').read eliminate_red_hashes(JSON.parse file_str) puts file_str.scan(/-?\d+/).inject(0) { |sum, num| sum += num.to_i } - @subtractor
24.96
83
0.676282
b9b8acc7937691a0f03b5744058541eb4a5bc5aa
1,368
# frozen_string_literal: true require_relative "lib/matchable/version" Gem::Specification.new do |spec| spec.name = "matchable" spec.version = Matchable::VERSION spec.authors = ["Brandon Weaver"] spec.email = ["[email protected]"] spec.summary = "Pattern Matching interfaces for Ruby classes" spec.homepage = "https://www.github.com/baweaver/matchable" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 3.0.0") spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage spec.metadata["changelog_uri"] = "#{spec.homepage}/CHANGELOG.md" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] # Uncomment to register a new dependency of your gem # spec.add_dependency "example-gem", "~> 1.0" # For more information and examples about making a new gem, checkout our # guide at: https://bundler.io/guides/creating_gem.html end
39.085714
88
0.677632
e862e89f703ed288a5e65e63f62b28267cbf3a2e
1,362
# frozen_string_literal: true require "git" require "uri" require "open-uri" require "zip" require "fileutils" OFile = File def download_method(str) case OFile.extname(URI(str).path) when ".git", "git" "git" when ".zip", "zip" "zip" else return "git" if str.include?("github") || str.include?("gitlab") "web" end end module Geode module File def self.download(url, file_name: false, **kws) path = kws.fetch :path, "./" ofile = !file_name file_name ||= URI(url).path.match(%r{[^/\\]+$}).to_s file = OFile.join(path, file_name) case download_method url when "zip" zip_path = "#{path}/#{+OFile.basename(file, OFile.extname(file))}" FileUtils.mkpath zip_path unless OFile.exists? zip_path Zip::File.open_buffer open(url) do |zip| zip.each do |e| epath = OFile.join zip_path, e.name e.extract epath unless OFile.exists? epath end end OFile.rename zip_path.to_s, "#{path}/#{+OFile.basename(file, ".zip")}" unless ofile when "web" FileUtils.mkpath path unless OFile.exists? path open file.to_s, "w" do |of| IO.copy_stream URI.open(url.strip), of end when "git" Git.clone url, OFile.basename(file, ".git"), recursive: true, **kws end end end end
25.222222
91
0.598385
1848cfac2b2ad1a8a82cd90d97de24f92040001a
242
class Listing < ActiveRecord::Base validates :title, presence: true belongs_to :user # validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ } has_many :features, dependent: :destroy has_many :pictures, dependent: :destroy end
30.25
68
0.681818
3806d20b7ee671213d9230623235790f79dd93d9
17,557
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'seahorse/client/plugins/content_length.rb' require 'aws-sdk-core/plugins/credentials_configuration.rb' require 'aws-sdk-core/plugins/logging.rb' require 'aws-sdk-core/plugins/param_converter.rb' require 'aws-sdk-core/plugins/param_validator.rb' require 'aws-sdk-core/plugins/user_agent.rb' require 'aws-sdk-core/plugins/helpful_socket_errors.rb' require 'aws-sdk-core/plugins/retry_errors.rb' require 'aws-sdk-core/plugins/global_configuration.rb' require 'aws-sdk-core/plugins/regional_endpoint.rb' require 'aws-sdk-core/plugins/endpoint_discovery.rb' require 'aws-sdk-core/plugins/endpoint_pattern.rb' require 'aws-sdk-core/plugins/response_paging.rb' require 'aws-sdk-core/plugins/stub_responses.rb' require 'aws-sdk-core/plugins/idempotency_token.rb' require 'aws-sdk-core/plugins/jsonvalue_converter.rb' require 'aws-sdk-core/plugins/client_metrics_plugin.rb' require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb' require 'aws-sdk-core/plugins/transfer_encoding.rb' require 'aws-sdk-core/plugins/signature_v4.rb' require 'aws-sdk-core/plugins/protocols/json_rpc.rb' Aws::Plugins::GlobalConfiguration.add_identifier(:qldbsession) module Aws::QLDBSession class Client < Seahorse::Client::Base include Aws::ClientStubs @identifier = :qldbsession set_api(ClientApi::API) add_plugin(Seahorse::Client::Plugins::ContentLength) add_plugin(Aws::Plugins::CredentialsConfiguration) add_plugin(Aws::Plugins::Logging) add_plugin(Aws::Plugins::ParamConverter) add_plugin(Aws::Plugins::ParamValidator) add_plugin(Aws::Plugins::UserAgent) add_plugin(Aws::Plugins::HelpfulSocketErrors) add_plugin(Aws::Plugins::RetryErrors) add_plugin(Aws::Plugins::GlobalConfiguration) add_plugin(Aws::Plugins::RegionalEndpoint) add_plugin(Aws::Plugins::EndpointDiscovery) add_plugin(Aws::Plugins::EndpointPattern) add_plugin(Aws::Plugins::ResponsePaging) add_plugin(Aws::Plugins::StubResponses) add_plugin(Aws::Plugins::IdempotencyToken) add_plugin(Aws::Plugins::JsonvalueConverter) add_plugin(Aws::Plugins::ClientMetricsPlugin) add_plugin(Aws::Plugins::ClientMetricsSendPlugin) add_plugin(Aws::Plugins::TransferEncoding) add_plugin(Aws::Plugins::SignatureV4) add_plugin(Aws::Plugins::Protocols::JsonRpc) # @overload initialize(options) # @param [Hash] options # @option options [required, Aws::CredentialProvider] :credentials # Your AWS credentials. This can be an instance of any one of the # following classes: # # * `Aws::Credentials` - Used for configuring static, non-refreshing # credentials. # # * `Aws::InstanceProfileCredentials` - Used for loading credentials # from an EC2 IMDS on an EC2 instance. # # * `Aws::SharedCredentials` - Used for loading credentials from a # shared file, such as `~/.aws/config`. # # * `Aws::AssumeRoleCredentials` - Used when you need to assume a role. # # When `:credentials` are not configured directly, the following # locations will be searched for credentials: # # * `Aws.config[:credentials]` # * The `:access_key_id`, `:secret_access_key`, and `:session_token` options. # * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] # * `~/.aws/credentials` # * `~/.aws/config` # * EC2 IMDS instance profile - When used by default, the timeouts are # very aggressive. Construct and pass an instance of # `Aws::InstanceProfileCredentails` to enable retries and extended # timeouts. # # @option options [required, String] :region # The AWS region to connect to. The configured `:region` is # used to determine the service `:endpoint`. When not passed, # a default `:region` is search for in the following locations: # # * `Aws.config[:region]` # * `ENV['AWS_REGION']` # * `ENV['AMAZON_REGION']` # * `ENV['AWS_DEFAULT_REGION']` # * `~/.aws/credentials` # * `~/.aws/config` # # @option options [String] :access_key_id # # @option options [Boolean] :active_endpoint_cache (false) # When set to `true`, a thread polling for endpoints will be running in # the background every 60 secs (default). Defaults to `false`. # # @option options [Boolean] :client_side_monitoring (false) # When `true`, client-side metrics will be collected for all API requests from # this client. # # @option options [String] :client_side_monitoring_client_id ("") # Allows you to provide an identifier for this client which will be attached to # all generated client side metrics. Defaults to an empty string. # # @option options [String] :client_side_monitoring_host ("127.0.0.1") # Allows you to specify the DNS hostname or IPv4 or IPv6 address that the client # side monitoring agent is running on, where client metrics will be published via UDP. # # @option options [Integer] :client_side_monitoring_port (31000) # Required for publishing client metrics. The port that the client side monitoring # agent is running on, where client metrics will be published via UDP. # # @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher) # Allows you to provide a custom client-side monitoring publisher class. By default, # will use the Client Side Monitoring Agent Publisher. # # @option options [Boolean] :convert_params (true) # When `true`, an attempt is made to coerce request parameters into # the required types. # # @option options [Boolean] :disable_host_prefix_injection (false) # Set to true to disable SDK automatically adding host prefix # to default service endpoint when available. # # @option options [String] :endpoint # The client endpoint is normally constructed from the `:region` # option. You should only configure an `:endpoint` when connecting # to test endpoints. This should be avalid HTTP(S) URI. # # @option options [Integer] :endpoint_cache_max_entries (1000) # Used for the maximum size limit of the LRU cache storing endpoints data # for endpoint discovery enabled operations. Defaults to 1000. # # @option options [Integer] :endpoint_cache_max_threads (10) # Used for the maximum threads in use for polling endpoints to be cached, defaults to 10. # # @option options [Integer] :endpoint_cache_poll_interval (60) # When :endpoint_discovery and :active_endpoint_cache is enabled, # Use this option to config the time interval in seconds for making # requests fetching endpoints information. Defaults to 60 sec. # # @option options [Boolean] :endpoint_discovery (false) # When set to `true`, endpoint discovery will be enabled for operations when available. Defaults to `false`. # # @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default) # The log formatter. # # @option options [Symbol] :log_level (:info) # The log level to send messages to the `:logger` at. # # @option options [Logger] :logger # The Logger instance to send log messages to. If this option # is not set, logging will be disabled. # # @option options [String] :profile ("default") # Used when loading credentials from the shared credentials file # at HOME/.aws/credentials. When not specified, 'default' is used. # # @option options [Float] :retry_base_delay (0.3) # The base delay in seconds used by the default backoff function. # # @option options [Symbol] :retry_jitter (:none) # A delay randomiser function used by the default backoff function. Some predefined functions can be referenced by name - :none, :equal, :full, otherwise a Proc that takes and returns a number. # # @see https://www.awsarchitectureblog.com/2015/03/backoff.html # # @option options [Integer] :retry_limit (3) # The maximum number of times to retry failed requests. Only # ~ 500 level server errors and certain ~ 400 level client errors # are retried. Generally, these are throttling errors, data # checksum errors, networking errors, timeout errors and auth # errors from expired credentials. # # @option options [Integer] :retry_max_delay (0) # The maximum number of seconds to delay between retries (0 for no limit) used by the default backoff function. # # @option options [String] :secret_access_key # # @option options [String] :session_token # # @option options [Boolean] :simple_json (false) # Disables request parameter conversion, validation, and formatting. # Also disable response data type conversions. This option is useful # when you want to ensure the highest level of performance by # avoiding overhead of walking request parameters and response data # structures. # # When `:simple_json` is enabled, the request parameters hash must # be formatted exactly as the DynamoDB API expects. # # @option options [Boolean] :stub_responses (false) # Causes the client to return stubbed responses. By default # fake responses are generated and returned. You can specify # the response data to return or errors to raise by calling # {ClientStubs#stub_responses}. See {ClientStubs} for more information. # # ** Please note ** When response stubbing is enabled, no HTTP # requests are made, and retries are disabled. # # @option options [Boolean] :validate_params (true) # When `true`, request parameters are validated before # sending the request. # # @option options [URI::HTTP,String] :http_proxy A proxy to send # requests through. Formatted like 'http://proxy.com:123'. # # @option options [Float] :http_open_timeout (15) The number of # seconds to wait when opening a HTTP session before rasing a # `Timeout::Error`. # # @option options [Integer] :http_read_timeout (60) The default # number of seconds to wait for response data. This value can # safely be set # per-request on the session yeidled by {#session_for}. # # @option options [Float] :http_idle_timeout (5) The number of # seconds a connection is allowed to sit idble before it is # considered stale. Stale connections are closed and removed # from the pool before making a request. # # @option options [Float] :http_continue_timeout (1) The number of # seconds to wait for a 100-continue response before sending the # request body. This option has no effect unless the request has # "Expect" header set to "100-continue". Defaults to `nil` which # disables this behaviour. This value can safely be set per # request on the session yeidled by {#session_for}. # # @option options [Boolean] :http_wire_trace (false) When `true`, # HTTP debug output will be sent to the `:logger`. # # @option options [Boolean] :ssl_verify_peer (true) When `true`, # SSL peer certificates are verified when establishing a # connection. # # @option options [String] :ssl_ca_bundle Full path to the SSL # certificate authority bundle file that should be used when # verifying peer certificates. If you do not pass # `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default # will be used if available. # # @option options [String] :ssl_ca_directory Full path of the # directory that contains the unbundled SSL certificate # authority files for verifying peer certificates. If you do # not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the # system default will be used if available. # def initialize(*args) super end # @!group API Operations # Sends a command to an Amazon QLDB ledger. # # @option params [String] :session_token # Specifies the session token for the current command. A session token # is constant throughout the life of the session. # # To obtain a session token, run the `StartSession` command. This # `SessionToken` is required for every subsequent command that is issued # during the current session. # # @option params [Types::StartSessionRequest] :start_session # Command to start a new session. A session token is obtained as part of # the response. # # @option params [Types::StartTransactionRequest] :start_transaction # Command to start a new transaction. # # @option params [Types::EndSessionRequest] :end_session # Command to end the current session. # # @option params [Types::CommitTransactionRequest] :commit_transaction # Command to commit the specified transaction. # # @option params [Types::AbortTransactionRequest] :abort_transaction # Command to abort the current transaction. # # @option params [Types::ExecuteStatementRequest] :execute_statement # Command to execute a statement in the specified transaction. # # @option params [Types::FetchPageRequest] :fetch_page # Command to fetch a page. # # @return [Types::SendCommandResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::SendCommandResult#start_session #start_session} => Types::StartSessionResult # * {Types::SendCommandResult#start_transaction #start_transaction} => Types::StartTransactionResult # * {Types::SendCommandResult#end_session #end_session} => Types::EndSessionResult # * {Types::SendCommandResult#commit_transaction #commit_transaction} => Types::CommitTransactionResult # * {Types::SendCommandResult#abort_transaction #abort_transaction} => Types::AbortTransactionResult # * {Types::SendCommandResult#execute_statement #execute_statement} => Types::ExecuteStatementResult # * {Types::SendCommandResult#fetch_page #fetch_page} => Types::FetchPageResult # # @example Request syntax with placeholder values # # resp = client.send_command({ # session_token: "SessionToken", # start_session: { # ledger_name: "LedgerName", # required # }, # start_transaction: { # }, # end_session: { # }, # commit_transaction: { # transaction_id: "TransactionId", # required # commit_digest: "data", # required # }, # abort_transaction: { # }, # execute_statement: { # transaction_id: "TransactionId", # required # statement: "Statement", # required # parameters: [ # { # ion_binary: "data", # ion_text: "IonText", # }, # ], # }, # fetch_page: { # transaction_id: "TransactionId", # required # next_page_token: "PageToken", # required # }, # }) # # @example Response structure # # resp.start_session.session_token #=> String # resp.start_transaction.transaction_id #=> String # resp.commit_transaction.transaction_id #=> String # resp.commit_transaction.commit_digest #=> String # resp.execute_statement.first_page.values #=> Array # resp.execute_statement.first_page.values[0].ion_binary #=> String # resp.execute_statement.first_page.values[0].ion_text #=> String # resp.execute_statement.first_page.next_page_token #=> String # resp.fetch_page.page.values #=> Array # resp.fetch_page.page.values[0].ion_binary #=> String # resp.fetch_page.page.values[0].ion_text #=> String # resp.fetch_page.page.next_page_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/qldb-session-2019-07-11/SendCommand AWS API Documentation # # @overload send_command(params = {}) # @param [Hash] params ({}) def send_command(params = {}, options = {}) req = build_request(:send_command, params) req.send_request(options) end # @!endgroup # @param params ({}) # @api private def build_request(operation_name, params = {}) handlers = @handlers.for(operation_name) context = Seahorse::Client::RequestContext.new( operation_name: operation_name, operation: config.api.operation(operation_name), client: self, params: params, config: config) context[:gem_name] = 'aws-sdk-qldbsession' context[:gem_version] = '1.1.0' Seahorse::Client::Request.new(handlers, context) end # @api private # @deprecated def waiter_names [] end class << self # @api private attr_reader :identifier # @api private def errors_module Errors end end end end
43.674129
201
0.66942
016579e00ecf9b26a930f9170519a83214b376d0
1,407
require 'refinerycms-core' require 'awesome_nested_set' require 'globalize3' require 'friendly_id' require 'seo_meta' module Refinery autoload :PagesGenerator, 'generators/refinery/pages/pages_generator' module Pages require 'refinery/pages/engine' require 'refinery/pages/tab' require 'refinery/pages/type' require 'refinery/pages/types' # Load configuration last so that everything above is available to it. require 'refinery/pages/configuration' autoload :InstanceMethods, 'refinery/pages/instance_methods' class << self def root @root ||= Pathname.new(File.expand_path('../../../', __FILE__)) end def factory_paths @factory_paths ||= [ root.join('spec', 'factories').to_s ] end def valid_templates(*pattern) [Rails.root, Refinery::Plugins.registered.pathnames].flatten.uniq.map do |p| p.join(*pattern) end.map(&:to_s).map do |p| Dir[p] end.select(&:any?).flatten.map do |f| File.basename(f) end.map do |p| p.split('.').first end end def default_parts_for(page) return default_parts unless page.view_template.present? types.find_by_name(page.view_template).parts.map &:titleize end end module Admin autoload :InstanceMethods, 'refinery/pages/admin/instance_methods' end end end
26.055556
84
0.656006
112edfcbbff3516f2d6b733f5c68a2efb8787a09
2,512
require_relative './controller_logger' class Controller prepend ControllerLogger attr_reader :voting_machine class InvalidChoiceException < Exception;end def self.run_controller(controller_name, machine) raise InvalidChoiceException unless valid_controller_name?(controller_name) # Find controller controller_class = lookup_controller(controller_name) # Instatiate it and run it controller = controller_class.new(machine) controller.run end # Find Subclass based on name convention def self.lookup_controller(name) return nil unless valid_controller_name?(name) controller_name = "#{name.to_s.capitalize}Controller" return const_get(controller_name) end # Check if the controller name is valid # by checking if a constant is defined that matches the convention # The constants are declared via the class definition def self.valid_controller_name?(controller_name) return false if controller_name == "" || controller_name.nil? const_defined?("#{controller_name.to_s.capitalize}Controller") end def initialize(voting_machine) @voting_machine = voting_machine end # wrap the get input def get_input(variable_symbol, question=nil) present(question, newline: false) if question # creating this method allows us to test it easily # without requiring terminal input set_input_variable(variable_symbol, gets.chomp) end # For the same reason as logging, we want to have a central # method that is responsible for showing output to the user # This way if we want to customize it, we can do it in one # place def present(output, newline: true) # ternary operator FTW newline ? puts(output) : print(output) end def run # For methods that must be implemented by subclasses # Its a good practice to implement the method at the # base class and to raise an exception with the appropriate # message. raise "Must be implemented by subclass" end def set_input_variable(variable_symbol, value) # be careful setting instance variables in this way # if the variable_symbol comes from user input or # is not validated, it could have unintended consequences instance_variable_set("@#{variable_symbol}", value) end end # you have to require the subclasses at the bottom of this file # to ensure that the base class is loaded. There are other ways # to accomplish this, but this will suffice for this activity. Dir["./controllers/*rb"].each { |f| require f }
32.623377
79
0.749602
2816bb0ed36fc98fdf9d0563ac88a9e187e1f55b
281
cask :v1 => 'paw' do version :latest sha256 :no_check url 'https://luckymarmot.com/paw/download' homepage 'http://luckymarmot.com/paw' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Paw.app' end
25.545455
115
0.711744
08be4417bba5f4fb983a7e6691918c03d470bb8d
170
module ActiveModel class Serializer # @api private class HasManyReflection < CollectionReflection def macro :has_many end end end end
15.454545
50
0.658824
4a762dbc0accf2d200538478aeebfe66b1ce1f90
2,313
module SPARQL; module Algebra class Operator ## # The SPARQL Property Path `path` operator. # # [88] Path ::= PathAlternative # # @example SPARQL Grammar # PREFIX : <http://www.example.org/> # SELECT ?t # WHERE { # :a :p1|:p2/:p3|:p4 ?t # } # # @example SSE # (prefix ((: <http://www.example.org/>)) # (project (?t) # (path :a # (alt # (alt :p1 (seq :p2 :p3)) # :p4) # ?t))) # # @see https://www.w3.org/TR/sparql11-query/#sparqlTranslatePathExpressions class Path < Operator::Ternary include Query NAME = :path ## # Finds solutions from `queryable` matching the path. # # @param [RDF::Queryable] queryable # the graph or repository to query # @param [Hash{Symbol => Object}] options # any additional keyword options # @yield [solution] # each matching solution # @yieldparam [RDF::Query::Solution] solution # @yieldreturn [void] ignored # @return [RDF::Query::Solutions] # the resulting solution sequence # @see https://www.w3.org/TR/sparql11-query/#sparqlAlgebra def execute(queryable, **options, &block) debug(options) {"Path #{operands.to_sse}"} subject, path_op, object = operands @solutions = RDF::Query::Solutions.new path_op.execute(queryable, subject: subject, object: object, graph_name: options.fetch(:graph_name, false), depth: options[:depth].to_i + 1, **options ) do |solution| @solutions << solution end debug(options) {"=> #{@solutions.inspect}"} @solutions.uniq! @solutions.each(&block) if block_given? @solutions end ## # # Returns a partial SPARQL grammar for this operator. # # @param [Boolean] top_level (true) # Treat this as a top-level, generating SELECT ... WHERE {} # @return [String] def to_sparql(top_level: true, **options) str = operands.to_sparql(top_level: false, **options) + " ." top_level ? Operator.to_sparql(str, **options) : str end end # Path end # Operator end; end # SPARQL::Algebra
29.653846
79
0.553394
01a2df4c0d907d782f7dad757ca95a1470f260c0
45
module RezultVersion VERSION = "0.2.0" end
11.25
20
0.711111
bb5023a714b8d667f3c064dedb7bacde197145dc
76
# frozen_string_literal: true module SimpleSauce class Session end end
10.857143
29
0.789474
1a519b5474c950ae6694af3549bc3849e8cdbd1b
3,586
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. # config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "Tumblr_clone_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
41.218391
102
0.758784
088d4a4a28902a467aa4bfcbdb6a078546447ffb
2,423
require 'uri' require 'net/http' require 'cgi' require 'json' require 'net/http/digest_auth' module PuppetX module Wildfly class APIClient def initialize(address, port, user, password, timeout, secure) @username = user @password = password @uri = if secure URI.parse "https://#{address}:#{port}/management" else URI.parse "http://#{address}:#{port}/management" end @uri.user = CGI.escape(user) @uri.password = CGI.escape(password) @http_client = Net::HTTP.new @uri.host, @uri.port, nil @http_client.read_timeout = timeout return unless secure == true @http_client.use_ssl = true @http_client.verify_mode = OpenSSL::SSL::VERIFY_NONE end def authz_header digest_auth = Net::HTTP::DigestAuth.new authz_request = Net::HTTP::Get.new @uri.request_uri retried = 0 # All http_api providers require Wildfly service to be up, but with systemd there is no guarantee that the service is actually running, therefore we need to retry begin response = @http_client.request authz_request rescue => e raise e unless retried + 1 < 6 retried += 1 sleep 10 retry end sleep 0.05 # We've been returned an auth token. But if we don't wait a small amount of time before using it, we might stil get a 401. :( if response['www-authenticate'] =~ /digest/i digest_auth.auth_header @uri, response['www-authenticate'], 'POST' else response['www-authenticate'] end end def submit(body, ignore_failed_outcome = false) http_request = Net::HTTP::Post.new @uri.request_uri http_request.add_field 'Content-type', 'application/json' authz = authz_header if authz =~ /digest/i http_request.add_field 'Authorization', authz else http_request.basic_auth @username, @password end http_request.body = body.to_json http_response = @http_client.request http_request response = JSON.parse(http_response.body) unless response['outcome'] == 'success' || ignore_failed_outcome raise "Failed with: #{response['failure-description']} for #{body.to_json}" end response end end end end
31.467532
170
0.613702
1cd541c548328d05059bc3ff653d6544ede2c1e5
557
require 'chefspec' describe 'ifconfig::add' do platform 'ubuntu' describe 'adds a ifconfig with the default action' do it { is_expected.to add_ifconfig('10.0.0.1') } it { is_expected.to_not add_ifconfig('10.0.0.10') } end describe 'adds a ifconfig with an explicit action' do it { is_expected.to add_ifconfig('10.0.0.2') } end describe 'adds a ifconfig with attributes' do it { is_expected.to add_ifconfig('10.0.0.3').with(device: 'en0') } it { is_expected.to_not add_ifconfig('10.0.0.3').with(device: 'en1') } end end
27.85
74
0.682226
6206a35732de6a52c7f00b324c0582ae91626265
935
module TaskEngine module Tasks class WaitingTask PARAMETER_WAITING_TIME = 'waiting_time' # @param [Hash] parameters # @return [Hash, nil] def execute(parameters) sleep(parameters[PARAMETER_WAITING_TIME]) nil end end class FailingTask # @param [Hash] parameters # @return [Hash, nil] def execute(parameters) 1 / 0 end end class FailingNotRetryTask include TaskEngine::NoRetryTask # @param [Hash] parameters # @return [Hash, nil] def execute(parameters) 1 / 0 end end class FailingNotRetryExceptionTask class FailingNotRetryTaskException < Exception include TaskEngine::NoRetryException end # @param [Hash] parameters # @return [Hash, nil] def execute(parameters) raise FailingNotRetryTaskException.new('Oh no') end end end end
21.25
55
0.618182
28be62b68d0e1434c6032a0274b3b4c8d0f0d8ad
1,428
module Pageflow class PagesController < Pageflow::ApplicationController respond_to :json before_filter :authenticate_user! def create chapter = Chapter.find(params[:chapter_id]) page = chapter.pages.build(page_params) authorize!(:create, page) verify_edit_lock!(page.chapter.entry) page.save respond_with(page) end def update page = Page.find(params[:id]) authorize!(:update, page) verify_edit_lock!(page.chapter.entry) page.update_attributes(page_params) respond_with(page) end def order chapter = Chapter.find(params[:chapter_id]) entry = DraftEntry.new(chapter.entry) authorize!(:edit_outline, entry.to_model) verify_edit_lock!(chapter.entry) params.require(:ids).each_with_index do |id, index| entry.pages.update(id, :chapter_id => chapter.id, :position => index) end head :no_content end def destroy page = Page.find(params[:id]) authorize!(:destroy, page) verify_edit_lock!(page.chapter.entry) page.chapter.entry.snapshot(:creator => current_user) page.destroy respond_with(page) end private def page_params configuration = params.require(:page)[:configuration].try(:permit!) params.require(:page).permit(:template, :position, :title).merge(:configuration => configuration) end end end
23.409836
103
0.663165
4a7f8124c7269ed9d3504769a780fdf1ba86cc14
742
# # Cookbook Name:: download_zookeeper # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # #package 'hadoop-2.7.2' do # action :install #package_name 'hadoop-2.7.2' #end cookbook_file "/home/hhuser/zookeeper-3.5.1-alpha.tar.gz" do source "zookeeper-3.5.1-alpha.tar.gz" mode "777" end execute "extract zookeeper source" do command "tar -xzvf /home/hhuser/zookeeper-3.5.1-alpha.tar.gz" end execute "copy extracted file from / to /home/hhuser/zookeeper-3.5.1-alpha" do command "mv /zookeeper-3.5.1-alpha /home/hhuser/zookeeper-3.5.1-alpha" end execute "change ownership of hadoop folder to hhuser" do command "chown hhuser:hungryhippos -R /home/hhuser/zookeeper-3.5.1-alpha" end
24.733333
77
0.739892
7a656034b83423227cb200d889bdbb3e7626ba68
1,072
# rubocop:disable Metrics/LineLength # == Schema Information # # Table name: quotes # # id :integer not null, primary key # character_name :string(255) not null # content :text not null # likes_count :integer default(0), not null # media_type :string not null, indexed => [media_id] # created_at :datetime not null # updated_at :datetime not null # character_id :integer indexed # media_id :integer not null, indexed, indexed => [media_type] # user_id :integer # # Indexes # # index_quotes_on_character_id (character_id) # index_quotes_on_media_id (media_id) # index_quotes_on_media_id_and_media_type (media_id,media_type) # # Foreign Keys # # fk_rails_bd0c2ee7f3 (character_id => characters.id) # # rubocop:enable Metrics/LineLength FactoryBot.define do factory :quote do association :user, factory: :user, strategy: :build association :media, factory: :anime, strategy: :build end end
30.628571
78
0.636194
5d0a0023fa7c8cbcc2223432557a736c7559ed59
8,655
# frozen_string_literal: true describe "Acceptance::AssessorList" do include RSpecRegisterApiServiceMixin let(:valid_assessor_request_body) do { firstName: "Someone", middleNames: "Muddle", lastName: "Person", dateOfBirth: "1991-02-25", searchResultsComparisonPostcode: "", qualifications: { domestic_rd_sap: "ACTIVE", domestic_sap: "INACTIVE", non_domestic_sp3: "INACTIVE", non_domestic_cc4: "INACTIVE", nonDomesticDec: "INACTIVE", non_domestic_nos3: "INACTIVE", non_domestic_nos4: "INACTIVE", non_domestic_nos5: "INACTIVE", gda: "INACTIVE", }, contact_details: { email: "[email protected]", telephone_number: "01234 567", }, } end context "when a scheme doesn't exist" do context "when a client is authorised" do it "returns status 404 for a get" do fetch_assessors(scheme_id: 20, accepted_responses: [404], auth_data: { 'scheme_ids': [20] }) end it "returns the 404 error response" do response = fetch_assessors(scheme_id: 20, accepted_responses: [404], auth_data: { 'scheme_ids': [20] }) expect(response.body).to eq( { errors: [ { "code": "NOT_FOUND", title: "The requested scheme was not found", }, ], }.to_json, ) end end context "when a client is not authorised" do it "returns status 403 for a get" do fetch_assessors(scheme_id: 20, accepted_responses: [403]) end it "returns the 403 error response for a get" do response = fetch_assessors(scheme_id: 20, accepted_responses: [403]) expect(response.body).to eq( { errors: [ { "code": "UNAUTHORISED", title: "You are not authorised to perform this request", }, ], }.to_json, ) end end end context "when a scheme has no assessors" do it "returns status 200 for a get" do scheme_id = add_scheme_and_get_id fetch_assessors(scheme_id: scheme_id, auth_data: { 'scheme_ids': [scheme_id] }) end it "returns an empty list" do scheme_id = add_scheme_and_get_id expected = { "assessors" => [] } response = fetch_assessors(scheme_id: scheme_id, auth_data: { 'scheme_ids': [scheme_id] }) actual = JSON.parse(response.body)["data"] expect(actual).to eq expected end it "returns JSON for a get" do scheme_id = add_scheme_and_get_id response = fetch_assessors(scheme_id: scheme_id, auth_data: { 'scheme_ids': [scheme_id] }) expect(response.headers["Content-type"]).to eq("application/json") end end context "when a scheme has one assessor" do it "returns an array of assessors" do scheme_id = add_scheme_and_get_id add_assessor(scheme_id: scheme_id, assessor_id: "SCHE423344", body: valid_assessor_request_body) response = fetch_assessors(scheme_id: scheme_id, auth_data: { 'scheme_ids': [scheme_id] }) actual = JSON.parse(response.body)["data"] expected = { "assessors" => [ { "registeredBy" => { "schemeId" => scheme_id, "name" => "test scheme", }, "schemeAssessorId" => "SCHE423344", "firstName" => valid_assessor_request_body[:firstName], "middleNames" => valid_assessor_request_body[:middleNames], "lastName" => valid_assessor_request_body[:lastName], "dateOfBirth" => valid_assessor_request_body[:dateOfBirth], "contactDetails" => { "telephoneNumber" => "01234 567", "email" => "[email protected]", }, "searchResultsComparisonPostcode" => "", "address" => {}, "companyDetails" => {}, "qualifications" => { "domesticSap" => "INACTIVE", "domesticRdSap" => "ACTIVE", "nonDomesticSp3" => "INACTIVE", "nonDomesticCc4" => "INACTIVE", "nonDomesticDec" => "INACTIVE", "nonDomesticNos3" => "INACTIVE", "nonDomesticNos4" => "INACTIVE", "nonDomesticNos5" => "INACTIVE", "gda" => "INACTIVE", }, }, ], } expect(actual).to eq expected end end context "when a scheme has multiple assessors" do it "returns an array of assessors" do scheme_id = add_scheme_and_get_id add_assessor(scheme_id: scheme_id, assessor_id: "SCHE123456", body: valid_assessor_request_body) add_assessor(scheme_id: scheme_id, assessor_id: "SCHE567890", body: valid_assessor_request_body) response = fetch_assessors(scheme_id: scheme_id, auth_data: { 'scheme_ids': [scheme_id] }) actual = JSON.parse(response.body)["data"] expected = { "assessors" => [ { "registeredBy" => { "schemeId" => scheme_id, "name" => "test scheme", }, "schemeAssessorId" => "SCHE123456", "firstName" => valid_assessor_request_body[:firstName], "middleNames" => valid_assessor_request_body[:middleNames], "lastName" => valid_assessor_request_body[:lastName], "dateOfBirth" => valid_assessor_request_body[:dateOfBirth], "contactDetails" => { "telephoneNumber" => "01234 567", "email" => "[email protected]", }, "searchResultsComparisonPostcode" => "", "address" => {}, "companyDetails" => {}, "qualifications" => { "domesticSap" => "INACTIVE", "domesticRdSap" => "ACTIVE", "nonDomesticSp3" => "INACTIVE", "nonDomesticCc4" => "INACTIVE", "nonDomesticDec" => "INACTIVE", "nonDomesticNos3" => "INACTIVE", "nonDomesticNos4" => "INACTIVE", "nonDomesticNos5" => "INACTIVE", "gda" => "INACTIVE", }, }, { "registeredBy" => { "schemeId" => scheme_id, "name" => "test scheme", }, "schemeAssessorId" => "SCHE567890", "firstName" => valid_assessor_request_body[:firstName], "middleNames" => valid_assessor_request_body[:middleNames], "lastName" => valid_assessor_request_body[:lastName], "dateOfBirth" => valid_assessor_request_body[:dateOfBirth], "contactDetails" => { "telephoneNumber" => "01234 567", "email" => "[email protected]", }, "searchResultsComparisonPostcode" => "", "address" => {}, "companyDetails" => {}, "qualifications" => { "domesticSap" => "INACTIVE", "domesticRdSap" => "ACTIVE", "nonDomesticSp3" => "INACTIVE", "nonDomesticCc4" => "INACTIVE", "nonDomesticDec" => "INACTIVE", "nonDomesticNos3" => "INACTIVE", "nonDomesticNos4" => "INACTIVE", "nonDomesticNos5" => "INACTIVE", "gda" => "INACTIVE", }, }, ], } expect(expected["assessors"]).to match_array actual["assessors"] end end context "when a client is not authenticated" do it "returns a 401 unauthorised" do fetch_assessors(scheme_id: add_scheme_and_get_id, accepted_responses: [401], should_authenticate: false) end end context "when a client does not have the right scope" do it "returns a 403 forbidden" do fetch_assessors(scheme_id: add_scheme_and_get_id, accepted_responses: [403], scopes: []) end end context "when a client tries to access another clients assessors" do it "returns a 403 forbidden" do scheme_id = add_scheme_and_get_id second_scheme_id = add_scheme_and_get_id(name: "second test scheme") fetch_assessors( scheme_id: second_scheme_id, accepted_responses: [403], auth_data: { 'scheme_ids': [scheme_id] }, ) end end context "when supplemental data object does not contain the schemes_ids key" do it "returns a 403 forbidden" do scheme_id = add_scheme_and_get_id fetch_assessors(scheme_id: scheme_id, accepted_responses: [403], auth_data: { 'test': [scheme_id] }) end end end
34.209486
111
0.567187
18c96f0382b89022d2f34a4e25e52bfde99eb36b
272
name 'test_nginx_certs' maintainer 'Tom Noonan II' maintainer_email '[email protected]' license 'All rights reserved' description 'Test fixture to provide SSL certs' long_description 'Test fixture to provide SSL certs' version '0.1.0'
34
52
0.680147
339167d6a220dc27611c2603a0e3ad855fa52bb8
2,201
require 'spec_helper' module Cellect::Server describe API do include_context 'API' { 'Ungrouped' => nil, 'Grouped' => 'grouped' }.each_pair do |grouping_type, grouping| SET_TYPES.shuffle.each do |set_type| context "#{ grouping_type } #{ set_type }" do let(:workflow_type){ [grouping, set_type].compact.join '_' } let(:workflow){ Workflow[workflow_type] } let(:user){ workflow.user 123 } before(:each){ pass_until_state_of workflow, is: :ready } let(:opts) do { subject_id: 123 }.tap do |h| h[:group_id] = 1 if workflow.grouped? end end it 'should remove subjects' do if workflow.grouped? expect(workflow).to receive(:remove).with subject_id: 123, group_id: 1, priority: nil else expect(workflow).to receive(:remove).with subject_id: 123, group_id: nil, priority: nil end put "/workflows/#{ workflow_type }/remove", opts expect(last_response.status).to eq 200 end it 'should handle invalid subject_ids' do bad_opts = opts.merge subject_id: '%(*ERRRR)' put "/workflows/#{ workflow_type }/remove", bad_opts expect(last_response.status).to eql 400 expect(last_response.body).to match /Bad Request/ end it 'should handle invalid group_ids' do if workflow.grouped? bad_opts = opts.merge group_id: '%(*ERRRR)' put "/workflows/#{ workflow_type }/remove", bad_opts expect(last_response.status).to eql 400 expect(last_response.body).to match /Bad Request/ else put "/workflows/#{ workflow_type }/remove", opts expect(last_response).to be_ok end end end end end it 'should handle missing workflows' do allow(Workflow).to receive(:[]).with('missing').and_return nil put '/workflows/missing/remove', subject_id: 123 expect(last_response.status).to eql 404 expect(last_response.body).to match /Not Found/ end end end
35.5
101
0.585643
1cb278e912303af618a8e635e7c2d932b1150e6e
6,918
# frozen_string_literal: true RSpec.describe "git base name" do it "base_name should strip private repo uris" do source = Bundler::Source::Git.new("uri" => "[email protected]:bundler.git") expect(source.send(:base_name)).to eq("bundler") end it "base_name should strip network share paths" do source = Bundler::Source::Git.new("uri" => "//MachineName/ShareFolder") expect(source.send(:base_name)).to eq("ShareFolder") end end %w[cache package].each do |cmd| RSpec.describe "bundle #{cmd} with git" do it "copies repository to vendor cache and uses it" do git = build_git "foo" ref = git.ref_for("master", 11) install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "config set cache_all true" bundle cmd expect(bundled_app("vendor/cache/foo-1.0-#{ref}")).to exist expect(bundled_app("vendor/cache/foo-1.0-#{ref}/.git")).not_to exist expect(bundled_app("vendor/cache/foo-1.0-#{ref}/.bundlecache")).to be_file FileUtils.rm_rf lib_path("foo-1.0") expect(the_bundle).to include_gems "foo 1.0" end it "copies repository to vendor cache and uses it even when installed with bundle --path" do git = build_git "foo" ref = git.ref_for("master", 11) install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "install --path vendor/bundle" bundle "config set cache_all true" bundle cmd expect(bundled_app("vendor/cache/foo-1.0-#{ref}")).to exist expect(bundled_app("vendor/cache/foo-1.0-#{ref}/.git")).not_to exist FileUtils.rm_rf lib_path("foo-1.0") expect(the_bundle).to include_gems "foo 1.0" end it "runs twice without exploding" do build_git "foo" install_gemfile! <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "config set cache_all true" bundle! cmd bundle! cmd expect(out).to include "Updating files in vendor/cache" FileUtils.rm_rf lib_path("foo-1.0") expect(the_bundle).to include_gems "foo 1.0" end it "tracks updates" do git = build_git "foo" old_ref = git.ref_for("master", 11) install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "config set cache_all true" bundle cmd update_git "foo" do |s| s.write "lib/foo.rb", "puts :CACHE" end ref = git.ref_for("master", 11) expect(ref).not_to eq(old_ref) bundle! "update", :all => true bundle "config set cache_all true" bundle! cmd expect(bundled_app("vendor/cache/foo-1.0-#{ref}")).to exist expect(bundled_app("vendor/cache/foo-1.0-#{old_ref}")).not_to exist FileUtils.rm_rf lib_path("foo-1.0") run! "require 'foo'" expect(out).to eq("CACHE") end it "tracks updates when specifying the gem" do git = build_git "foo" old_ref = git.ref_for("master", 11) install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "config set cache_all true" bundle! cmd update_git "foo" do |s| s.write "lib/foo.rb", "puts :CACHE" end ref = git.ref_for("master", 11) expect(ref).not_to eq(old_ref) bundle "update foo" expect(bundled_app("vendor/cache/foo-1.0-#{ref}")).to exist expect(bundled_app("vendor/cache/foo-1.0-#{old_ref}")).not_to exist FileUtils.rm_rf lib_path("foo-1.0") run "require 'foo'" expect(out).to eq("CACHE") end it "uses the local repository to generate the cache" do git = build_git "foo" ref = git.ref_for("master", 11) gemfile <<-G gem "foo", :git => '#{lib_path("foo-invalid")}', :branch => :master G bundle %(config set local.foo #{lib_path("foo-1.0")}) bundle "install" bundle "config set cache_all true" bundle cmd expect(bundled_app("vendor/cache/foo-invalid-#{ref}")).to exist # Updating the local still uses the local. update_git "foo" do |s| s.write "lib/foo.rb", "puts :LOCAL" end run "require 'foo'" expect(out).to eq("LOCAL") end it "copies repository to vendor cache, including submodules" do build_git "submodule", "1.0" git = build_git "has_submodule", "1.0" do |s| s.add_dependency "submodule" end Dir.chdir(lib_path("has_submodule-1.0")) do sys_exec "git submodule add #{lib_path("submodule-1.0")} submodule-1.0" `git commit -m "submodulator"` end install_gemfile <<-G git "#{lib_path("has_submodule-1.0")}", :submodules => true do gem "has_submodule" end G ref = git.ref_for("master", 11) bundle "config set cache_all true" bundle cmd expect(bundled_app("vendor/cache/has_submodule-1.0-#{ref}")).to exist expect(bundled_app("vendor/cache/has_submodule-1.0-#{ref}/submodule-1.0")).to exist expect(the_bundle).to include_gems "has_submodule 1.0" end it "displays warning message when detecting git repo in Gemfile", :bundler => "< 3" do build_git "foo" install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle cmd expect(err).to include("Your Gemfile contains path and git dependencies.") end it "does not display warning message if cache_all is set in bundle config" do build_git "foo" install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "config set cache_all true" bundle cmd bundle cmd expect(err).not_to include("Your Gemfile contains path and git dependencies.") end it "caches pre-evaluated gemspecs" do git = build_git "foo" # Insert a gemspec method that shells out spec_lines = lib_path("foo-1.0/foo.gemspec").read.split("\n") spec_lines.insert(-2, "s.description = `echo bob`") update_git("foo") {|s| s.write "foo.gemspec", spec_lines.join("\n") } install_gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle "config set cache_all true" bundle cmd ref = git.ref_for("master", 11) gemspec = bundled_app("vendor/cache/foo-1.0-#{ref}/foo.gemspec").read expect(gemspec).to_not match("`echo bob`") end it "can install after #{cmd} with git not installed" do build_git "foo" gemfile <<-G gem "foo", :git => '#{lib_path("foo-1.0")}' G bundle! "config set cache_all true" bundle! cmd, "all-platforms" => true, :install => false, :path => "./vendor/cache" simulate_new_machine with_path_as "" do bundle! "config set deployment true" bundle! :install, :local => true expect(the_bundle).to include_gem "foo 1.0" end end end end
28.586777
96
0.605088
186c559b7a898cff95b2618b006e87212469660a
1,705
# This module points the FileSet to the location of the technical metdata. # By default, the file holding the metadata is :original_file and the terms # are listed under ::characterization_terms. # Implementations may define their own terms or use a different source file, but # any terms must be set on the ::characterization_proxy by the Hydra::Works::CharacterizationService # # class MyFileSet # include Hyrax::FileSetBehavior # end # # MyFileSet.characterization_proxy = :master_file # MyFileSet.characterization_terms = [:term1, :term2, :term3] module Hyrax module FileSet module Characterization extend ActiveSupport::Concern included do class_attribute :characterization_terms, :characterization_proxy self.characterization_terms = [ :format_label, :file_size, :height, :width, :filename, :well_formed, :page_count, :file_title, :last_modified, :original_checksum, :duration, :sample_rate ] self.characterization_proxy = :original_file delegate(*characterization_terms, to: :characterization_proxy) def characterization_proxy send(self.class.characterization_proxy) || NullCharacterizationProxy.new end def characterization_proxy? !characterization_proxy.is_a?(NullCharacterizationProxy) end def mime_type @mime_type ||= characterization_proxy.mime_type end end class NullCharacterizationProxy def method_missing(*_args) [] end def respond_to_missing?(_method_name, _include_private = false) super end def mime_type; end end end end end
30.446429
100
0.696188
abbf3258e7853a3addac8c5b24a5fe8eecebbaa5
503
# frozen_string_literal: true require File.expand_path("../compact_index", __FILE__) Artifice.deactivate class CompactIndexStrictBasicAuthentication < CompactIndexAPI before do unless env["HTTP_AUTHORIZATION"] halt 401, "Authentication info not supplied" end # Only accepts password == "password" unless env["HTTP_AUTHORIZATION"] == "Basic dXNlcjpwYXNz" halt 403, "Authentication failed" end end end Artifice.activate_with(CompactIndexStrictBasicAuthentication)
23.952381
61
0.759443
4a9f1af986cb184b8507d1eab7fd13e2fcdc50ba
64
json.partial! "dispersions/dispersion", dispersion: @dispersion
32
63
0.8125
61adff7e221d3ce2f3729a5afe7b82f632b195fb
2,445
# frozen_string_literal: true require 'spec_helper' RSpec.describe Atlassian::JiraConnect::Jwt::Symmetric do let(:shared_secret) { 'secret' } describe '#iss_claim' do let(:jwt) { Atlassian::Jwt.encode({ iss: '123' }, shared_secret) } subject { described_class.new(jwt).iss_claim } it { is_expected.to eq('123') } context 'invalid JWT' do let(:jwt) { '123' } it { is_expected.to eq(nil) } end end describe '#sub_claim' do let(:jwt) { Atlassian::Jwt.encode({ sub: '123' }, shared_secret) } subject { described_class.new(jwt).sub_claim } it { is_expected.to eq('123') } context 'invalid JWT' do let(:jwt) { '123' } it { is_expected.to eq(nil) } end end describe '#valid?' do subject { described_class.new(jwt).valid?(shared_secret) } context 'invalid JWT' do let(:jwt) { '123' } it { is_expected.to eq(false) } end context 'valid JWT' do let(:jwt) { Atlassian::Jwt.encode({}, shared_secret) } it { is_expected.to eq(true) } end end describe '#verify_qsh_claim' do let(:jwt) { Atlassian::Jwt.encode({ qsh: qsh_claim }, shared_secret) } let(:qsh_claim) do Atlassian::Jwt.create_query_string_hash('https://gitlab.test/subscriptions', 'GET', 'https://gitlab.test') end subject(:verify_qsh_claim) do described_class.new(jwt).verify_qsh_claim('https://gitlab.test/subscriptions', 'GET', 'https://gitlab.test') end it { is_expected.to eq(true) } context 'qsh does not match' do let(:qsh_claim) do Atlassian::Jwt.create_query_string_hash('https://example.com/foo', 'POST', 'https://example.com') end it { is_expected.to eq(false) } end context 'creating query string hash raises an error' do let(:qsh_claim) { '123' } specify do expect(Atlassian::Jwt).to receive(:create_query_string_hash).and_raise(StandardError) expect(verify_qsh_claim).to eq(false) end end end describe '#verify_context_qsh_claim' do let(:jwt) { Atlassian::Jwt.encode({ qsh: qsh_claim }, shared_secret) } let(:qsh_claim) { 'context-qsh' } subject(:verify_context_qsh_claim) { described_class.new(jwt).verify_context_qsh_claim } it { is_expected.to eq(true) } context 'jwt does not contain a context qsh' do let(:qsh_claim) { '123' } it { is_expected.to eq(false) } end end end
24.94898
114
0.640082
d510dc98d46b54bf5a34c28c818a7c9eecd249e6
62
module Manabo module Pusher VERSION = "0.0.1" end end
10.333333
21
0.645161
ab5cf86e9a6ca39fd6cbe8f42d335bbec417917b
204
class Shoutout attr_reader :apikey def initialize(apikey) @apikey=apikey end def sendSms(from:,to:,body:) return SMS.send(self.apikey,from,to,body) end end require 'shoutout/sms'
14.571429
47
0.691176
18beafc1b03c6dc081d564397db5f2620f860ece
1,461
require 'spec_helper' describe Spree::WalletPaymentSource, type: :model do subject { Spree::WalletPaymentSource } describe "validation" do context 'with a non-PaymentSource model' do with_model 'NonPaymentSource', scope: :all do model do # We have to set this up or else `inverse_of` prevents us from testing our code has_many :wallet_payment_sources, class_name: 'Spree::WalletPaymentSource', as: :payment_source, inverse_of: :payment_source end end let(:payment_source) { NonPaymentSource.create! } it "errors when `payment_source` is not a `Spree::PaymentSource`" do wallet_payment_source = Spree::WalletPaymentSource.new( payment_source: payment_source, user: create(:user) ) expect(wallet_payment_source).not_to be_valid expect(wallet_payment_source.errors.messages).to eq( { payment_source: ["has to be a Spree::PaymentSource"] } ) end end it "is valid with a `credit_card` as `payment_source`" do valid_attrs = { payment_source: create(:credit_card), user: create(:user) } expect(subject.new(valid_attrs)).to be_valid end it "is valid with `store_credit` as `payment_source`" do valid_attrs = { payment_source: create(:store_credit), user: create(:user) } expect(subject.new(valid_attrs)).to be_valid end end end
31.085106
134
0.6564
5dc2f8aebc0900481971f27a04b92eedb837d7fd
1,229
Pod::Spec.new do |s| s.name = "APNGKit" s.version = "2.2.0" s.summary = "High performance and delightful way to play with APNG format in iOS." s.description = <<-DESC APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS. It's built with high-level abstractions and brings a delightful API. Since be that, you will feel at home and joy when using APNGKit to play with images in APNG format. DESC s.homepage = "https://github.com/onevcat/APNGKit" s.screenshots = "https://user-images.githubusercontent.com/1019875/139824374-c83a0d99-7ef6-4497-b980-ee3e3ad7565e.png" s.license = { :type => "MIT", :file => "LICENSE" } s.authors = { "onevcat" => "[email protected]" } s.social_media_url = "http://twitter.com/onevcat" s.ios.deployment_target = "9.0" s.osx.deployment_target = "10.12" s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/onevcat/APNGKit.git", :tag => s.version } s.source_files = "Source/**/*.swift" s.swift_versions = ["5.3", "5.4", "5.5"] s.dependency "Delegate", "~> 1.1" end
39.645161
140
0.615134
1d9d4aa41f73b27e0c298635f771a9a8a83733e9
823
cask 'tower-beta' do version '3.0.0-151,151-c0ce1e07' sha256 'f3f9b7a0e4b3dd2f68920277f285a03ccba9f23ecbe76b5c7173a8866f146caa' # amazonaws.com/apps/tower3-mac was verified as official when first introduced to the cask url "https://fournova-app-updates.s3.amazonaws.com/apps/tower3-mac/#{version.after_comma}/Tower-#{version.before_comma}.zip" appcast "https://updates.fournova.com/updates/tower#{version.major}-mac/beta" name 'Tower' homepage 'https://www.git-tower.com/public-beta-2018' auto_updates true app 'Tower.app' binary "#{appdir}/Tower.app/Contents/MacOS/gittower" zap trash: [ '~/Library/Application Support/com.fournova.Tower*', '~/Library/Caches/com.fournova.Tower*', '~/Library/Preferences/com.fournova.Tower*.plist', ] end
37.409091
126
0.704739
edaeaf54f2ebcaf2895dda066a6de59bef266939
555
# frozen_string_literal: true RSpec.describe Hyrax::Admin::UserActivityPresenter do let(:instance) { described_class.new } describe "#to_json" do subject { instance.to_json } let(:users) do instance_double(Hyrax::Statistics::Users::OverTime, points: [['2017-02-16', '12']]) end before do allow(Hyrax::Statistics::Users::OverTime).to receive(:new).and_return(users) end it "returns points" do expect(subject).to eq "[{\"y\":\"2017-02-16\",\"a\":\"12\",\"b\":null}]" end end end
25.227273
82
0.616216
f825975fef8d9e48c379b3e3b2acd4f9744be490
1,085
class Api::V1::ProfilesController < Api::BaseController before_action :set_user def show; end def update if password_params[:password].present? render_could_not_create_error('Invalid current password') and return unless @user.valid_password?(password_params[:current_password]) @user.update!(password_params.except(:current_password)) end @user.update!(profile_params) end def availability @user.account_users.find_by!(account_id: availability_params[:account_id]).update!(availability: availability_params[:availability]) @user.update!(profile_params) end private def set_user @user = current_user end def availability_params params.require(:profile).permit(:account_id, :availability) end def profile_params params.require(:profile).permit( :email, :name, :display_name, :avatar, :availability, ui_settings: {} ) end def password_params params.require(:profile).permit( :current_password, :password, :password_confirmation ) end end
21.7
139
0.704147
3823566056f80b1c4f4f1e02e497fd336f480b70
303
#!/usr/bin/env ruby $:.push File.expand_path('../../lib', __FILE__) require 'celluloid/autostart' module Enumerable # Simple parallel map using Celluloid::Futures def pmap(&block) futures = map { |elem| Celluloid::Future.new(elem, &block) } futures.map { |future| future.value } end end
23.307692
64
0.686469
081f05b2d7f848bc592ef3231687c0ecffc43e5f
5,918
# frozen_string_literal: true require "active_support/deprecation" require "active_support/core_ext/string/filters" require "rails/command/environment_argument" module Rails class DBConsole def self.start(*args) new(*args).start end def initialize(options = {}) @options = options end def start ENV["RAILS_ENV"] ||= @options[:environment] || environment case db_config.adapter when /^(jdbc)?mysql/ args = { host: "--host", port: "--port", socket: "--socket", username: "--user", encoding: "--default-character-set", sslca: "--ssl-ca", sslcert: "--ssl-cert", sslcapath: "--ssl-capath", sslcipher: "--ssl-cipher", sslkey: "--ssl-key" }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact if config[:password] && @options[:include_password] args << "--password=#{config[:password]}" elsif config[:password] && !config[:password].to_s.empty? args << "-p" end args << db_config.database find_cmd_and_exec(["mysql", "mysql5"], *args) when /^postgres|^postgis/ ENV["PGUSER"] = config[:username] if config[:username] ENV["PGHOST"] = config[:host] if config[:host] ENV["PGPORT"] = config[:port].to_s if config[:port] ENV["PGPASSWORD"] = config[:password].to_s if config[:password] && @options[:include_password] find_cmd_and_exec("psql", db_config.database) when "sqlite3" args = [] args << "-#{@options[:mode]}" if @options[:mode] args << "-header" if @options[:header] args << File.expand_path(db_config.database, Rails.respond_to?(:root) ? Rails.root : nil) find_cmd_and_exec("sqlite3", *args) when "oracle", "oracle_enhanced" logon = "" if config[:username] logon = config[:username].dup logon << "/#{config[:password]}" if config[:password] && @options[:include_password] logon << "@#{db_config.database}" if db_config.database end find_cmd_and_exec("sqlplus", logon) when "sqlserver" args = [] args += ["-D", "#{db_config.database}"] if db_config.database args += ["-U", "#{config[:username]}"] if config[:username] args += ["-P", "#{config[:password]}"] if config[:password] if config[:host] host_arg = +"#{config[:host]}" host_arg << ":#{config[:port]}" if config[:port] args += ["-S", host_arg] end find_cmd_and_exec("sqsh", *args) else abort "Unknown command-line client for #{db_config.database}." end end def config db_config.configuration_hash end def db_config return @db_config if @db_config # We need to check whether the user passed the database the # first time around to show a consistent error message to people # relying on 2-level database configuration. @db_config = configurations.configs_for(env_name: environment, spec_name: database) unless @db_config raise ActiveRecord::AdapterNotSpecified, "'#{database}' database is not configured for '#{environment}'. Available configuration: #{configurations.inspect}" end @db_config end def environment Rails.respond_to?(:env) ? Rails.env : Rails::Command.environment end def database @options.fetch(:database, "primary") end private def configurations # :doc: require APP_PATH ActiveRecord::Base.configurations = Rails.application.config.database_configuration ActiveRecord::Base.configurations end def find_cmd_and_exec(commands, *args) # :doc: commands = Array(commands) dirs_on_path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR) unless (ext = RbConfig::CONFIG["EXEEXT"]).empty? commands = commands.map { |cmd| "#{cmd}#{ext}" } end full_path_command = nil found = commands.detect do |cmd| dirs_on_path.detect do |path| full_path_command = File.join(path, cmd) begin stat = File.stat(full_path_command) rescue SystemCallError else stat.file? && stat.executable? end end end if found exec full_path_command, *args else abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") end end end module Command class DbconsoleCommand < Base # :nodoc: include EnvironmentArgument class_option :include_password, aliases: "-p", type: :boolean, desc: "Automatically provide the password from database.yml" class_option :mode, enum: %w( html list line column ), type: :string, desc: "Automatically put the sqlite3 database in the specified mode (html, list, line, column)." class_option :header, type: :boolean class_option :connection, aliases: "-c", type: :string, desc: "Specifies the connection to use." class_option :database, aliases: "--db", type: :string, desc: "Specifies the database to use." def perform extract_environment_option_from_argument # RAILS_ENV needs to be set before config/application is required. ENV["RAILS_ENV"] = options[:environment] if options["connection"] ActiveSupport::Deprecation.warn(<<-MSG.squish) `connection` option is deprecated and will be removed in Rails 6.1. Please use `database` option instead. MSG options["database"] = options["connection"] end require_application_and_environment! Rails::DBConsole.start(options) end end end end
30.505155
125
0.599189
1c035925f59682c5020571a8cc11cdd712917949
152
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_sign-in-with-twitter_session'
38
90
0.802632
874d9abda84e177bb308f6cfece560468d3f2137
1,226
require 'json' module Berkshelf class APIClient # A representation of cookbook metadata indexed by a Berkshelf API Server. Returned # by sending messages to a {Berkshelf::APIClient} and used to download cookbooks # indexed by the Berkshelf API Server. class RemoteCookbook # @return [String] attr_reader :name # @return [String] attr_reader :version # @param [String] name # @param [String] version # @param [Hash] attributes def initialize(name, version, attributes = {}) @name = name @version = version @attributes = attributes end # @return [Hash] def dependencies @attributes[:dependencies] end # @return [Hash] def platforms @attributes[:platforms] end # @return [Symbol] def location_type @attributes[:location_type].to_sym end # @return [String] def location_path @attributes[:location_path] end def to_hash { name: name, version: version } end def to_json(options = {}) ::JSON.pretty_generate(to_hash, options) end end end end
21.892857
87
0.583197
18aaabfc686c88f8d9c47bb612cbe8f07359dcd8
9,587
# Only define freeze and unfreeze tasks in instance mode unless File.directory? "#{RAILS_ROOT}/app" namespace :bionic do namespace :freeze do desc "Lock this application to the current gems (by unpacking them into vendor/bionic)" task :gems do require 'rubygems' require 'rubygems/gem_runner' bionic = (version = ENV['VERSION']) ? Gem.cache.search('bionic', "= #{version}").first : Gem.cache.search('bionic').sort_by { |g| g.version }.last version ||= bionic.version unless bionic puts "No bionic gem #{version} is installed. Do 'gem list bionic' to see what you have available." exit end puts "Freezing to the gems for Bionic #{bionic.version}" rm_rf "vendor/bionic" chdir("vendor") do Gem::GemRunner.new.run(["unpack", "bionic", "--version", "=#{version}"]) FileUtils.mv(Dir.glob("bionic*").first, "bionic") end end desc "Lock to latest Edge Bionic or a specific revision with REVISION=X (ex: REVISION=245484e), a tag with TAG=Y (ex: TAG=0.6.6), or a branch with BRANCH=Z (ex: BRANCH=mental)" task :edge do $verbose = false unless system "git --version" $stderr.puts "ERROR: Must have git available in the PATH to lock this application to Edge Bionic" exit 1 end bionic_git = "git://github.com/BigRefT/bionic_cms.git" if File.exist?("vendor/bionic/.git/HEAD") system "cd vendor/bionic; git checkout master; git pull origin master" else system "git clone #{bionic_git} vendor/bionic" end case when ENV['TAG'] system "cd vendor/bionic; git checkout -b v#{ENV['TAG']} #{ENV['TAG']}" when ENV['BRANCH'] system "cd vendor/bionic; git checkout --track -b #{ENV['BRANCH']} origin/#{ENV['BRANCH']}" when ENV['REVISION'] system "cd vendor/bionic; git checkout -b REV_#{ENV['REVISION']} #{ENV['REVISION']}" end system "cd vendor/bionic; git submodule init; git submodule update" end end desc "Unlock this application from freeze of gems or edge and return to a fluid use of system gems" task :unfreeze do rm_rf "vendor/bionic" end desc "Update configs, scripts, sass, stylesheets and javascripts from Bionic." task :update do tasks = %w{scripts javascripts configs initializers images stylesheets } tasks = tasks & ENV['ONLY'].split(',') if ENV['ONLY'] tasks = tasks - ENV['EXCEPT'].split(',') if ENV['EXCEPT'] tasks.each do |task| puts "* Updating #{task}" Rake::Task["bionic:update:#{task}"].invoke end end namespace :update do desc "Add new scripts to the instance script/ directory" task :scripts do local_base = "script" edge_base = "#{File.dirname(__FILE__)}/../../script" local = Dir["#{local_base}/**/*"].reject { |path| File.directory?(path) } edge = Dir["#{edge_base}/**/*"].reject { |path| File.directory?(path) } edge = edge.reject { |f| f =~ /(generate|plugin|destroy)$/ } edge.each do |script| base_name = script[(edge_base.length+1)..-1] next if local.detect { |path| base_name == path[(local_base.length+1)..-1] } if !File.directory?("#{local_base}/#{File.dirname(base_name)}") mkdir_p "#{local_base}/#{File.dirname(base_name)}" end install script, "#{local_base}/#{base_name}", :mode => 0755 end install "#{File.dirname(__FILE__)}/../generators/instance/templates/instance_generate", "#{local_base}/generate", :mode => 0755 end desc "Update config/boot.rb from your current bionic install" task :configs do require 'erb' FileUtils.cp("#{File.dirname(__FILE__)}/../generators/instance/templates/instance_boot.rb", RAILS_ROOT + '/config/boot.rb') instances = { :env => "#{RAILS_ROOT}/config/environment.rb", :development => "#{RAILS_ROOT}/config/environments/development.rb", :test => "#{RAILS_ROOT}/config/environments/test.rb", :production => "#{RAILS_ROOT}/config/environments/production.rb", :staging => "#{RAILS_ROOT}/config/environments/staging.rb" } tmps = { :env => "#{RAILS_ROOT}/config/environment.tmp", :development => "#{RAILS_ROOT}/config/environments/development.tmp", :test => "#{RAILS_ROOT}/config/environments/test.tmp", :production => "#{RAILS_ROOT}/config/environments/production.tmp", :staging => "#{RAILS_ROOT}/config/environments/staging.tmp" } gens = { :env => "#{File.dirname(__FILE__)}/../generators/instance/templates/instance_environment.rb", :development => "#{File.dirname(__FILE__)}/../../config/environments/development.rb", :test => "#{File.dirname(__FILE__)}/../../config/environments/test.rb", :production => "#{File.dirname(__FILE__)}/../../config/environments/production.rb", :staging => "#{File.dirname(__FILE__)}/../../config/environments/staging.rb" } backups = { :env => "#{RAILS_ROOT}/config/environment.bak", :development => "#{RAILS_ROOT}/config/environments/development.bak", :test => "#{RAILS_ROOT}/config/environments/test.bak", :production => "#{RAILS_ROOT}/config/environments/production.bak", :staging => "#{RAILS_ROOT}/config/environments/staging.bak" } @warning_start = "** WARNING ** The following files have been changed in Bionic. Your originals have been backed up with .bak extensions. Please copy your customizations to the new files:" [:env, :development, :test, :production, :staging].each do |env_type| File.open(tmps[env_type], 'w') do |f| app_name = File.basename(File.expand_path(RAILS_ROOT)) f.write ERB.new(File.read(gens[env_type])).result(binding) end unless FileUtils.compare_file(instances[env_type], tmps[env_type]) FileUtils.cp(instances[env_type], backups[env_type]) FileUtils.cp(tmps[env_type], instances[env_type]) @warnings ||= "" case env_type when :env @warnings << " - config/environment.rb" else @warnings << " - config/environments/#{env_type.to_s}.rb" end end FileUtils.rm(tmps[env_type]) end if @warnings puts @warning_start + @warnings end end desc "Update your javascripts from your current bionic install" task :javascripts do FileUtils.mkdir_p("#{RAILS_ROOT}/public/javascripts/admin/") copy_javascripts = proc do |project_dir, scripts| scripts.reject!{|s| File.basename(s) == 'overrides.js'} if File.exists?(project_dir + 'overrides.js') FileUtils.cp(scripts, project_dir) end copy_javascripts[RAILS_ROOT + '/public/javascripts/', Dir["#{File.dirname(__FILE__)}/../../public/javascripts/*.js"]] copy_javascripts[RAILS_ROOT + '/public/javascripts/admin/', Dir["#{File.dirname(__FILE__)}/../../public/javascripts/admin/*.js"]] FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/javascripts/calendar_date_select", RAILS_ROOT + '/public/javascripts/') FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/javascripts/edit_area", RAILS_ROOT + '/public/javascripts/') FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/javascripts/fckeditor", RAILS_ROOT + '/public/javascripts/') FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/javascripts/livepipe", RAILS_ROOT + '/public/javascripts/') end desc "Update admin images from your current bionic install" task :images do FileUtils.mkdir_p("#{RAILS_ROOT}/public/images/admin/") FileUtils.mkdir_p("#{RAILS_ROOT}/public/images/calendar_date_select/") FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/images/admin", RAILS_ROOT + '/public/images/') FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/images/calendar_date_select", RAILS_ROOT + '/public/images/') end desc "Update admin stylesheets from your current bionic install" task :stylesheets do FileUtils.mkdir_p("#{RAILS_ROOT}/public/stylesheets/admin/") copy_stylesheets = proc do |project_dir, scripts| scripts.reject!{|s| File.basename(s) == 'overrides.css'} if File.exists?(project_dir + 'overrides.css') FileUtils.cp(scripts, project_dir) end copy_stylesheets[RAILS_ROOT + '/public/stylesheets/', Dir["#{File.dirname(__FILE__)}/../../public/stylesheets/*.css"]] copy_stylesheets[RAILS_ROOT + '/public/stylesheets/admin/', Dir["#{File.dirname(__FILE__)}/../../public/stylesheets/admin/*.css"]] FileUtils.cp_r("#{File.dirname(__FILE__)}/../../public/stylesheets/calendar_date_select", RAILS_ROOT + '/public/stylesheets/') end desc "Update initializers from your current bionic install" task :initializers do project_dir = RAILS_ROOT + '/config/initializers/' FileUtils.mkpath project_dir initializers = Dir["#{File.dirname(__FILE__)}/../../config/initializers/*.rb"] FileUtils.cp(initializers, project_dir) end end end end
47.696517
182
0.616251
1abc20fbceeb15284c1b911e91d34c02bc807c11
14,783
require 'rexml/document' module ActiveMerchant #:nodoc: module Billing #:nodoc: # In NZ DPS supports ANZ, Westpac, National Bank, ASB and BNZ. # In Australia DPS supports ANZ, NAB, Westpac, CBA, St George and Bank of South Australia. # The Maybank in Malaysia is supported and the Citibank for Singapore. class PaymentExpressGateway < Gateway self.default_currency = 'NZD' # PS supports all major credit cards; Visa, Mastercard, Amex, Diners, BankCard & JCB. # Various white label cards can be accepted as well; Farmers, AirNZCard and Elders etc. # Please note that not all acquirers and Eftpos networks can support some of these card types. # VISA, Mastercard, Diners Club and Farmers cards are supported # # However, regular accounts with DPS only support VISA and Mastercard self.supported_cardtypes = %i[visa master american_express diners_club jcb] self.supported_countries = %w[AU FJ GB HK IE MY NZ PG SG US] self.homepage_url = 'https://www.windcave.com/' self.display_name = 'Windcave (formerly PaymentExpress)' self.live_url = 'https://sec.paymentexpress.com/pxpost.aspx' self.test_url = 'https://uat.paymentexpress.com/pxpost.aspx' APPROVED = '1' TRANSACTIONS = { purchase: 'Purchase', credit: 'Refund', authorization: 'Auth', capture: 'Complete', validate: 'Validate' } # We require the DPS gateway username and password when the object is created. # # The PaymentExpress gateway also supports a :use_custom_payment_token boolean option. # If set to true the gateway will use BillingId for the Token type. If set to false, # then the token will be sent as the DPS specified "DpsBillingId". This is per the documentation at # http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Tokenbilling def initialize(options = {}) requires!(options, :login, :password) super end # Funds are transferred immediately. # # `payment_source` can be a usual ActiveMerchant credit_card object, or can also # be a string of the `DpsBillingId` or `BillingId` which can be gotten through the # store method. If you are using a `BillingId` instead of `DpsBillingId` you must # also set the instance method `#use_billing_id_for_token` to true, see the `#store` # method for an example of how to do this. def purchase(money, payment_source, options = {}) request = build_purchase_or_authorization_request(money, payment_source, options) commit(:purchase, request) end # NOTE: Perhaps in options we allow a transaction note to be inserted # Verifies that funds are available for the requested card and amount and reserves the specified amount. # See: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Authcomplete # # `payment_source` can be a usual ActiveMerchant credit_card object or a token, see #purchased method def authorize(money, payment_source, options = {}) request = build_purchase_or_authorization_request(money, payment_source, options) commit(:authorization, request) end # Transfer pre-authorized funds immediately # See: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Authcomplete def capture(money, identification, options = {}) request = build_capture_or_credit_request(money, identification, options) commit(:capture, request) end # Refund funds to the card holder def refund(money, identification, options = {}) requires!(options, :description) request = build_capture_or_credit_request(money, identification, options) commit(:credit, request) end def credit(money, identification, options = {}) ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE refund(money, identification, options) end # Token Based Billing # # Instead of storing the credit card details locally, you can store them inside the # Payment Express system and instead bill future transactions against a token. # # This token can either be specified by your code or autogenerated by the PaymentExpress # system. The default is to let PaymentExpress generate the token for you and so use # the `DpsBillingId`. If you do not pass in any option of the `billing_id`, then the store # method will ask PaymentExpress to create a token for you. Additionally, if you are # using the default `DpsBillingId`, you do not have to do anything extra in the # initialization of your gateway object. # # To specify and use your own token, you need to do two things. # # Firstly, pass in a `:billing_id` as an option in the hash of this store method. No # validation is done on this BillingId by PaymentExpress so you must ensure that it is unique. # # gateway.store(credit_card, {:billing_id => 'YourUniqueBillingId'}) # # Secondly, you will need to pass in the option `{:use_custom_payment_token => true}` when # initializing your gateway instance, like so: # # gateway = ActiveMerchant::Billing::PaymentExpressGateway.new( # :login => 'USERNAME', # :password => 'PASSWORD', # :use_custom_payment_token => true # ) # # see: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Tokenbilling # # Note, once stored, PaymentExpress does not support unstoring a stored card. def store(credit_card, options = {}) request = build_token_request(credit_card, options) commit(:validate, request) end def supports_scrubbing true end def scrub(transcript) transcript. gsub(%r((<PostPassword>).+(</PostPassword>)), '\1[FILTERED]\2'). gsub(%r((Authorization: Basic )\w+), '\1[FILTERED]\2'). gsub(%r((<CardNumber>)\d+(</CardNumber>)), '\1[FILTERED]\2'). gsub(%r((<Cvc2>)\d+(</Cvc2>)), '\1[FILTERED]\2') end private def use_custom_payment_token? @options[:use_custom_payment_token] end def build_purchase_or_authorization_request(money, payment_source, options) result = new_transaction if payment_source.is_a?(String) add_billing_token(result, payment_source) else add_credit_card(result, payment_source) end add_amount(result, money, options) add_invoice(result, options) add_address_verification_data(result, options) add_optional_elements(result, options) add_ip(result, options) result end def build_capture_or_credit_request(money, identification, options) result = new_transaction add_amount(result, money, options) add_invoice(result, options) add_reference(result, identification) add_optional_elements(result, options) add_ip(result, options) result end def build_token_request(credit_card, options) result = new_transaction add_credit_card(result, credit_card) add_amount(result, 100, options) # need to make an auth request for $1 add_token_request(result, options) add_optional_elements(result, options) add_ip(result, options) result end def add_credentials(xml) xml.add_element('PostUsername').text = @options[:login] xml.add_element('PostPassword').text = @options[:password] end def add_reference(xml, identification) xml.add_element('DpsTxnRef').text = identification end def add_credit_card(xml, credit_card) xml.add_element('CardHolderName').text = credit_card.name xml.add_element('CardNumber').text = credit_card.number xml.add_element('DateExpiry').text = format_date(credit_card.month, credit_card.year) if credit_card.verification_value? xml.add_element('Cvc2').text = credit_card.verification_value xml.add_element('Cvc2Presence').text = '1' end end def add_billing_token(xml, token) if use_custom_payment_token? xml.add_element('BillingId').text = token else xml.add_element('DpsBillingId').text = token end end def add_token_request(xml, options) xml.add_element('BillingId').text = options[:billing_id] if options[:billing_id] xml.add_element('EnableAddBillCard').text = 1 end def add_amount(xml, money, options) xml.add_element('Amount').text = amount(money) xml.add_element('InputCurrency').text = options[:currency] || currency(money) end def add_transaction_type(xml, action) xml.add_element('TxnType').text = TRANSACTIONS[action] end def add_invoice(xml, options) xml.add_element('TxnId').text = options[:order_id].to_s.slice(0, 16) unless options[:order_id].blank? xml.add_element('MerchantReference').text = options[:description].to_s.slice(0, 50) unless options[:description].blank? end def add_address_verification_data(xml, options) address = options[:billing_address] || options[:address] return if address.nil? xml.add_element('EnableAvsData').text = 1 xml.add_element('AvsAction').text = 1 xml.add_element('AvsStreetAddress').text = address[:address1] xml.add_element('AvsPostCode').text = address[:zip] end def add_ip(xml, options) xml.add_element('ClientInfo').text = options[:ip] if options[:ip] end # The options hash may contain optional data which will be passed # through the specialized optional fields at PaymentExpress # as follows: # # { # :client_type => :web, # Possible values are: :web, :ivr, :moto, :unattended, :internet, or :recurring # :txn_data1 => "String up to 255 characters", # :txn_data2 => "String up to 255 characters", # :txn_data3 => "String up to 255 characters" # } # # +:client_type+, while not documented for PxPost, will be sent as # the +ClientType+ XML element as described in the documentation for # the PaymentExpress WebService: http://www.paymentexpress.com/Technical_Resources/Ecommerce_NonHosted/WebService#clientType # (PaymentExpress have confirmed that this value works the same in PxPost). # The value sent for +:client_type+ will be normalized and sent # as one of the explicit values allowed by PxPost: # # :web => "Web" # :ivr => "IVR" # :moto => "MOTO" # :unattended => "Unattended" # :internet => "Internet" # :recurring => "Recurring" # # If you set the +:client_type+ to any value not listed above, # the ClientType element WILL NOT BE INCLUDED at all in the # POST data. # # +:txn_data1+, +:txn_data2+, and +:txn_data3+ will be sent as # +TxnData1+, +TxnData2+, and +TxnData3+, respectively, and are # free form fields of the merchant's choosing, as documented here: # http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#txndata # # These optional elements are added to all transaction types: # +purchase+, +authorize+, +capture+, +refund+, +store+ def add_optional_elements(xml, options) if client_type = normalized_client_type(options[:client_type]) xml.add_element('ClientType').text = client_type end xml.add_element('TxnData1').text = options[:txn_data1].to_s.slice(0, 255) unless options[:txn_data1].blank? xml.add_element('TxnData2').text = options[:txn_data2].to_s.slice(0, 255) unless options[:txn_data2].blank? xml.add_element('TxnData3').text = options[:txn_data3].to_s.slice(0, 255) unless options[:txn_data3].blank? end def new_transaction REXML::Document.new.add_element('Txn') end # Take in the request and post it to DPS def commit(action, request) add_credentials(request) add_transaction_type(request, action) url = test? ? self.test_url : self.live_url # Parse the XML response response = parse(ssl_post(url, request.to_s)) # Return a response PaymentExpressResponse.new(response[:success] == APPROVED, message_from(response), response, test: response[:test_mode] == '1', authorization: authorization_from(action, response) ) end # Response XML documentation: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#XMLTxnOutput def parse(xml_string) response = {} xml = REXML::Document.new(xml_string) # Gather all root elements such as HelpText xml.elements.each('Txn/*') do |element| response[element.name.underscore.to_sym] = element.text unless element.name == 'Transaction' end # Gather all transaction elements and prefix with "account_" # So we could access the MerchantResponseText by going # response[account_merchant_response_text] xml.elements.each('Txn/Transaction/*') do |element| response[element.name.underscore.to_sym] = element.text end response end def message_from(response) (response[:card_holder_help_text] || response[:response_text]) end def authorization_from(action, response) case action when :validate (response[:billing_id] || response[:dps_billing_id]) else response[:dps_txn_ref] end end def format_date(month, year) "#{format(month, :two_digits)}#{format(year, :two_digits)}" end def normalized_client_type(client_type_from_options) case client_type_from_options.to_s.downcase when 'web' then 'Web' when 'ivr' then 'IVR' when 'moto' then 'MOTO' when 'unattended' then 'Unattended' when 'internet' then 'Internet' when 'recurring' then 'Recurring' else nil end end end class PaymentExpressResponse < Response # add a method to response so we can easily get the token # for Validate transactions def token @params['billing_id'] || @params['dps_billing_id'] end end end end
39.954054
130
0.656633
1ca4b7b57a329e598d2356c51aa10db5aafa1d85
277
maintainer "VMware" maintainer_email "[email protected]" license "Apache 2.0" description "Installs/Configures ACM Database" long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) version "0.0.1" depends "postgresql"
30.777778
74
0.68231
877c0caaf0a38376ba239d8ec369b675834be823
990
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v7/services/hotel_performance_view_service.proto require 'google/ads/googleads/v7/resources/hotel_performance_view_pb' require 'google/api/annotations_pb' require 'google/api/client_pb' require 'google/api/field_behavior_pb' require 'google/api/resource_pb' require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v7/services/hotel_performance_view_service.proto", :syntax => :proto3) do add_message "google.ads.googleads.v7.services.GetHotelPerformanceViewRequest" do optional :resource_name, :string, 1 end end end module Google module Ads module GoogleAds module V7 module Services GetHotelPerformanceViewRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.services.GetHotelPerformanceViewRequest").msgclass end end end end end
33
175
0.777778
ab1cb53ca5094024fa59af1c74ecb4db8796620a
946
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## Plugin.define "Zeus-Traffic-Manager" do author "Brendan Coles <[email protected]>" # 2011-03-17 version "0.1" description "Zeus Traffic Manager - Application Delivery Controller - allows you to deliver fast, secure and available applications to your users at minimum infrastructure cost across any combination of physical, virtual and cloud infrastructures." website "http://www.zeus.com/products/traffic-manager/index.html" # ShodanHQ results as at 2011-03-17 # # 8,788 for set-cookie X-Mapping # Passive # def passive m=[] # Set-Cookie # X-Mapping m << { :name=>"Set-Cookie" } if @headers["set-cookie"] =~ /^X-Mapping-[a-z]{8}=([A-F\d]{32}|deleted);/ # Return passive matches m end end
29.5625
248
0.739958
33e367f3776ba4eb6426bf0191c8c3ef33a8698a
178
# Superdigit # Time Complexity - ? # Space Complexity - ? def super_digit(n) end # Time Complexity - ? # Space Complexity - ? def refined_super_digit(n, k) end
11.866667
29
0.634831
03f3977d02857d769941ebb6c0737d3ac9311672
1,367
$:.push File.expand_path("lib", __dir__) require "openopus/core/people/version" Gem::Specification.new do |spec| spec.name = "openopus-core-people" spec.version = Openopus::Core::People::VERSION spec.authors = ["Brian J. Fox"] spec.email = ["[email protected]"] spec.homepage = "https://github.com/opuslogica/openopus-core-people" spec.summary = "Model the real world of people in your application, making user interaction robust." spec.description = "A person can have many email addresses, but this is not usually represented in applications. openopus/core/people creates the database structure, relations, and convenience functions for your application so you don't have to. Just connect your end user model, and away you go." spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata["allowed_push_host"] = "https://rubygems.org" else raise "RubyGems 2.0 or newer is required to protect against public gem pushes." end spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] spec.add_dependency "rails", "~> 6.0.3" spec.add_dependency "bcrypt", "~> 3.1.13" end
48.821429
301
0.713241
d51df05a516dc44333d86fceaf0b5415f488c519
213
class CreateCategories < ActiveRecord::Migration[6.0] def change create_table :categories do |t| t.string :name t.boolean :display_in_navbar, default: false t.timestamps end end end
19.363636
53
0.685446
e9ecdd558b0af17cde6b141861e44b74e0525b23
1,699
# tests for ability to set defaults for Watir $LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..') unless $SETUP_LOADED require 'unittests/setup' class TC_instance_options < Test::Unit::TestCase tags :fails_on_firefox def setup @ie4 = Watir::IE.new end def test_using_default @ie4.speed = :fast assert_equal(:fast, @ie4.speed) @ie4.speed = :slow assert_equal(:slow, @ie4.speed) @ie4.speed = :zippy assert_equal(:zippy, @ie4.speed) assert_raise(ArgumentError){@ie4.speed = :fubar} end def teardown @ie4.close if @ie4.exists? end end class TC_class_options < Test::Unit::TestCase tags :fails_on_firefox include Watir @@hide_ie = $HIDE_IE def setup @previous = IE.options end def test_class_defaults assert_equal({:speed => IE.speed, :visible => IE.visible, :attach_timeout => IE.attach_timeout}, IE.options) end def test_change_defaults IE.set_options(:speed => :fast) assert_equal(:fast, IE.speed) IE.set_options(:visible => false) assert_equal(false, IE.visible) IE.set_options(:speed => :slow) assert_equal(:slow, IE.speed) IE.set_options(:visible => true) assert_equal(true, IE.visible) IE.set_options(:attach_timeout => 22.0) assert_equal(22.0, IE.attach_timeout) end def test_defaults_affect_on_instance IE.set_options(:speed => :fast) @ie1 = IE.new assert_equal(:fast, @ie1.speed) IE.set_options(:speed => :slow) @ie2 = IE.new assert_equal(:slow, @ie2.speed) IE.set_options(:speed => :zippy) @ie3 = IE.new assert_equal(:zippy, @ie3.speed) end def teardown IE.set_options @previous @ie1.close if @ie1 @ie2.close if @ie2 @ie3.close if @ie3 end end
25.358209
110
0.695115
18b940993e850979b14e6ee7a6d590d4e3d39ae6
2,178
require 'rails_helper' RSpec.describe BulkAttendanceImporter do let(:bulk_attendance_importer) { BulkAttendanceImporter.new } describe '#import' do context 'json' do let(:file) { File.open("#{Rails.root}/spec/fixtures/kipp_nj_fixtures/fake_att.json").read } let(:transformer) { JsonTransformer.new } let(:json) { transformer.transform(file) } context 'mixed good & bad rows' do it 'imports the valid absences' do expect { bulk_attendance_importer.start_import(json) }.to change(Absence, :count).by(2) end it 'does not import any tardies' do expect { bulk_attendance_importer.start_import(json) }.not_to change(Tardy, :count) end end end context 'csv' do let(:file) { File.open("#{Rails.root}/spec/fixtures/fake_attendance_export.txt") } let(:local_id_from_file) { '10' } let(:date_from_file) { DateTime.parse('2005-09-16') } let(:school_year) { DateToSchoolYear.new(date_from_file).convert } let(:transformer) { CsvTransformer.new } let(:csv) { transformer.transform(file) } context 'mixed good & bad rows' do it 'imports two valid attendance rows' do expect { bulk_attendance_importer.start_import(csv) }.to change(Absence, :count).by 2 end context 'existing student school year' do let(:student) { FactoryGirl.create(:student, local_id: local_id_from_file) } let(:student_school_year) { StudentSchoolYear.create(student: student, school_year: school_year) } it 'assigns absences to the existing student' do expect { bulk_attendance_importer.start_import(csv) }.to change { student_school_year.reload.absences.count }.by(1) end end context 'missing students' do it 'creates new students' do expect { bulk_attendance_importer.start_import(csv) }.to change(Student, :count).by 2 end end end end end end
33
97
0.606061
f7e7354760e28239ba652bb54ee70c822dc2799e
2,337
require 'test_helper' require 'mailer_helpers' class DbMailerHelperTest < ActionMailer::TestCase include MailerHelpers setup do @user = { full_name: "Ezra Bridger", email: "[email protected]" } end test "can send a basic template email" do assert true end test 'get this mailer from the db' do mail_template = email_me_mail_templates(:mail_template_one) email = GenericMailer.generic_email("mail_template_one_name", @user).deliver_now assert_not ActionMailer::Base.deliveries.empty? assert_equal ['[email protected]'], email.from assert_equal mail_template.subject, email.subject assert_not_empty get_message_part(email, /plain/) assert_not_empty get_message_part(email, /html/) end test 'should correctly translate links' do mail_template = email_me_mail_templates(:mail_template_with_md_url) email = GenericMailer.generic_email("mail_template_with_md_url_name", @user).deliver_now assert_not ActionMailer::Base.deliveries.empty? assert_equal ['[email protected]'], email.from assert_equal mail_template.subject, email.subject plain_text = get_message_part(email, /plain/) assert_not_empty plain_text assert plain_text.include? "(http://www.devis.com)" html_text = get_message_part(email, /html/) assert_not_empty html_text assert html_text.include? 'href="http://www.devis.com"' end test 'can replace fields with liquid' do mail_template = email_me_mail_templates(:mail_template_with_liquid) email = GenericMailer.generic_email("mail_template_with_liquid_name", @user).deliver_now assert_not ActionMailer::Base.deliveries.empty? assert_equal ['[email protected]'], email.from assert_equal mail_template.subject, email.subject plain_text = get_message_part(email, /plain/) assert_not_empty plain_text assert plain_text.include? @user[:full_name] html_text = get_message_part(email, /html/) assert_not_empty html_text assert html_text.include? @user[:full_name] end end class GenericMailer < ActionMailer::Base include EmailMe::DbMailerHelper default :from => '[email protected]' def generic_email(template_name, user) params = {'user_full_name' => user[:full_name]} mail_template_email template_name, user[:email], params end end
31.581081
92
0.749679
7a91887b405d74f244157839d3a82204a2218980
437
#!/usr/local/bin/ruby -w ENV['GEM_SKIP'] = 'ParseTree:RubyInline' $:.push 'lib', '../../ParseTree/dev/lib', '../../RubyInline/dev', '../../ruby_to_c/dev' require 'r2c_hacks' class Example def example(arg1) return "Blah: " + arg1.to_s end end e = Example.new puts "Code (via cat):" puts `cat #{$0}` puts "sexp:" p e.method(:example).to_sexp puts "C:" puts e.method(:example).to_c puts "Ruby:" puts e.method(:example).to_ruby
18.208333
87
0.645309
87ccdeac9851ff1012019a2c01b776f4bb9ffefa
91
require "test/unit" require "win-service" class TestWinService < Test::Unit::TestCase end
15.166667
43
0.769231
b934c9648d6ab3a122944f361d8e413f314a30c3
620
# encoding: utf-8 # frozen_string_literal: true require 'helper' class TestFakerEducationCN < Test::Unit::TestCase include DeterministicHelper assert_methods_are_deterministic(FFaker::EducationCN, :degree, :major, :location, :school) def setup @tester = FFaker::EducationCN end def test_degree assert @tester.degree.match(/[\u4e00-\u9fa5]{4,}/) end def test_major assert @tester.major.match(/[\u4e00-\u9fa5]{2,}/) end def test_location assert @tester.location.match(/[\u4e00-\u9fa5]{2,}/) end def test_school assert @tester.school.match(/[\u4e00-\u9fa5]{4,}/) end end
20
92
0.7
b98fd5c7513f80ccb288f4d14eb242b4d5f02266
1,076
Given('there is an event called {string} that has an instance for the year {int}') do |event_name, year| event = create(:event, name: event_name) create(:event_instance, event: event, year: year) end When(/^I add an event instance with the following information:$/) do |table| instance_info = table.raw.to_h if Event.find_by(name: instance_info['name']) page.select(instance_info['name'], from: :event_instance_event_id) else page.fill_in(:event_instance_new_parent_event_name, with: instance_info['name']) end page.fill_in(:event_instance_year, with: instance_info['year']) page.click_on('Add event') end When('I am on the {string} event instance page for the year {int}') do |event_name, year| instance = Event.find_by(name: event_name).instances.find_by(year: year) page.visit event_instance_path(instance) end Then('I should see {string} in the {int} instance block') do |proposal_title, year| event_id = @event.name.downcase.split.join('-') within("##{event_id}-#{year}") do expect(page).to have_content(proposal_title) end end
35.866667
104
0.732342
ff48650f3526320ef2bc892fa842c0484c3d2fa8
1,125
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "Nabeel_gem/version" Gem::Specification.new do |spec| spec.name = "Nabeel_gem" spec.version = NabeelGem::VERSION spec.authors = ["NabeelMustafa"] spec.email = ["[email protected]"] spec.summary = %q{Various method added to this gem using in my app.} spec.description = %q{Add copy wright basic syntax in footer} spec.homepage = "https://nabeelmustafa.me" spec.license = "MIT" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 10.0" end
38.793103
87
0.651556
38d4412a98c46fe04f919942f13f1a797c82af30
1,546
cask 'totalspaces' do if MacOS.release <= :mountain_lion version '1.2.11' sha256 'fd54c6ea092f6fae2035745959ff6e080953e77ec6c76715e532b4b0352235d4' url "http://downloads.binaryage.com/TotalSpaces-#{version}.zip" appcast 'http://updates-s3.binaryage.com/totalspaces.xml', :checkpoint => 'f52e1870289fb95d89b1cab7c42da7c824cbc582b0ea46d8bd3e9c47be81a69a' pkg 'TotalSpaces.pkg' uninstall :pkgutil => 'com.switchstep.totalspaces', :quit => 'com.binaryage.TotalSpaces' else version '2.3.6' sha256 '1771d91df0a9fe74fa80425cfb774d8342837ec5fb570d66c3726c96143ac0a9' url "http://downloads.binaryage.com/TotalSpaces2-#{version}.dmg" appcast 'http://updates-s3.binaryage.com/totalspaces2.xml', :checkpoint => 'f52e1870289fb95d89b1cab7c42da7c824cbc582b0ea46d8bd3e9c47be81a69a' installer :manual => 'TotalSpaces2.app' uninstall :pkgutil => 'com.binaryage.TotalSpaces2', :script => { :executable => 'TotalSpaces2 Uninstaller.app/Contents/MacOS/TotalSpaces2 Uninstaller', :args => %w[--headless], }, :quit => 'com.binaryage.TotalSpaces2' end name 'TotalSpaces' homepage 'http://totalspaces.binaryage.com/' license :commercial uninstall :signal => [ ['INT', 'com.binaryage.totalspacescrashwatcher'], ['KILL', 'com.binaryage.totalspacescrashwatcher'], ] end
37.707317
114
0.638422
e2caadf6768d73abdc005edbcda2f3807cf5e1c3
2,368
# +------------------------------------------------------------------------- # | Copyright (C) 2016 Yunify, Inc. # +------------------------------------------------------------------------- # | Licensed under the Apache License, Version 2.0 (the "License"); # | you may not use this work except in compliance with the License. # | You may obtain a copy of the License in the LICENSE file, or at: # | # | http://www.apache.org/licenses/LICENSE-2.0 # | # | Unless required by applicable law or agreed to in writing, software # | distributed under the License is distributed on an "AS IS" BASIS, # | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # | See the License for the specific language governing permissions and # | limitations under the License. # +------------------------------------------------------------------------- require "active_support/core_ext/hash/keys" module QingCloud module SDK class JobService attr_accessor :config, :properties def initialize(config, properties) self.config = config self.properties = properties.deep_symbolize_keys end # Documentation URL: https://docs.qingcloud.com/api/job/describe_jobs.html def describe_jobs(jobs: [], limit: nil, offset: nil, owner: "", status: [], verbose: nil) input = { config: config, properties: properties, api_name: "DescribeJobs", request_method: "GET", request_params: { "jobs" => jobs, "limit" => limit, "offset" => offset, "owner" => owner, "status" => status, "verbose" => verbose, # verbose's available values: 0 }, } describe_jobs_input_validate input request = Request.new input request.send end private def describe_jobs_input_validate(input) input.deep_stringify_keys! unless input["request_params"]["verbose"].to_s.empty? verbose_valid_values = ["0"] unless verbose_valid_values.include? input["request_params"]["verbose"].to_s raise ParameterValueNotAllowedError.new( "verbose", input["request_params"]["verbose"], verbose_valid_values ) end end end end end end
33.352113
95
0.556588
e9efa45fcc566fd7e8a4d0382b71a29cfeacc449
516
cask 'people-plus-content-ip' do version '1.0.1' sha256 '4a29e7eb0901db45572e7dac108df74b52015c75d4aaa9fe774b5027b8bf9990' url "http://www.polycom.co.uk/content/dam/polycom/common/documents/firmware/PPCIPmac_v#{version}.dmg.zip" name 'People + Content IP' homepage 'http://www.polycom.co.uk/products-services/hd-telepresence-video-conferencing/realpresence-accessories/people-content-ip.html#stab1' license :gratis container :nested => "PPCIPmac_v#{version}.dmg" app 'People + Content IP.app' end
36.857143
144
0.775194
e8a9e3cec30cf58ac564f2c3d5b902180b537831
25
module BillingHelper end
8.333333
20
0.88
013798f8e8fb96284374e824473493aa227fa2d5
7,865
require File.dirname(__FILE__) + '/test_helper' class HashExtensionsTest < Test::Unit::TestCase def test_to_query_string # Because hashes aren't ordered, I'm mostly testing against hashes with just one key symbol_keys = {:one => 1} string_keys = {'one' => 1} expected = '?one=1' [symbol_keys, string_keys].each do |hash| assert_equal expected, hash.to_query_string end end def test_empty_hash_returns_no_query_string assert_equal '', {}.to_query_string end def test_include_question_mark hash = {:one => 1} assert_equal '?one=1', hash.to_query_string assert_equal 'one=1', hash.to_query_string(false) end def test_elements_joined_by_ampersand hash = {:one => 1, :two => 2} qs = hash.to_query_string assert qs['one=1&two=2'] || qs['two=2&one=1'] end def test_normalized_options expectations = [ [{:foo_bar => 1}, {'foo-bar' => '1'}], [{'foo_bar' => 1}, {'foo-bar' => '1'}], [{'foo-bar' => 1}, {'foo-bar' => '1'}], [{}, {}] ] expectations.each do |(before, after)| assert_equal after, before.to_normalized_options end end end class StringExtensionsTest < Test::Unit::TestCase def test_previous expectations = {'abc' => 'abb', '123' => '122', '1' => '0'} expectations.each do |before, after| assert_equal after, before.previous end end def test_to_header transformations = { 'foo' => 'foo', :foo => 'foo', 'foo-bar' => 'foo-bar', 'foo_bar' => 'foo-bar', :foo_bar => 'foo-bar', 'Foo-Bar' => 'foo-bar', 'Foo_Bar' => 'foo-bar' } transformations.each do |before, after| assert_equal after, before.to_header end end def test_utf8? assert !"318597/620065/GTL_75\24300_A600_A610.zip".utf8? assert "318597/620065/GTL_75£00_A600_A610.zip".utf8? end def test_remove_extended assert "318597/620065/GTL_75\24300_A600_A610.zip".remove_extended.utf8? assert "318597/620065/GTL_75£00_A600_A610.zip".remove_extended.utf8? end end class CoercibleStringTest < Test::Unit::TestCase def test_coerce coercions = [ ['1', 1], ['false', false], ['true', true], ['2006-10-29T23:14:47.000Z', Time.parse('2006-10-29T23:14:47.000Z')], ['Hello!', 'Hello!'], ['false23', 'false23'], ['03 1-2-3-Apple-Tree.mp3', '03 1-2-3-Apple-Tree.mp3'], ['0815', '0815'] # This number isn't coerced because the leading zero would be lost ] coercions.each do |before, after| assert_nothing_raised do assert_equal after, CoercibleString.coerce(before) end end end end class KerneltExtensionsTest < Test::Unit::TestCase class Foo def foo __method__ end def bar foo end def baz bar end end class Bar def foo calling_method end def bar calling_method end def calling_method __method__(1) end end def test___method___works_regardless_of_nesting f = Foo.new [:foo, :bar, :baz].each do |method| assert_equal 'foo', f.send(method) end end def test___method___depth b = Bar.new assert_equal 'foo', b.foo assert_equal 'bar', b.bar end end class ModuleExtensionsTest < Test::Unit::TestCase class Foo def foo(reload = false) expirable_memoize(reload) do Time.now end end def bar(reload = false) expirable_memoize(reload, :baz) do Time.now end end def quux Time.now end memoized :quux end def setup @instance = Foo.new end def test_memoize assert [email protected]_variables.include?('@foo') cached_result = @instance.foo assert_equal cached_result, @instance.foo assert @instance.instance_variables.include?('@foo') assert_equal cached_result, @instance.send(:instance_variable_get, :@foo) assert_not_equal cached_result, new_cache = @instance.foo(:reload) assert_equal new_cache, @instance.foo assert_equal new_cache, @instance.send(:instance_variable_get, :@foo) end def test_customizing_memoize_storage assert [email protected]_variables.include?('@bar') assert [email protected]_variables.include?('@baz') cached_result = @instance.bar assert [email protected]_variables.include?('@bar') assert @instance.instance_variables.include?('@baz') assert_equal cached_result, @instance.bar assert_equal cached_result, @instance.send(:instance_variable_get, :@baz) assert_nil @instance.send(:instance_variable_get, :@bar) end def test_memoized assert [email protected]_variables.include?('@quux') cached_result = @instance.quux assert_equal cached_result, @instance.quux assert @instance.instance_variables.include?('@quux') assert_equal cached_result, @instance.send(:instance_variable_get, :@quux) assert_not_equal cached_result, new_cache = @instance.quux(:reload) assert_equal new_cache, @instance.quux assert_equal new_cache, @instance.send(:instance_variable_get, :@quux) end def test_constant_setting some_module = Module.new assert !some_module.const_defined?(:FOO) assert_nothing_raised do some_module.constant :FOO, 'bar' end assert some_module.const_defined?(:FOO) assert_nothing_raised do some_module::FOO some_module.foo end assert_equal 'bar', some_module::FOO assert_equal 'bar', some_module.foo assert_nothing_raised do some_module.constant :FOO, 'baz' end assert_equal 'bar', some_module::FOO assert_equal 'bar', some_module.foo end end class AttributeProxyTest < Test::Unit::TestCase class BlindProxyUsingDefaultAttributesHash include SelectiveAttributeProxy proxy_to :exlusively => false end class BlindProxyUsingCustomAttributeHash include SelectiveAttributeProxy proxy_to :settings end class ProxyUsingPassedInAttributeHash include SelectiveAttributeProxy def initialize(attributes = {}) @attributes = attributes end end class RestrictedProxy include SelectiveAttributeProxy private def proxiable_attribute?(name) %w(foo bar baz).include?(name) end end class NonExclusiveProxy include SelectiveAttributeProxy proxy_to :settings, :exclusively => false end def test_using_all_defaults b = BlindProxyUsingDefaultAttributesHash.new assert_nothing_raised do b.foo = 'bar' end assert_nothing_raised do b.foo end assert_equal 'bar', b.foo end def test_storage_is_autovivified b = BlindProxyUsingDefaultAttributesHash.new assert_nothing_raised do b.send(:attributes)['foo'] = 'bar' end assert_nothing_raised do b.foo end assert_equal 'bar', b.foo end def test_limiting_which_attributes_are_proxiable r = RestrictedProxy.new assert_nothing_raised do r.foo = 'bar' end assert_nothing_raised do r.foo end assert_equal 'bar', r.foo assert_raises(NoMethodError) do r.quux = 'foo' end assert_raises(NoMethodError) do r.quux end end def test_proxying_is_exclusive_by_default p = ProxyUsingPassedInAttributeHash.new('foo' => 'bar') assert_nothing_raised do p.foo p.foo = 'baz' end assert_equal 'baz', p.foo assert_raises(NoMethodError) do p.quux end end def test_setting_the_proxy_as_non_exclusive n = NonExclusiveProxy.new assert_nothing_raised do n.foo = 'baz' end assert_nothing_raised do n.foo end assert_equal 'baz', n.foo end end
23.761329
89
0.65658
d51534fda49a009c80c2b370368f106cb91c3963
3,502
require 'sequel' require 'merb_global/plural' module Merb module Global module MessageProviders class Sequel #:nodoc: all include Merb::Global::MessageProviders::Base include Merb::Global::MessageProviders::Base::Importer include Merb::Global::MessageProviders::Base::Exporter def localize(singular, plural, n, locale) # I hope it's from MemCache language = Language[:name => locale.to_s] unless language.nil? unless plural.nil? pn = Plural.which_form n, language[:plural] translation = Translation[language.pk, singular, pn] else translation = Translation[language.pk, singular, nil] end return translation[:msgstr] unless translation.nil? end return n > 1 ? plural : singular # Fallback if not in database end def create! migration_exists = Dir[File.join(Merb.root, 'schema', 'migrations', "*.rb")].detect do |f| f =~ /translations\.rb/ end if migration_exists puts "\nThe Translation Migration File already exists\n\n" else sh %{merb-gen translations_migration} end end def import data = {} DB.transaction do Language.each do |lang| data[lang[:name]] = lang_hash = { :plural => lang[:plural], :nplural => lang[:nplural] } lang.translations.each do |translation| lang_hash[translation[:msgid]] ||= { :plural => translation[:msgid_plural] } lang_hash[translation[:msgid]][translation[:msgstr_index]] = translation[:msgstr] end end end data end def export(data) DB.transaction do Language.delete Translation.delete data.each do |lang_name, lang| lang_obj = Language.create(:name => lang_name, :plural => lang[:plural], :nplural => lang[:nplural]) or raise lang_id = lang_obj[:id] lang.each do |msgid, msgstrs| if msgid.is_a? String plural = msgstrs[:plural] msgstrs.each do |index, msgstr| if index.nil? or index.is_a? Fixnum Translation.create(:language_id => lang_id, :msgid => msgid, :msgid_plural => plural, :msgstr => msgstr, :msgstr_index => index) or raise end end end end end end end class Language < ::Sequel::Model(:merb_global_languages) set_primary_key :id one_to_many :translations, :class => "Merb::Global::MessageProviders::Sequel::Translation", :key => :language_id end class Translation < ::Sequel::Model(:merb_global_translations) set_primary_key :language_id, :msgid, :msgstr_index unrestrict_primary_key end end end end end
34.673267
86
0.488007
5dcb7369bac8fea64692a587895565ebc8ea7a87
1,547
module Spree class CustomUserGenerator < Rails::Generators::NamedBase include Rails::Generators::ResourceHelpers include Rails::Generators::Migration desc "Set up a Spree installation with a custom User class" def self.source_paths paths = self.superclass.source_paths paths << File.expand_path('../templates', __FILE__) paths.flatten end def check_for_constant begin klass rescue NameError @shell.say "Couldn't find #{class_name}. Are you sure that this class exists within your application and is loaded?", :red exit(1) end end def generate migration_template 'migration.rb.tt', "db/migrate/add_spree_fields_to_custom_user_table.rb" template 'authentication_helpers.rb.tt', "lib/spree/authentication_helpers.rb" file_action = File.exist?('config/initializers/spree.rb') ? :append_file : :create_file send(file_action, 'config/initializers/spree.rb') do %Q{ Rails.application.config.to_prepare do require_dependency 'spree/authentication_helpers' end\n} end end def self.next_migration_number(dirname) if ApplicationRecord.timestamped_migrations sleep 1 # make sure to get a different migration every time Time.new.utc.strftime("%Y%m%d%H%M%S") else "%.3d" % (current_migration_number(dirname) + 1) end end def klass class_name.constantize end def table_name klass.table_name end end end
27.140351
130
0.672915
037ca7ab2f0c478aad3dc464fb8c0623c8d04bb8
1,965
Rails.application.routes.draw do resources :user_sessions resources :users resources :groups do member do post :remove_permission post :add_permission end resources :forms do resources :responses end end get 'login' => 'user_sessions#new', :as => :login post 'logout' => 'user_sessions#destroy', :as => :logout root to: 'groups', action: 'home' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
26.2
84
0.64631
218dfd0621adb41e041e95805169dde00beba7e5
1,862
describe 'API configuration (config/api.yml)' do let(:api_settings) { Api::ApiConfig } describe 'collections' do let(:collection_settings) { api_settings.collections } it "is sorted a-z" do actual = collection_settings.keys expected = collection_settings.keys.sort expect(actual).to eq(expected) end describe 'identifiers' do let(:miq_product_features) do identifiers = Set.new each_product_feature { |f| identifiers.add(f[:identifier]) } identifiers end let(:api_feature_identifiers) do collection_settings.each_with_object(Set.new) do |(_, cfg), set| Array(cfg[:identifier]).each { |id| set.add(id) } keys = [:collection_actions, :resource_actions, :subcollection_actions, :subresource_actions] Array(cfg[:subcollections]).each do |s| keys << "#{s}_subcollection_actions" << "#{s}_subresource_actions" end keys.each do |action_type| next unless cfg[action_type] cfg[action_type].each do |_, method_cfg| method_cfg.each do |action_cfg| next unless action_cfg[:identifier] Array(action_cfg[:identifier]).each { |id| set.add(id) } end end end end end it 'is not empty' do expect(api_feature_identifiers).not_to be_empty end it 'contains only valid miq_feature identifiers' do dangling = api_feature_identifiers - miq_product_features expect(dangling).to be_empty end def each_product_feature(feature = YAML.load_file("#{MiqProductFeature::FIXTURE_PATH}.yml"), &block) block.call(feature) Array(feature[:children]).each do |child| each_product_feature(child, &block) end end end end end
32.666667
106
0.626208
e246ad86cd202de858e251c83d8457aa464d65ed
1,269
class ProtectedFoodDrinkName < Document validates :register, presence: true validates :status, presence: true validates :class_category, presence: true validates :protection_type, presence: true validates :country, presence: true validates :traditional_term_grapevine_product_category, presence: true, allow_blank: true validates :traditional_term_type, presence: true, allow_blank: true validates :traditional_term_language, presence: true, allow_blank: true validates :date_application, presence: true, date: true, allow_blank: true validates :date_registration, presence: true, date: true validates :date_registration_eu, presence: true, date: true, allow_blank: true FORMAT_SPECIFIC_FIELDS = %i( register status class_category protection_type country traditional_term_grapevine_product_category traditional_term_type traditional_term_language date_application date_registration date_registration_eu ).freeze attr_accessor(*FORMAT_SPECIFIC_FIELDS) def initialize(params = {}) super(params, FORMAT_SPECIFIC_FIELDS) end def self.title "Protected Geographical Food and Drink Name" end def primary_publishing_organisation "de4e9dc6-cca4-43af-a594-682023b84d6c" end end
30.214286
91
0.781718
6224d08248959fa65b0b0e5bcb61e113bdf6bb91
1,440
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/spanner_v1/service.rb' require 'google/apis/spanner_v1/classes.rb' require 'google/apis/spanner_v1/representations.rb' module Google module Apis # Cloud Spanner API # # Cloud Spanner is a managed, mission-critical, globally consistent and scalable # relational database service. # # @see https://cloud.google.com/spanner/ module SpannerV1 VERSION = 'V1' REVISION = '20200905' # View and manage your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' # Administer your Spanner databases AUTH_SPANNER_ADMIN = 'https://www.googleapis.com/auth/spanner.admin' # View and manage the contents of your Spanner databases AUTH_SPANNER_DATA = 'https://www.googleapis.com/auth/spanner.data' end end end
34.285714
84
0.732639