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
|
---|---|---|---|---|---|
ffe09e63aee5faf69d286ba3a3414aa63851fe2a | 811 | Pod::Spec.new do |s|
s.name = "Localytics-AMP"
s.version = "2.21.0"
s.summary = "Localytics AMP iOS SDK"
s.description = "Localytics analytics and marketing platform"
s.homepage = "http://www.localytics.com"
s.license = {
:type => 'Copyright',
:file => 'LICENSE'
}
s.author = 'Char Software, Inc. d/b/a Localytics'
s.source = { :http => "http://downloads.localytics.com/SDKs/iOS/archive/AMP-SDK-2.21.0.bin.zip" }
s.platform = :ios, '5.1.1'
s.source_files = '*.h'
s.preserve_paths = 'libLocalyticsAMP.a'
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/Localytics-AMP"' }
s.weak_frameworks = 'AdSupport'
s.frameworks = 'SystemConfiguration'
s.libraries = 'LocalyticsAMP', 'z', 'sqlite3'
s.requires_arc = false
end
| 32.44 | 105 | 0.620222 |
1c7de6c904619f5a95ca27f96a67198b086f69fe | 881 | require "rails_helper"
describe "error handling" do
let(:configuration) { StripeModelCallbacks::Configuration.current }
let!(:stripe_coupon) { create :stripe_coupon, stripe_id: "some-coupon" }
let!(:stripe_customer) { create :stripe_customer, stripe_id: "cus_CGNFgjPGtHlvXI" }
after do
configuration.instance_variable_set(:@on_error_callbacks, [])
end
it "creates an invoice" do
expect(StripeModelCallbacks::Invoice::UpdatedService).to receive(:execute_with_advisory_lock!).and_raise("BOOM!")
called = false
callback = proc do
called = true
end
configuration.instance_variable_set(:@on_error_callbacks, [callback])
expect { PublicActivity.with_tracking { mock_stripe_event("invoice.created") } }
.to raise_error(RuntimeError, "BOOM!")
.and change(StripeInvoice, :count).by(0)
expect(called).to eq true
end
end
| 30.37931 | 117 | 0.728717 |
ab4852f2c46764cac7aa8df91909d224c0931ab4 | 3,930 | require 'spec_helper'
class TransactionMailer; end
describe UserService::API::Users do
include UserService::API::Users
include EmailSpec::Helpers
include EmailSpec::Matchers
PERSON_HASH = {
given_name: "Raymond",
family_name: "Xperiment",
email: "[email protected]",
password: "test",
locale: "fr"
}
describe "#create_user" do
before { ActionMailer::Base.deliveries = [] }
before (:each) do
expect(ActionMailer::Base.deliveries).to be_empty
@community = FactoryGirl.create(:community)
end
it "should create a user" do
c = FactoryGirl.create(:community)
u = create_user(PERSON_HASH, c.id).data
expect(u[:given_name]).to eql "Raymond"
expect(Person.find_by(username: "raymondx").family_name).to eql "Xperiment"
expect(u[:locale]).to eql "fr"
end
it "should fail if email is taken" do
c = FactoryGirl.create(:community)
create_user(PERSON_HASH, c.id)
expect{create_user(PERSON_HASH, c.id)}.to raise_error(ArgumentError, /Email [email protected] is already in use/)
end
it "should send the confirmation email" do
create_user(PERSON_HASH.merge({:locale => "en"}), @community.id)
expect(ActionMailer::Base.deliveries).not_to be_empty
email = ActionMailer::Base.deliveries.first
expect(email).to have_subject "Confirmation instructions"
# simple check that link to right community exists
expect(email.body).to match @community.full_domain
expect(email.body).to match "Sharetribe Team"
end
it "should send the confirmation email in right language" do
create_user(PERSON_HASH.merge({:locale => "fr"}), @community.id)
expect(ActionMailer::Base.deliveries).not_to be_empty
email = ActionMailer::Base.deliveries.first
expect(email).to have_subject "Instructions de confirmation"
end
end
describe "#delete_user" do
let(:user) { FactoryGirl.create(:person) }
let!(:membership) { FactoryGirl.create(:community_membership, person: user) }
let!(:braintree_account) { FactoryGirl.create(:braintree_account, person: user) }
let!(:checkout_account) { FactoryGirl.create(:checkout_account, person: user) }
let!(:auth_token) { FactoryGirl.create(:auth_token, person: user) }
let!(:follower) { FactoryGirl.create(:person) }
let!(:followed) { FactoryGirl.create(:person) }
let!(:follower_relationship) { FactoryGirl.create(:follower_relationship, person: user, follower: follower) }
let!(:followed_relationship) { FactoryGirl.create(:follower_relationship, person: followed, follower: user) }
it "removes user data and adds deleted flag" do
new_user = Person.find(user.id)
expect(new_user.given_name).not_to be_nil
expect(new_user.family_name).not_to be_nil
expect(new_user.emails).not_to be_empty
expect(new_user.community_membership).not_to be_nil
expect(new_user.braintree_account).not_to be_nil
expect(new_user.checkout_account).not_to be_nil
expect(new_user.auth_tokens).not_to be_nil
expect(new_user.follower_relationships.length).to eql(1)
expect(new_user.inverse_follower_relationships.length).to eql(1)
# flag
expect(new_user.deleted).not_to eql(true)
delete_user(user.id)
deleted_user = Person.find(user.id)
expect(deleted_user.given_name).to be_nil
expect(deleted_user.family_name).to be_nil
expect(deleted_user.emails).to be_empty
expect(deleted_user.community_membership.status).to eq("deleted_user")
expect(deleted_user.braintree_account).to be_nil
expect(deleted_user.checkout_account).to be_nil
expect(deleted_user.auth_tokens).to be_empty
expect(deleted_user.follower_relationships.length).to eql(0)
expect(deleted_user.inverse_follower_relationships.length).to eql(0)
expect(deleted_user.deleted).to eql(true)
end
end
end
| 36.388889 | 117 | 0.71374 |
87dd93cafa73c83882aea0ffd69adc22e872a1d4 | 929 | test_name "should remove directory, but force required"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
target = agent.tmpdir("delete-dir")
step "clean up the system before we begin"
on agent, "rm -rf #{target} ; mkdir -p #{target}"
step "verify we can't remove a directory without 'force'"
on(agent, oregano_resource("file", target, 'ensure=absent')) do
fail_test "didn't tell us that force was required" unless
stdout.include? "Not removing directory; use 'force' to override" unless agent['locale'] == 'ja'
end
step "verify the directory still exists"
on agent, "test -d #{target}"
step "verify we can remove a directory with 'force'"
on(agent, oregano_resource("file", target, 'ensure=absent', 'force=true'))
step "verify that the directory is gone"
on agent, "test -d #{target}", :acceptable_exit_codes => [1]
end
| 34.407407 | 102 | 0.692142 |
91cc94e662b9c4390a41f74bfedcd7b576a664d6 | 1,687 | # frozen_string_literal: true
describe Travis::Logs::ContentDecoder do
subject { described_class }
context 'when base64-encoded' do
let(:ascii_entry) do
{
'log' => Base64.strict_encode64('hello to the world'),
'encoding' => 'base64'
}
end
let(:bytemess_entry) do
{
'log' => Base64.strict_encode64("hello to the world\xf1\xe5\x7a!"),
'encoding' => 'base64'
}
end
it 'passes through ascii bytes unaltered' do
expect(subject.decode_content(ascii_entry))
.to eq('hello to the world')
end
it 'cleans out messy bytes' do
expect(subject.decode_content(bytemess_entry))
.to eq('hello to the worldz!')
end
it 'encodes to UTF-8' do
expect(subject.decode_content(ascii_entry).encoding)
.to eq(Encoding::UTF_8)
expect(subject.decode_content(bytemess_entry).encoding)
.to eq(Encoding::UTF_8)
end
end
context 'when unencoded' do
let(:ascii_entry) do
{
'log' => 'hello to the world'
}
end
let(:bytemess_entry) do
{
'log' => "hello to the world\xf1\xe5\x7a!"
}
end
it 'passes through ascii bytes unaltered' do
expect(subject.decode_content(ascii_entry))
.to eq('hello to the world')
end
it 'cleans out messy bytes' do
expect(subject.decode_content(bytemess_entry))
.to eq('hello to the worldz!')
end
it 'encodes to UTF-8' do
expect(subject.decode_content(ascii_entry).encoding)
.to eq(Encoding::UTF_8)
expect(subject.decode_content(bytemess_entry).encoding)
.to eq(Encoding::UTF_8)
end
end
end
| 24.1 | 75 | 0.61885 |
d5437eb02b1c79ebe4d97659878d7e295e09a5c9 | 320 | require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'
describe "Kernel#select" do
it "is a private method" do
Kernel.private_instance_methods.should include("select")
end
end
describe "Kernel.select" do
it "needs to be reviewed for spec completeness"
end
| 24.615385 | 60 | 0.74375 |
7ae1fb84d9d803ff624db06dba141452f83f77ff | 4,799 | require 'ebay/types/country_details'
require 'ebay/types/currency_details'
require 'ebay/types/dispatch_time_max_details'
require 'ebay/types/payment_option_details'
require 'ebay/types/region_details'
require 'ebay/types/shipping_location_details'
require 'ebay/types/shipping_service_details'
require 'ebay/types/site_details'
require 'ebay/types/tax_jurisdiction'
require 'ebay/types/url_details'
require 'ebay/types/time_zone_details'
require 'ebay/types/item_specific_details'
require 'ebay/types/unit_of_measurement_details'
require 'ebay/types/region_of_origin_details'
require 'ebay/types/shipping_package_details'
require 'ebay/types/shipping_carrier_details'
require 'ebay/types/return_policy_details'
module Ebay # :nodoc:
module Responses # :nodoc:
# == Attributes
# array_node :country_details, 'CountryDetails', :class => CountryDetails, :default_value => []
# array_node :currency_details, 'CurrencyDetails', :class => CurrencyDetails, :default_value => []
# array_node :dispatch_time_max_details, 'DispatchTimeMaxDetails', :class => DispatchTimeMaxDetails, :default_value => []
# array_node :payment_option_details, 'PaymentOptionDetails', :class => PaymentOptionDetails, :default_value => []
# array_node :region_details, 'RegionDetails', :class => RegionDetails, :default_value => []
# array_node :shipping_location_details, 'ShippingLocationDetails', :class => ShippingLocationDetails, :default_value => []
# array_node :shipping_service_details, 'ShippingServiceDetails', :class => ShippingServiceDetails, :default_value => []
# array_node :site_details, 'SiteDetails', :class => SiteDetails, :default_value => []
# array_node :tax_jurisdictions, 'TaxJurisdiction', :class => TaxJurisdiction, :default_value => []
# array_node :url_details, 'URLDetails', :class => URLDetails, :default_value => []
# array_node :time_zone_details, 'TimeZoneDetails', :class => TimeZoneDetails, :default_value => []
# array_node :item_specific_details, 'ItemSpecificDetails', :class => ItemSpecificDetails, :default_value => []
# array_node :unit_of_measurement_details, 'UnitOfMeasurementDetails', :class => UnitOfMeasurementDetails, :default_value => []
# array_node :region_of_origin_details, 'RegionOfOriginDetails', :class => RegionOfOriginDetails, :default_value => []
# array_node :shipping_package_details, 'ShippingPackageDetails', :class => ShippingPackageDetails, :default_value => []
# array_node :shipping_carrier_details, 'ShippingCarrierDetails', :class => ShippingCarrierDetails, :default_value => []
# object_node :return_policy_details, 'ReturnPolicyDetails', :class => ReturnPolicyDetails, :optional => true
class GeteBayDetails < Abstract
include XML::Mapping
include Initializer
root_element_name 'GeteBayDetailsResponse'
array_node :country_details, 'CountryDetails', :class => CountryDetails, :default_value => []
array_node :currency_details, 'CurrencyDetails', :class => CurrencyDetails, :default_value => []
array_node :dispatch_time_max_details, 'DispatchTimeMaxDetails', :class => DispatchTimeMaxDetails, :default_value => []
array_node :payment_option_details, 'PaymentOptionDetails', :class => PaymentOptionDetails, :default_value => []
array_node :region_details, 'RegionDetails', :class => RegionDetails, :default_value => []
array_node :shipping_location_details, 'ShippingLocationDetails', :class => ShippingLocationDetails, :default_value => []
array_node :shipping_service_details, 'ShippingServiceDetails', :class => ShippingServiceDetails, :default_value => []
array_node :site_details, 'SiteDetails', :class => SiteDetails, :default_value => []
array_node :tax_jurisdictions, 'TaxJurisdiction', :class => TaxJurisdiction, :default_value => []
array_node :url_details, 'URLDetails', :class => URLDetails, :default_value => []
array_node :time_zone_details, 'TimeZoneDetails', :class => TimeZoneDetails, :default_value => []
array_node :item_specific_details, 'ItemSpecificDetails', :class => ItemSpecificDetails, :default_value => []
array_node :unit_of_measurement_details, 'UnitOfMeasurementDetails', :class => UnitOfMeasurementDetails, :default_value => []
array_node :region_of_origin_details, 'RegionOfOriginDetails', :class => RegionOfOriginDetails, :default_value => []
array_node :shipping_package_details, 'ShippingPackageDetails', :class => ShippingPackageDetails, :default_value => []
array_node :shipping_carrier_details, 'ShippingCarrierDetails', :class => ShippingCarrierDetails, :default_value => []
object_node :return_policy_details, 'ReturnPolicyDetails', :class => ReturnPolicyDetails, :optional => true
end
end
end
| 73.830769 | 132 | 0.754949 |
d5681feca5b07a18725b10e6cc38f8ade5a57078 | 3,052 | module Zuck
# Including this module does three things:
#
# 1. Lets you use `x[:foo]` to access keys of the
# underlying Hash
# 2. Lets you use `x[:foo] = :bar` to set values in
# the underlying Hash
# 3. Lets you define which keys are to be expected in
# the underlying hash. These keys will become methods
#
# Here's an example:
#
# class MyObjectWithHash
#
# include Zuck::HashDelegator
#
# known_keys :foo, :bar
#
# def initialize(initial_data)
# set_data(initial_data)
# end
# end
#
# > x = MyObjectWithHash.new(foo: :foo)
# > x.foo
# => :foo
# > x.bar
# => nil
# > x['bar'] = :everything_is_a_symbol
# > x[:bar]
# => :everything_is_a_symbol
# > x['bar']
# => :everything_is_a_symbol
# > x.foo
# => :everything_is_a_symbol
# > x.foo = :you_also_have_setters
# => :you_also_have_setters
#
# As you can see, all string keys become symbols and the
# foo and bar methods were added because they are known keys
#
module HashDelegator
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def known_keys(*args)
args.each do |key|
# Define list of known keys
self.send(:define_method, :known_keys) do
args || []
end
# Define getter
self.send(:define_method, key) do
init_hash
send('[]', key)
end
# Define setter
self.send(:define_method, "#{key}=") do |val|
init_hash
@hash_delegator_hash[key] = val
end
end
end
end
def set_data(d)
e = "You can only assign a Hash to #{self.class}, not a #{d.class}"
raise e unless d.is_a? Hash
hash = Hash.new
d.each do |key, value|
hash[(key.to_sym rescue key) || key] = value
end
@hash_delegator_hash = hash.symbolize_keys
end
def merge_data(d)
init_hash
@hash_delegator_hash.merge!(d.symbolize_keys)
end
def data=(d)
set_data(d)
end
def data
@hash_delegator_hash
end
def [](key)
init_hash
k = key.to_sym
reload_once_on_nil_value(k)
@hash_delegator_hash[k]
end
def []=(key, value)
init_hash
@hash_delegator_hash[key.to_sym] = value
end
def to_s
init_hash
vars = @hash_delegator_hash.map do |k, v|
"#{k}: #{v.to_json}"
end.join(", ")
"#<#{self.class} #{vars}>"
end
private
def init_hash
@hash_delegator_hash ||= {}
end
# For a hash that has been initialized with only an id,
# lazy reload from facebook when a nil attribute is accessed
# (but only do that once)
def reload_once_on_nil_value(key)
return if @hash_delegator_reloaded_once
return if @hash_delegator_hash[key.to_sym]
@hash_delegator_reloaded_once = true
reload
end
end
end
| 22.947368 | 73 | 0.569463 |
ff8c123d6b4daae780f29a8efcf9117c4e40a4d4 | 4,733 | class Container < ApplicationRecord
before_create :set_default_values
# Setup transient attributes for your model (attr_accessor)
# e.g.
# attr_accessor :temp
enum statuses: {
pending: 'PENDING',
scheduled: 'SCHEDULED',
provisioned: 'PROVISIONED',
provision_error: 'PROVISION_ERROR',
bootstrap_started: 'BOOTSTRAP_STARTED',
bootstrapped: 'BOOTSTRAPPED',
bootstrap_error: 'BOOTSTRAP_ERROR',
schedule_deletion: 'SCHEDULE_DELETION',
schedule_relocation: 'SCHEDULE_RELOCATION',
relocate_started: 'RELOCATE_STARTED',
relocate_error: 'RELOCATE_ERROR',
deleted: 'DELETED',
}
enum container_type: {
stateful: 'STATEFUL',
stateless: 'STATELESS',
}
# Setup validations for your model
# e.g.
# validates_presence_of :name
# validates_uniqueness_of :name, case_sensitive: false
validates :hostname,
presence: true,
format: { with: HOSTNAME_FORMAT },
length: { minimum: 1, maximum: 255 }
validate :unique_hostname_unless_deleted, if: :new_record?
# Setup relations to other models
# e.g.
# has_one :user
# has_many :users
# has_and_belongs_to_many :users
# has_many :employees, through: :users
belongs_to :cluster
belongs_to :node, required: false
belongs_to :source, required: false
#
# Setup scopes
#
scope :pending, -> {
where(status: 'PENDING').order(last_status_update_at: :asc)
}
scope :exists, -> {
where.not(status: 'DELETED').order(hostname: :asc)
}
#
# Setup for additional gem-related configuration
#
#
# Setup callbacks & state machines
#
#
# Setup additional methods
#
def apply_params_with_source(params)
errors.add(:source, "must be present.") unless params[:source].present?
remote_name = params.dig(:source, :remote, :name)
remote = Remote.find_by(name: remote_name) if remote_name.present?
source = Source.find_or_create_by(
source_type: params.dig(:source, :source_type),
mode: params.dig(:source, :mode),
remote_id: remote&.id || params.dig(:source, :remote_id),
fingerprint: params.dig(:source, :fingerprint),
alias: params.dig(:source, :alias)
)
self.source = source
self.bootstrappers = params[:bootstrappers]
self.container_type = params[:container_type].upcase if params[:container_type].present?
end
def self.create_with_source(cluster_id, params)
container = Container.new
container.cluster_id = cluster_id
container.hostname = params[:hostname]
container.apply_params_with_source(params)
container.save
container
end
def self.create_with_source!(cluster_id, params)
container = create_with_source(cluster_id, params)
raise ActiveRecord::RecordInvalid.new(container) if container.errors.any?
container
end
def duplicate
Container.create(
cluster_id: self.cluster_id,
hostname: self.hostname,
source: self.source,
image_alias: self.image_alias,
bootstrappers: self.bootstrappers,
container_type: self.container_type,
)
end
def update_bootstrappers(bootstrappers)
if bootstrappers.nil? || bootstrappers.empty?
false
else
update_column(:bootstrappers, bootstrappers)
end
end
def update_status(status)
status = status.downcase.to_sym
if Container.statuses.key?(status)
update_column(:status, Container.statuses[status])
update_column(:last_status_update_at, DateTime.current)
else
false
end
end
def relocate!(node_id)
raise StandardError.new "Can't relocate container to same node" if self.node_id == node_id
raise StandardError.new "Container can't relocated when in #{self.status} state" if !self.allow_relocation?
node = Node.find(node_id)
self.update(status: "SCHEDULE_RELOCATION", node_id: node.id)
end
def allow_deletion?
%w(PENDING SCHEDULED PROVISIONED PROVISION_ERROR BOOTSTRAPPED BOOTSTRAP_ERROR).include? self.status
end
def allow_reschedule?
%w(PROVISIONED PROVISION_ERROR BOOTSTRAPPED BOOTSTRAP_ERROR).include? self.status
end
def allow_relocation?
%w(BOOTSTRAPPED BOOTSTRAP_ERROR).include? self.status
end
def ready?
status == self.class.statuses[:bootstrapped]
end
def unique_hostname_unless_deleted
exists = Container.
where('cluster_id = ?', self.cluster_id).
where('hostname LIKE ?', self.hostname).
where.not(status: ['DELETED', 'SCHEDULE_DELETION']).
present?
errors.add(:hostname, I18n.t('errors.messages.unique')) if exists
end
private
def set_default_values
self.bootstrappers ||= []
self.status = Container.statuses[:pending]
self.last_status_update_at = DateTime.current
end
end
| 27.517442 | 111 | 0.706951 |
61c3e5bc739e8ce1fdcc74e81117385d8083c571 | 521 | module Sightengine
module Api
module Responses
module Nudity
def self.included(base)
base.class_eval do
attr_accessor :nudity
end
end
def raw_nudity?(min_prob = 0.9)
nudity["raw"].to_f >= min_prob.to_f
end
def partial_nudity?(min_prob = 0.9)
nudity["partial"].to_f >= min_prob.to_f
end
def safe?(min_prob = 0.9)
nudity["safe"].to_f >= min_prob.to_f
end
end
end
end
end | 20.84 | 49 | 0.539347 |
4ac79f80c90c23f0baae878636c4061c6a8eace0 | 1,489 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20150515170833) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "bands", force: :cascade do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "bands_venues", id: false, force: :cascade do |t|
t.integer "band_id"
t.integer "venue_id"
end
add_index "bands_venues", ["band_id"], name: "index_bands_venues_on_band_id", using: :btree
add_index "bands_venues", ["venue_id"], name: "index_bands_venues_on_venue_id", using: :btree
create_table "venues", force: :cascade do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| 37.225 | 95 | 0.748153 |
ab65a344cb9fa6b8b1bc266c6261582201ba980f | 107 | # frozen_string_literal: true
class DbDateCertainty < ActiveRecord::Base
belongs_to :db_single_date
end
| 17.833333 | 42 | 0.82243 |
62f43e52dbf89a3f0115ba84ab8dae881cb007ab | 278 | # frozen_string_literal: true
module Dry
module Slack
module Blocks
class Image < Block
attribute? :type, Types.type_string(0, 'image')
attribute :image_url, Types::UrlString
attribute :alt_text, Types::AltString
end
end
end
end
| 19.857143 | 55 | 0.654676 |
ac2614db08f0c0095864fde0d3cf3d5fbc84dbba | 597 | module DumpMailerWorker
extend ActiveSupport::Concern
included do
set_callback :dump, :after, :send_email
end
def send_email
return unless emails.present?
mailer.perform_async(@project.id, media_get_url, emails)
end
def mailer
"#{dump_target.singularize}_data_mailer_worker".camelize.constantize
end
def emails
if recipients = medium.try(:metadata).try(:[], "recipients")
User.where(id: recipients).pluck(:email)
else
[project.owner.email]
end
end
def media_get_url(expires=24*60)
medium.get_url(get_expires: expires)
end
end
| 20.586207 | 72 | 0.711893 |
bfa00f3dab53643abf397f67eb2e7ed948a7705c | 3,117 | RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| 44.528571 | 129 | 0.735002 |
bba4ee88e1f3fb0e94a3d5e6dbd47622ac8db5cb | 361 | # frozen_string_literal: true
require_relative '../span'
module Polites
class Span::Link < Span
attr_reader :url, :title
def initialize(children = [], url:, title: nil)
super(children)
@url = url
@title = title
end
def eql?(other)
super &&
url == other.url &&
title == other.title
end
end
end
| 16.409091 | 51 | 0.578947 |
037a8b20394b932c87425c7b13c0309a4c9bb23d | 3,485 | module CustomLandingPage
module LinkResolver
class LinkResolvingError < StandardError; end
class PathResolver
def initialize(paths)
@_paths = paths
end
def call(type, id, _)
path = @_paths[id]
if path.nil?
raise LinkResolvingError.new("Couldn't find path '#{id}'.")
else
{ "id" => id, "type" => type, "value" => path }
end
end
end
class MarketplaceDataResolver
def initialize(data, cta)
@_data = data
@_cta = cta
end
def call(type, id, _)
unless @_data.key?(id)
raise LinkResolvingError.new("Unknown marketplace data value '#{id}'.")
end
value =
case id
when "search_type"
search_type
else
value = @_data[id]
end
{ "id" => id, "type" => type, "value" => value }
end
def search_type
case @_cta
when "signup"
"private"
else
@_data["search_type"]
end
end
end
class AssetResolver
def initialize(asset_url, sitename)
unless sitename.present?
raise CustomLandingPage::LandingPageConfigurationError.new("Missing sitename.")
end
@_asset_url = asset_url
@_sitename = sitename
end
def call(type, id, normalized_data)
asset = normalized_data[type].find { |item| item["id"] == id }
if asset.nil?
raise LinkResolvingError.new("Unable to find an asset with id '#{id}'.")
else
append_asset_path(asset)
end
end
private
def append_asset_path(asset)
host = @_asset_url || ""
src = URLUtils.join(@_asset_url, asset["src"]).sub("%{sitename}", @_sitename)
asset.merge("src" => src)
end
end
class TranslationResolver
def initialize(locale)
@_locale = locale
end
def call(type, id, _)
translation_keys = {
"search_button" => "landing_page.hero.search",
"signup_button" => "landing_page.hero.signup",
"no_listing_image" => "landing_page.listings.no_listing_image"
}
key = translation_keys[id]
raise LinkResolvingError.new("Couldn't find translation key for '#{id}'.") if key.nil?
value = I18n.translate(key, locale: @_locale)
if value.nil?
raise LinkResolvingError.new("Unknown translation for key '#{key}' and locale '#{locale}'.")
else
{ "id" => id, "type" => type, "value" => value }
end
end
end
class CategoryResolver
def initialize(data)
@_data = data
end
def call(type, id, _)
if @_data.key?(id)
@_data[id].merge("id" => id, "type" => type)
end
end
end
class ListingResolver
def initialize(cid, landing_page_locale, locale_param, name_display_type)
@_cid = cid
@_landing_page_locale = landing_page_locale
@_locale_param = locale_param
@_name_display_type = name_display_type
end
def call(type, id, _)
ListingStore.listing(id: id,
community_id: @_cid,
landing_page_locale: @_landing_page_locale,
locale_param: @_locale_param,
name_display_type: @_name_display_type)
end
end
end
end
| 24.542254 | 102 | 0.550359 |
01330e086a081efd561d27557761a89c9fb78c81 | 5,584 | =begin
#Hydrogen Integration API
#The Hydrogen Integration API
OpenAPI spec version: 1.3.1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.21
=end
require 'date'
module IntegrationApi
class AccountingInvoiceResponseVO
attr_accessor :body
attr_accessor :message
attr_accessor :status_code
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'body' => :'body',
:'message' => :'message',
:'status_code' => :'status_code'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'body' => :'Invoice',
:'message' => :'String',
:'status_code' => :'Integer'
}
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?(:'body')
self.body = attributes[:'body']
end
if attributes.has_key?(:'message')
self.message = attributes[:'message']
end
if attributes.has_key?(:'status_code')
self.status_code = attributes[:'status_code']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
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?
true
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 &&
body == o.body &&
message == o.message &&
status_code == o.status_code
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
[body, message, status_code].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
value
when :Date
value
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/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
temp_model = IntegrationApi.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
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
| 27.92 | 107 | 0.612285 |
21bd2a23ef44b140a5b09ba21158ad716f0f64db | 897 | class Mutations::MergeUsers < Mutations::BaseMutation
field :user, Types::UserType, null: false
argument :user_ids, [Integer], required: true
argument :winning_user_id, Integer, required: true
argument :winning_user_con_profiles, [Types::WinningUserConProfileInputType], required: true
define_authorization_check do |args|
users = User.find(args[:user_ids])
users.all? { |user| policy(user).merge? }
end
def resolve(user_ids:, winning_user_id:, winning_user_con_profiles:)
winning_profile_ids_by_convention_id = winning_user_con_profiles
.index_by(&:convention_id)
.transform_values(&:user_con_profile_id)
result = MergeUsersService.new(
user_ids: user_ids,
winning_user_id: winning_user_id,
winning_user_con_profile_ids_by_convention_id: winning_profile_ids_by_convention_id
).call!
{ user: result.winning_user }
end
end
| 33.222222 | 94 | 0.758082 |
03d8c6b404701127ebf9e4a0fcfed85fd8d11491 | 1,932 | # Cookbook Name:: abiquo
# Recipe:: install_rabbitmq
#
# Copyright 2014, Abiquo
#
# 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.
include_recipe 'rabbitmq'
rabbitmq_user node['abiquo']['rabbitmq']['username'] do
password node['abiquo']['rabbitmq']['password']
action :add
end
rabbitmq_user node['abiquo']['rabbitmq']['username'] do
tag node['abiquo']['rabbitmq']['tags']
action :set_tags
end
rabbitmq_user node['abiquo']['rabbitmq']['username'] do
vhost node['abiquo']['rabbitmq']['vhost']
permissions '.* .* .*'
action :set_permissions
notifies :restart, 'service[abiquo-tomcat]' unless node['abiquo']['profile'] == 'ext_services'
end
# Generate a certificate if the node is configured to use SSL and no
# certificate has bene provided
if node['abiquo']['rabbitmq']['generate_cert']
ssl_certificate 'rabbitmq-certificate' do
namespace node['abiquo']['certificate']
cert_path node['rabbitmq']['ssl_cert']
key_path node['rabbitmq']['ssl_key']
owner 'rabbitmq'
group 'rabbitmq'
not_if { ::File.exist? node['rabbitmq']['ssl_cert'] }
notifies :import, 'java_management_truststore_certificate[rabbitmq-certificate]', :immediately
notifies :restart, "service[#{node['rabbitmq']['service_name']}]"
end
java_management_truststore_certificate 'rabbitmq-certificate' do
file node['rabbitmq']['ssl_cert']
action :nothing
notifies :restart, 'service[abiquo-tomcat]'
end
end
| 33.894737 | 98 | 0.72619 |
625a831c5bd423aedc90b6320573f43d02c3073b | 4,090 | #
# ServerEngine
#
# Copyright (C) 2012-2013 Sadayuki Furuhashi
#
# 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 'socket'
module ServerEngine
module SocketManagerUnix
module ClientModule
private
def connect_peer(path)
return UNIXSocket.new(path)
end
def recv(family, proto, peer, sent)
server_class = case proto
when :tcp then TCPServer
when :udp then UDPSocket
else
raise ArgumentError, "invalid protocol: #{proto}"
end
peer.recv_io(server_class)
end
def recv_tcp(family, peer, sent)
recv(family, :tcp, peer, sent)
end
def recv_udp(family, peer, sent)
recv(family, :udp, peer, sent)
end
end
module ServerModule
private
def listen_tcp_new(bind_ip, port)
if ENV['SERVERENGINE_USE_SOCKET_REUSEPORT'] == '1'
# Based on Addrinfo#listen
tsock = Socket.new(bind_ip.ipv6? ? ::Socket::AF_INET6 : ::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
tsock.ipv6only! if bind_ip.ipv6?
tsock.setsockopt(:SOCKET, :REUSEPORT, true)
tsock.setsockopt(:SOCKET, :REUSEADDR, true)
tsock.bind(Addrinfo.tcp(bind_ip.to_s, port))
tsock.listen(::Socket::SOMAXCONN)
tsock.autoclose = false
TCPServer.for_fd(tsock.fileno)
else
# TCPServer.new doesn't set IPV6_V6ONLY flag, so use Addrinfo class instead.
# TODO: make backlog configurable if necessary
tsock = Addrinfo.tcp(bind_ip.to_s, port).listen(::Socket::SOMAXCONN)
tsock.autoclose = false
TCPServer.for_fd(tsock.fileno)
end
end
def listen_udp_new(bind_ip, port)
# UDPSocket.new doesn't set IPV6_V6ONLY flag, so use Addrinfo class instead.
usock = Addrinfo.udp(bind_ip.to_s, port).bind
usock.autoclose = false
UDPSocket.for_fd(usock.fileno)
end
def start_server(path)
# return absolute path so that client can connect to this path
# when client changed working directory
path = File.expand_path(path)
begin
old_umask = File.umask(0077) # Protect unix socket from other users
@server = UNIXServer.new(path)
ensure
File.umask(old_umask)
end
@thread = Thread.new do
begin
while peer = @server.accept
Thread.new(peer, &method(:process_peer)) # process_peer calls send_socket
end
rescue => e
unless @server.closed?
ServerEngine.dump_uncaught_error(e)
end
end
end
return path
end
def stop_server
@tcp_sockets.reject! {|key,lsock| lsock.close; true }
@udp_sockets.reject! {|key,usock| usock.close; true }
@server.close unless @server.closed?
# It cause dead lock and can't finish when joining thread using Ruby 2.1 on linux.
@thread.join if RUBY_VERSION >= "2.2"
end
def send_socket(peer, pid, method, bind, port)
sock = case method
when :listen_tcp
listen_tcp(bind, port)
when :listen_udp
listen_udp(bind, port)
else
raise ArgumentError, "Unknown method: #{method.inspect}"
end
SocketManager.send_peer(peer, nil)
peer.send_io sock
end
end
end
end
| 30.984848 | 110 | 0.600733 |
3834acfdb1422a709cdb2928177e0ecade90b89d | 43 | module EncryptedId
VERSION = '1.1.1'
end
| 10.75 | 19 | 0.697674 |
389218324c696bed8458c7faaf9dc8c93e211d5f | 876 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
require 'fileutils'
module Multiverse
# <ruby_agent>/test/multiverse
#
ROOT = File.expand_path '../..', __FILE__
# append <ruby_agent>/test/multiverse/lib to the load path
#
$: << File.expand_path('lib', ROOT)
# append <ruby_agent>/test/new_relic to the load path
# ... to share fake_collector
#
$: << File.expand_path('../new_relic', ROOT)
# suites dir from env var, default to <ruby_agent>/test/multiverse/suites
#
SUITES_DIRECTORY = ENV['SUITES_DIRECTORY'] || File.expand_path('suites', ROOT)
end
require 'multiverse/bundler_patch'
require 'multiverse/color'
require 'multiverse/output_collector'
require 'multiverse/runner'
require 'multiverse/envfile'
require 'multiverse/suite'
| 25.764706 | 80 | 0.729452 |
e803a20c5197ae8e8b5ec8df1fb66f5b9625e1c7 | 548 | # == Schema Information
#
# Table name: transactions
#
# id :integer(4) not null, primary key
# type :string(255)
# batch_id :integer(4)
# created_at :datetime
# updated_at :datetime
#
class ReturnMerchandiseComplete < Transaction
def self.new_complete_rma(transacting_user, total_cost, at = Time.zone.now)
transaction = ReturnMerchandiseComplete.new()
transaction.new_transaction_ledgers( transacting_user, TransactionAccount::CASH_ID, TransactionAccount::REVENUE_ID, total_cost, at)
transaction
end
end
| 28.842105 | 135 | 0.737226 |
7a5bbb8b9cf2fde0d7f9edf4452ab54fdeadc226 | 4,121 | ENV["RAILS_ENV"] ||= 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rspec/rails'
Dir[File.expand_path('../../spec/support/*.rb', __FILE__)].each { |file| require file }
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
config.include CredentialHelper
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| 45.788889 | 92 | 0.735016 |
5d4c302c433f350db137947b8886c9fdfc4fd437 | 3,609 | # == Schema Information
#
# Table name: trackers
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# remote_id :integer
# url :string not null
# name :string not null
# full_name :string
# is_fork :boolean default(FALSE)
# watchers :integer default(0), not null
# forks :integer default(0)
# pushed_at :datetime
# description :text
# featured :boolean default(FALSE), not null
# open_issues :integer default(0), not null
# synced_at :datetime
# project_tax :decimal(9, 4) default(0.0)
# has_issues :boolean default(TRUE), not null
# has_wiki :boolean default(FALSE), not null
# has_downloads :boolean default(FALSE), not null
# private :boolean default(FALSE), not null
# homepage :string
# sync_in_progress :boolean default(FALSE), not null
# bounty_total :decimal(10, 2) default(0.0), not null
# account_balance :decimal(10, 2) default(0.0)
# type :string default("Tracker"), not null
# cloudinary_id :string
# closed_issues :integer default(0), not null
# delta :boolean default(TRUE), not null
# can_edit :boolean default(TRUE), not null
# repo_url :text
# rank :integer default(0), not null
# remote_cloudinary_id :string
# remote_name :string
# remote_description :text
# remote_homepage :string
# remote_language_ids :integer default([]), is an Array
# language_ids :integer default([]), is an Array
# team_id :integer
# deleted_at :datetime
#
# Indexes
#
# index_trackers_on_bounty_total (bounty_total)
# index_trackers_on_closed_issues (closed_issues)
# index_trackers_on_delta (delta)
# index_trackers_on_open_issues (open_issues)
# index_trackers_on_rank (rank)
# index_trackers_on_remote_id (remote_id)
# index_trackers_on_team_id (team_id)
# index_trackers_on_type (type)
# index_trackers_on_url (url) UNIQUE
# index_trackers_on_watchers (watchers)
#
class Trac::Tracker < ::Tracker
has_many :issues, class_name: "Trac::Issue", foreign_key: :tracker_id
MAX_RESULT_PER_PAGE = 25
# REMOTE SYNC INSTANCE METHODS
def remote_sync_if_necessary(options={})
if synced_at.nil?
remote_sync(options)
elsif synced_at < 1.week.ago
delay.remote_sync(options)
end
end
def remote_sync(options={})
update_attributes!(synced_at: Time.now)
# which page to start on
page_number = options[:page] || 1
params = {
max: MAX_RESULT_PER_PAGE,
col: ['id', 'status', 'summary', 'priority', 'milestone'],
order: 'priority',
page: page_number,
status: '!closed'
}
# update from API response, if data changed since last sync
results = Trac::API.fetch_issue_list(
url: self.url,
path: Trac::API.generate_issue_list_path(params)
)
sync_issues_from_array(results)
# fetch next page if current page has full results
(options[:force] ? self : delay).remote_sync(page: page_number+1) if results.length == MAX_RESULT_PER_PAGE
end
end
| 37.206186 | 110 | 0.585481 |
edbd15b0cb31ad6e1d6f6b5736e321b1e256e966 | 98 | module Certmeister
module DynamoDB
VERSION = '0.1.2' unless defined?(VERSION)
end
end
| 9.8 | 46 | 0.683673 |
e819ac509ab51ddc5f269df3727bdd6bb10d2a9c | 743 | # frozen_string_literal: true
require 'bundler/setup'
require 'webmock/rspec'
# require 'json-schema'
# require_relative "support/have_attributes_matcher"
require 'simplecov'
if RSpec.configuration.files_to_run.size > 1
SimpleCov.start do
track_files 'lib/**/*.rb'
add_filter '/lib/komtet/version.rb' # already loaded by bundler, so 0% coverage in report
add_filter %r{^/spec/}
end
end
require 'komtet'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.766667 | 93 | 0.745626 |
11616e763f0e8048b798d9092abc44b0c6db90b2 | 1,637 | require 'rails_helper'
describe "GET 'nearby'" do
before :each do
@loc = create(:location)
@nearby = create(:nearby_loc)
create(:far_loc)
end
it 'is paginated' do
get api_location_nearby_url(
@loc, page: 2, per_page: 1, radius: 5
)
expect(json.first['name']).to eq('Belmont Farmers Market')
end
it 'returns a summarized JSON representation' do
get api_location_nearby_url(@loc, radius: 2)
expect(json.first.keys).
to eq %w[id alternate_name latitude longitude name slug address]
end
it 'only returns active locations' do
@nearby.update(active: false)
get api_location_nearby_url(@loc, per_page: 2, radius: 5)
expect(json.length).to eq(1)
end
context 'with no radius' do
it 'displays nearby locations within 0.5 miles' do
get api_location_nearby_url(@loc)
expect(json).to eq([])
end
end
context 'with valid radius' do
it 'displays nearby locations within 2 miles' do
get api_location_nearby_url(@loc, radius: 2)
expect(json.length).to eq 1
expect(json.first['name']).to eq('Library')
end
end
context 'with invalid radius' do
it 'returns an invalid radius message' do
get api_location_nearby_url(@loc, radius: 'script')
expect(json['description']).
to eq('Radius must be a Float between 0.1 and 50.')
expect(response).to have_http_status(400)
end
end
context 'when the location has no coordinates' do
it 'returns empty array' do
no_address = create(:no_address)
get api_location_nearby_url(no_address)
expect(json).to eq([])
end
end
end
| 26.836066 | 70 | 0.67135 |
03f4fd10ec660507180b87c6702fe3f1cbfbba33 | 3,361 | module OpenVZ
#
# This code is completely borrowed from marionette-collective.
#
# Wrapper around systemu that handles executing of system commands
# in a way that makes stdout, stderr and status available. Supports
# timeouts and sets a default sane environment.
#
# s = Shell.new("date", opts)
# s.runcommand
# puts s.stdout
# puts s.stderr
# puts s.status.exitcode
#
# Options hash can have:
#
# cwd - the working directory the command will be run from
# stdin - a string that will be sent to stdin of the program
# stdout - a variable that will receive stdout, must support <<
# stderr - a variable that will receive stdin, must support <<
# environment - the shell environment, defaults to include LC_ALL=C
# set to nil to clear the environment even of LC_ALL
#
class Shell
attr_reader :environment, :command, :status, :stdout, :stderr, :stdin, :cwd
def initialize(command, options={})
@environment = {"LC_ALL" => "C"}
@command = command
@status = nil
@stdout = ""
@stderr = ""
@stdin = nil
@cwd = "/tmp"
options.each do |opt, val|
case opt.to_s
when "stdout"
raise "stdout should support <<" unless val.respond_to?("<<")
@stdout = val
when "stderr"
raise "stderr should support <<" unless val.respond_to?("<<")
@stderr = val
when "stdin"
raise "stdin should be a String" unless val.is_a?(String)
@stdin = val
when "cwd"
raise "Directory #{val} does not exist" unless File.directory?(val)
@cwd = val
when "environment"
if val.nil?
@environment = {}
else
@environment.merge!(val.dup)
end
end
end
end
# Actually does the systemu call passing in the correct environment, stdout and stderr
def runcommand
require 'systemu'
opts = {"env" => @environment,
"stdout" => @stdout,
"stderr" => @stderr,
"cwd" => @cwd}
opts["stdin"] = @stdin if @stdin
# Running waitpid on the cid here will start a thread
# with the waitpid in it, this way even if the thread
# that started this process gets killed due to agent
# timeout or such there will still be a waitpid waiting
# for the child to exit and not leave zombies.
@status = systemu(@command, opts) do |cid|
begin
sleep 1
Process::waitpid(cid)
rescue SystemExit
rescue Errno::ECHILD
rescue Exception => e
Log.info("Unexpected exception received while waiting for child process: #{e.class}: #{e}")
end
end
end
end
end
| 36.532609 | 111 | 0.489438 |
1cbe927db0b16328fd22858a72c01c9f11c9519c | 909 | require 'test_helper'
class ArtistUrlsControllerTest < ActionDispatch::IntegrationTest
context "The artist urls controller" do
setup do
@artist = create(:artist, name: "bkub", url_string: "-http://bkub.com")
@banned = create(:artist, name: "danbo", is_banned: true, url_string: "https://danbooru.donmai.us")
end
context "index page" do
should "render" do
get artist_urls_path
assert_response :success
end
should respond_to_search({}).with { @banned.urls + @artist.urls }
should respond_to_search(url_matches: "*bkub*").with { @artist.urls }
should respond_to_search(is_active: "false").with { @artist.urls }
context "using includes" do
should respond_to_search(artist: {name: "bkub"}).with { @artist.urls }
should respond_to_search(artist: {is_banned: "true"}).with { @banned.urls }
end
end
end
end
| 33.666667 | 105 | 0.663366 |
117cb345beab49015263ecc386a7cd3f38f27163 | 583 | require 'spec_helper'
describe Puppet::Type.type(:eselect) do
describe "when validating attributes" do
params = [:name]
properties = [:set]
params.each do |param|
it "should have the #{param} param" do
described_class.attrtype(param).should == :param
end
end
properties.each do |property|
it "should have the #{property} property" do
described_class.attrtype(property).should == :property
end
end
end
it "should have name as the namevar" do
described_class.key_attributes.should == [:name]
end
end
| 22.423077 | 62 | 0.653516 |
edfd02cf6b93c5d98096c4d00506cbd4d3568d53 | 1,556 | RSpec.describe "Integration Test: Archiving Using In Batches From Rails 6" do
subject(:archive) do
Tartarus::ArchiveModelWithTenant.new(registry: registry).archive(User, "Partition_1")
end
let(:registry) { Tartarus::Registry.new }
let(:archivable_item) do
Tartarus::ArchivableItem.new.tap do |item|
item.model = User
item.timestamp_field = :created_at
item.archive_items_older_than = -> { Date.today }
item.archive_with = archive_with
item.tenants_range = -> { ["Partition_1", "Partition_2"] }
item.tenant_id_field = :partition_name
end
end
before do
registry.register(archivable_item)
100.times { User.create!(created_at: Time.new(2020, 1, 1, 12, 0, 0, 0), partition_name: "Partition_1") }
50.times { User.create!(created_at: Time.new(2020, 1, 1, 12, 0, 0, 0), partition_name: "Partition_2") }
20.times { User.create!(created_at: Time.new(2030, 1, 1, 12, 0, 0, 0), partition_name: "Partition_1") }
20.times { User.create!(created_at: Time.new(2030, 1, 1, 12, 0, 0, 0), partition_name: "Partition_2") }
end
after do
User.delete_all
end
describe "for delete_all" do
let(:archive_with) { :delete_all }
it "deletes Users using in_batches" do
expect {
archive
}.to change { User.count }.from(190).to(90)
end
end
describe "for destroy_all" do
let(:archive_with) { :destroy_all }
it "deletes Users using in_batches" do
expect {
archive
}.to change { User.count }.from(190).to(90)
end
end
end
| 30.509804 | 108 | 0.659383 |
87e301b67ddb4062e9a5826c1b9b7f3861e3447a | 811 | class Jflex < Formula
desc "Lexical analyzer generator for Java, written in Java"
homepage "https://jflex.de/"
url "https://jflex.de/release/jflex-1.8.2.tar.gz"
sha256 "a1e0d25e341d01de6b93ec32b45562905e69d06598113934b74f76b1be7927ab"
bottle :unneeded
depends_on "openjdk"
def install
pkgshare.install "examples"
libexec.install "lib/jflex-full-#{version}.jar" => "jflex-#{version}.jar"
(bin/"jflex").write <<~EOS
#!/bin/bash
export JAVA_HOME="${JAVA_HOME:-#{Formula["openjdk"].opt_prefix}}"
exec "${JAVA_HOME}/bin/java" -jar "#{libexec}/jflex-#{version}.jar" "$@"
EOS
end
test do
system bin/"jflex", "-d", testpath, pkgshare/"examples/cup-java/src/main/jflex/java.flex"
assert_match /public static void/, (testpath/"Scanner.java").read
end
end
| 31.192308 | 93 | 0.685573 |
91b0381345f15606188ec1b40a6c6d47629ba064 | 1,207 | class Darcs < Formula
desc "Distributed version control system that tracks changes, via Haskell"
homepage "http://darcs.net/"
url "https://hackage.haskell.org/package/darcs-2.14.3/darcs-2.14.3.tar.gz"
sha256 "240f2c0bbd4a019428d87ed89db3aeaebebd2019f835b08680a59ac5eb673e78"
bottle do
cellar :any_skip_relocation
sha256 "a03abe9838c948f87f9ceb1e10e2c5e3d0483022eb0b7184043a65ac3d7109d2" => :catalina
sha256 "ed8b61d553e3c4d15b6c1bc898bb2cc28314599309b7a68ad97120753b4114e4" => :mojave
sha256 "80a61a6abc44c1f7a759c279966024bf994ab391174bcf39df74269a2f50e6f3" => :high_sierra
end
depends_on "cabal-install" => :build
depends_on "ghc" => :build
depends_on "gmp"
def install
system "cabal", "v2-update"
system "cabal", "v2-install", *std_cabal_v2_args
end
test do
mkdir "my_repo" do
system bin/"darcs", "init"
(Pathname.pwd/"foo").write "hello homebrew!"
system bin/"darcs", "add", "foo"
system bin/"darcs", "record", "-am", "add foo", "--author=homebrew"
end
system bin/"darcs", "get", "my_repo", "my_repo_clone"
cd "my_repo_clone" do
assert_match "hello homebrew!", (Pathname.pwd/"foo").read
end
end
end
| 33.527778 | 93 | 0.714996 |
ac65f0a18124a44e2da1835e7e2efacaddb58937 | 2,985 | # frozen_string_literal: true
require 'dry/monads'
require 'dry/monads/do'
module Operations
module People
class CreateOrUpdate
include Dry::Monads[:result, :do]
PersonCandidate = Struct.new(:ssn, :dob, :first_name, :last_name)
def call(params:)
person_values = yield validate(params)
person_entity = yield create_entity(person_values)
person = yield match_or_update_or_create_person(person_entity.to_h)
Success(person)
end
private
def sanitize_params(params)
params[:hbx_id] = params.delete :person_hbx_id
params
end
def validate(params)
result = Validators::PersonContract.new.call(sanitize_params(params))
if result.success?
Success(result)
else
Failure(result)
end
end
def create_entity(values)
result = Entities::Person.new(values.to_h)
Success(result)
end
def match_or_update_or_create_person(person_entity)
person = find_existing_person(person_entity.to_h)
#create new person
if person.blank?
person = Person.new(person_entity.to_h) #if person_valid_params.success?
person.save!
else
return Success(person) if no_infomation_changed?({params: {attributes_hash: person_entity, person: person}})
person.assign_attributes(person_entity.except(:addresses, :phones, :emails, :hbx_id))
person.save!
create_or_update_associations(person, person_entity.to_h, :addresses)
create_or_update_associations(person, person_entity.to_h, :emails)
create_or_update_associations(person, person_entity.to_h, :phones)
end
Success(person)
rescue StandardError => e
Failure(person.errors.messages)
end
def create_or_update_associations(person, applicant_params, assoc)
records = applicant_params[assoc.to_sym]
return if records.empty?
records.each do |attrs|
address_matched = person.send(assoc).detect {|adr| adr.kind == attrs[:kind]}
if address_matched
address_matched.update(attrs)
else
person.send(assoc).create(attrs)
end
end
end
def no_infomation_changed?(params:)
result = ::Operations::People::CompareForDataChange.new.call(params: params)
result.failure?
end
def find_existing_person(params)
person = Person.by_hbx_id(params[:hbx_id]).first
return person if person.present?
candidate = PersonCandidate.new(params[:ssn], params[:dob], params[:first_name], params[:last_name])
if params[:no_ssn] == '1'
Person.where(first_name: /^#{candidate.first_name}$/i, last_name: /^#{candidate.last_name}$/i,
dob: candidate.dob).first
else
Person.match_existing_person(candidate)
end
end
end
end
end
| 30.151515 | 118 | 0.644891 |
e2cdadfcaf2ef08a1062cb5e97a84f9486ff83fe | 269 | require "trailblazer/rails/version"
module Trailblazer
module Rails
end
end
require "reform/rails"
require "trailblazer/rails/controller"
require "trailblazer/rails/cell"
require "trailblazer/rails/form"
require "trailblazer/rails/railtie"
require "trailblazer"
| 17.933333 | 38 | 0.806691 |
21cf6fb92b183dc9f11edb84dd5c9610a89136f5 | 2,947 | class GpCategory::Content::Setting < Cms::ContentSetting
set_config :list_style,
name: "#{GpArticle::Doc.model_name.human}表示形式",
form_type: :text_area,
upper_text: '<a href="#" class="show_dialog">置き換えテキストを確認する</a>',
default_value: '@title_link@(@publish_date@ @group@)'
set_config :date_style,
name: "#{GpArticle::Doc.model_name.human}日付形式",
comment: I18n.t('comments.date_style'),
default_value: '%Y年%m月%d日 %H時%M分'
set_config :time_style,
name: "#{GpArticle::Doc.model_name.human}時間形式",
comment: I18n.t('comments.time_style'),
default_value: '%H時%M分'
set_config :category_type_style,
name: "#{GpCategory::CategoryType.model_name.human}表示形式",
options: [['全カテゴリ一覧', 'all_categories'], ['全記事一覧', 'all_docs'], ['カテゴリ+記事', 'categories_with_docs']],
default_extra_values: {
category_type_doc_style: '@title_link@',
category_type_docs_number: nil
}
set_config :category_style,
name: "#{GpCategory::Category.model_name.human}表示形式",
options: [['カテゴリ一覧+記事一覧', 'categories_and_docs'], ['カテゴリ+記事', 'categories_with_docs']],
default_extra_values: {
category_doc_style: '@title_link@',
category_docs_number: nil,
category_more_docs_number: 30
}
set_config :doc_style,
name: '新着記事一覧表示形式',
options: [['全記事一覧', 'all_docs']],
default_extra_values: {
doc_doc_style: '@title_link@',
doc_docs_number: nil
}
set_config :docs_order,
name: '記事一覧表示順',
options: GpCategory::Content::CategoryType::DOCS_ORDER_OPTIONS,
default_value: 'published_at_desc'
set_config :index_template_id,
name: 'index設定',
options: lambda {->(content=nil) do
if content
GpCategory::Content::CategoryType.find_by(id: content.id).templates.map{|t| [t.title, t.id] }
else
[]
end
end}
set_config :feed,
name: "フィード",
form_type: :radio_buttons,
options: [['表示する', 'enabled'], ['表示しない', 'disabled']],
default_value: 'enabled',
default_extra_values: {
feed_docs_number: '10',
feed_docs_period: nil
}
belongs_to :content, foreign_key: :content_id, class_name: 'GpCategory::Content::CategoryType'
def extra_values=(params)
ex = extra_values
case name
when 'category_type_style'
ex[:category_type_doc_style] = params[:category_type_doc_style]
ex[:category_type_docs_number] = params[:category_type_docs_number]
when 'category_style'
ex[:category_doc_style] = params[:category_doc_style]
ex[:category_docs_number] = params[:category_docs_number]
ex[:category_more_docs_number] = params[:category_more_docs_number]
when 'doc_style'
ex[:doc_doc_style] = params[:doc_doc_style]
ex[:doc_docs_number] = params[:doc_docs_number]
when 'feed'
ex[:feed_docs_number] = params[:feed_docs_number]
ex[:feed_docs_period] = params[:feed_docs_period]
end
super(ex)
end
end
| 35.939024 | 105 | 0.680353 |
f86be95adcf17f125bb01291630c47c70e038944 | 2,734 | # Copyright 2017 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 'spec_helper'
require 'find'
require 'copyright'
describe 'ensure files have copyright notice' do
let(:my_path) { File.expand_path(__dir__) }
let(:my_root) { File.expand_path('..', __dir__) }
it do
files = Find.find(File.expand_path(File.join(my_path, '..')))
.select { |f| File.file?(f) }
.select do |f|
my_tests = f.start_with?("#{my_path}/data/copyright_")
artifacts = f.start_with?("#{my_root}/build/")
presubmit = f.start_with?("#{my_root}/build/presubmit/")
!my_tests && !artifacts || presubmit
end
checker = Google::CopyrightChecker.new(files)
missing = checker.check_missing.collect { |f| " - #{f}" }
raise "Files missing (or outdated) copyright:\n#{missing.join("\n")}" \
unless missing.empty?
end
end
describe 'check the checker' do
it 'should pass if all files are good' do
expect(Google::CopyrightChecker.new(['spec/data/copyright_good1.rb',
'spec/data/copyright_good2.rb'])
.check_missing)
.to eq []
end
it 'should fail if files do not exist' do
expect do
Google::CopyrightChecker.new(['spec/data/copyright_good1.rb',
'spec/data/copyright_bad1.rb',
'spec/data/copyright_missing1.rb'])
.check_missing
end.to raise_error(StandardError, /not found.*missing1.rb/)
end
it 'should trigger missing copyright' do
expect(Google::CopyrightChecker.new(['spec/data/copyright_good1.rb',
'spec/data/copyright_bad1.rb',
'spec/data/copyright_good2.rb'])
.check_missing)
.to contain_exactly 'spec/data/copyright_bad1.rb'
end
it 'should fail if year is incorrect' do
expect(Google::CopyrightChecker.new(['spec/data/copyright_bad2.rb'])
.check_missing)
.to contain_exactly 'spec/data/copyright_bad2.rb'
end
end
| 39.623188 | 75 | 0.603146 |
ed8047f85bc24b93828a16255493fabb6ebc9ce8 | 410 | module RecurlyLegacyGem
# Recurly Documentation: https://dev.recurly.com/docs/list-accounts-shipping-address
class ShippingAddress < Resource
define_attribute_methods %w(
id
address1
address2
first_name
last_name
city
state
zip
country
phone
nickname
company
email
geo_code
)
alias to_param address1
end
end
| 17.826087 | 86 | 0.634146 |
f8592c641f7bdaad4b6a6a9006aeeeb2ad7af873 | 15,145 | module RbsRails
module ActiveRecord
def self.generatable?(klass)
return false if klass.abstract_class?
klass.connection.table_exists?(klass.table_name)
end
def self.class_to_rbs(klass, dependencies: [])
Generator.new(klass, dependencies: dependencies).generate
end
class Generator
def initialize(klass, dependencies:)
@klass = klass
@dependencies = dependencies
@klass_name = Util.module_name(klass)
namespaces = klass_name.split('::').tap{ |names| names.pop }
@dependencies << namespaces.join('::') unless namespaces.empty?
end
def generate
Util.format_rbs klass_decl
end
private def klass_decl
<<~RBS
#{header}
extend _ActiveRecord_Relation_ClassMethods[#{klass_name}, #{relation_class_name}, #{pk_type}]
#{columns}
#{associations}
#{delegated_type_instance}
#{delegated_type_scope(singleton: true)}
#{enum_instance_methods}
#{enum_scope_methods(singleton: true)}
#{scopes(singleton: true)}
#{generated_relation_methods_decl}
#{relation_decl}
#{collection_proxy_decl}
#{footer}
RBS
end
private def pk_type
pk = klass.primary_key
return 'top' unless pk
col = klass.columns.find {|col| col.name == pk }
sql_type_to_class(col.type)
end
private def generated_relation_methods_decl
<<~RBS
module GeneratedRelationMethods
#{enum_scope_methods(singleton: false)}
#{scopes(singleton: false)}
#{delegated_type_scope(singleton: false)}
end
RBS
end
private def relation_decl
<<~RBS
class #{relation_class_name} < ActiveRecord::Relation
include GeneratedRelationMethods
include _ActiveRecord_Relation[#{klass_name}, #{pk_type}]
include Enumerable[#{klass_name}]
end
RBS
end
private def collection_proxy_decl
<<~RBS
class ActiveRecord_Associations_CollectionProxy < ActiveRecord::Associations::CollectionProxy
include GeneratedRelationMethods
include _ActiveRecord_Relation[#{klass_name}, #{pk_type}]
end
RBS
end
private def header
namespace = +''
klass_name.split('::').map do |mod_name|
namespace += "::#{mod_name}"
mod_object = Object.const_get(namespace)
case mod_object
when Class
# @type var superclass: Class
superclass = _ = mod_object.superclass
superclass_name = Util.module_name(superclass)
@dependencies << superclass_name
"class #{mod_name} < #{superclass_name}"
when Module
"module #{mod_name}"
else
raise 'unreachable'
end
end.join("\n")
end
private def footer
"end\n" * klass_name.split('::').size
end
private def associations
[
has_many,
has_one,
belongs_to,
].join("\n")
end
private def has_many
klass.reflect_on_all_associations(:has_many).map do |a|
singular_name = a.name.to_s.singularize
type = Util.module_name(a.klass)
collection_type = "#{type}::ActiveRecord_Associations_CollectionProxy"
<<~RUBY.chomp
def #{a.name}: () -> #{collection_type}
def #{a.name}=: (#{collection_type} | Array[#{type}]) -> (#{collection_type} | Array[#{type}])
def #{singular_name}_ids: () -> Array[Integer]
def #{singular_name}_ids=: (Array[Integer]) -> Array[Integer]
RUBY
end.join("\n")
end
private def has_one
klass.reflect_on_all_associations(:has_one).map do |a|
type = a.polymorphic? ? 'untyped' : Util.module_name(a.klass)
type_optional = optional(type)
<<~RUBY.chomp
def #{a.name}: () -> #{type_optional}
def #{a.name}=: (#{type_optional}) -> #{type_optional}
def build_#{a.name}: (untyped) -> #{type}
def create_#{a.name}: (untyped) -> #{type}
def create_#{a.name}!: (untyped) -> #{type}
def reload_#{a.name}: () -> #{type_optional}
RUBY
end.join("\n")
end
private def belongs_to
klass.reflect_on_all_associations(:belongs_to).map do |a|
type = a.polymorphic? ? 'untyped' : Util.module_name(a.klass)
type_optional = optional(type)
# @type var methods: Array[String]
methods = []
methods << "def #{a.name}: () -> #{type}"
methods << "def #{a.name}=: (#{type_optional}) -> #{type_optional}"
methods << "def reload_#{a.name}: () -> #{type_optional}"
if !a.polymorphic?
methods << "def build_#{a.name}: (untyped) -> #{type}"
methods << "def create_#{a.name}: (untyped) -> #{type}"
methods << "def create_#{a.name}!: (untyped) -> #{type}"
end
methods.join("\n")
end.join("\n")
end
private def delegated_type_scope(singleton:)
definitions = delegated_type_definitions
return "" unless definitions
definitions.map do |definition|
definition[:types].map do |type|
scope_name = type.tableize.gsub("/", "_")
"def #{singleton ? 'self.' : ''}#{scope_name}: () -> #{relation_class_name}"
end
end.flatten.join("\n")
end
private def delegated_type_instance
definitions = delegated_type_definitions
return "" unless definitions
# @type var methods: Array[String]
methods = []
definitions.each do |definition|
methods << "def #{definition[:role]}_class: () -> Class"
methods << "def #{definition[:role]}_name: () -> String"
methods << definition[:types].map do |type|
scope_name = type.tableize.gsub("/", "_")
singular = scope_name.singularize
<<~RUBY.chomp
def #{singular}?: () -> bool
def #{singular}: () -> #{type.classify}?
def #{singular}_id: () -> Integer?
RUBY
end.join("\n")
end
methods.join("\n")
end
private def delegated_type_definitions
ast = parse_model_file
return unless ast
traverse(ast).map do |node|
# @type block: { role: Symbol, types: Array[String] }?
next unless node.type == :send
next unless node.children[0].nil?
next unless node.children[1] == :delegated_type
role_node = node.children[2]
next unless role_node
next unless role_node.type == :sym
# @type var role: Symbol
role = role_node.children[0]
args_node = node.children[3]
next unless args_node
next unless args_node.type == :hash
types = traverse(args_node).map do |n|
# @type block: Array[String]?
next unless n.type == :pair
key_node = n.children[0]
next unless key_node
next unless key_node.type == :sym
next unless key_node.children[0] == :types
types_node = n.children[1]
next unless types_node
next unless types_node.type == :array
code = types_node.loc.expression.source
eval(code)
end.compact.flatten
{ role: role, types: types }
end.compact
end
private def enum_instance_methods
# @type var methods: Array[String]
methods = []
enum_definitions.each do |hash|
hash.each do |name, values|
next if name == :_prefix || name == :_suffix
values.each do |label, value|
value_method_name = enum_method_name(hash, name, label)
methods << "def #{value_method_name}!: () -> bool"
methods << "def #{value_method_name}?: () -> bool"
end
end
end
methods.join("\n")
end
private def enum_scope_methods(singleton:)
# @type var methods: Array[String]
methods = []
enum_definitions.each do |hash|
hash.each do |name, values|
next if name == :_prefix || name == :_suffix
values.each do |label, value|
value_method_name = enum_method_name(hash, name, label)
methods << "def #{singleton ? 'self.' : ''}#{value_method_name}: () -> #{relation_class_name}"
end
end
end
methods.join("\n")
end
private def enum_definitions
@enum_definitions ||= build_enum_definitions
end
# We need static analysis to detect enum.
# ActiveRecord has `defined_enums` method,
# but it does not contain _prefix and _suffix information.
private def build_enum_definitions
ast = parse_model_file
return [] unless ast
traverse(ast).map do |node|
# @type block: nil | Hash[untyped, untyped]
next unless node.type == :send
next unless node.children[0].nil?
next unless node.children[1] == :enum
definitions = node.children[2]
next unless definitions
next unless definitions.type == :hash
next unless traverse(definitions).all? { |n| [:str, :sym, :int, :hash, :pair, :true, :false].include?(n.type) }
code = definitions.loc.expression.source
code = "{#{code}}" if code[0] != '{'
eval(code)
end.compact
end
private def enum_method_name(hash, name, label)
enum_prefix = hash[:_prefix]
enum_suffix = hash[:_suffix]
if enum_prefix == true
prefix = "#{name}_"
elsif enum_prefix
prefix = "#{enum_prefix}_"
end
if enum_suffix == true
suffix = "_#{name}"
elsif enum_suffix
suffix = "_#{enum_suffix}"
end
"#{prefix}#{label}#{suffix}"
end
private def scopes(singleton:)
ast = parse_model_file
return '' unless ast
traverse(ast).map do |node|
# @type block: nil | String
next unless node.type == :send
next unless node.children[0].nil?
next unless node.children[1] == :scope
name_node = node.children[2]
next unless name_node
next unless name_node.type == :sym
name = name_node.children[0]
body_node = node.children[3]
next unless body_node
next unless body_node.type == :block
args = args_to_type(body_node.children[1])
"def #{singleton ? 'self.' : ''}#{name}: #{args} -> #{relation_class_name}"
end.compact.join("\n")
end
private def args_to_type(args_node)
# @type var res: Array[String]
res = []
# @type var block: String?
block = nil
args_node.children.each do |node|
case node.type
when :arg
res << "untyped `#{node.children[0]}`"
when :optarg
res << "?untyped `#{node.children[0]}`"
when :kwarg
res << "#{node.children[0]}: untyped"
when :kwoptarg
res << "?#{node.children[0]}: untyped"
when :restarg
res << "*untyped `#{node.children[0]}`"
when :kwrestarg
res << "**untyped `#{node.children[0]}`"
when :blockarg
block = " { (*untyped) -> untyped }"
else
raise "unexpected: #{node}"
end
end
"(#{res.join(", ")})#{block}"
end
private def parse_model_file
return @parse_model_file if defined?(@parse_model_file)
path = Rails.root.join('app/models/', klass_name.underscore + '.rb')
return @parse_model_file = nil unless path.exist?
return [] unless path.exist?
ast = Parser::CurrentRuby.parse path.read
return @parse_model_file = nil unless path.exist?
@parse_model_file = ast
end
private def traverse(node, &block)
return to_enum(__method__ || raise, node) unless block_given?
# @type var block: ^(Parser::AST::Node) -> untyped
block.call node
node.children.each do |child|
traverse(child, &block) if child.is_a?(Parser::AST::Node)
end
end
private def relation_class_name
"ActiveRecord_Relation"
end
private def columns
klass.columns.map do |col|
class_name = if enum_definitions.any? { |hash| hash.key?(col.name) || hash.key?(col.name.to_sym) }
'String'
else
sql_type_to_class(col.type)
end
class_name_opt = optional(class_name)
column_type = col.null ? class_name_opt : class_name
sig = <<~EOS
attr_accessor #{col.name} (): #{column_type}
def #{col.name}_changed?: () -> bool
def #{col.name}_change: () -> [#{class_name_opt}, #{class_name_opt}]
def #{col.name}_will_change!: () -> void
def #{col.name}_was: () -> #{class_name_opt}
def #{col.name}_previously_changed?: () -> bool
def #{col.name}_previous_change: () -> Array[#{class_name_opt}]?
def #{col.name}_previously_was: () -> #{class_name_opt}
def #{col.name}_before_last_save: () -> #{class_name_opt}
def #{col.name}_change_to_be_saved: () -> Array[#{class_name_opt}]?
def #{col.name}_in_database: () -> #{class_name_opt}
def saved_change_to_#{col.name}: () -> Array[#{class_name_opt}]?
def saved_change_to_#{col.name}?: () -> bool
def will_save_change_to_#{col.name}?: () -> bool
def restore_#{col.name}!: () -> void
def clear_#{col.name}_change: () -> void
EOS
sig << "attr_accessor #{col.name}? (): #{class_name}\n" if col.type == :boolean
sig
end.join("\n")
end
private def optional(class_name)
class_name.include?("|") ? "(#{class_name})?" : "#{class_name}?"
end
private def sql_type_to_class(t)
case t
when :integer
'Integer'
when :float
'Float'
when :decimal
'BigDecimal'
when :string, :text, :citext, :uuid, :binary
'String'
when :datetime
'ActiveSupport::TimeWithZone'
when :boolean
"bool"
when :jsonb, :json
"untyped"
when :date
'Date'
when :time
'Time'
when :inet
"IPAddr"
else
# Unknown column type, give up
'untyped'
end
end
private
attr_reader :klass, :klass_name
end
end
end
| 32.430407 | 121 | 0.546913 |
bfcca93d60945fc112774d9f986085ba2926ff1d | 1,606 | cask 'racket' do
version '6.10'
sha256 '1b9813c53bb55cc443f794e607f6bbfb14d734ceb02fa1e264c9f9e790f2b676'
url "https://mirror.racket-lang.org/installers/#{version}/racket-#{version}-x86_64-macosx.dmg"
appcast 'https://download.racket-lang.org/all-versions.html',
checkpoint: 'fd8e1ab40210ae188f13986e6fe4665f8e90563ffc9c20601e6dfb7de3654fad'
name 'Racket'
homepage 'https://racket-lang.org/'
suite "Racket v#{version}"
binary "#{appdir}/Racket v#{version}/bin/drracket"
binary "#{appdir}/Racket v#{version}/bin/gracket"
binary "#{appdir}/Racket v#{version}/bin/gracket-text"
binary "#{appdir}/Racket v#{version}/bin/mred"
binary "#{appdir}/Racket v#{version}/bin/mred-text"
binary "#{appdir}/Racket v#{version}/bin/mzc"
binary "#{appdir}/Racket v#{version}/bin/mzpp"
binary "#{appdir}/Racket v#{version}/bin/mzscheme"
binary "#{appdir}/Racket v#{version}/bin/mztext"
binary "#{appdir}/Racket v#{version}/bin/pdf-slatex"
binary "#{appdir}/Racket v#{version}/bin/plt-games"
binary "#{appdir}/Racket v#{version}/bin/plt-help"
binary "#{appdir}/Racket v#{version}/bin/plt-r5rs"
binary "#{appdir}/Racket v#{version}/bin/plt-r6rs"
binary "#{appdir}/Racket v#{version}/bin/plt-web-server"
binary "#{appdir}/Racket v#{version}/bin/racket"
binary "#{appdir}/Racket v#{version}/bin/raco"
binary "#{appdir}/Racket v#{version}/bin/scribble"
binary "#{appdir}/Racket v#{version}/bin/setup-plt"
binary "#{appdir}/Racket v#{version}/bin/slatex"
binary "#{appdir}/Racket v#{version}/bin/slideshow"
binary "#{appdir}/Racket v#{version}/bin/swindle"
end
| 45.885714 | 96 | 0.709215 |
2112f72fdeaa5c7513caae71dac7359110e0ece3 | 226 | class Time
def api(time = Time.now)
# Time.now.utc.iso8601
# Time.now.utc.to_datetime.rfc3339(9)
# DateTime.parse(Time.now.utc.to_s).rfc3339(9)
time.utc.to_datetime.rfc3339(9).gsub(/\+00:00$/, 'Z')
end
end
| 25.111111 | 57 | 0.654867 |
33b3ed1fd45ed8c63bce5a53c71c01f70dad50fa | 339 | RSpec.configure do |config|
# config.before(:suite) do
# DatabaseCleaner.clean_with :truncation, except: %w(ar_internal_metadata)
# end
# config.before do
# DatabaseCleaner.strategy = :transaction
# end
# config.before do
# DatabaseCleaner.start
# end
# config.after do
# DatabaseCleaner.clean
# end
end
| 18.833333 | 78 | 0.687316 |
1c098ff3294f3859409079a7dd971989345b2761 | 10,298 | # 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 'aws-sdk-core/waiters'
module Aws::SageMaker
module Waiters
class EndpointDeleted
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (60)
# @option options [Integer] :delay (30)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 60,
delay: 30,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_endpoint,
acceptors: [
{
"expected" => "ValidationException",
"matcher" => "error",
"state" => "success"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "endpoint_status"
}
]
)
}.merge(options))
end
# @option (see Client#describe_endpoint)
# @return (see Client#describe_endpoint)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
class EndpointInService
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (120)
# @option options [Integer] :delay (30)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 120,
delay: 30,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_endpoint,
acceptors: [
{
"expected" => "InService",
"matcher" => "path",
"state" => "success",
"argument" => "endpoint_status"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "endpoint_status"
},
{
"expected" => "ValidationException",
"matcher" => "error",
"state" => "failure"
}
]
)
}.merge(options))
end
# @option (see Client#describe_endpoint)
# @return (see Client#describe_endpoint)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
class NotebookInstanceDeleted
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (60)
# @option options [Integer] :delay (30)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 60,
delay: 30,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_notebook_instance,
acceptors: [
{
"expected" => "ValidationException",
"matcher" => "error",
"state" => "success"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "notebook_instance_status"
}
]
)
}.merge(options))
end
# @option (see Client#describe_notebook_instance)
# @return (see Client#describe_notebook_instance)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
class NotebookInstanceInService
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (60)
# @option options [Integer] :delay (30)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 60,
delay: 30,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_notebook_instance,
acceptors: [
{
"expected" => "InService",
"matcher" => "path",
"state" => "success",
"argument" => "notebook_instance_status"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "notebook_instance_status"
}
]
)
}.merge(options))
end
# @option (see Client#describe_notebook_instance)
# @return (see Client#describe_notebook_instance)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
class NotebookInstanceStopped
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (60)
# @option options [Integer] :delay (30)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 60,
delay: 30,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_notebook_instance,
acceptors: [
{
"expected" => "Stopped",
"matcher" => "path",
"state" => "success",
"argument" => "notebook_instance_status"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "notebook_instance_status"
}
]
)
}.merge(options))
end
# @option (see Client#describe_notebook_instance)
# @return (see Client#describe_notebook_instance)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
class TrainingJobCompletedOrStopped
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (180)
# @option options [Integer] :delay (120)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 180,
delay: 120,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_training_job,
acceptors: [
{
"expected" => "Completed",
"matcher" => "path",
"state" => "success",
"argument" => "training_job_status"
},
{
"expected" => "Stopped",
"matcher" => "path",
"state" => "success",
"argument" => "training_job_status"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "training_job_status"
},
{
"expected" => "ValidationException",
"matcher" => "error",
"state" => "failure"
}
]
)
}.merge(options))
end
# @option (see Client#describe_training_job)
# @return (see Client#describe_training_job)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
class TransformJobCompletedOrStopped
# @param [Hash] options
# @option options [required, Client] :client
# @option options [Integer] :max_attempts (60)
# @option options [Integer] :delay (60)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
def initialize(options)
@client = options.fetch(:client)
@waiter = Aws::Waiters::Waiter.new({
max_attempts: 60,
delay: 60,
poller: Aws::Waiters::Poller.new(
operation_name: :describe_transform_job,
acceptors: [
{
"expected" => "Completed",
"matcher" => "path",
"state" => "success",
"argument" => "transform_job_status"
},
{
"expected" => "Stopped",
"matcher" => "path",
"state" => "success",
"argument" => "transform_job_status"
},
{
"expected" => "Failed",
"matcher" => "path",
"state" => "failure",
"argument" => "transform_job_status"
},
{
"expected" => "ValidationException",
"matcher" => "error",
"state" => "failure"
}
]
)
}.merge(options))
end
# @option (see Client#describe_transform_job)
# @return (see Client#describe_transform_job)
def wait(params = {})
@waiter.wait(client: @client, params: params)
end
# @api private
attr_reader :waiter
end
end
end
| 29.677233 | 74 | 0.494853 |
1d9f65b90a25a3e27d52d0490f822c595c8cb393 | 1,770 | require 'test_helper'
class OrganizationsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
sign_in users(:admin)
@organization = organizations(:org1)
end
test "should get index" do
get organizations_url
assert_response :success
end
test "should get new" do
get new_organization_url
assert_response :success
end
test "should create organization" do
assert_difference('Organization.count') do
post organizations_url, params: { organization: { name: 'new org' } }
end
assert_redirected_to organizations_url
end
test "should show organization" do
get organizations_url
assert_response :success
end
test "should get edit" do
get edit_organization_url('en',@organization)
assert_response :success
end
test "should update organization" do
patch organization_url('en',@organization), params: { organization: { name: 'new org 2' } }
assert_redirected_to organizations_url
end
test "should destroy organization" do
assert_difference('Organization.count', -1) do
delete organization_url('en',@organization)
end
assert_redirected_to organizations_url
end
test "Organization name must be unique" do
duplicate_organization = @organization.dup
@organization.save
assert_not duplicate_organization.valid?
end
test "Organization name must be present" do
assert @organization.valid?
end
test "Organization name must not be blank" do
new_organization = Organization.new(name: ' ')
assert !new_organization.valid?
end
test "Organization name must not be nil" do
new_organization = Organization.new(name: nil)
assert !new_organization.valid?
end
end
| 24.246575 | 96 | 0.728249 |
216cfdb9a008083ddd340216dc605f429054cf49 | 1,536 | $:.unshift File.join(File.dirname(__FILE__),"..","lib")
require 'test/unit'
require 'rgen/array_extensions'
class ArrayExtensionsTest < Test::Unit::TestCase
def test_element_methods
c = Struct.new("SomeClass",:name,:age)
a = []
a << c.new('MyName',33)
a << c.new('YourName',22)
assert_equal ["MyName", "YourName"], a >> :name
assert_raise NoMethodError do
a.name
end
assert_equal [33, 22], a>>:age
assert_raise NoMethodError do
a.age
end
# unfortunately, any method can be called on an empty array
assert_equal [], [].age
end
class MMBaseClass < RGen::MetamodelBuilder::MMBase
has_attr 'name'
has_attr 'age', Integer
end
def test_with_mmbase
e1 = MMBaseClass.new
e1.name = "MyName"
e1.age = 33
e2 = MMBaseClass.new
e2.name = "YourName"
e2.age = 22
a = [e1, e2]
assert_equal ["MyName", "YourName"], a >> :name
assert_equal ["MyName", "YourName"], a.name
assert_equal [33, 22], a>>:age
assert_equal [33, 22], a.age
# put something into the array that is not an MMBase
a << "not a MMBase"
# the dot operator will tell that there is something not a MMBase
assert_raise StandardError do
a.age
end
# the >> operator will try to call the method anyway
assert_raise NoMethodError do
a >> :age
end
end
def test_hash_square
assert_equal({}, Hash[[]])
end
def test_to_str_on_empty_array
assert_raise NoMethodError do
[].to_str
end
end
end
| 23.630769 | 69 | 0.636719 |
ace68d83957910cfa4bb5e617f0f4929be7bb465 | 838 | Capistrano::Configuration.instance(true).load do
namespace :redis do
desc "Install the latest release of Redis"
task :install, roles: :app do
run "#{sudo} add-apt-repository -y ppa:chris-lea/redis-server"
run "#{sudo} apt-get -y update"
run "#{sudo} apt-get -y install redis-server"
end
after "cap_vps:prepare", "redis:install"
# desc "Setup redis configuration for this application"
# task :setup, roles: :web do
# template "redis.conf.erb", "/tmp/redis.conf"
# run "#{sudo} mv /tmp/redis.conf /etc/redis/redis.conf"
# restart
# end
# after "deploy:setup", "redis:setup"
%w[start stop restart].each do |command|
desc "#{command} redis"
task command, roles: :web do
run "#{sudo} service redis-server #{command}"
end
end
end
end
| 28.896552 | 68 | 0.626492 |
e98f22f01fa7fda21187e5368f8bdaca9f9d4bc0 | 4,117 | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for uses of `and` and `or`, and suggests using `&&` and
# `||` instead. It can be configured to check only in conditions or in
# all contexts.
#
# @example EnforcedStyle: always
# # bad
# foo.save and return
#
# # bad
# if foo and bar
# end
#
# # good
# foo.save && return
#
# # good
# if foo && bar
# end
#
# @example EnforcedStyle: conditionals (default)
# # bad
# if foo and bar
# end
#
# # good
# foo.save && return
#
# # good
# foo.save and return
#
# # good
# if foo && bar
# end
class AndOr < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
def on_and(node)
process_logical_operator(node) if style == :always
end
alias on_or on_and
def on_if(node)
on_conditionals(node) if style == :conditionals
end
alias on_while on_if
alias on_while_post on_if
alias on_until on_if
alias on_until_post on_if
private
def process_logical_operator(node)
return if node.logical_operator?
message = message(node)
add_offense(node.loc.operator, message: message) do |corrector|
node.each_child_node do |expr|
if expr.send_type?
correct_send(expr, corrector)
elsif expr.return_type? || expr.assignment?
correct_other(expr, corrector)
end
end
corrector.replace(node.loc.operator, node.alternate_operator)
end
end
def on_conditionals(node)
node.condition.each_node(*AST::Node::OPERATOR_KEYWORDS) do |operator|
process_logical_operator(operator)
end
end
def message(node)
format(MSG, prefer: node.alternate_operator, current: node.operator)
end
def correct_send(node, corrector)
return correct_not(node, node.receiver, corrector) if node.method?(:!)
return correct_setter(node, corrector) if node.setter_method?
return correct_other(node, corrector) if node.comparison_method?
return unless correctable_send?(node)
corrector.replace(whitespace_before_arg(node), '(')
corrector.insert_after(node.last_argument, ')')
end
def correct_setter(node, corrector)
corrector.insert_before(node.receiver, '(')
corrector.insert_after(node.last_argument, ')')
end
# ! is a special case:
# 'x and !obj.method arg' can be auto-corrected if we
# recurse down a level and add parens to 'obj.method arg'
# however, 'not x' also parses as (send x :!)
def correct_not(node, receiver, corrector)
if node.prefix_bang?
return unless receiver.send_type?
correct_send(receiver, corrector)
elsif node.prefix_not?
correct_other(node, corrector)
else
raise 'unrecognized unary negation operator'
end
end
def correct_other(node, corrector)
return if node.source_range.begin.is?('(')
corrector.wrap(node, '(', ')')
end
def correctable_send?(node)
!node.parenthesized? && node.arguments? && !node.method?(:[])
end
def whitespace_before_arg(node)
begin_paren = node.loc.selector.end_pos
end_paren = begin_paren
# Increment position of parenthesis, unless message is a predicate
# method followed by a non-whitespace char (e.g. is_a?String).
end_paren += 1 unless /\?\S/.match?(node.source)
range_between(begin_paren, end_paren)
end
end
end
end
end
| 28.992958 | 80 | 0.569832 |
ff634f04324df977ec22e0a076bba1f4e1ae0073 | 178 | module Prpr
module Handler
class CodeDeploy < Base
handle Event::Push do
Action::CodeDeploy::Deploy.new(event).call
end
end
end
end
| 17.8 | 52 | 0.589888 |
ff10ad8963a1cfe699486913aa43808eaf8002a4 | 544 | class CreateArtists < ActiveRecord::Migration[5.2]
def up
end
def down
end
def change
create_table :artists do |t|
create_table :artists do |t|
t.string :name
t.string :genre
t.integer :age
t.string :hometown
end
end
end
class artists < ActiveRecord::Base
end
class AddFavoriteFoodToArtists < ActiveRecord::Migration[5.2]
def change
add_column :artists, :favorite_food, :string
end
end | 20.148148 | 63 | 0.558824 |
d55228e8cf00e5af822fc07a4f79fb95b5e1be72 | 661 | class ProcessDeployCommits
def process
return if ENV['DISABLE_PROCESS_DEPLOY_COMMITS'] == 'true'
puts "[gci] #{DateTime.now.utc.iso8601} Clockwork ProcessDeployCommits Started Running"
deploys = Deploy.all
deploy_commit_count = 0
deploys.each do |deploy|
sha = DeployedShaScraper.new.scrape(deploy)
if sha
DeployCommit.create_with(sha: sha).find_or_create_by!(deploy_id: deploy.id)
deploy_commit_count += 1
end
end
puts "[gci] #{DateTime.now.utc.iso8601} Clockwork ProcessDeployCommits Finished Running, " \
"processed #{deploys.size} deploys and #{deploy_commit_count} commits."
end
end
| 34.789474 | 96 | 0.711044 |
613c1145e47c7c8e7d09f4a5dcb7d93fc3bc7c44 | 669 | cask 'sqlpro-studio' do
version '1.0.320'
sha256 '2ccc078818cd2c6b0157c7743532d72ef31323bdf986320f603115161801b84f'
# d3fwkemdw8spx3.cloudfront.net/studio was verified as official when first introduced to the cask
url "https://d3fwkemdw8spx3.cloudfront.net/studio/SQLProStudio.#{version}.app.zip"
name 'SQLPro Studio'
homepage 'https://www.sqlprostudio.com/'
app 'SQLPro Studio.app'
zap trash: [
'~/Library/Containers/com.hankinsoft.osx.sqlprostudio',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.hankinsoft.osx.sqlprostudio.sfl*',
]
end
| 39.352941 | 163 | 0.7429 |
38e9b9d0e0f34003dee0b9a3fdb686c26408aa80 | 336 | require 'chartjs/chart_helpers'
module Chartjs
class Engine < Rails::Engine
initializer 'chartjs.chart_helpers' do
if ::Chartjs.no_conflict
ActionView::Base.send :include, Chartjs::ChartHelpers::Explicit
else
ActionView::Base.send :include, Chartjs::ChartHelpers::Implicit
end
end
end
end
| 24 | 71 | 0.699405 |
084eb82e438aeda14defe05630383cd27d8011e4 | 500 | # typed: false
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| 31.25 | 96 | 0.782 |
6aa5e32eddbc432af97141de17511dd4be9d0f71 | 5,958 | module LLVM
module Script
# Converts an object into a LLVM::Value. A hint can be specified to ensure that the value is
# of a given kind or type.
#
# <b>Conversion Table</b>
#
# Ruby | LLVM | Possible Kinds | Possible Types
# -------------------------------------------------------------------------------------------
# nil, 0 | null pointer | (none) | A pointer type
# true | i1 0 | :numeric, :integer | Int1
# false | i1 1 | :numeric, :integer | Int1
# Float | Float or Double | :numeric, :decimal | Float, Double
# Numeric | ConstantInt | :numeric, :integer | Int1 to Int64
# String* | ConstantArray, i8 pointer | :pointer, :array | Int8 array or pointer
# Array | ConstantArray, ConstantVector | :array, :vector | An array type
#
# * Strings can only be converted into i8 pointers in the {LLVM::Script::Generator#Convert Generator version of convert}.
# @param [Object] val The object to convert into a LLVM::Value.
# @param [Symbol, LLVM::Type] hint A symbolic kind or a LLVM::Type that signifies what kind
# an object should be. If nil, the value will be converted based on its class.
# @return [LLVM::Value] The newly converted LLVM::Value
def self.Convert(val, hint=nil)
type = LLVM::Type(hint)
kind = hint if hint.is_a?(Symbol)
kind = type.kind if type.kind_of?(LLVM::Type)
klass = Types::DOUBLE if type == LLVM::Double.type || kind == :double
klass = LLVM.const_get("Int#{type.width}".to_sym) if type.kind_of?(LLVM::IntType)
if val.kind_of?(LLVM::Value)
if hint.nil? || val.type == type || (type.nil? && ((kind == :decimal && Decimal(val.type.kind)) ||
(kind == :numeric && (val.type.kind == :integer || Decimal(val.type.kind))) || val.type.kind == kind))
return val
end
elsif val.kind_of?(LLVM::Script::ScriptObject)
return val
elsif (val == 0 || val.nil?) && !type.nil? && kind == :pointer
return type.null_pointer
elsif val == true && (kind.nil? || kind == :numeric || kind == :integer)
return (klass || Types::BOOL).from_i(1)
elsif val == false && (kind.nil? || kind == :numeric || kind == :integer)
return (klass || Types::BOOL).from_i(0)
elsif Decimal(kind) || (val.kind_of?(::Float) && (kind.nil? || kind == :numeric))
return (klass || Types::FLOAT).from_f(val.to_f)
elsif kind == :integer || kind == :numeric || (kind.nil? && val.kind_of?(Numeric))
return (klass || Types::INT).from_i(val.to_i)
elsif val.kind_of?(String) && (kind.nil? || kind == :array)
return LLVM::ConstantArray.string(val.to_s)
elsif kind == :array || (kind.nil? && val.kind_of?(Array))
type = !type.nil? ? type.element_type : Convert(val.to_a.first).type
return LLVM::ConstantArray.const(type, val.to_a.map{|elm| Convert(elm, type)})
elsif kind == :vector
type = !type.nil? ? type.element_type : Convert(val.to_a.first).type
return LLVM::ConstantVector.const(val.to_a.map{|elm| Convert(elm, type)})
end
if hint.nil?
possibles = "LLVM::Value, Numeric, Array, String, or True/False/Nil"
raise ArgumentError, "Cannot convert #{Typename(val)}, it is not of #{possibles}."
else
raise ArgumentError, "Cannot convert #{Typename(val)} into a #{Typename(hint)}."
end
end
# Checks that the given kind is a float kind (:decimal, :float, :double, :x86_fp80, :fp128, or :ppc_fp128).
# :decimal in ruby-llvm-script signifies any kind of float.
# @param [Object] kind The kind to check.
# @return [Boolean] The resulting true/false value.
def self.Decimal(kind)
case kind
when :decimal, :float, :double, :x86_fp80, :fp128, :ppc_fp128
return true
end
return false
end
# Validates that an object is of the given kind.
# @param [Object] obj The object to validate.
# @param [:value, :type] kind The kind of object +obj+ should be. :value means an LLVM::Value,
# :type means an LLVM::Type.
# @return [LLVM::Value, LLVM::Type] The valid object.
def self.Validate(obj, kind)
case kind
when :value
unless obj.kind_of?(LLVM::Value)
raise ArgumentError, "#{obj.class.name} is not a valid LLVM::Value."
end
return obj
when :type
type = LLVM::Type(obj)
unless type.kind_of?(LLVM::Type) || type.kind_of?(LLVM::Script::Struct)
raise ArgumentError, "#{obj.class.name} is not a valid LLVM::Type."
end
return type
else
raise ArgumentError, "Kind passed to validate must be either :value or :type. #{kind.inspect} given."
end
end
# Returns a human-readable description of the given object's type.
# @param [Object] obj The object to inspect.
# @return [String] The resulting type-name.
def self.Typename(obj)
return obj.name if obj.kind_of?(Class)
type = LLVM::Type(obj)
if type.kind_of?(LLVM::Type)
case type.kind
when :pointer
level = 0
while type.kind == :pointer
type = type.element_type
level += 1
end
return Typename(type) + (" pointer" * level)
when :integer
return LLVM.const_get("Int#{type.width}".to_sym).name
else
return type.kind.to_s.capitalize
end
elsif obj.kind_of?(Symbol)
return obj.to_s.capitalize
else
return obj.class.name
end
end
end
end | 47.664 | 125 | 0.560759 |
18a819452491e277d37f6d627379943da42ab23d | 2,293 | require "test/unit"
require "mime"
class TestMessage < Test::Unit::TestCase #:nodoc:
include Mime
def test_message_1
message = Message.new(
CompositeContent.new(
"mixed",
"boundary",
PlainContent.textual("Lorem ipsum dolor sit amet, ..."),
AdvancedContent.new(
PlainContent.binary("..."),
filename: "foo",
creation_date: DateTime.new(2017, 1, 1, 1),
modification_date: DateTime.new(2017, 1, 2, 2),
read_date: DateTime.new(2017, 2, 1, 3)
)
),
From: Mailbox.new("[email protected]", "Allison Smith"),
To: Mailbox.new("[email protected]", "Thomas Müller"),
Subject: "Welcome Thomas"
)
assert_equal(message.to_s, expected_message)
end
def test_message_2
message = Message.new
message["From"] = Mailbox.new("[email protected]", "Allison Smith")
message["To"] = Mailbox.new("[email protected]", "Thomas Müller")
message["Subject"] = "Welcome Thomas"
multipart = CompositeContent.new
multipart.type = "mixed"
multipart.boundary = "boundary"
message << multipart
body = PlainContent.textual("Lorem ipsum dolor sit amet, ...")
multipart << body
attachment = AdvancedContent.new(PlainContent.binary("..."))
attachment.filename = "foo"
attachment.creation_date = DateTime.new(2017, 1, 1, 1)
attachment.modification_date = DateTime.new(2017, 1, 2, 2)
attachment.read_date = DateTime.new(2017, 2, 1, 3)
multipart << attachment
assert_equal(message.to_s, expected_message)
end
def expected_message
<<EOS
MIME-Version: 1.0
From: Allison Smith <[email protected]>
To: =?utf-8?Q?Thomas=20M=C3=BCller?= <[email protected]>
Subject: Welcome Thomas
Content-Type: multipart/mixed; boundary="=_boundary"
--=_boundary
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Lorem ipsum dolor sit amet, ...
--=_boundary
Content-Disposition: attachment; filename=foo;
creation-date="Sun, 01 Jan 2017 01:00:00 +0000";
modification-date="Mon, 02 Jan 2017 02:00:00 +0000";
read-date="Wed, 01 Feb 2017 03:00:00 +0000"; size=3
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Li4u
--=_boundary--
EOS
end
end | 28.6625 | 69 | 0.657654 |
28cff183a0d1120eae82cf472fdddd086f28ef86 | 168 | # typed: strict
# frozen_string_literal: true
require 'test_helper'
class LocatorTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.272727 | 43 | 0.720238 |
4a1d146b459635f07f50730787c4dd068a3c5ae9 | 1,986 | require 'dotenv/format_error'
module Dotenv
class Environment < Hash
LINE = /
\A
(?:export\s+)? # optional export
([\w\.]+) # key
(?:\s*=\s*|:\s+?) # separator
( # optional value begin
'(?:\'|[^'])*' # single quoted value
| # or
"(?:\"|[^"])*" # double quoted value
| # or
[^#\n]+ # unquoted value
)? # value end
(?:\s*\#.*)? # optional comment
\z
/x
VARIABLE = /
(\\)?
(\$)
( # collect braces with var for sub
\{? # allow brace wrapping
([A-Z0-9_]+) # match the variable
\}? # closing brace
)
/xi
def initialize(filename)
@filename = filename
load
end
def load
read.each do |line|
if match = line.match(LINE)
key, value = match.captures
value ||= ''
# Remove surrounding quotes
value = value.strip.sub(/\A(['"])(.*)\1\z/, '\2')
if $1 == '"'
value = value.gsub('\n', "\n")
# Unescape all characters except $ so variables can be escaped properly
value = value.gsub(/\\([^$])/, '\1')
end
# Process embedded variables
value.scan(VARIABLE).each do |parts|
if parts.first == '\\'
replace = parts[1...-1].join('')
else
replace = self.fetch(parts.last) { ENV[parts.last] }
end
value = value.sub(parts[0...-1].join(''), replace || '')
end
self[key] = value
elsif line !~ /\A\s*(?:#.*)?\z/ # not comment or blank line
raise FormatError, "Line #{line.inspect} doesn't match format"
end
end
end
def read
File.read(@filename).split("\n")
end
def apply
each { |k,v| ENV[k] ||= v }
end
end
end
| 25.792208 | 83 | 0.430514 |
8735022e221920deafffba161991f2ecb4d4a5fa | 9,471 | #
# Copyright (c) 2015-2016, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Arista Networks nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
require 'spec_helper'
include FixtureHelpers
describe Puppet::Type.type(:eos_acl_entry).provider(:eos) do
# Puppet RAL memoized methods
let(:resource) do
resource_hash = {
name: 'test1:10',
ensure: :present,
acltype: :standard,
action: :permit,
srcaddr: '1.2.3.0',
srcprefixlen: 8,
log: :true,
provider: described_class.name
}
Puppet::Type.type(:eos_acl_entry).new(resource_hash)
end
let(:remark_resource) do
resource_hash = {
name: 'test2:15',
ensure: :present,
acltype: :standard,
action: :remark,
remark: 'Test remark.',
provider: described_class.name
}
Puppet::Type.type(:eos_acl_entry).new(resource_hash)
end
let(:provider) { resource.provider }
let(:remark_provider) { remark_resource.provider }
let(:api) { double('acl_entry') }
def acl_entry
acl_entry = Fixtures[:acl_entry]
return acl_entry if acl_entry
fixture('acl_entry', dir: File.dirname(__FILE__))
end
before :each do
allow(described_class.node).to receive(:api).with('acl').and_return(api)
allow(provider.node).to receive(:api).with('acl').and_return(api)
allow(remark_provider.node).to receive(:api).with('acl').and_return(api)
end
context 'class methods' do
before { allow(api).to receive(:getall).and_return(acl_entry) }
describe '.instances' do
subject { described_class.instances }
it { is_expected.to be_an Array }
it 'has four entries' do
expect(subject.size).to eq 5
end
it 'has an instance for test1 and test2 entries' do
%w[test1:10 test1:20 test2:10 test2:15 test2:20].each do |name|
instance = subject.find { |p| p.name == name }
expect(instance).to be_a described_class
end
end
context 'eos_acl_entry { test1:10 }' do
subject { described_class.instances.find { |p| p.name == 'test1:10' } }
include_examples 'provider resource methods',
acltype: :standard,
action: :permit,
srcaddr: 'host 1.2.3.4',
srcprefixlen: :absent,
log: :true
end
context 'eos_acl_entry { test2:15 } remark' do
subject { described_class.instances.find { |p| p.name == 'test2:15' } }
include_examples 'provider resource methods',
acltype: :standard,
action: :remark,
remark: 'this is a comment'
end
end
describe '.prefetch' do
let :resources do
{
'test1:10' => Puppet::Type.type(:eos_acl_entry).new(name: 'test1:10'),
'test2:10' => Puppet::Type.type(:eos_acl_entry).new(name: 'test2:10'),
'test3:10' => Puppet::Type.type(:eos_acl_entry).new(name: 'test3:10')
}
end
subject { described_class.prefetch(resources) }
it 'resource providers are absent prior to calling .prefetch' do
resources.values.each do |rsrc|
expect(rsrc.provider.acltype).to eq(:absent)
expect(rsrc.provider.action).to eq(:absent)
expect(rsrc.provider.srcaddr).to eq(:absent)
expect(rsrc.provider.srcprefixlen).to eq(:absent)
expect(rsrc.provider.log).to eq(:absent)
end
end
it 'sets the provider instance of the managed resource test1' do
subject
expect(resources['test1:10'].provider.acltype).to eq(:standard)
expect(resources['test1:10'].provider.action).to eq(:permit)
expect(resources['test1:10'].provider.srcaddr).to eq('host 1.2.3.4')
expect(resources['test1:10'].provider.srcprefixlen).to be_truthy
expect(resources['test1:10'].provider.log).to be_truthy
end
it 'sets the provider instance of the managed resource test2' do
subject
expect(resources['test2:10'].provider.acltype).to eq(:standard)
expect(resources['test2:10'].provider.action).to eq(:deny)
expect(resources['test2:10'].provider.srcaddr).to eq('1.2.3.0')
expect(resources['test2:10'].provider.srcprefixlen).to eq(8)
expect(resources['test2:10'].provider.log).to eq(:false)
end
it 'does not set the provider instance of the unmanaged resource' do
subject
expect(resources['test3:10'].provider.acltype).to eq(:absent)
expect(resources['test3:10'].provider.action).to eq(:absent)
expect(resources['test3:10'].provider.srcaddr).to eq(:absent)
expect(resources['test3:10'].provider.srcprefixlen).to eq(:absent)
expect(resources['test3:10'].provider.log).to eq(:absent)
end
end
end
context 'resource (instance) methods' do
describe '#exists?' do
subject { provider.exists? }
context 'when the resource does not exist on the system' do
it { is_expected.to be_falsey }
end
context 'when the resource exists on the system' do
let(:provider) do
allow(api).to receive(:getall).and_return(acl_entry)
described_class.instances.first
end
it { is_expected.to be_truthy }
end
end
describe '#create' do
before do
update_values = resource.to_hash
update_values[:seqno] = 10
expect(api).to receive(:update_entry).with('test1', update_values)
allow(api).to receive_messages(
acltype: true,
action: true,
srcaddr: true,
srcprefixlen: true,
log: true
)
end
it 'sets ensure on the resource' do
provider.create
provider.flush
expect(provider.ensure).to eq(:present)
end
it 'sets acltype on the resource' do
provider.create
provider.flush
expect(provider.acltype).to eq(:standard)
end
it 'sets action on the resource' do
provider.create
provider.flush
expect(provider.action).to eq(:permit)
end
it 'sets srcaddr on the resource' do
provider.create
provider.flush
expect(provider.srcaddr).to eq('1.2.3.0')
end
it 'sets srcprefixlen on the resource' do
provider.create
provider.flush
expect(provider.srcprefixlen).to eq(8)
end
it 'sets log on the resource' do
provider.create
provider.flush
expect(provider.log).to eq(:true)
end
end
describe '#create a remark' do
before do
update_values = remark_resource.to_hash
update_values[:seqno] = 15
expect(api).to receive(:update_entry).with('test2', update_values)
allow(api).to receive_messages(
acltype: true,
action: true,
srcaddr: false,
srcprefixlen: false,
log: true,
remark: true
)
end
it 'sets remark on the resource' do
remark_provider.create
remark_provider.flush
expect(remark_provider.action).to eq(:remark)
expect(remark_provider.remark).to eq('Test remark.')
end
it '#remark updates the remark' do
remark_provider.create
remark_provider.flush
update_values = remark_resource.to_hash
update_values[:seqno] = 15
update_values[:remark] = 'Change me!'
expect(api).to receive(:update_entry).with('test2', update_values)
remark_provider.remark = 'Change me!'
remark_provider.flush
expect(remark_provider.action).to eq(:remark)
expect(remark_provider.remark).to eq('Change me!')
end
end
describe '#destroy' do
it 'sets ensure to :absent' do
resource[:ensure] = :absent
expect(api).to receive(:remove_entry).with('test1', 10)
provider.destroy
provider.flush
expect(provider.ensure).to eq(:absent)
end
end
end
end
| 33 | 80 | 0.636997 |
3924964b75ad72aac8776eef7deb03d949be73b7 | 26,071 | # encoding: UTF-8
require 'support/ruby_interpreter'
require 'yaml'
require 'vcr/structs'
require 'vcr/errors'
require 'zlib'
require 'stringio'
require 'support/limited_uri'
require 'support/configuration_stubbing'
RSpec.shared_examples_for "a header normalizer" do
let(:instance) do
with_headers('Some_Header' => 'value1', 'aNother' => ['a', 'b'], 'third' => [], 'fourth' => nil)
end
it 'ensures header keys are serialized to yaml as raw strings' do
key = 'my-key'
key.instance_variable_set(:@foo, 7)
instance = with_headers(key => ['value1'])
expect(YAML.dump(instance.headers)).to eq(YAML.dump('my-key' => ['value1']))
end
it 'ensures header values are serialized to yaml as raw strings' do
value = 'my-value'
value.instance_variable_set(:@foo, 7)
instance = with_headers('my-key' => [value])
expect(YAML.dump(instance.headers)).to eq(YAML.dump('my-key' => ['my-value']))
end
it 'handles nested arrays' do
accept_encoding = [["gzip", "1.0"], ["deflate", "1.0"], ["sdch", "1.0"]]
instance = with_headers('accept-encoding' => accept_encoding)
expect(instance.headers['accept-encoding']).to eq(accept_encoding)
end
it 'handles nested arrays with floats' do
accept_encoding = [["gzip", 1.0], ["deflate", 1.0], ["sdch", 1.0]]
instance = with_headers('accept-encoding' => accept_encoding)
expect(instance.headers['accept-encoding']).to eq(accept_encoding)
end
end
RSpec.shared_examples_for "a body normalizer" do
it "ensures the body is serialized to yaml as a raw string" do
body = "My String"
body.instance_variable_set(:@foo, 7)
expect(YAML.dump(instance(body).body)).to eq(YAML.dump("My String"))
end
it 'converts nil to a blank string' do
expect(instance(nil).body).to eq("")
end
it 'raises an error if given another type of object as the body' do
expect {
instance(:a => "hash")
}.to raise_error(ArgumentError)
end
end
module VCR
::RSpec.describe HTTPInteraction do
include_context "configuration stubbing"
before { allow(config).to receive(:uri_parser) { LimitedURI } }
if ''.respond_to?(:encoding)
def body_hash(key, value)
{ key => value, 'encoding' => 'UTF-8' }
end
else
def body_hash(key, value)
{ key => value }
end
end
describe "#recorded_at" do
let(:now) { Time.now }
it 'is initialized to the current time' do
allow(Time).to receive(:now).and_return(now)
expect(VCR::HTTPInteraction.new.recorded_at).to eq(now)
end
end
let(:status) { ResponseStatus.new(200, "OK") }
let(:response) { Response.new(status, { "foo" => ["bar"] }, "res body") }
let(:request) { Request.new(:get, "http://foo.com/", "req body", { "bar" => ["foo"] }) }
let(:recorded_at) { Time.utc(2011, 5, 4, 12, 30) }
let(:interaction) { HTTPInteraction.new(request, response, recorded_at) }
describe ".from_hash" do
let(:hash) do
{
'request' => {
'method' => 'get',
'uri' => 'http://foo.com/',
'body' => body_hash('string', 'req body'),
'headers' => { "bar" => ["foo"] }
},
'response' => {
'status' => {
'code' => 200,
'message' => 'OK'
},
'headers' => { "foo" => ["bar"] },
'body' => body_hash('string', 'res body')
},
'recorded_at' => "Wed, 04 May 2011 12:30:00 GMT"
}
end
it 'constructs an HTTP interaction from the given hash' do
expect(HTTPInteraction.from_hash(hash)).to eq(interaction)
end
it 'initializes the recorded_at timestamp from the hash' do
expect(HTTPInteraction.from_hash(hash).recorded_at).to eq(recorded_at)
end
it 'initializes the response http_version from the hash if it is included' do
hash['response']['http_version'] = '1.1'
interaction = HTTPInteraction.from_hash(hash)
expect(interaction.response.http_version).to eq('1.1')
end
it 'initializes the response adapter_metadata from the hash if it is included' do
hash['response']['adapter_metadata'] = { 'foo' => 12 }
interaction = HTTPInteraction.from_hash(hash)
expect(interaction.response.adapter_metadata).to eq("foo" => 12)
end
it 'works when the response http_version is missing' do
expect(hash['response'].keys).not_to include('http_version')
interaction = HTTPInteraction.from_hash(hash)
expect(interaction.response.http_version).to be_nil
end
it 'works when the response adapter_metadata is missing' do
expect(hash['response'].keys).not_to include('adapter_metadata')
interaction = HTTPInteraction.from_hash(hash)
expect(interaction.response.adapter_metadata).to eq({})
end
it 'uses a blank request when the hash lacks one' do
hash.delete('request')
i = HTTPInteraction.from_hash(hash)
expect(i.request).to eq(Request.new)
end
it 'uses a blank response when the hash lacks one' do
hash.delete('response')
i = HTTPInteraction.from_hash(hash)
expect(i.response).to eq(Response.new(ResponseStatus.new))
end
it 'decodes the base64 body string' do
hash['request']['body'] = body_hash('base64_string', Base64.encode64('req body'))
hash['response']['body'] = body_hash('base64_string', Base64.encode64('res body'))
i = HTTPInteraction.from_hash(hash)
expect(i.request.body).to eq('req body')
expect(i.response.body).to eq('res body')
end
if ''.respond_to?(:encoding)
it 'force encodes the decoded base64 string as the original encoding' do
string = "café"
string.force_encoding("US-ASCII")
expect(string).not_to be_valid_encoding
hash['request']['body'] = { 'base64_string' => Base64.encode64(string.dup), 'encoding' => 'US-ASCII' }
hash['response']['body'] = { 'base64_string' => Base64.encode64(string.dup), 'encoding' => 'US-ASCII' }
i = HTTPInteraction.from_hash(hash)
expect(i.request.body.encoding.name).to eq("US-ASCII")
expect(i.response.body.encoding.name).to eq("US-ASCII")
expect(i.request.body.bytes.to_a).to eq(string.bytes.to_a)
expect(i.response.body.bytes.to_a).to eq(string.bytes.to_a)
expect(i.request.body).not_to be_valid_encoding
expect(i.response.body).not_to be_valid_encoding
end
it 'does not attempt to force encode the decoded base64 string when there is no encoding given (i.e. if the cassette was recorded on ruby 1.8)' do
hash['request']['body'] = { 'base64_string' => Base64.encode64('foo') }
i = HTTPInteraction.from_hash(hash)
expect(i.request.body).to eq('foo')
expect(i.request.body.encoding.name).to eq("ASCII-8BIT")
end
it 'tries to encode strings to the original encoding' do
hash['request']['body'] = { 'string' => "abc", 'encoding' => 'ISO-8859-1' }
hash['response']['body'] = { 'string' => "abc", 'encoding' => 'ISO-8859-1' }
i = HTTPInteraction.from_hash(hash)
expect(i.request.body).to eq("abc")
expect(i.response.body).to eq("abc")
expect(i.request.body.encoding.name).to eq("ISO-8859-1")
expect(i.response.body.encoding.name).to eq("ISO-8859-1")
end
it 'does not attempt to encode the string when there is no encoding given (i.e. if the cassette was recorded on ruby 1.8)' do
string = 'foo'
string.force_encoding("ISO-8859-1")
hash['request']['body'] = { 'string' => string }
i = HTTPInteraction.from_hash(hash)
expect(i.request.body).to eq('foo')
expect(i.request.body.encoding.name).to eq("ISO-8859-1")
end
it 'force encodes to ASCII-8BIT (since it just means "no encoding" or binary)' do
string = "\u00f6"
string.encode("UTF-8")
expect(string).to be_valid_encoding
hash['request']['body'] = { 'string' => string, 'encoding' => 'ASCII-8BIT' }
expect(Request).not_to receive(:warn)
i = HTTPInteraction.from_hash(hash)
expect(i.request.body).to eq(string)
expect(i.request.body.bytes.to_a).to eq(string.bytes.to_a)
expect(i.request.body.encoding.name).to eq("ASCII-8BIT")
end
context 'when the string cannot be encoded as the original encoding' do
def verify_encoding_error
expect { "\xFAbc".encode("ISO-8859-1") }.to raise_error(EncodingError)
end
before do
allow(Request).to receive(:warn)
allow(Response).to receive(:warn)
hash['request']['body'] = { 'string' => "\xFAbc", 'encoding' => 'ISO-8859-1' }
hash['response']['body'] = { 'string' => "\xFAbc", 'encoding' => 'ISO-8859-1' }
verify_encoding_error
end
it 'does not force the encoding' do
i = HTTPInteraction.from_hash(hash)
expect(i.request.body).to eq("\xFAbc")
expect(i.response.body).to eq("\xFAbc")
expect(i.request.body.encoding.name).not_to eq("ISO-8859-1")
expect(i.response.body.encoding.name).not_to eq("ISO-8859-1")
end
it 'prints a warning and informs users of the :preserve_exact_body_bytes option' do
expect(Request).to receive(:warn).with(/ISO-8859-1.*preserve_exact_body_bytes/)
expect(Response).to receive(:warn).with(/ISO-8859-1.*preserve_exact_body_bytes/)
HTTPInteraction.from_hash(hash)
end
end
end
end
describe "#to_hash" do
include_context "configuration stubbing"
before(:each) do
allow(config).to receive(:preserve_exact_body_bytes_for?).and_return(false)
allow(config).to receive(:uri_parser).and_return(URI)
end
let(:hash) { interaction.to_hash }
it 'returns a nested hash containing all of the pertinent details' do
expect(hash.keys).to match_array %w[ request response recorded_at ]
expect(hash['recorded_at']).to eq(interaction.recorded_at.httpdate)
expect(hash['request']).to eq({
'method' => 'get',
'uri' => 'http://foo.com/',
'body' => body_hash('string', 'req body'),
'headers' => { "bar" => ["foo"] }
})
expect(hash['response']).to eq({
'status' => {
'code' => 200,
'message' => 'OK'
},
'headers' => { "foo" => ["bar"] },
'body' => body_hash('string', 'res body')
})
end
it 'includes the response adapter metadata when it is not empty' do
interaction.response.adapter_metadata['foo'] = 17
expect(hash['response']['adapter_metadata']).to eq('foo' => 17)
end
it 'does not include the response adapter metadata when it is empty' do
expect(interaction.response.adapter_metadata).to eq({})
expect(hash['response'].keys).not_to include('adapter_metadata')
end
context "when the body is extended with a module and some state" do
it 'serializes to YAML w/o the extra state' do
interaction.request.body.extend Module.new { attr_accessor :foo }
interaction.response.body.extend Module.new { attr_accessor :foo }
interaction.request.body.foo = 98765
interaction.response.body.foo = 98765
expect(YAML.dump(interaction.to_hash)).not_to include("98765")
end
end
it 'encodes the body as base64 when the configuration is so set' do
allow(config).to receive(:preserve_exact_body_bytes_for?).and_return(true)
expect(hash['request']['body']).to eq(body_hash('base64_string', Base64.encode64('req body')))
expect(hash['response']['body']).to eq(body_hash('base64_string', Base64.encode64('res body')))
end
it "sets the string's original encoding", :if => ''.respond_to?(:encoding) do
interaction.request.body.force_encoding('ISO-8859-10')
interaction.response.body.force_encoding('ASCII-8BIT')
expect(hash['request']['body']['encoding']).to eq('ISO-8859-10')
expect(hash['response']['body']['encoding']).to eq('ASCII-8BIT')
end
def assert_yielded_keys(hash, *keys)
yielded_keys = []
hash.each { |k, v| yielded_keys << k }
expect(yielded_keys).to eq(keys)
end
it 'yields the entries in the expected order so the hash can be serialized in that order' do
assert_yielded_keys hash, 'request', 'response', 'recorded_at'
assert_yielded_keys hash['request'], 'method', 'uri', 'body', 'headers'
assert_yielded_keys hash['response'], 'status', 'headers', 'body'
assert_yielded_keys hash['response']['status'], 'code', 'message'
end
it 'yields `adapter_metadata` if it has any data' do
interaction.response.adapter_metadata['foo'] = 17
assert_yielded_keys hash['response'], 'status', 'headers', 'body', 'adapter_metadata'
end
it 'yields `http_version` if it has any data' do
interaction.response.http_version = '1.1'
assert_yielded_keys hash['response'], 'status', 'headers', 'body', 'http_version'
end
end
describe "#parsed_uri" do
before :each do
allow(uri_parser).to receive(:parse).and_return(uri)
allow(config).to receive(:uri_parser).and_return(uri_parser)
end
let(:uri_parser){ double('parser') }
let(:uri){ double('uri').as_null_object }
it "parses the uri using the current uri_parser" do
expect(uri_parser).to receive(:parse).with(request.uri)
request.parsed_uri
end
it "returns the parsed uri" do
expect(request.parsed_uri).to eq uri
end
end
end
::RSpec.describe HTTPInteraction::HookAware do
include_context "configuration stubbing"
before do
allow(config).to receive(:uri_parser) { LimitedURI }
end
let(:response_status) { VCR::ResponseStatus.new(200, "OK foo") }
let(:body) { "The body foo this is (foo-Foo)" }
let(:headers) do {
'x-http-foo' => ['bar23', '23foo'],
'x-http-bar' => ['foo23', '18']
} end
let(:response) do
VCR::Response.new(
response_status,
headers.dup,
body.dup
)
end
let(:request) do
VCR::Request.new(
:get,
'http://example-foo.com:80/foo/',
body.dup,
headers.dup
)
end
let(:interaction) { VCR::HTTPInteraction.new(request, response) }
subject { HTTPInteraction::HookAware.new(interaction) }
describe '#ignored?' do
it 'returns false by default' do
should_not be_ignored
end
it 'returns true when #ignore! has been called' do
subject.ignore!
should be_ignored
end
end
describe '#filter!' do
let(:filtered) { subject.filter!('foo', 'AAA') }
it 'does nothing when given a blank argument' do
expect {
subject.filter!(nil, 'AAA')
subject.filter!('foo', nil)
subject.filter!("", 'AAA')
subject.filter!('foo', "")
}.not_to change { interaction }
end
[:request, :response].each do |part|
it "replaces the sensitive text in the #{part} header keys and values" do
expect(filtered.send(part).headers).to eq({
'x-http-AAA' => ['bar23', '23AAA'],
'x-http-bar' => ['AAA23', '18']
})
end
it "replaces the sensitive text in the #{part} body" do
expect(filtered.send(part).body).to eq("The body AAA this is (AAA-Foo)")
end
end
it 'replaces the sensitive text in the response status' do
expect(filtered.response.status.message).to eq('OK AAA')
end
it 'replaces sensitive text in the request URI' do
expect(filtered.request.uri).to eq('http://example-AAA.com/AAA/')
end
it 'handles numbers (such as the port) properly' do
request.uri = "http://foo.com:9000/bar"
subject.filter!(9000, "<PORT>")
expect(request.uri).to eq("http://foo.com:<PORT>/bar")
end
end
end
::RSpec.describe Request::Typed do
[:uri, :method, :headers, :body].each do |method|
it "delegates ##{method} to the request" do
request = double(method => "delegated value")
expect(Request::Typed.new(request, :type).send(method)).to eq("delegated value")
end
end
describe "#type" do
it 'returns the initialized type' do
expect(Request::Typed.new(double, :ignored).type).to be(:ignored)
end
end
valid_types = [:ignored, :stubbed_by_vcr, :externally_stubbed, :recordable, :unhandled]
valid_types.each do |type|
describe "##{type}?" do
it "returns true if the type is set to :#{type}" do
expect(Request::Typed.new(double, type).send("#{type}?")).to be true
end
it "returns false if the type is set to :other" do
expect(Request::Typed.new(double, :other).send("#{type}?")).to be false
end
end
end
describe "#real?" do
real_types = [:ignored, :recordable]
real_types.each do |type|
it "returns true if the type is set to :#{type}" do
expect(Request::Typed.new(double, type)).to be_real
end
end
(valid_types - real_types).each do |type|
it "returns false if the type is set to :#{type}" do
expect(Request::Typed.new(double, type)).not_to be_real
end
end
end
describe "#stubbed?" do
stubbed_types = [:externally_stubbed, :stubbed_by_vcr]
stubbed_types.each do |type|
it "returns true if the type is set to :#{type}" do
expect(Request::Typed.new(double, type)).to be_stubbed
end
end
(valid_types - stubbed_types).each do |type|
it "returns false if the type is set to :#{type}" do
expect(Request::Typed.new(double, type)).not_to be_stubbed
end
end
end
end
::RSpec.describe Request do
include_context "configuration stubbing"
before do
allow(config).to receive(:uri_parser) { LimitedURI }
end
describe '#method' do
subject { VCR::Request.new(:get) }
context 'when given no arguments' do
it 'returns the HTTP method' do
expect(subject.method).to eq(:get)
end
end
context 'when given an argument' do
it 'returns the method object for the named method' do
m = subject.method(:class)
expect(m).to be_a(Method)
expect(m.call).to eq(described_class)
end
end
it 'gets normalized to a lowercase symbol' do
expect(VCR::Request.new("GET").method).to eq(:get)
expect(VCR::Request.new(:GET).method).to eq(:get)
expect(VCR::Request.new(:get).method).to eq(:get)
expect(VCR::Request.new("get").method).to eq(:get)
end
end
describe "#uri" do
def uri_for(uri)
VCR::Request.new(:get, uri).uri
end
it 'removes the default http port' do
expect(uri_for("http://foo.com:80/bar")).to eq("http://foo.com/bar")
end
it 'removes the default https port' do
expect(uri_for("https://foo.com:443/bar")).to eq("https://foo.com/bar")
end
it 'does not remove a non-standard http port' do
expect(uri_for("http://foo.com:81/bar")).to eq("http://foo.com:81/bar")
end
it 'does not remove a non-standard https port' do
expect(uri_for("https://foo.com:442/bar")).to eq("https://foo.com:442/bar")
end
end
describe Request::FiberAware do
subject { Request::FiberAware.new(Request.new) }
it 'adds a #proceed method that yields in a fiber' do
fiber = Fiber.new do |request|
request.proceed
:done
end
expect(fiber.resume(subject)).to be_nil
expect(fiber.resume).to eq(:done)
end
it 'can be cast to a proc' do
expect(Fiber).to receive(:yield)
call_later = subject.to_proc
call_later.call
end
end
it_behaves_like 'a header normalizer' do
def with_headers(headers)
described_class.new(:get, 'http://example.com/', nil, headers)
end
end
it_behaves_like 'a body normalizer' do
def instance(body)
described_class.new(:get, 'http://example.com/', body, {})
end
end
end
::RSpec.describe Response do
it_behaves_like 'a header normalizer' do
def with_headers(headers)
described_class.new(:status, headers, nil, '1.1')
end
end
it_behaves_like 'a body normalizer' do
def instance(body)
described_class.new(:status, {}, body, '1.1')
end
end
describe "#adapter_metadata" do
it 'returns the hash given as the last #initialize argument' do
response = Response.new(
ResponseStatus.new(200, "OK"),
{}, "the body", "1.1",
{ "meta" => "value" }
)
expect(response.adapter_metadata).to eq("meta" => "value")
end
it 'returns a blank hash when nil is passed to #initialize' do
response = Response.new(
ResponseStatus.new(200, "OK"),
{}, "the body", "1.1", nil
)
expect(response.adapter_metadata).to eq({})
end
end
describe '#update_content_length_header' do
%w[ content-length Content-Length ].each do |header|
context "for the #{header} header" do
define_method :instance do |body, content_length|
headers = { 'content-type' => 'text' }
headers.merge!(header => content_length) if content_length
described_class.new(VCR::ResponseStatus.new, headers, body)
end
it 'does nothing when the response lacks a content_length header' do
inst = instance('the body', nil)
expect {
inst.update_content_length_header
}.not_to change { inst.headers[header] }
end
it 'sets the content_length header to the response body length when the header is present' do
inst = instance('the body', '3')
expect {
inst.update_content_length_header
}.to change { inst.headers[header] }.from(['3']).to(['8'])
end
it 'sets the content_length header to 0 if the response body is nil' do
inst = instance(nil, '3')
expect {
inst.update_content_length_header
}.to change { inst.headers[header] }.from(['3']).to(['0'])
end
it 'sets the header according to RFC 2616 based on the number of bytes (not the number of characters)' do
inst = instance('aؼ', '2') # the second char is a double byte char
expect {
inst.update_content_length_header
}.to change { inst.headers[header] }.from(['2']).to(['3'])
end
end
end
end
describe '#decompress' do
%w[ content-encoding Content-Encoding ].each do |header|
context "for the #{header} header" do
define_method :instance do |body, content_encoding|
headers = { 'content-type' => 'text',
'content-length' => body.bytesize.to_s }
headers[header] = content_encoding if content_encoding
described_class.new(VCR::ResponseStatus.new, headers, body)
end
let(:content) { 'The quick brown fox jumps over the lazy dog' }
it "does nothing when no compression" do
resp = instance('Hello', nil)
expect(resp).not_to be_compressed
expect {
expect(resp.decompress).to equal(resp)
}.to_not change { resp.headers['content-length'] }
end
it "does nothing when encoding is 'identity'" do
resp = instance('Hello', 'identity')
expect(resp).not_to be_compressed
expect {
expect(resp.decompress).to equal(resp)
}.to_not change { resp.headers['content-length'] }
end
it "raises error for unrecognized encoding" do
resp = instance('Hello', 'flabbergaster')
expect(resp).not_to be_compressed
expect { resp.decompress }.
to raise_error(Errors::UnknownContentEncodingError, 'unknown content encoding: flabbergaster')
end
it "unzips gzipped response" do
io = StringIO.new
writer = Zlib::GzipWriter.new(io)
writer << content
writer.close
gzipped = io.string
resp = instance(gzipped, 'gzip')
expect(resp).to be_compressed
expect {
expect(resp.decompress).to equal(resp)
expect(resp).not_to be_compressed
expect(resp.body).to eq(content)
}.to change { resp.headers['content-length'] }.
from([gzipped.bytesize.to_s]).
to([content.bytesize.to_s])
end
it "inflates deflated response" do
deflated = Zlib::Deflate.deflate(content)
resp = instance(deflated, 'deflate')
expect(resp).to be_compressed
expect {
expect(resp.decompress).to equal(resp)
expect(resp).not_to be_compressed
expect(resp.body).to eq(content)
}.to change { resp.headers['content-length'] }.
from([deflated.bytesize.to_s]).
to([content.bytesize.to_s])
end
end
end
end
end
end
| 34.854278 | 154 | 0.595528 |
083071a324160a31dd40fc9d9da1b393036b4304 | 578 | module ApplicationHelper
# display error message
def error_helper(object)
content_tag(:h2, "Oops:", id: "error_explanation")
end
#create a list of errors for the object being created
def error_list(object)
content_tag(:ul, :class => "error msgs") do
object.errors.full_messages.each do |msg|
concat content_tag(:li, msg)
# build a create watchlist link if no watchlist is selected
if msg == "Watchlist can't be blank"
concat link_to "Create a Watchlist", new_watchlist_path
end
end
end
end
end
| 25.130435 | 65 | 0.66436 |
2899aa22557e6cec06e959a72491734c5501ef51 | 469 | cask 'hstracker' do
version '1.5.3'
sha256 'ab816511bfa84de56be93f250c264cb2131197e8bd2e0259a71776eb8dbd5ac3'
# github.com/HearthSim/HSTracker was verified as official when first introduced to the cask
url "https://github.com/HearthSim/HSTracker/releases/download/#{version}/HSTracker.app.zip"
appcast 'https://github.com/HearthSim/HSTracker/releases.atom'
name 'Hearthstone Deck Tracker'
homepage 'https://hsdecktracker.net/'
app 'HSTracker.app'
end
| 36.076923 | 93 | 0.784648 |
0130d216c75572fa81a4f36a5c885cbe507b2ac3 | 337 | cask 'camunda-modeler' do
version '1.4.0'
sha256 '7b7c46e198283fa10377f774cc4e93c6f843f91a8f9b0a44c718b4a4626ba4a1'
url "https://camunda.org/release/camunda-modeler/#{version}/camunda-modeler-#{version}-darwin-x64.tar.gz"
name 'Camunda Modeler'
homepage 'https://camunda.org/'
app 'camunda-modeler/Camunda Modeler.app'
end
| 30.636364 | 107 | 0.768546 |
18b5d72b3174954a9d566d947c1a0a444b6cf6fc | 10,182 | =begin
#Hydrogen Nucleus API
#The Hydrogen Nucleus API
OpenAPI spec version: 1.9.4
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.19
=end
require 'uri'
module NucleusApi
class BulkApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Create a bulk data
# Create a new bulk data for your firm.
# @param data data
# @param entity_uri UUID entity_uri
# @param [Hash] opts the optional parameters
# @return [BulkTransaction]
def create_bulk_using_post(data, entity_uri, opts = {})
data, _status_code, _headers = create_bulk_using_post_with_http_info(data, entity_uri, opts)
data
end
# Create a bulk data
# Create a new bulk data for your firm.
# @param data data
# @param entity_uri UUID entity_uri
# @param [Hash] opts the optional parameters
# @return [Array<(BulkTransaction, Fixnum, Hash)>] BulkTransaction data, response status code and response headers
def create_bulk_using_post_with_http_info(data, entity_uri, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: BulkApi.create_bulk_using_post ...'
end
# verify the required parameter 'data' is set
if @api_client.config.client_side_validation && data.nil?
fail ArgumentError, "Missing the required parameter 'data' when calling BulkApi.create_bulk_using_post"
end
# verify the required parameter 'entity_uri' is set
if @api_client.config.client_side_validation && entity_uri.nil?
fail ArgumentError, "Missing the required parameter 'entity_uri' when calling BulkApi.create_bulk_using_post"
end
# resource path
local_var_path = '/nucleus/v1/bulk/{entity_uri}'.sub('{' + 'entity_uri' + '}', entity_uri.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(data)
auth_names = ['oauth2']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'BulkTransaction')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: BulkApi#create_bulk_using_post\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Delete a bulk data
# Delete a bulk data for your firm.
# @param data data
# @param entity_uri UUID entity_uri
# @param [Hash] opts the optional parameters
# @return [BulkTransaction]
def delete_bulk_using_delete(data, entity_uri, opts = {})
data, _status_code, _headers = delete_bulk_using_delete_with_http_info(data, entity_uri, opts)
data
end
# Delete a bulk data
# Delete a bulk data for your firm.
# @param data data
# @param entity_uri UUID entity_uri
# @param [Hash] opts the optional parameters
# @return [Array<(BulkTransaction, Fixnum, Hash)>] BulkTransaction data, response status code and response headers
def delete_bulk_using_delete_with_http_info(data, entity_uri, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: BulkApi.delete_bulk_using_delete ...'
end
# verify the required parameter 'data' is set
if @api_client.config.client_side_validation && data.nil?
fail ArgumentError, "Missing the required parameter 'data' when calling BulkApi.delete_bulk_using_delete"
end
# verify the required parameter 'entity_uri' is set
if @api_client.config.client_side_validation && entity_uri.nil?
fail ArgumentError, "Missing the required parameter 'entity_uri' when calling BulkApi.delete_bulk_using_delete"
end
# resource path
local_var_path = '/nucleus/v1/bulk/{entity_uri}'.sub('{' + 'entity_uri' + '}', entity_uri.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(data)
auth_names = ['oauth2']
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'BulkTransaction')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: BulkApi#delete_bulk_using_delete\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Status of bulk transaction
# Get the status of bulk transaction.
# @param id UUID Bulk Transaction Id
# @param [Hash] opts the optional parameters
# @return [BulkTransactionVO]
def get_bulk_status_using_get(id, opts = {})
data, _status_code, _headers = get_bulk_status_using_get_with_http_info(id, opts)
data
end
# Status of bulk transaction
# Get the status of bulk transaction.
# @param id UUID Bulk Transaction Id
# @param [Hash] opts the optional parameters
# @return [Array<(BulkTransactionVO, Fixnum, Hash)>] BulkTransactionVO data, response status code and response headers
def get_bulk_status_using_get_with_http_info(id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: BulkApi.get_bulk_status_using_get ...'
end
# verify the required parameter 'id' is set
if @api_client.config.client_side_validation && id.nil?
fail ArgumentError, "Missing the required parameter 'id' when calling BulkApi.get_bulk_status_using_get"
end
# resource path
local_var_path = '/nucleus/v1/bulk/status/{id}'.sub('{' + 'id' + '}', id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['oauth2']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'BulkTransactionVO')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: BulkApi#get_bulk_status_using_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Update a bulk data
# Update a bulk data for your firm.
# @param data data
# @param entity_uri UUID entity_uri
# @param [Hash] opts the optional parameters
# @return [BulkTransaction]
def update_bulk_using_put(data, entity_uri, opts = {})
data, _status_code, _headers = update_bulk_using_put_with_http_info(data, entity_uri, opts)
data
end
# Update a bulk data
# Update a bulk data for your firm.
# @param data data
# @param entity_uri UUID entity_uri
# @param [Hash] opts the optional parameters
# @return [Array<(BulkTransaction, Fixnum, Hash)>] BulkTransaction data, response status code and response headers
def update_bulk_using_put_with_http_info(data, entity_uri, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: BulkApi.update_bulk_using_put ...'
end
# verify the required parameter 'data' is set
if @api_client.config.client_side_validation && data.nil?
fail ArgumentError, "Missing the required parameter 'data' when calling BulkApi.update_bulk_using_put"
end
# verify the required parameter 'entity_uri' is set
if @api_client.config.client_side_validation && entity_uri.nil?
fail ArgumentError, "Missing the required parameter 'entity_uri' when calling BulkApi.update_bulk_using_put"
end
# resource path
local_var_path = '/nucleus/v1/bulk/{entity_uri}'.sub('{' + 'entity_uri' + '}', entity_uri.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(data)
auth_names = ['oauth2']
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'BulkTransaction')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: BulkApi#update_bulk_using_put\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 40.086614 | 160 | 0.683166 |
61fc5e6ac5ebcef7f03a20252bd6e6196e730195 | 419 | require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", home_path, count: 2
assert_select "a[href=?]", help_path
assert_select "a[href=?]", about_path
assert_select "a[href=?]", contact_path
get contact_path
assert_select "title", full_title("Contact")
end
end
| 27.933333 | 54 | 0.71599 |
6acb075290cddab31a3619f88e547eb2d58d36ab | 30 | module MinhaPaginasHelper
end
| 10 | 25 | 0.9 |
e88885dfc7fbcabb294cb55d5de5175949ef2c8f | 17,936 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
# require "google/ads/google_ads/error"
require "google/ads/google_ads/v5/services/location_view_service_pb"
module Google
module Ads
module GoogleAds
module V5
module Services
module LocationViewService
##
# Client for the LocationViewService service.
#
# Service to fetch location views.
#
class Client
include Paths
# @private
attr_reader :location_view_service_stub
##
# Configure the LocationViewService Client class.
#
# See {::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client::Configuration}
# for a description of the configuration fields.
#
# ## Example
#
# To modify the configuration for all LocationViewService clients:
#
# ::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
default_config = Client::Configuration.new
default_config.timeout = 3600.0
default_config.retry_policy = {
initial_delay: 5.0,
max_delay: 60.0,
multiplier: 1.3,
retry_codes: [14, 4]
}
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the LocationViewService Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new LocationViewService client object.
#
# ## Examples
#
# To create a new LocationViewService client with the default
# configuration:
#
# client = ::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client.new
#
# To create a new LocationViewService client with a custom
# configuration:
#
# client = ::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the LocationViewService client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/ads/google_ads/v5/services/location_view_service_services_pb"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
credentials ||= Credentials.default scope: @config.scope
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@location_view_service_stub = ::Gapic::ServiceStub.new(
::Google::Ads::GoogleAds::V5::Services::LocationViewService::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
# Service calls
##
# Returns the requested location view in full detail.
#
# @overload get_location_view(request, options = nil)
# Pass arguments to `get_location_view` via a request object, either of type
# {::Google::Ads::GoogleAds::V5::Services::GetLocationViewRequest} or an equivalent Hash.
#
# @param request [::Google::Ads::GoogleAds::V5::Services::GetLocationViewRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_location_view(resource_name: nil)
# Pass arguments to `get_location_view` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param resource_name [::String]
# Required. The resource name of the location view to fetch.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Ads::GoogleAds::V5::Resources::LocationView]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Ads::GoogleAds::V5::Resources::LocationView]
#
# @raise [Google::Ads::GoogleAds::Error] if the RPC is aborted.
#
def get_location_view request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Ads::GoogleAds::V5::Services::GetLocationViewRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_location_view.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Ads::GoogleAds::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"resource_name" => request.resource_name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_location_view.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_location_view.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@location_view_service_stub.call_rpc :get_location_view, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
# rescue GRPC::BadStatus => grpc_error
# raise Google::Ads::GoogleAds::Error.new grpc_error.message
end
##
# Configuration class for the LocationViewService API.
#
# This class represents the configuration for LocationViewService,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for get_location_view
# to 20 seconds, and all remaining timeouts to 10 seconds:
#
# ::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.get_location_view.timeout = 20.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Ads::GoogleAds::V5::Services::LocationViewService::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.get_location_view.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"googleads.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "googleads.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution"=>1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config&.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the LocationViewService API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in milliseconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `get_location_view`
# @return [::Gapic::Config::Method]
#
attr_reader :get_location_view
# @private
def initialize parent_rpcs = nil
get_location_view_config = parent_rpcs&.get_location_view if parent_rpcs&.respond_to? :get_location_view
@get_location_view = ::Gapic::Config::Method.new get_location_view_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
end
| 48.085791 | 126 | 0.536574 |
1a2e82839f00f1ca9f0ab42d91b23e6b2a57e737 | 3,539 | require 'socket'
require 'io/console/size'
require_relative 'config'
require_relative 'version'
# $VERBOSE = true
module DEBUGGER__
class CommandLineOptionError < Exception; end
class Client
begin
require 'readline'
def readline
Readline.readline("\n(rdb) ", true)
end
rescue LoadError
def readline
print "\n(rdb) "
gets
end
end
def initialize argv
return util(argv) if String === argv
case argv.size
when 0
connect_unix
when 1
case arg = argv.shift
when /-h/, /--help/
help
exit
when /\A\d+\z/
connect_tcp nil, arg.to_i
else
connect_unix arg
end
when 2
connect_tcp argv[0], argv[1]
else
raise CommandLineOptionError
end
@width = IO.console_size[1]
@width_changed = false
send "version: #{VERSION} width: #{@width} cookie: #{CONFIG[:cookie]}"
end
def util name
case name
when 'gen-sockpath'
puts DEBUGGER__.create_unix_domain_socket_name
when 'list-socks'
cleanup_unix_domain_sockets
puts list_connections
else
raise "Unknown utility: #{name}"
end
end
def cleanup_unix_domain_sockets
Dir.glob(DEBUGGER__.create_unix_domain_socket_name_prefix + '*') do |file|
if /(\d+)$/ =~ file
begin
Process.kill(0, $1.to_i)
rescue Errno::ESRCH
File.unlink(file)
end
end
end
end
def list_connections
Dir.glob(DEBUGGER__.create_unix_domain_socket_name_prefix + '*')
end
def connect_unix name = nil
if name
if File.exist? name
@s = Socket.unix(name)
else
@s = Socket.unix(File.join(DEBUGGER__.unix_domain_socket_dir, name))
end
else
cleanup_unix_domain_sockets
files = list_connections
case files.size
when 0
$stderr.puts "No debug session is available."
exit
when 1
@s = Socket.unix(files.first)
else
$stderr.puts "Please select a debug session:"
files.each{|f|
$stderr.puts " #{File.basename(f)}"
}
exit
end
end
end
def connect_tcp host, port
@s = Socket.tcp(host, port)
end
def send msg
p send: msg if $VERBOSE
@s.puts msg
end
def connect
trap(:SIGINT){
send "pause"
}
trap(:SIGWINCH){
@width = IO.console_size[1]
@width_changed = true
}
while line = @s.gets
p recv: line if $VERBOSE
case line
when /^out (.*)/
puts "#{$1}"
when /^input/
prev_trap = trap(:SIGINT, 'DEFAULT')
begin
line = readline
rescue Interrupt
retry
ensure
trap(:SIGINT, prev_trap)
end
line = (line || 'quit').strip
if @width_changed
@width_changed = false
send "width #{@width}"
end
send "command #{line}"
when /^ask (.*)/
print $1
send "answer #{gets || ''}"
when /^quit/
raise 'quit'
else
puts "(unknown) #{line.inspect}"
end
end
rescue
STDERR.puts "disconnected (#{$!})"
exit
end
end
end
if __FILE__ == $0
DEBUGGER__::Client.new(argv).connect
end
| 21.065476 | 80 | 0.52755 |
1cc2217f2de15277b20779ea0cbc27365e9f4c9e | 1,334 | require 'tmpdir'
require 'digest/md5'
require 'cocaine'
module Cryptopro
class Base
CERTIFICATE_FILE_NAME = "certificate.cer"
CERTIFICATE_LINE_LENGTH = 64
def self.create_temp_dir
uniq_name = Digest::MD5.hexdigest("#{rand(1_000_000)}#{Time.now}")
full_name = "#{Dir.tmpdir}/cryptcp/#{uniq_name}"
FileUtils.mkdir_p(full_name)
end
def self.create_temp_file(dir_name, file_name, content)
full_path = "#{dir_name}/#{file_name}"
File.open(full_path, "w") { |file| file.write(content) }
full_path
end
# Добавляет -----BEGIN CERTIFICATE----- / -----END CERTIFICATE-----, если их нет.
# Так же делит длинную строку Base64 на строки по 64 символа.
# Это требование cryptcp к файл с сертификатом.
def self.add_container_to_certificate(certificate)
return certificate if certificate.downcase.include?("begin")
parts = certificate.scan(/.{1,#{CERTIFICATE_LINE_LENGTH}}/)
certificate_with_container = "-----BEGIN CERTIFICATE-----\n#{parts.join("\n")}\n-----END CERTIFICATE-----"
end
def self.create_temp_certificate_file(content)
tmp_dir = create_temp_dir
certificate_with_container = add_container_to_certificate(content)
create_temp_file(tmp_dir, CERTIFICATE_FILE_NAME, certificate_with_container)
end
end
end
| 33.35 | 112 | 0.697151 |
6a7aceb9aef53c0faa4333f4087ddb6474bf2050 | 74 | # frozen_string_literal: true
module ProjectHome
VERSION = '0.3.0'
end
| 12.333333 | 29 | 0.743243 |
ffc428c99a3d30cbd9e6bdc7a31b9ec8212e21f6 | 326 | require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
## Luxembourg
class LUTest < Phonie::TestCase
def test_local
parse_test('+352 2422 1234', '352', '2422', '1234', "Luxembourg", false)
end
def test_mobile
parse_test('+352 671 123456', '352', '671', '123456', "Luxembourg", true)
end
end
| 25.076923 | 77 | 0.668712 |
9111cd6cf239f660a0358fc2377132ce7ad241d8 | 6,369 | require 'spec_helper'
require 'ruby_event_store'
module RailsEventStore
RSpec.describe AsyncDispatcher do
class CustomScheduler
def call(klass, serialized_event)
klass.new.perform_async(serialized_event)
end
def async_handler?(klass)
not_async_class = [CallableHandler, NotCallableHandler, HandlerClass].include?(klass)
!(not_async_class || klass.is_a?(HandlerClass))
end
end
before(:each) do
CallableHandler.reset
MyAsyncHandler.reset
end
let!(:event) { RailsEventStore::Event.new(event_id: "83c3187f-84f6-4da7-8206-73af5aca7cc8") }
let!(:serialized_event) { RubyEventStore::Mappers::Default.new.event_to_serialized_record(event) }
it "async proxy for defined adapter enqueue job immediately when no transaction is open" do
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_to_have_enqueued_job(MyAsyncHandler) do
dispatcher.call(MyAsyncHandler, event, serialized_event)
end
expect(MyAsyncHandler.received).to be_nil
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to eq(serialized_event)
end
it "async proxy for defined adapter enqueue job only after transaction commit" do
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_to_have_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction do
expect_no_enqueued_job(MyAsyncHandler) do
dispatcher.call(MyAsyncHandler, event, serialized_event)
end
end
end
expect(MyAsyncHandler.received).to be_nil
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to eq(serialized_event)
end
it "async proxy for defined adapter do not enqueue job after transaction rollback" do
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_no_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction do
dispatcher.call(MyAsyncHandler, event, serialized_event)
raise ActiveRecord::Rollback
end
end
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to be_nil
end
it "async proxy for defined adapter does not enqueue job after transaction rollback (with raises)" do
was = ActiveRecord::Base.raise_in_transactional_callbacks
begin
ActiveRecord::Base.raise_in_transactional_callbacks = true
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_no_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction do
dispatcher.call(MyAsyncHandler, event, serialized_event)
raise ActiveRecord::Rollback
end
end
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to be_nil
ensure
ActiveRecord::Base.raise_in_transactional_callbacks = was
end
end if ActiveRecord::Base.respond_to?(:raise_in_transactional_callbacks)
it "async proxy for defined adapter enqueue job only after top-level transaction (nested is not new) commit" do
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_to_have_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction do
expect_no_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction(requires_new: false) do
dispatcher.call(MyAsyncHandler, event, serialized_event)
end
end
end
end
expect(MyAsyncHandler.received).to be_nil
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to eq(serialized_event)
end
it "async proxy for defined adapter enqueue job only after top-level transaction commit" do
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_to_have_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction do
expect_no_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction(requires_new: true) do
dispatcher.call(MyAsyncHandler, event, serialized_event)
end
end
end
end
expect(MyAsyncHandler.received).to be_nil
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to eq(serialized_event)
end
it "async proxy for defined adapter do not enqueue job after nested transaction rollback" do
dispatcher = AsyncDispatcher.new(proxy_strategy: AsyncProxyStrategy::AfterCommit.new, scheduler: CustomScheduler.new)
expect_no_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction do
expect_no_enqueued_job(MyAsyncHandler) do
ActiveRecord::Base.transaction(requires_new: true) do
dispatcher.call(MyAsyncHandler, event, serialized_event)
raise ActiveRecord::Rollback
end
end
end
end
MyAsyncHandler.perform_enqueued_jobs
expect(MyAsyncHandler.received).to be_nil
end
def expect_no_enqueued_job(job, &proc)
raise unless block_given?
yield
expect(job.queued).to be_nil
end
def expect_to_have_enqueued_job(job, &proc)
raise unless block_given?
yield
expect(job.queued).not_to be_nil
end
private
class CallableHandler
@@received = nil
def self.reset
@@received = nil
end
def self.received
@@received
end
def call(event)
@@received = event
end
end
class NotCallableHandler
end
class MyAsyncHandler
@@received = nil
@@queued = nil
def self.reset
@@received = nil
@@queued = nil
end
def self.queued
@@queued
end
def self.received
@@received
end
def self.perform_enqueued_jobs
@@received = @@queued
end
def perform_async(event)
@@queued = event
end
end
end
end
| 35.780899 | 125 | 0.700738 |
016f9bba7c266c3c736b7c10fa51ff51ce1a8dc0 | 702 | require('sinatra')
require('sinatra/reloader')
also_reload('lib/**/*.rb')
require('./lib/team')
require('./lib/member')
get('/') do
@teams = Team.all()
erb(:index)
end
post('/team_added') do
name = params.fetch('name')
@team = Team.new(:name => name)
@team.save()
erb(:success_team)
end
get('/teams/:id') do
id = params.fetch('id')
@team = Team.find(id.to_i)
erb(:team)
end
post('/member_added') do
first_name = params.fetch("first_name")
last_name = params.fetch("last_name")
@member = Member.new(:first_name => first_name, :last_name => last_name)
@member.save()
@team = Team.find(params.fetch('team_id').to_i)
@team.add_member(@member)
erb(:success_member)
end | 21.272727 | 74 | 0.655271 |
7afbd0a65faade51f862a89e0534e03ec3a655f9 | 258 | module Locomotive
module Regexps
SUBDOMAIN = /^[a-z][a-z0-9_-]*[a-z0-9]{1}$/
DOMAIN = /^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,}(:[0-9]{1,5})?(\/.*)?$/ix
URL = /((http|https|ftp):\/)?\/\S*/
end
end
| 21.5 | 94 | 0.372093 |
e2d36d76549e7e32bb4d87323fa645d91ce399a5 | 2,763 | # frozen_string_literal: true
require "rails/application_controller"
class Rails::MailersController < Rails::ApplicationController # :nodoc:
prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH
before_action :require_local!, unless: :show_previews?
before_action :find_preview, :set_locale, only: :preview
helper_method :part_query, :locale_query
content_security_policy(false)
def index
@previews = ActionMailer::Preview.all
@page_title = "Mailer Previews"
end
def preview
if params[:path] == @preview.preview_name
@page_title = "Mailer Previews for #{@preview.preview_name}"
render action: "mailer"
else
@email_action = File.basename(params[:path])
if @preview.email_exists?(@email_action)
@email = @preview.call(@email_action, params)
if params[:part]
part_type = Mime::Type.lookup(params[:part])
if part = find_part(part_type)
response.content_type = part_type
render plain: part.respond_to?(:decoded) ? part.decoded : part
else
raise AbstractController::ActionNotFound, "Email part '#{part_type}' not found in #{@preview.name}##{@email_action}"
end
else
@part = find_preferred_part(request.format, Mime[:html], Mime[:text])
render action: "email", layout: false, formats: %w[html]
end
else
raise AbstractController::ActionNotFound, "Email '#{@email_action}' not found in #{@preview.name}"
end
end
end
private
def show_previews? # :doc:
ActionMailer::Base.show_previews
end
def find_preview # :doc:
candidates = []
params[:path].to_s.scan(%r{/|$}) { candidates << $` }
preview = candidates.detect { |candidate| ActionMailer::Preview.exists?(candidate) }
if preview
@preview = ActionMailer::Preview.find(preview)
else
raise AbstractController::ActionNotFound, "Mailer preview '#{params[:path]}' not found"
end
end
def find_preferred_part(*formats) # :doc:
formats.each do |format|
if part = @email.find_first_mime_type(format)
return part
end
end
if formats.any? { |f| @email.mime_type == f }
@email
end
end
def find_part(format) # :doc:
if part = @email.find_first_mime_type(format)
part
elsif @email.mime_type == format
@email
end
end
def part_query(mime_type)
request.query_parameters.merge(part: mime_type).to_query
end
def locale_query(locale)
request.query_parameters.merge(locale: locale).to_query
end
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
| 28.193878 | 128 | 0.648208 |
383038446974c1c065636fb2452cd4e7431f6258 | 280 | ##
# Admin User model
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
end
| 31.111111 | 62 | 0.75 |
8725a9f978a3b637d3cb85914c2fc88d5e1fa948 | 207 | require 'rails_helper'
require 'support/devise'
require 'support/content_controller_example'
RSpec.describe UniversesController, type: :controller do
it_behaves_like 'a controller for a content item'
end
| 25.875 | 56 | 0.826087 |
e841612b8cfef4112873d2e843002fbc39a77270 | 166 | class AddCategoryToHangout < ActiveRecord::Migration[4.2]
def change
add_column :hangouts, :uid, :string
add_column :hangouts, :category, :string
end
end
| 23.714286 | 57 | 0.73494 |
d57b8aeda789e393e11b8fe1e96e8b953ab6715d | 15,038 | # 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::Network::Mgmt::V2020_08_01
#
# ExpressRouteLinks
#
class ExpressRouteLinks
include MsRestAzure
#
# Creates and initializes a new instance of the ExpressRouteLinks class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# Retrieves the specified ExpressRouteLink resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param link_name [String] The name of the ExpressRouteLink resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ExpressRouteLink] operation results.
#
def get(resource_group_name, express_route_port_name, link_name, custom_headers:nil)
response = get_async(resource_group_name, express_route_port_name, link_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Retrieves the specified ExpressRouteLink resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param link_name [String] The name of the ExpressRouteLink resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, express_route_port_name, link_name, custom_headers:nil)
get_async(resource_group_name, express_route_port_name, link_name, custom_headers:custom_headers).value!
end
#
# Retrieves the specified ExpressRouteLink resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param link_name [String] The name of the ExpressRouteLink resource.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, express_route_port_name, link_name, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'express_route_port_name is nil' if express_route_port_name.nil?
fail ArgumentError, 'link_name is nil' if link_name.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links/{linkName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'expressRoutePortName' => express_route_port_name,'linkName' => link_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::ExpressRouteLink.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<ExpressRouteLink>] operation results.
#
def list(resource_group_name, express_route_port_name, custom_headers:nil)
first_page = list_as_lazy(resource_group_name, express_route_port_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(resource_group_name, express_route_port_name, custom_headers:nil)
list_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value!
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(resource_group_name, express_route_port_name, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'express_route_port_name is nil' if express_route_port_name.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'expressRoutePortName' => express_route_port_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::ExpressRouteLinkListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ExpressRouteLinkListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::ExpressRouteLinkListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort
# resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param express_route_port_name [String] The name of the ExpressRoutePort
# resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ExpressRouteLinkListResult] which provide lazy access to pages of
# the response.
#
def list_as_lazy(resource_group_name, express_route_port_name, custom_headers:nil)
response = list_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 43.715116 | 186 | 0.707474 |
212e4534d653e460afac04e7c73e91af20485244 | 4,367 | require 'uri'
require 'awesome_spawn'
module MiqCockpit
class WS
DEFAULT_PORT = 9002
# Used when the cockpit-ws worker is not enabled
COCKPIT_PUBLIC_PORT = 9090
MIQ_REDIRECT_URL = "/dashboard/cockpit_redirect".freeze
COCKPIT_WS_PATH = '/usr/libexec/cockpit-ws'.freeze
COCKPIT_SSH_PATH = '/usr/libexec/cockpit-ssh'.freeze
attr_accessor :config_dir, :cockpit_dir
def self.can_start_cockpit_ws?
MiqEnvironment::Command.is_linux? &&
File.exist?(COCKPIT_WS_PATH) &&
File.exist?(COCKPIT_SSH_PATH)
end
def self.direct_url(address)
URI::HTTP.build(:host => address,
:port => MiqCockpit::WS::COCKPIT_PUBLIC_PORT)
end
def self.server_address(miq_server)
address = miq_server.ipaddress
if miq_server.hostname && (::Settings.webservices.contactwith == 'hostname' || !address)
address = miq_server.hostname
end
address
end
def self.current_ui_server?(miq_server)
return false unless MiqServer.my_server == miq_server
miq_server.has_active_userinterface
end
def self.url_from_server(miq_server, opts)
opts ||= {}
# Assume we are using apache unless we are the only server
has_apache = current_ui_server?(miq_server) ? MiqEnvironment::Command.supports_apache? : true
cls = has_apache ? URI::HTTPS : URI::HTTP
cls.build(:host => server_address(miq_server),
:port => has_apache ? nil : opts[:port] || DEFAULT_PORT,
:path => MiqCockpit::ApacheConfig.url_root)
end
def self.url(miq_server, opts, address)
return MiqCockpit::WS.direct_url(address) if miq_server.nil?
opts ||= {}
url = if opts[:external_url]
URI.parse(opts[:external_url])
else
url_from_server(miq_server, opts)
end
# Make sure we have a path that ends in a /
url.path = MiqCockpit::ApacheConfig.url_root if url.path.empty?
url.path = "#{url.path}/" unless url.path.end_with?("/")
# Add address to path if needed, note this is a path
# not a querystring
url.path = "#{url.path}=#{address}" if address
url
end
def initialize(opts = {})
@opts = opts || {}
@config_dir = File.join(__dir__, "..", "config")
@cockpit_conf_dir = File.join(@config_dir, "cockpit")
FileUtils.mkdir_p(@cockpit_conf_dir)
end
def command(address)
args = { :port => @opts[:port] || DEFAULT_PORT.to_s }
if address
args[:address] = address
end
args[:no_tls] = nil
AwesomeSpawn.build_command_line(COCKPIT_WS_PATH, args)
end
def save_config
fname = File.join(@cockpit_conf_dir, "cockpit.conf")
update_config
File.write(fname, @config)
end
def web_ui_url
if @opts[:web_ui_url]
url = URI.parse(@opts[:web_ui_url])
else
server = MiqRegion.my_region.try(:remote_ui_miq_server)
unless server.nil?
opts = { :port => 3000 }
url = MiqCockpit::WS.url_from_server(server, opts)
end
end
if url.nil?
ret = MiqCockpit::WS::MIQ_REDIRECT_URL
else
# Force the dashboard redirect path
url.path = MiqCockpit::WS::MIQ_REDIRECT_URL
ret = url.to_s
end
ret
end
def update_config
title = @opts[:title] || "ManageIQ Cockpit"
login_command = Rails.root.join("tools", "cockpit", "cockpit-auth-miq")
@config = <<-END_OF_CONFIG
[Webservice]
LoginTitle = #{title}
UrlRoot = #{MiqCockpit::ApacheConfig::URL_ROOT}
ProtocolHeader = X-Forwarded-Proto
[Negotiate]
Action = none
[Basic]
Action = none
[Bearer]
Action = remote-login-ssh
[SSH-Login]
command = #{login_command}
authFD=10
[OAuth]
Url = #{web_ui_url}
END_OF_CONFIG
@config
end
def setup_ssl
dir = File.join(@cockpit_conf_dir, "ws-certs.d")
FileUtils.mkdir_p(dir)
cert = File.open('certs/server.cer') { |f| OpenSSL::X509::Certificate.new(f).to_pem }
key = File.open('certs/server.cer.key') { |f| OpenSSL::PKey::RSA.new(f).to_pem }
contents = [cert, key].join("\n")
File.write(File.join(dir, "0-miq.cert"), contents)
end
end
class ApacheConfig
URL_ROOT = "cws".freeze
def self.url_root
"/#{URL_ROOT}/"
end
end
end
| 26.628049 | 99 | 0.630639 |
f823fdd17af7a3b50e53f2a2101e9e45f250e859 | 1,389 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_07_17_151544) do
create_table "airports", force: :cascade do |t|
t.string "airport_code"
t.string "airport_name"
t.integer "user_id"
t.index ["user_id"], name: "index_airports_on_user_id"
end
create_table "reviews", force: :cascade do |t|
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "airport_id"
t.integer "user_id"
t.index ["airport_id"], name: "index_reviews_on_airport_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.string "password_digest"
end
end
| 36.552632 | 86 | 0.741541 |
621f88c907537720c04ed30eada89eb9f5f1c026 | 1,101 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'componentize/version'
Gem::Specification.new do |spec|
spec.name = "componentize"
spec.version = Componentize::VERSION
spec.authors = ["Kyle Shevlin"]
spec.email = ["[email protected]"]
spec.summary = %q{Generator for inline and block level Rails components. Similar to Ember's component generator.}
spec.description = %q{Generator for inline and block level Rails components. Similar to Ember's component generator.}
spec.homepage = "https://github.com/kyleshevlin/componentize"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rails", ">= 3.1"
end
| 45.875 | 121 | 0.669391 |
ff8d1b6b1c64f15603f9ccb8b67d7118d8edebc2 | 269 | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password_digest
t.boolean :public, :default => false #user can choose to keep reviews private
end
end
end
| 24.454545 | 83 | 0.680297 |
bb7f8bb323d18850331296248e4edbf596d241e4 | 759 | class ApiUser
include HTTParty
base_uri "http://127.0.0.1:5000/"
headers "Content-Type" => "application/json"
def self.create(user)
post("/cadastro", body: user.to_json)
end
def self.auth(user)
post("/login", body: user.to_json)
end
def self.logout(token)
post("/logout", :headers => { "Authorization" => "Bearer #{token}" })
end
def self.find_users(user_id)
get("/usuarios/#{user_id}")
end
def self.delete_users(user_id, token)
delete("/usuarios/#{user_id}", :headers => { "Authorization" => "Bearer #{token}" })
end
def self.token(user_email, user_pass)
result = post("/auth/authenticate", body: { email: user_email, password: user_pass }.to_json)
"#{result.parsed_response["token"]}"
end
end
| 24.483871 | 97 | 0.653491 |
33096510c1eec5ad6a6b7f932d77e5d75125ef65 | 624 | module Fog
module Identity
class OpenStack
class Real
def delete_user(user_id)
request(
:expects => [200, 204],
:method => 'DELETE',
:path => "users/#{user_id}"
)
end
end
class Mock
def delete_user(user_id)
self.data[:users].delete(
list_users.body['users'].find {|x| x['id'] == user_id }['id'])
response = Excon::Response.new
response.status = 204
response
rescue
raise Fog::Identity::OpenStack::NotFound
end
end
end
end
end
| 21.517241 | 74 | 0.495192 |
0348b0f78aa80575831ffbcbbed2b0a343d6aaeb | 665 | module Spree
class ItemRefund
module StateMachine
extend ActiveSupport::Concern
included do
state_machine initial: :new do
event :renew do
transition from: :prepared, to: :new
end
event :prepare do
transition from: :new, to: :prepared
end
before_transition to: :prepared, do: :ensure_units_not_empty
after_transition to: :prepared, do: :calculate_totals
event :refund do
transition from: :prepared, to: :refunded
end
before_transition to: :refunded, do: :perform_refund
end
end
end
end
end
| 24.62963 | 70 | 0.589474 |
ab0ef1f62cde38dfca7a88649cc5b85aacca1dfb | 1,305 | # Redmine Messenger plugin for Redmine
class CreateMessengerSettings < ActiveRecord::Migration
def change
create_table :messenger_settings do |t|
t.references :project, null: false, index: true
t.string :messenger_url
t.string :messenger_icon
t.string :messenger_channel
t.string :messenger_username
t.integer :messenger_verify_ssl, default: 0, null: false
t.integer :auto_mentions, default: 0, null: false
t.integer :display_watchers, default: 0, null: false
t.integer :post_updates, default: 0, null: false
t.integer :new_include_description, default: 0, null: false
t.integer :updated_include_description, default: 0, null: false
t.integer :post_private_issues, default: 0, null: false
t.integer :post_private_notes, default: 0, null: false
t.integer :post_wiki, default: 0, null: false
t.integer :post_wiki_updates, default: 0, null: false
t.integer :post_db, default: 0, null: false
t.integer :post_db_updates, default: 0, null: false
t.integer :post_contact, default: 0, null: false
t.integer :post_contact_updates, default: 0, null: false
t.integer :post_password, default: 0, null: false
t.integer :post_password_updates, default: 0, null: false
end
end
end
| 43.5 | 69 | 0.704981 |
bf579884e7611e10b40da981b2c829637efd7b68 | 58 | ActiveSupport.halt_callback_chains_on_return_false = false | 58 | 58 | 0.931034 |
386aea6c23a53d19548e13579029b23b7ab65ed9 | 830 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Tracking::Docs::Renderer do
describe 'contents' do
let(:dictionary_path) { described_class::DICTIONARY_PATH }
let(:items) { Gitlab::Tracking::EventDefinition.definitions.first(10).to_h }
it 'generates dictionary for given items' do
generated_dictionary = described_class.new(items).contents
table_of_contents_items = items.values.map { |item| "#{item.category} #{item.action}"}
generated_dictionary_keys = RDoc::Markdown
.parse(generated_dictionary)
.table_of_contents
.select { |metric_doc| metric_doc.level == 3 }
.map { |item| item.text.match(%r{<code>(.*)</code>})&.captures&.first }
expect(generated_dictionary_keys).to match_array(table_of_contents_items)
end
end
end
| 34.583333 | 92 | 0.708434 |
39d02c1d26b42c8b0c0a0a67f033a2c1169e489a | 71,653 | # frozen_string_literal: true
# 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/http_checksum.rb'
require 'aws-sdk-core/plugins/signature_v4.rb'
require 'aws-sdk-core/plugins/protocols/rest_json.rb'
Aws::Plugins::GlobalConfiguration.add_identifier(:groundstation)
module Aws::GroundStation
# An API client for GroundStation. To construct a client, you need to configure a `:region` and `:credentials`.
#
# client = Aws::GroundStation::Client.new(
# region: region_name,
# credentials: credentials,
# # ...
# )
#
# For details on configuring region and credentials see
# the [developer guide](/sdk-for-ruby/v3/developer-guide/setup-config.html).
#
# See {#initialize} for a full list of supported configuration options.
class Client < Seahorse::Client::Base
include Aws::ClientStubs
@identifier = :groundstation
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::HttpChecksum)
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::SharedCredentials` - Used for loading static credentials from a
# shared file, such as `~/.aws/config`.
#
# * `Aws::AssumeRoleCredentials` - Used when you need to assume a role.
#
# * `Aws::AssumeRoleWebIdentityCredentials` - Used when you need to
# assume a role after providing credentials via the web.
#
# * `Aws::SSOCredentials` - Used for loading credentials from AWS SSO using an
# access token generated from `aws login`.
#
# * `Aws::ProcessCredentials` - Used for loading credentials from a
# process that outputs to stdout.
#
# * `Aws::InstanceProfileCredentials` - Used for loading credentials
# from an EC2 IMDS on an EC2 instance.
#
# * `Aws::ECSCredentials` - Used for loading credentials from
# instances running in ECS.
#
# * `Aws::CognitoIdentityCredentials` - Used for loading credentials
# from the Cognito Identity service.
#
# 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/ECS IMDS instance profile - When used by default, the timeouts
# are very aggressive. Construct and pass an instance of
# `Aws::InstanceProfileCredentails` or `Aws::ECSCredentials` 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 searched 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] :adaptive_retry_wait_to_fill (true)
# Used only in `adaptive` retry mode. When true, the request will sleep
# until there is sufficent client side capacity to retry the request.
# When false, the request will raise a `RetryCapacityNotAvailableError` and will
# not retry instead of sleeping.
#
# @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] :correct_clock_skew (true)
# Used only in `standard` and adaptive retry modes. Specifies whether to apply
# a clock skew correction and retry requests with skewed client clocks.
#
# @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 or custom endpoints. This should be a valid 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.
#
# @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 [Integer] :max_attempts (3)
# An integer representing the maximum number attempts that will be made for
# a single request, including the initial attempt. For example,
# setting this value to 5 will result in a request being retried up to
# 4 times. Used in `standard` and `adaptive` retry modes.
#
# @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 [Proc] :retry_backoff
# A proc or lambda used for backoff. Defaults to 2**retries * retry_base_delay.
# This option is only used in the `legacy` retry mode.
#
# @option options [Float] :retry_base_delay (0.3)
# The base delay in seconds used by the default backoff function. This option
# is only used in the `legacy` retry mode.
#
# @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. This option is only used
# in the `legacy` retry mode.
#
# @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, auth errors,
# endpoint discovery, and errors from expired credentials.
# This option is only used in the `legacy` retry mode.
#
# @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. This option is only used in the
# `legacy` retry mode.
#
# @option options [String] :retry_mode ("legacy")
# Specifies which retry algorithm to use. Values are:
#
# * `legacy` - The pre-existing retry behavior. This is default value if
# no retry mode is provided.
#
# * `standard` - A standardized set of retry rules across the AWS SDKs.
# This includes support for retry quotas, which limit the number of
# unsuccessful retries a client can make.
#
# * `adaptive` - An experimental retry mode that includes all the
# functionality of `standard` mode along with automatic client side
# throttling. This is a provisional mode that may change behavior
# in the future.
#
#
# @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 raising 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.
#
# @option options [Float] :http_idle_timeout (5) The number of
# seconds a connection is allowed to sit idle 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.
#
# @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
# Cancels a contact with a specified contact ID.
#
# @option params [required, String] :contact_id
# UUID of a contact.
#
# @return [Types::ContactIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ContactIdResponse#contact_id #contact_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.cancel_contact({
# contact_id: "String", # required
# })
#
# @example Response structure
#
# resp.contact_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/CancelContact AWS API Documentation
#
# @overload cancel_contact(params = {})
# @param [Hash] params ({})
def cancel_contact(params = {}, options = {})
req = build_request(:cancel_contact, params)
req.send_request(options)
end
# Creates a `Config` with the specified `configData` parameters.
#
# Only one type of `configData` can be specified.
#
# @option params [required, Types::ConfigTypeData] :config_data
# Parameters of a `Config`.
#
# @option params [required, String] :name
# Name of a `Config`.
#
# @option params [Hash<String,String>] :tags
# Tags assigned to a `Config`.
#
# @return [Types::ConfigIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ConfigIdResponse#config_arn #config_arn} => String
# * {Types::ConfigIdResponse#config_id #config_id} => String
# * {Types::ConfigIdResponse#config_type #config_type} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_config({
# config_data: { # required
# antenna_downlink_config: {
# spectrum_config: { # required
# bandwidth: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# center_frequency: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# polarization: "LEFT_HAND", # accepts LEFT_HAND, NONE, RIGHT_HAND
# },
# },
# antenna_downlink_demod_decode_config: {
# decode_config: { # required
# unvalidated_json: "JsonString", # required
# },
# demodulation_config: { # required
# unvalidated_json: "JsonString", # required
# },
# spectrum_config: { # required
# bandwidth: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# center_frequency: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# polarization: "LEFT_HAND", # accepts LEFT_HAND, NONE, RIGHT_HAND
# },
# },
# antenna_uplink_config: {
# spectrum_config: { # required
# center_frequency: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# polarization: "LEFT_HAND", # accepts LEFT_HAND, NONE, RIGHT_HAND
# },
# target_eirp: { # required
# units: "dBW", # required, accepts dBW
# value: 1.0, # required
# },
# transmit_disabled: false,
# },
# dataflow_endpoint_config: {
# dataflow_endpoint_name: "String", # required
# dataflow_endpoint_region: "String",
# },
# tracking_config: {
# autotrack: "PREFERRED", # required, accepts PREFERRED, REMOVED, REQUIRED
# },
# uplink_echo_config: {
# antenna_uplink_config_arn: "ConfigArn", # required
# enabled: false, # required
# },
# },
# name: "SafeName", # required
# tags: {
# "String" => "String",
# },
# })
#
# @example Response structure
#
# resp.config_arn #=> String
# resp.config_id #=> String
# resp.config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/CreateConfig AWS API Documentation
#
# @overload create_config(params = {})
# @param [Hash] params ({})
def create_config(params = {}, options = {})
req = build_request(:create_config, params)
req.send_request(options)
end
# Creates a `DataflowEndpoint` group containing the specified list of
# `DataflowEndpoint` objects.
#
# The `name` field in each endpoint is used in your mission profile
# `DataflowEndpointConfig` to specify which endpoints to use during a
# contact.
#
# When a contact uses multiple `DataflowEndpointConfig` objects, each
# `Config` must match a `DataflowEndpoint` in the same group.
#
# @option params [required, Array<Types::EndpointDetails>] :endpoint_details
# Endpoint details of each endpoint in the dataflow endpoint group.
#
# @option params [Hash<String,String>] :tags
# Tags of a dataflow endpoint group.
#
# @return [Types::DataflowEndpointGroupIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DataflowEndpointGroupIdResponse#dataflow_endpoint_group_id #dataflow_endpoint_group_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_dataflow_endpoint_group({
# endpoint_details: [ # required
# {
# endpoint: {
# address: {
# name: "String", # required
# port: 1, # required
# },
# mtu: 1,
# name: "SafeName",
# status: "created", # accepts created, creating, deleted, deleting, failed
# },
# security_details: {
# role_arn: "RoleArn", # required
# security_group_ids: ["String"], # required
# subnet_ids: ["String"], # required
# },
# },
# ],
# tags: {
# "String" => "String",
# },
# })
#
# @example Response structure
#
# resp.dataflow_endpoint_group_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/CreateDataflowEndpointGroup AWS API Documentation
#
# @overload create_dataflow_endpoint_group(params = {})
# @param [Hash] params ({})
def create_dataflow_endpoint_group(params = {}, options = {})
req = build_request(:create_dataflow_endpoint_group, params)
req.send_request(options)
end
# Creates a mission profile.
#
# `dataflowEdges` is a list of lists of strings. Each lower level list
# of strings has two elements: a *from* ARN and a *to* ARN.
#
# @option params [Integer] :contact_post_pass_duration_seconds
# Amount of time after a contact ends that you’d like to receive a
# CloudWatch event indicating the pass has finished.
#
# @option params [Integer] :contact_pre_pass_duration_seconds
# Amount of time prior to contact start you’d like to receive a
# CloudWatch event indicating an upcoming pass.
#
# @option params [required, Array<Array>] :dataflow_edges
# A list of lists of ARNs. Each list of ARNs is an edge, with a *from*
# `Config` and a *to* `Config`.
#
# @option params [required, Integer] :minimum_viable_contact_duration_seconds
# Smallest amount of time in seconds that you’d like to see for an
# available contact. AWS Ground Station will not present you with
# contacts shorter than this duration.
#
# @option params [required, String] :name
# Name of a mission profile.
#
# @option params [Hash<String,String>] :tags
# Tags assigned to a mission profile.
#
# @option params [required, String] :tracking_config_arn
# ARN of a tracking `Config`.
#
# @return [Types::MissionProfileIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::MissionProfileIdResponse#mission_profile_id #mission_profile_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_mission_profile({
# contact_post_pass_duration_seconds: 1,
# contact_pre_pass_duration_seconds: 1,
# dataflow_edges: [ # required
# ["ConfigArn"],
# ],
# minimum_viable_contact_duration_seconds: 1, # required
# name: "SafeName", # required
# tags: {
# "String" => "String",
# },
# tracking_config_arn: "ConfigArn", # required
# })
#
# @example Response structure
#
# resp.mission_profile_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/CreateMissionProfile AWS API Documentation
#
# @overload create_mission_profile(params = {})
# @param [Hash] params ({})
def create_mission_profile(params = {}, options = {})
req = build_request(:create_mission_profile, params)
req.send_request(options)
end
# Deletes a `Config`.
#
# @option params [required, String] :config_id
# UUID of a `Config`.
#
# @option params [required, String] :config_type
# Type of a `Config`.
#
# @return [Types::ConfigIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ConfigIdResponse#config_arn #config_arn} => String
# * {Types::ConfigIdResponse#config_id #config_id} => String
# * {Types::ConfigIdResponse#config_type #config_type} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_config({
# config_id: "String", # required
# config_type: "antenna-downlink", # required, accepts antenna-downlink, antenna-downlink-demod-decode, antenna-uplink, dataflow-endpoint, tracking, uplink-echo
# })
#
# @example Response structure
#
# resp.config_arn #=> String
# resp.config_id #=> String
# resp.config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/DeleteConfig AWS API Documentation
#
# @overload delete_config(params = {})
# @param [Hash] params ({})
def delete_config(params = {}, options = {})
req = build_request(:delete_config, params)
req.send_request(options)
end
# Deletes a dataflow endpoint group.
#
# @option params [required, String] :dataflow_endpoint_group_id
# UUID of a dataflow endpoint group.
#
# @return [Types::DataflowEndpointGroupIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DataflowEndpointGroupIdResponse#dataflow_endpoint_group_id #dataflow_endpoint_group_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_dataflow_endpoint_group({
# dataflow_endpoint_group_id: "String", # required
# })
#
# @example Response structure
#
# resp.dataflow_endpoint_group_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/DeleteDataflowEndpointGroup AWS API Documentation
#
# @overload delete_dataflow_endpoint_group(params = {})
# @param [Hash] params ({})
def delete_dataflow_endpoint_group(params = {}, options = {})
req = build_request(:delete_dataflow_endpoint_group, params)
req.send_request(options)
end
# Deletes a mission profile.
#
# @option params [required, String] :mission_profile_id
# UUID of a mission profile.
#
# @return [Types::MissionProfileIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::MissionProfileIdResponse#mission_profile_id #mission_profile_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_mission_profile({
# mission_profile_id: "String", # required
# })
#
# @example Response structure
#
# resp.mission_profile_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/DeleteMissionProfile AWS API Documentation
#
# @overload delete_mission_profile(params = {})
# @param [Hash] params ({})
def delete_mission_profile(params = {}, options = {})
req = build_request(:delete_mission_profile, params)
req.send_request(options)
end
# Describes an existing contact.
#
# @option params [required, String] :contact_id
# UUID of a contact.
#
# @return [Types::DescribeContactResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeContactResponse#contact_id #contact_id} => String
# * {Types::DescribeContactResponse#contact_status #contact_status} => String
# * {Types::DescribeContactResponse#dataflow_list #dataflow_list} => Array<Types::DataflowDetail>
# * {Types::DescribeContactResponse#end_time #end_time} => Time
# * {Types::DescribeContactResponse#error_message #error_message} => String
# * {Types::DescribeContactResponse#ground_station #ground_station} => String
# * {Types::DescribeContactResponse#maximum_elevation #maximum_elevation} => Types::Elevation
# * {Types::DescribeContactResponse#mission_profile_arn #mission_profile_arn} => String
# * {Types::DescribeContactResponse#post_pass_end_time #post_pass_end_time} => Time
# * {Types::DescribeContactResponse#pre_pass_start_time #pre_pass_start_time} => Time
# * {Types::DescribeContactResponse#region #region} => String
# * {Types::DescribeContactResponse#satellite_arn #satellite_arn} => String
# * {Types::DescribeContactResponse#start_time #start_time} => Time
# * {Types::DescribeContactResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.describe_contact({
# contact_id: "String", # required
# })
#
# @example Response structure
#
# resp.contact_id #=> String
# resp.contact_status #=> String, one of "AVAILABLE", "AWS_CANCELLED", "AWS_FAILED", "CANCELLED", "CANCELLING", "COMPLETED", "FAILED", "FAILED_TO_SCHEDULE", "PASS", "POSTPASS", "PREPASS", "SCHEDULED", "SCHEDULING"
# resp.dataflow_list #=> Array
# resp.dataflow_list[0].destination.config_details.antenna_demod_decode_details.output_node #=> String
# resp.dataflow_list[0].destination.config_details.endpoint_details.endpoint.address.name #=> String
# resp.dataflow_list[0].destination.config_details.endpoint_details.endpoint.address.port #=> Integer
# resp.dataflow_list[0].destination.config_details.endpoint_details.endpoint.mtu #=> Integer
# resp.dataflow_list[0].destination.config_details.endpoint_details.endpoint.name #=> String
# resp.dataflow_list[0].destination.config_details.endpoint_details.endpoint.status #=> String, one of "created", "creating", "deleted", "deleting", "failed"
# resp.dataflow_list[0].destination.config_details.endpoint_details.security_details.role_arn #=> String
# resp.dataflow_list[0].destination.config_details.endpoint_details.security_details.security_group_ids #=> Array
# resp.dataflow_list[0].destination.config_details.endpoint_details.security_details.security_group_ids[0] #=> String
# resp.dataflow_list[0].destination.config_details.endpoint_details.security_details.subnet_ids #=> Array
# resp.dataflow_list[0].destination.config_details.endpoint_details.security_details.subnet_ids[0] #=> String
# resp.dataflow_list[0].destination.config_id #=> String
# resp.dataflow_list[0].destination.config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
# resp.dataflow_list[0].destination.dataflow_destination_region #=> String
# resp.dataflow_list[0].error_message #=> String
# resp.dataflow_list[0].source.config_details.antenna_demod_decode_details.output_node #=> String
# resp.dataflow_list[0].source.config_details.endpoint_details.endpoint.address.name #=> String
# resp.dataflow_list[0].source.config_details.endpoint_details.endpoint.address.port #=> Integer
# resp.dataflow_list[0].source.config_details.endpoint_details.endpoint.mtu #=> Integer
# resp.dataflow_list[0].source.config_details.endpoint_details.endpoint.name #=> String
# resp.dataflow_list[0].source.config_details.endpoint_details.endpoint.status #=> String, one of "created", "creating", "deleted", "deleting", "failed"
# resp.dataflow_list[0].source.config_details.endpoint_details.security_details.role_arn #=> String
# resp.dataflow_list[0].source.config_details.endpoint_details.security_details.security_group_ids #=> Array
# resp.dataflow_list[0].source.config_details.endpoint_details.security_details.security_group_ids[0] #=> String
# resp.dataflow_list[0].source.config_details.endpoint_details.security_details.subnet_ids #=> Array
# resp.dataflow_list[0].source.config_details.endpoint_details.security_details.subnet_ids[0] #=> String
# resp.dataflow_list[0].source.config_id #=> String
# resp.dataflow_list[0].source.config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
# resp.dataflow_list[0].source.dataflow_source_region #=> String
# resp.end_time #=> Time
# resp.error_message #=> String
# resp.ground_station #=> String
# resp.maximum_elevation.unit #=> String, one of "DEGREE_ANGLE", "RADIAN"
# resp.maximum_elevation.value #=> Float
# resp.mission_profile_arn #=> String
# resp.post_pass_end_time #=> Time
# resp.pre_pass_start_time #=> Time
# resp.region #=> String
# resp.satellite_arn #=> String
# resp.start_time #=> Time
# resp.tags #=> Hash
# resp.tags["String"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/DescribeContact AWS API Documentation
#
# @overload describe_contact(params = {})
# @param [Hash] params ({})
def describe_contact(params = {}, options = {})
req = build_request(:describe_contact, params)
req.send_request(options)
end
# Returns `Config` information.
#
# Only one `Config` response can be returned.
#
# @option params [required, String] :config_id
# UUID of a `Config`.
#
# @option params [required, String] :config_type
# Type of a `Config`.
#
# @return [Types::GetConfigResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetConfigResponse#config_arn #config_arn} => String
# * {Types::GetConfigResponse#config_data #config_data} => Types::ConfigTypeData
# * {Types::GetConfigResponse#config_id #config_id} => String
# * {Types::GetConfigResponse#config_type #config_type} => String
# * {Types::GetConfigResponse#name #name} => String
# * {Types::GetConfigResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.get_config({
# config_id: "String", # required
# config_type: "antenna-downlink", # required, accepts antenna-downlink, antenna-downlink-demod-decode, antenna-uplink, dataflow-endpoint, tracking, uplink-echo
# })
#
# @example Response structure
#
# resp.config_arn #=> String
# resp.config_data.antenna_downlink_config.spectrum_config.bandwidth.units #=> String, one of "GHz", "MHz", "kHz"
# resp.config_data.antenna_downlink_config.spectrum_config.bandwidth.value #=> Float
# resp.config_data.antenna_downlink_config.spectrum_config.center_frequency.units #=> String, one of "GHz", "MHz", "kHz"
# resp.config_data.antenna_downlink_config.spectrum_config.center_frequency.value #=> Float
# resp.config_data.antenna_downlink_config.spectrum_config.polarization #=> String, one of "LEFT_HAND", "NONE", "RIGHT_HAND"
# resp.config_data.antenna_downlink_demod_decode_config.decode_config.unvalidated_json #=> String
# resp.config_data.antenna_downlink_demod_decode_config.demodulation_config.unvalidated_json #=> String
# resp.config_data.antenna_downlink_demod_decode_config.spectrum_config.bandwidth.units #=> String, one of "GHz", "MHz", "kHz"
# resp.config_data.antenna_downlink_demod_decode_config.spectrum_config.bandwidth.value #=> Float
# resp.config_data.antenna_downlink_demod_decode_config.spectrum_config.center_frequency.units #=> String, one of "GHz", "MHz", "kHz"
# resp.config_data.antenna_downlink_demod_decode_config.spectrum_config.center_frequency.value #=> Float
# resp.config_data.antenna_downlink_demod_decode_config.spectrum_config.polarization #=> String, one of "LEFT_HAND", "NONE", "RIGHT_HAND"
# resp.config_data.antenna_uplink_config.spectrum_config.center_frequency.units #=> String, one of "GHz", "MHz", "kHz"
# resp.config_data.antenna_uplink_config.spectrum_config.center_frequency.value #=> Float
# resp.config_data.antenna_uplink_config.spectrum_config.polarization #=> String, one of "LEFT_HAND", "NONE", "RIGHT_HAND"
# resp.config_data.antenna_uplink_config.target_eirp.units #=> String, one of "dBW"
# resp.config_data.antenna_uplink_config.target_eirp.value #=> Float
# resp.config_data.antenna_uplink_config.transmit_disabled #=> Boolean
# resp.config_data.dataflow_endpoint_config.dataflow_endpoint_name #=> String
# resp.config_data.dataflow_endpoint_config.dataflow_endpoint_region #=> String
# resp.config_data.tracking_config.autotrack #=> String, one of "PREFERRED", "REMOVED", "REQUIRED"
# resp.config_data.uplink_echo_config.antenna_uplink_config_arn #=> String
# resp.config_data.uplink_echo_config.enabled #=> Boolean
# resp.config_id #=> String
# resp.config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
# resp.name #=> String
# resp.tags #=> Hash
# resp.tags["String"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/GetConfig AWS API Documentation
#
# @overload get_config(params = {})
# @param [Hash] params ({})
def get_config(params = {}, options = {})
req = build_request(:get_config, params)
req.send_request(options)
end
# Returns the dataflow endpoint group.
#
# @option params [required, String] :dataflow_endpoint_group_id
# UUID of a dataflow endpoint group.
#
# @return [Types::GetDataflowEndpointGroupResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDataflowEndpointGroupResponse#dataflow_endpoint_group_arn #dataflow_endpoint_group_arn} => String
# * {Types::GetDataflowEndpointGroupResponse#dataflow_endpoint_group_id #dataflow_endpoint_group_id} => String
# * {Types::GetDataflowEndpointGroupResponse#endpoints_details #endpoints_details} => Array<Types::EndpointDetails>
# * {Types::GetDataflowEndpointGroupResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.get_dataflow_endpoint_group({
# dataflow_endpoint_group_id: "String", # required
# })
#
# @example Response structure
#
# resp.dataflow_endpoint_group_arn #=> String
# resp.dataflow_endpoint_group_id #=> String
# resp.endpoints_details #=> Array
# resp.endpoints_details[0].endpoint.address.name #=> String
# resp.endpoints_details[0].endpoint.address.port #=> Integer
# resp.endpoints_details[0].endpoint.mtu #=> Integer
# resp.endpoints_details[0].endpoint.name #=> String
# resp.endpoints_details[0].endpoint.status #=> String, one of "created", "creating", "deleted", "deleting", "failed"
# resp.endpoints_details[0].security_details.role_arn #=> String
# resp.endpoints_details[0].security_details.security_group_ids #=> Array
# resp.endpoints_details[0].security_details.security_group_ids[0] #=> String
# resp.endpoints_details[0].security_details.subnet_ids #=> Array
# resp.endpoints_details[0].security_details.subnet_ids[0] #=> String
# resp.tags #=> Hash
# resp.tags["String"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/GetDataflowEndpointGroup AWS API Documentation
#
# @overload get_dataflow_endpoint_group(params = {})
# @param [Hash] params ({})
def get_dataflow_endpoint_group(params = {}, options = {})
req = build_request(:get_dataflow_endpoint_group, params)
req.send_request(options)
end
# Returns the number of minutes used by account.
#
# @option params [required, Integer] :month
# The month being requested, with a value of 1-12.
#
# @option params [required, Integer] :year
# The year being requested, in the format of YYYY.
#
# @return [Types::GetMinuteUsageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetMinuteUsageResponse#estimated_minutes_remaining #estimated_minutes_remaining} => Integer
# * {Types::GetMinuteUsageResponse#is_reserved_minutes_customer #is_reserved_minutes_customer} => Boolean
# * {Types::GetMinuteUsageResponse#total_reserved_minute_allocation #total_reserved_minute_allocation} => Integer
# * {Types::GetMinuteUsageResponse#total_scheduled_minutes #total_scheduled_minutes} => Integer
# * {Types::GetMinuteUsageResponse#upcoming_minutes_scheduled #upcoming_minutes_scheduled} => Integer
#
# @example Request syntax with placeholder values
#
# resp = client.get_minute_usage({
# month: 1, # required
# year: 1, # required
# })
#
# @example Response structure
#
# resp.estimated_minutes_remaining #=> Integer
# resp.is_reserved_minutes_customer #=> Boolean
# resp.total_reserved_minute_allocation #=> Integer
# resp.total_scheduled_minutes #=> Integer
# resp.upcoming_minutes_scheduled #=> Integer
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/GetMinuteUsage AWS API Documentation
#
# @overload get_minute_usage(params = {})
# @param [Hash] params ({})
def get_minute_usage(params = {}, options = {})
req = build_request(:get_minute_usage, params)
req.send_request(options)
end
# Returns a mission profile.
#
# @option params [required, String] :mission_profile_id
# UUID of a mission profile.
#
# @return [Types::GetMissionProfileResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetMissionProfileResponse#contact_post_pass_duration_seconds #contact_post_pass_duration_seconds} => Integer
# * {Types::GetMissionProfileResponse#contact_pre_pass_duration_seconds #contact_pre_pass_duration_seconds} => Integer
# * {Types::GetMissionProfileResponse#dataflow_edges #dataflow_edges} => Array<Array<String>>
# * {Types::GetMissionProfileResponse#minimum_viable_contact_duration_seconds #minimum_viable_contact_duration_seconds} => Integer
# * {Types::GetMissionProfileResponse#mission_profile_arn #mission_profile_arn} => String
# * {Types::GetMissionProfileResponse#mission_profile_id #mission_profile_id} => String
# * {Types::GetMissionProfileResponse#name #name} => String
# * {Types::GetMissionProfileResponse#region #region} => String
# * {Types::GetMissionProfileResponse#tags #tags} => Hash<String,String>
# * {Types::GetMissionProfileResponse#tracking_config_arn #tracking_config_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_mission_profile({
# mission_profile_id: "String", # required
# })
#
# @example Response structure
#
# resp.contact_post_pass_duration_seconds #=> Integer
# resp.contact_pre_pass_duration_seconds #=> Integer
# resp.dataflow_edges #=> Array
# resp.dataflow_edges[0] #=> Array
# resp.dataflow_edges[0][0] #=> String
# resp.minimum_viable_contact_duration_seconds #=> Integer
# resp.mission_profile_arn #=> String
# resp.mission_profile_id #=> String
# resp.name #=> String
# resp.region #=> String
# resp.tags #=> Hash
# resp.tags["String"] #=> String
# resp.tracking_config_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/GetMissionProfile AWS API Documentation
#
# @overload get_mission_profile(params = {})
# @param [Hash] params ({})
def get_mission_profile(params = {}, options = {})
req = build_request(:get_mission_profile, params)
req.send_request(options)
end
# Returns a satellite.
#
# @option params [required, String] :satellite_id
# UUID of a satellite.
#
# @return [Types::GetSatelliteResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetSatelliteResponse#ground_stations #ground_stations} => Array<String>
# * {Types::GetSatelliteResponse#norad_satellite_id #norad_satellite_id} => Integer
# * {Types::GetSatelliteResponse#satellite_arn #satellite_arn} => String
# * {Types::GetSatelliteResponse#satellite_id #satellite_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_satellite({
# satellite_id: "String", # required
# })
#
# @example Response structure
#
# resp.ground_stations #=> Array
# resp.ground_stations[0] #=> String
# resp.norad_satellite_id #=> Integer
# resp.satellite_arn #=> String
# resp.satellite_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/GetSatellite AWS API Documentation
#
# @overload get_satellite(params = {})
# @param [Hash] params ({})
def get_satellite(params = {}, options = {})
req = build_request(:get_satellite, params)
req.send_request(options)
end
# Returns a list of `Config` objects.
#
# @option params [Integer] :max_results
# Maximum number of `Configs` returned.
#
# @option params [String] :next_token
# Next token returned in the request of a previous `ListConfigs` call.
# Used to get the next page of results.
#
# @return [Types::ListConfigsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListConfigsResponse#config_list #config_list} => Array<Types::ConfigListItem>
# * {Types::ListConfigsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_configs({
# max_results: 1,
# next_token: "String",
# })
#
# @example Response structure
#
# resp.config_list #=> Array
# resp.config_list[0].config_arn #=> String
# resp.config_list[0].config_id #=> String
# resp.config_list[0].config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
# resp.config_list[0].name #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListConfigs AWS API Documentation
#
# @overload list_configs(params = {})
# @param [Hash] params ({})
def list_configs(params = {}, options = {})
req = build_request(:list_configs, params)
req.send_request(options)
end
# Returns a list of contacts.
#
# If `statusList` contains AVAILABLE, the request must include
# `groundStation`, `missionprofileArn`, and `satelliteArn`.
#
# @option params [required, Time,DateTime,Date,Integer,String] :end_time
# End time of a contact.
#
# @option params [String] :ground_station
# Name of a ground station.
#
# @option params [Integer] :max_results
# Maximum number of contacts returned.
#
# @option params [String] :mission_profile_arn
# ARN of a mission profile.
#
# @option params [String] :next_token
# Next token returned in the request of a previous `ListContacts` call.
# Used to get the next page of results.
#
# @option params [String] :satellite_arn
# ARN of a satellite.
#
# @option params [required, Time,DateTime,Date,Integer,String] :start_time
# Start time of a contact.
#
# @option params [required, Array<String>] :status_list
# Status of a contact reservation.
#
# @return [Types::ListContactsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListContactsResponse#contact_list #contact_list} => Array<Types::ContactData>
# * {Types::ListContactsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_contacts({
# end_time: Time.now, # required
# ground_station: "String",
# max_results: 1,
# mission_profile_arn: "MissionProfileArn",
# next_token: "String",
# satellite_arn: "satelliteArn",
# start_time: Time.now, # required
# status_list: ["AVAILABLE"], # required, accepts AVAILABLE, AWS_CANCELLED, AWS_FAILED, CANCELLED, CANCELLING, COMPLETED, FAILED, FAILED_TO_SCHEDULE, PASS, POSTPASS, PREPASS, SCHEDULED, SCHEDULING
# })
#
# @example Response structure
#
# resp.contact_list #=> Array
# resp.contact_list[0].contact_id #=> String
# resp.contact_list[0].contact_status #=> String, one of "AVAILABLE", "AWS_CANCELLED", "AWS_FAILED", "CANCELLED", "CANCELLING", "COMPLETED", "FAILED", "FAILED_TO_SCHEDULE", "PASS", "POSTPASS", "PREPASS", "SCHEDULED", "SCHEDULING"
# resp.contact_list[0].end_time #=> Time
# resp.contact_list[0].error_message #=> String
# resp.contact_list[0].ground_station #=> String
# resp.contact_list[0].maximum_elevation.unit #=> String, one of "DEGREE_ANGLE", "RADIAN"
# resp.contact_list[0].maximum_elevation.value #=> Float
# resp.contact_list[0].mission_profile_arn #=> String
# resp.contact_list[0].post_pass_end_time #=> Time
# resp.contact_list[0].pre_pass_start_time #=> Time
# resp.contact_list[0].region #=> String
# resp.contact_list[0].satellite_arn #=> String
# resp.contact_list[0].start_time #=> Time
# resp.contact_list[0].tags #=> Hash
# resp.contact_list[0].tags["String"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListContacts AWS API Documentation
#
# @overload list_contacts(params = {})
# @param [Hash] params ({})
def list_contacts(params = {}, options = {})
req = build_request(:list_contacts, params)
req.send_request(options)
end
# Returns a list of `DataflowEndpoint` groups.
#
# @option params [Integer] :max_results
# Maximum number of dataflow endpoint groups returned.
#
# @option params [String] :next_token
# Next token returned in the request of a previous
# `ListDataflowEndpointGroups` call. Used to get the next page of
# results.
#
# @return [Types::ListDataflowEndpointGroupsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListDataflowEndpointGroupsResponse#dataflow_endpoint_group_list #dataflow_endpoint_group_list} => Array<Types::DataflowEndpointListItem>
# * {Types::ListDataflowEndpointGroupsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_dataflow_endpoint_groups({
# max_results: 1,
# next_token: "String",
# })
#
# @example Response structure
#
# resp.dataflow_endpoint_group_list #=> Array
# resp.dataflow_endpoint_group_list[0].dataflow_endpoint_group_arn #=> String
# resp.dataflow_endpoint_group_list[0].dataflow_endpoint_group_id #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListDataflowEndpointGroups AWS API Documentation
#
# @overload list_dataflow_endpoint_groups(params = {})
# @param [Hash] params ({})
def list_dataflow_endpoint_groups(params = {}, options = {})
req = build_request(:list_dataflow_endpoint_groups, params)
req.send_request(options)
end
# Returns a list of ground stations.
#
# @option params [Integer] :max_results
# Maximum number of ground stations returned.
#
# @option params [String] :next_token
# Next token that can be supplied in the next call to get the next page
# of ground stations.
#
# @option params [String] :satellite_id
# Satellite ID to retrieve on-boarded ground stations.
#
# @return [Types::ListGroundStationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListGroundStationsResponse#ground_station_list #ground_station_list} => Array<Types::GroundStationData>
# * {Types::ListGroundStationsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_ground_stations({
# max_results: 1,
# next_token: "String",
# satellite_id: "String",
# })
#
# @example Response structure
#
# resp.ground_station_list #=> Array
# resp.ground_station_list[0].ground_station_id #=> String
# resp.ground_station_list[0].ground_station_name #=> String
# resp.ground_station_list[0].region #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListGroundStations AWS API Documentation
#
# @overload list_ground_stations(params = {})
# @param [Hash] params ({})
def list_ground_stations(params = {}, options = {})
req = build_request(:list_ground_stations, params)
req.send_request(options)
end
# Returns a list of mission profiles.
#
# @option params [Integer] :max_results
# Maximum number of mission profiles returned.
#
# @option params [String] :next_token
# Next token returned in the request of a previous `ListMissionProfiles`
# call. Used to get the next page of results.
#
# @return [Types::ListMissionProfilesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListMissionProfilesResponse#mission_profile_list #mission_profile_list} => Array<Types::MissionProfileListItem>
# * {Types::ListMissionProfilesResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_mission_profiles({
# max_results: 1,
# next_token: "String",
# })
#
# @example Response structure
#
# resp.mission_profile_list #=> Array
# resp.mission_profile_list[0].mission_profile_arn #=> String
# resp.mission_profile_list[0].mission_profile_id #=> String
# resp.mission_profile_list[0].name #=> String
# resp.mission_profile_list[0].region #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListMissionProfiles AWS API Documentation
#
# @overload list_mission_profiles(params = {})
# @param [Hash] params ({})
def list_mission_profiles(params = {}, options = {})
req = build_request(:list_mission_profiles, params)
req.send_request(options)
end
# Returns a list of satellites.
#
# @option params [Integer] :max_results
# Maximum number of satellites returned.
#
# @option params [String] :next_token
# Next token that can be supplied in the next call to get the next page
# of satellites.
#
# @return [Types::ListSatellitesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListSatellitesResponse#next_token #next_token} => String
# * {Types::ListSatellitesResponse#satellites #satellites} => Array<Types::SatelliteListItem>
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_satellites({
# max_results: 1,
# next_token: "String",
# })
#
# @example Response structure
#
# resp.next_token #=> String
# resp.satellites #=> Array
# resp.satellites[0].ground_stations #=> Array
# resp.satellites[0].ground_stations[0] #=> String
# resp.satellites[0].norad_satellite_id #=> Integer
# resp.satellites[0].satellite_arn #=> String
# resp.satellites[0].satellite_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListSatellites AWS API Documentation
#
# @overload list_satellites(params = {})
# @param [Hash] params ({})
def list_satellites(params = {}, options = {})
req = build_request(:list_satellites, params)
req.send_request(options)
end
# Returns a list of tags for a specified resource.
#
# @option params [required, String] :resource_arn
# ARN of a resource.
#
# @return [Types::ListTagsForResourceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListTagsForResourceResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.list_tags_for_resource({
# resource_arn: "String", # required
# })
#
# @example Response structure
#
# resp.tags #=> Hash
# resp.tags["String"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ListTagsForResource AWS API Documentation
#
# @overload list_tags_for_resource(params = {})
# @param [Hash] params ({})
def list_tags_for_resource(params = {}, options = {})
req = build_request(:list_tags_for_resource, params)
req.send_request(options)
end
# Reserves a contact using specified parameters.
#
# @option params [required, Time,DateTime,Date,Integer,String] :end_time
# End time of a contact.
#
# @option params [required, String] :ground_station
# Name of a ground station.
#
# @option params [required, String] :mission_profile_arn
# ARN of a mission profile.
#
# @option params [required, String] :satellite_arn
# ARN of a satellite
#
# @option params [required, Time,DateTime,Date,Integer,String] :start_time
# Start time of a contact.
#
# @option params [Hash<String,String>] :tags
# Tags assigned to a contact.
#
# @return [Types::ContactIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ContactIdResponse#contact_id #contact_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.reserve_contact({
# end_time: Time.now, # required
# ground_station: "String", # required
# mission_profile_arn: "MissionProfileArn", # required
# satellite_arn: "satelliteArn", # required
# start_time: Time.now, # required
# tags: {
# "String" => "String",
# },
# })
#
# @example Response structure
#
# resp.contact_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/ReserveContact AWS API Documentation
#
# @overload reserve_contact(params = {})
# @param [Hash] params ({})
def reserve_contact(params = {}, options = {})
req = build_request(:reserve_contact, params)
req.send_request(options)
end
# Assigns a tag to a resource.
#
# @option params [required, String] :resource_arn
# ARN of a resource tag.
#
# @option params [required, Hash<String,String>] :tags
# Tags assigned to a resource.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.tag_resource({
# resource_arn: "String", # required
# tags: { # required
# "String" => "String",
# },
# })
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/TagResource AWS API Documentation
#
# @overload tag_resource(params = {})
# @param [Hash] params ({})
def tag_resource(params = {}, options = {})
req = build_request(:tag_resource, params)
req.send_request(options)
end
# Deassigns a resource tag.
#
# @option params [required, String] :resource_arn
# ARN of a resource.
#
# @option params [required, Array<String>] :tag_keys
# Keys of a resource tag.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.untag_resource({
# resource_arn: "String", # required
# tag_keys: ["String"], # required
# })
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/UntagResource AWS API Documentation
#
# @overload untag_resource(params = {})
# @param [Hash] params ({})
def untag_resource(params = {}, options = {})
req = build_request(:untag_resource, params)
req.send_request(options)
end
# Updates the `Config` used when scheduling contacts.
#
# Updating a `Config` will not update the execution parameters for
# existing future contacts scheduled with this `Config`.
#
# @option params [required, Types::ConfigTypeData] :config_data
# Parameters of a `Config`.
#
# @option params [required, String] :config_id
# UUID of a `Config`.
#
# @option params [required, String] :config_type
# Type of a `Config`.
#
# @option params [required, String] :name
# Name of a `Config`.
#
# @return [Types::ConfigIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ConfigIdResponse#config_arn #config_arn} => String
# * {Types::ConfigIdResponse#config_id #config_id} => String
# * {Types::ConfigIdResponse#config_type #config_type} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_config({
# config_data: { # required
# antenna_downlink_config: {
# spectrum_config: { # required
# bandwidth: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# center_frequency: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# polarization: "LEFT_HAND", # accepts LEFT_HAND, NONE, RIGHT_HAND
# },
# },
# antenna_downlink_demod_decode_config: {
# decode_config: { # required
# unvalidated_json: "JsonString", # required
# },
# demodulation_config: { # required
# unvalidated_json: "JsonString", # required
# },
# spectrum_config: { # required
# bandwidth: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# center_frequency: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# polarization: "LEFT_HAND", # accepts LEFT_HAND, NONE, RIGHT_HAND
# },
# },
# antenna_uplink_config: {
# spectrum_config: { # required
# center_frequency: { # required
# units: "GHz", # required, accepts GHz, MHz, kHz
# value: 1.0, # required
# },
# polarization: "LEFT_HAND", # accepts LEFT_HAND, NONE, RIGHT_HAND
# },
# target_eirp: { # required
# units: "dBW", # required, accepts dBW
# value: 1.0, # required
# },
# transmit_disabled: false,
# },
# dataflow_endpoint_config: {
# dataflow_endpoint_name: "String", # required
# dataflow_endpoint_region: "String",
# },
# tracking_config: {
# autotrack: "PREFERRED", # required, accepts PREFERRED, REMOVED, REQUIRED
# },
# uplink_echo_config: {
# antenna_uplink_config_arn: "ConfigArn", # required
# enabled: false, # required
# },
# },
# config_id: "String", # required
# config_type: "antenna-downlink", # required, accepts antenna-downlink, antenna-downlink-demod-decode, antenna-uplink, dataflow-endpoint, tracking, uplink-echo
# name: "SafeName", # required
# })
#
# @example Response structure
#
# resp.config_arn #=> String
# resp.config_id #=> String
# resp.config_type #=> String, one of "antenna-downlink", "antenna-downlink-demod-decode", "antenna-uplink", "dataflow-endpoint", "tracking", "uplink-echo"
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/UpdateConfig AWS API Documentation
#
# @overload update_config(params = {})
# @param [Hash] params ({})
def update_config(params = {}, options = {})
req = build_request(:update_config, params)
req.send_request(options)
end
# Updates a mission profile.
#
# Updating a mission profile will not update the execution parameters
# for existing future contacts.
#
# @option params [Integer] :contact_post_pass_duration_seconds
# Amount of time after a contact ends that you’d like to receive a
# CloudWatch event indicating the pass has finished.
#
# @option params [Integer] :contact_pre_pass_duration_seconds
# Amount of time after a contact ends that you’d like to receive a
# CloudWatch event indicating the pass has finished.
#
# @option params [Array<Array>] :dataflow_edges
# A list of lists of ARNs. Each list of ARNs is an edge, with a *from*
# `Config` and a *to* `Config`.
#
# @option params [Integer] :minimum_viable_contact_duration_seconds
# Smallest amount of time in seconds that you’d like to see for an
# available contact. AWS Ground Station will not present you with
# contacts shorter than this duration.
#
# @option params [required, String] :mission_profile_id
# UUID of a mission profile.
#
# @option params [String] :name
# Name of a mission profile.
#
# @option params [String] :tracking_config_arn
# ARN of a tracking `Config`.
#
# @return [Types::MissionProfileIdResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::MissionProfileIdResponse#mission_profile_id #mission_profile_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_mission_profile({
# contact_post_pass_duration_seconds: 1,
# contact_pre_pass_duration_seconds: 1,
# dataflow_edges: [
# ["ConfigArn"],
# ],
# minimum_viable_contact_duration_seconds: 1,
# mission_profile_id: "String", # required
# name: "SafeName",
# tracking_config_arn: "ConfigArn",
# })
#
# @example Response structure
#
# resp.mission_profile_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/UpdateMissionProfile AWS API Documentation
#
# @overload update_mission_profile(params = {})
# @param [Hash] params ({})
def update_mission_profile(params = {}, options = {})
req = build_request(:update_mission_profile, 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-groundstation'
context[:gem_version] = '1.15.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
| 44.257566 | 235 | 0.657572 |
acd0fb818deb6a7e4d7e6410062df2247473d598 | 2,113 | #
# This file is used to configure the Omnibus projects in this repo. It contains
# some minimal configuration examples for working with Omnibus. For a full list
# of configurable options, please see the documentation for +omnibus/config.rb+.
#
# Build internally
# ------------------------------
# By default, Omnibus uses system folders (like +/var+ and +/opt+) to build and
# cache components. If you would to build everything internally, you can
# uncomment the following options. This will prevent the need for root
# permissions in most cases.
#
# Uncomment this line to change the default base directory to "local"
# -------------------------------------------------------------------
# base_dir './local'
#
# Alternatively you can tune the individual values
# ------------------------------------------------
# cache_dir './local/omnibus/cache'
# git_cache_dir './local/omnibus/cache/git_cache'
# source_dir './local/omnibus/src'
# build_dir './local/omnibus/build'
# package_dir './local/omnibus/pkg'
# package_tmp './local/omnibus/pkg-tmp'
# Windows architecture defaults - set to x86 unless otherwise specified.
# ------------------------------
windows_arch %w{x86 x64}.include?((ENV["OMNIBUS_WINDOWS_ARCH"] || "").downcase) ? ENV["OMNIBUS_WINDOWS_ARCH"].downcase.to_sym : :x86
# Build in FIPS compatability mode
# ------------------------------
fips_mode((ENV["OMNIBUS_FIPS_MODE"] || "").casecmp("true") == 0)
# Disable git caching
# ------------------------------
# use_git_caching false
# Enable S3 asset caching
# ------------------------------
use_s3_caching true
s3_access_key ENV["AWS_ACCESS_KEY_ID"]
s3_secret_key ENV["AWS_SECRET_ACCESS_KEY"]
s3_bucket "opscode-omnibus-cache"
build_retries 0
fetcher_retries 3
fetcher_read_timeout 120
# We limit this to 10 workers to eliminate transient timing issues in the
# way Ruby (and other components) compiles on some more esoteric *nixes.
workers 10
# Load additional software
# ------------------------------
# software_gems ['omnibus-software', 'my-company-software']
# local_software_dirs ['/path/to/local/software']
| 36.431034 | 132 | 0.644108 |
61d9810e5f86291c2677455ac9a9c20f7630d7a4 | 234 | class RemoveLeaderboardPrivaryFromUsersTable < ActiveRecord::Migration
def self.up
remove_column :users, :leaderboard_privacy
end
def self.down
add_column :users, :leaderboard_privacy, :boolean, default: false
end
end
| 23.4 | 70 | 0.782051 |
e8c027b7e6dfc12bafc786863ec7f2221c720550 | 753 | require 'test_helper'
class RoutesTest < ActionController::TestCase
test 'map new user invitation' do
assert_recognizes({:controller => 'devise/invitations', :action => 'new'}, {:path => 'users/invitation/new', :method => :get})
end
test 'map create user invitation' do
assert_recognizes({:controller => 'devise/invitations', :action => 'create'}, {:path => 'users/invitation', :method => :post})
end
test 'map accept user invitation' do
assert_recognizes({:controller => 'devise/invitations', :action => 'edit'}, 'users/invitation/accept')
end
test 'map update user invitation' do
assert_recognizes({:controller => 'devise/invitations', :action => 'update'}, {:path => 'users/invitation', :method => :put})
end
end
| 35.857143 | 130 | 0.681275 |
d5d9c27cdc043848b46b8ccfd69225b585aab442 | 6,167 | # encoding: UTF-8
def should_support_mysql_import_functionality
# Forcefully disable strict mode for this session.
ActiveRecord::Base.connection.execute "set sql_mode=''"
describe "#import with :on_duplicate_key_update option (mysql specific functionality)" do
extend ActiveSupport::TestCase::MySQLAssertions
asssertion_group(:should_support_on_duplicate_key_update) do
should_not_update_fields_not_mentioned
should_update_foreign_keys
should_not_update_created_at_on_timestamp_columns
should_update_updated_at_on_timestamp_columns
end
macro(:perform_import){ raise "supply your own #perform_import in a context below" }
macro(:updated_topic){ Topic.find(@topic.id) }
context "given columns and values with :validation checks turned off" do
let(:columns){ %w( id title author_name author_email_address parent_id ) }
let(:values){ [ [ 99, "Book", "John Doe", "[email protected]", 17 ] ] }
let(:updated_values){ [ [ 99, "Book - 2nd Edition", "Author Should Not Change", "[email protected]", 57 ] ] }
macro(:perform_import) do |*opts|
Topic.import columns, updated_values, opts.extract_options!.merge(:on_duplicate_key_update => update_columns, :validate => false)
end
setup do
Topic.import columns, values, :validate => false
@topic = Topic.find 99
end
context "using string column names" do
let(:update_columns){ [ "title", "author_email_address", "parent_id" ] }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using symbol column names" do
let(:update_columns){ [ :title, :author_email_address, :parent_id ] }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using string hash map" do
let(:update_columns){ { "title" => "title", "author_email_address" => "author_email_address", "parent_id" => "parent_id" } }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using string hash map, but specifying column mismatches" do
let(:update_columns){ { "title" => "author_email_address", "author_email_address" => "title", "parent_id" => "parent_id" } }
should_support_on_duplicate_key_update
should_update_fields_mentioned_with_hash_mappings
end
context "using symbol hash map" do
let(:update_columns){ { :title => :title, :author_email_address => :author_email_address, :parent_id => :parent_id } }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using symbol hash map, but specifying column mismatches" do
let(:update_columns){ { :title => :author_email_address, :author_email_address => :title, :parent_id => :parent_id } }
should_support_on_duplicate_key_update
should_update_fields_mentioned_with_hash_mappings
end
end
context "given array of model instances with :validation checks turned off" do
macro(:perform_import) do |*opts|
@topic.title = "Book - 2nd Edition"
@topic.author_name = "Author Should Not Change"
@topic.author_email_address = "[email protected]"
@topic.parent_id = 57
Topic.import [@topic], opts.extract_options!.merge(:on_duplicate_key_update => update_columns, :validate => false)
end
setup do
@topic = Generate(:topic, :id => 99, :author_name => "John Doe", :parent_id => 17)
end
context "using string column names" do
let(:update_columns){ [ "title", "author_email_address", "parent_id" ] }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using symbol column names" do
let(:update_columns){ [ :title, :author_email_address, :parent_id ] }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using string hash map" do
let(:update_columns){ { "title" => "title", "author_email_address" => "author_email_address", "parent_id" => "parent_id" } }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using string hash map, but specifying column mismatches" do
let(:update_columns){ { "title" => "author_email_address", "author_email_address" => "title", "parent_id" => "parent_id" } }
should_support_on_duplicate_key_update
should_update_fields_mentioned_with_hash_mappings
end
context "using symbol hash map" do
let(:update_columns){ { :title => :title, :author_email_address => :author_email_address, :parent_id => :parent_id } }
should_support_on_duplicate_key_update
should_update_fields_mentioned
end
context "using symbol hash map, but specifying column mismatches" do
let(:update_columns){ { :title => :author_email_address, :author_email_address => :title, :parent_id => :parent_id } }
should_support_on_duplicate_key_update
should_update_fields_mentioned_with_hash_mappings
end
end
end
describe "#import with :synchronization option" do
let(:topics){ Array.new }
let(:values){ [ [topics.first.id, "Jerry Carter"], [topics.last.id, "Chad Fowler"] ]}
let(:columns){ %W(id author_name) }
setup do
topics << Topic.create!(:title=>"LDAP", :author_name=>"Big Bird")
topics << Topic.create!(:title=>"Rails Recipes", :author_name=>"Elmo")
end
it "synchronizes passed in ActiveRecord model instances with the data just imported" do
columns2update = [ 'author_name' ]
expected_count = Topic.count
Topic.import( columns, values,
:validate=>false,
:on_duplicate_key_update=>columns2update,
:synchronize=>topics )
assert_equal expected_count, Topic.count, "no new records should have been created!"
assert_equal "Jerry Carter", topics.first.author_name, "wrong author!"
assert_equal "Chad Fowler", topics.last.author_name, "wrong author!"
end
end
end
| 41.668919 | 137 | 0.693368 |
26626a90f50cda39e3985ac90b26b04e49cce50e | 11,874 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# EDITING INSTRUCTIONS
# This file was generated from the file
# https://github.com/googleapis/googleapis/blob/master/google/devtools/clouderrorreporting/v1beta1/error_group_service.proto,
# and updates to that file get reflected here through a refresh process.
# For the short term, the refresh process will only be runnable by Google
# engineers.
require "json"
require "pathname"
require "google/gax"
require "google/devtools/clouderrorreporting/v1beta1/error_group_service_pb"
require "google/cloud/error_reporting/v1beta1/credentials"
module Google
module Cloud
module ErrorReporting
module V1beta1
# Service for retrieving and updating individual error groups.
#
# @!attribute [r] error_group_service_stub
# @return [Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroupService::Stub]
class ErrorGroupServiceClient
attr_reader :error_group_service_stub
# The default address of the service.
SERVICE_ADDRESS = "clouderrorreporting.googleapis.com".freeze
# The default port of the service.
DEFAULT_SERVICE_PORT = 443
# The default set of gRPC interceptors.
GRPC_INTERCEPTORS = []
DEFAULT_TIMEOUT = 30
# The scopes needed to make gRPC calls to all of the methods defined in
# this service.
ALL_SCOPES = [
"https://www.googleapis.com/auth/cloud-platform"
].freeze
GROUP_PATH_TEMPLATE = Google::Gax::PathTemplate.new(
"projects/{project}/groups/{group}"
)
private_constant :GROUP_PATH_TEMPLATE
# Returns a fully-qualified group resource name string.
# @param project [String]
# @param group [String]
# @return [String]
def self.group_path project, group
GROUP_PATH_TEMPLATE.render(
:"project" => project,
:"group" => group
)
end
# @param credentials [Google::Auth::Credentials, String, Hash, GRPC::Core::Channel, GRPC::Core::ChannelCredentials, Proc]
# Provides the means for authenticating requests made by the client. This parameter can
# be many types.
# A `Google::Auth::Credentials` uses a the properties of its represented keyfile for
# authenticating requests made by this client.
# A `String` will be treated as the path to the keyfile to be used for the construction of
# credentials for this client.
# A `Hash` will be treated as the contents of a keyfile to be used for the construction of
# credentials for this client.
# A `GRPC::Core::Channel` will be used to make calls through.
# A `GRPC::Core::ChannelCredentials` for the setting up the RPC client. The channel credentials
# should already be composed with a `GRPC::Core::CallCredentials` object.
# A `Proc` will be used as an updater_proc for the Grpc channel. The proc transforms the
# metadata for requests, generally, to give OAuth credentials.
# @param scopes [Array<String>]
# The OAuth scopes for this service. This parameter is ignored if
# an updater_proc is supplied.
# @param client_config [Hash]
# A Hash for call options for each method. See
# Google::Gax#construct_settings for the structure of
# this data. Falls back to the default config if not specified
# or the specified config is missing data points.
# @param timeout [Numeric]
# The default timeout, in seconds, for calls made through this client.
# @param metadata [Hash]
# Default metadata to be sent with each request. This can be overridden on a per call basis.
# @param exception_transformer [Proc]
# An optional proc that intercepts any exceptions raised during an API call to inject
# custom error handling.
def initialize \
credentials: nil,
scopes: ALL_SCOPES,
client_config: {},
timeout: DEFAULT_TIMEOUT,
metadata: nil,
exception_transformer: nil,
lib_name: nil,
lib_version: ""
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "google/gax/grpc"
require "google/devtools/clouderrorreporting/v1beta1/error_group_service_services_pb"
credentials ||= Google::Cloud::ErrorReporting::V1beta1::Credentials.default
if credentials.is_a?(String) || credentials.is_a?(Hash)
updater_proc = Google::Cloud::ErrorReporting::V1beta1::Credentials.new(credentials).updater_proc
end
if credentials.is_a?(GRPC::Core::Channel)
channel = credentials
end
if credentials.is_a?(GRPC::Core::ChannelCredentials)
chan_creds = credentials
end
if credentials.is_a?(Proc)
updater_proc = credentials
end
if credentials.is_a?(Google::Auth::Credentials)
updater_proc = credentials.updater_proc
end
package_version = Gem.loaded_specs['google-cloud-error_reporting'].version.version
google_api_client = "gl-ruby/#{RUBY_VERSION}"
google_api_client << " #{lib_name}/#{lib_version}" if lib_name
google_api_client << " gapic/#{package_version} gax/#{Google::Gax::VERSION}"
google_api_client << " grpc/#{GRPC::VERSION}"
google_api_client.freeze
headers = { :"x-goog-api-client" => google_api_client }
headers.merge!(metadata) unless metadata.nil?
client_config_file = Pathname.new(__dir__).join(
"error_group_service_client_config.json"
)
defaults = client_config_file.open do |f|
Google::Gax.construct_settings(
"google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
JSON.parse(f.read),
client_config,
Google::Gax::Grpc::STATUS_CODE_NAMES,
timeout,
errors: Google::Gax::Grpc::API_ERRORS,
metadata: headers
)
end
# Allow overriding the service path/port in subclasses.
service_path = self.class::SERVICE_ADDRESS
port = self.class::DEFAULT_SERVICE_PORT
interceptors = self.class::GRPC_INTERCEPTORS
@error_group_service_stub = Google::Gax::Grpc.create_stub(
service_path,
port,
chan_creds: chan_creds,
channel: channel,
updater_proc: updater_proc,
scopes: scopes,
interceptors: interceptors,
&Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroupService::Stub.method(:new)
)
@get_group = Google::Gax.create_api_call(
@error_group_service_stub.method(:get_group),
defaults["get_group"],
exception_transformer: exception_transformer
)
@update_group = Google::Gax.create_api_call(
@error_group_service_stub.method(:update_group),
defaults["update_group"],
exception_transformer: exception_transformer
)
end
# Service calls
# Get the specified group.
#
# @param group_name [String]
# [Required] The group resource name. Written as
# <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
# Call
# <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
# <code>groupStats.list</code></a> to return a list of groups belonging to
# this project.
#
# Example: <code>projects/my-project-123/groups/my-group</code>
# @param options [Google::Gax::CallOptions]
# Overrides the default settings for this call, e.g, timeout,
# retries, etc.
# @yield [result, operation] Access the result along with the RPC operation
# @yieldparam result [Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroup]
# @yieldparam operation [GRPC::ActiveCall::Operation]
# @return [Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroup]
# @raise [Google::Gax::GaxError] if the RPC is aborted.
# @example
# require "google/cloud/error_reporting"
#
# error_group_service_client = Google::Cloud::ErrorReporting::ErrorGroup.new(version: :v1beta1)
# formatted_group_name = Google::Cloud::ErrorReporting::V1beta1::ErrorGroupServiceClient.group_path("[PROJECT]", "[GROUP]")
# response = error_group_service_client.get_group(formatted_group_name)
def get_group \
group_name,
options: nil,
&block
req = {
group_name: group_name
}.delete_if { |_, v| v.nil? }
req = Google::Gax::to_proto(req, Google::Devtools::Clouderrorreporting::V1beta1::GetGroupRequest)
@get_group.call(req, options, &block)
end
# Replace the data for the specified group.
# Fails if the group does not exist.
#
# @param group [Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroup | Hash]
# [Required] The group which replaces the resource on the server.
# A hash of the same form as `Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroup`
# can also be provided.
# @param options [Google::Gax::CallOptions]
# Overrides the default settings for this call, e.g, timeout,
# retries, etc.
# @yield [result, operation] Access the result along with the RPC operation
# @yieldparam result [Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroup]
# @yieldparam operation [GRPC::ActiveCall::Operation]
# @return [Google::Devtools::Clouderrorreporting::V1beta1::ErrorGroup]
# @raise [Google::Gax::GaxError] if the RPC is aborted.
# @example
# require "google/cloud/error_reporting"
#
# error_group_service_client = Google::Cloud::ErrorReporting::ErrorGroup.new(version: :v1beta1)
#
# # TODO: Initialize +group+:
# group = {}
# response = error_group_service_client.update_group(group)
def update_group \
group,
options: nil,
&block
req = {
group: group
}.delete_if { |_, v| v.nil? }
req = Google::Gax::to_proto(req, Google::Devtools::Clouderrorreporting::V1beta1::UpdateGroupRequest)
@update_group.call(req, options, &block)
end
end
end
end
end
end
| 44.30597 | 135 | 0.615294 |
acc893b985b28415259a3b8376bba0422f807e9e | 765 | require "pipelines/version"
require "pipelines/exec"
require "psych"
module Pipelines
# Your code goes here...
def self.build
Exec.new(parse_["build"])
end
def self.parse_
parse("project/simple.yml")
end
def self.parse(file)
project = Psych.load_file(file)
end
class Pipeline
def initialize(actions)
@build = Exec.new(actions["build"], "build")
deploys = actions.select {|a,b| a != "build"}
@deploys = deploys.map {|key, value| Exec.new(value, key)}
end
def run
@build.run
@deploys.map {|deploy| deploy.run }
end
def show
puts @build.show
@deploys.map {|deploy| puts deploy.show }
end
end
end
a = Pipelines.parse_
e = Pipelines::Pipeline.new a
e.run
e.show
| 18.214286 | 64 | 0.628758 |
288240b55c012767c1c48e8aa96acaf88dc632c4 | 569 | require "spec_helper"
feature "Update a location's languages", :vcr do
background do
login_admin
end
xscenario "with empty description" do
visit_test_location
fill_in "description", with: ""
click_button "Save changes"
expect(page).to have_content "Please enter a description"
end
xscenario "with valid description" do
visit_test_location
fill_in "description", with: "This is a description"
click_button "Save changes"
visit_test_location
find_field('description').value.should eq "This is a description"
end
end
| 24.73913 | 69 | 0.731107 |
e2e3b0d162947358f1a13f6165f50f14a37d9602 | 897 | require_relative '../lib/lib'
require 'json'
def analyze(name:, text_content: text)
storage = Language::Storage.new
document = Language::Document.new(text_content: text_content)
hash = storage.read(name: name) || { name: name, text: text_content }
%w[analyze_sentiment].each do |method| # analyze_entities analyze_syntax classify_text
unless hash.has_key?(method.to_sym)
puts "[gcp] #{method} for #{name}"
response = document.send(method)
hash[method.to_sym] = response
else
puts "[gcp] #{method} for #{name} skipped: already defined"
end
end
storage.save(json: JSON.pretty_generate(hash), name: name)
end
search_storage = Twitter::SearchStorage.new(query: '$AMD')
search_storage.results.each_with_index do |tweet, index|
tweet = JSON.parse(tweet.to_json.to_s, object_class: OpenStruct)
analyze(name: tweet.id, text_content: tweet.text)
end
| 35.88 | 88 | 0.719064 |
62ae99bc865226cd9ef680d8f1ebbd5dae6e67af | 47 | module Refinery
module PagesHelper
end
end
| 9.4 | 20 | 0.787234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.