_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q18000 | Ooor.TypeCasting.cast_association | train | def cast_association(k)
if self.class.one2many_associations[k]
if @loaded_associations[k]
v = @loaded_associations[k].select {|i| i.changed?}
v = @associations[k] if v.empty?
else
v = @associations[k]
end
cast_o2m_association(v)
elsif self.class.many2many_associations[k]
v = @associations[k]
[[6, false, (v || []).map {|i| i.is_a?(Base) ? i.id : i}]]
elsif self.class.many2one_associations[k]
v = @associations[k] # TODO support for nested
cast_m2o_association(v)
end
end | ruby | {
"resource": ""
} |
q18001 | Ooor.Base.on_change | train | def on_change(on_change_method, field_name, field_value, *args)
# NOTE: OpenERP doesn't accept context systematically in on_change events unfortunately
ids = self.id ? [id] : []
result = self.class.object_service(:execute, self.class.openerp_model, on_change_method, ids, *args)
load_on_change_result(result, field_name, field_value)
end | ruby | {
"resource": ""
} |
q18002 | Ooor.Base.wkf_action | train | def wkf_action(action, context={}, reload=true)
self.class.object_service(:exec_workflow, self.class.openerp_model, action, self.id, context)
reload_fields if reload
end | ruby | {
"resource": ""
} |
q18003 | Ooor.Persistence.load | train | def load(attributes)
self.class.reload_fields_definition(false)
raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
@associations ||= {}
@attributes ||= {}
@loaded_associations = {}
attributes.each do |key, value|
self.send "#{key}=", value if self.respond_to?("#{key}=")
end
self
end | ruby | {
"resource": ""
} |
q18004 | Ooor.Persistence.copy | train | def copy(defaults={}, context={})
self.class.find(rpc_execute('copy', id, defaults, context), context: context)
end | ruby | {
"resource": ""
} |
q18005 | Ooor.Persistence.perform_validations | train | def perform_validations(options={}) # :nodoc:
if options.is_a?(Hash)
options[:validate] == false || valid?(options[:context])
else
valid?
end
end | ruby | {
"resource": ""
} |
q18006 | RSpec::ActiveModel::Mocks.Mocks.stub_model | train | def stub_model(model_class, stubs={})
model_class.new.tap do |m|
m.extend ActiveModelStubExtensions
if defined?(ActiveRecord) && model_class < ActiveRecord::Base && model_class.primary_key
m.extend ActiveRecordStubExtensions
primary_key = model_class.primary_key.to_sym
stubs = {primary_key => next_id}.merge(stubs)
stubs = {:persisted? => !!stubs[primary_key]}.merge(stubs)
else
stubs = {:id => next_id}.merge(stubs)
stubs = {:persisted? => !!stubs[:id]}.merge(stubs)
end
stubs = {:blank? => false}.merge(stubs)
stubs.each do |message, return_value|
if m.respond_to?("#{message}=")
m.__send__("#{message}=", return_value)
else
RSpec::Mocks.allow_message(m, message).and_return(return_value)
end
end
yield m if block_given?
end
end | ruby | {
"resource": ""
} |
q18007 | Pygments.Popen.stop | train | def stop(reason)
if @pid
begin
Process.kill('KILL', @pid)
Process.waitpid(@pid)
rescue Errno::ESRCH, Errno::ECHILD
end
end
@log.info "Killing pid: #{@pid.to_s}. Reason: #{reason}"
@pid = nil
end | ruby | {
"resource": ""
} |
q18008 | Pygments.Popen.mentos | train | def mentos(method, args=[], kwargs={}, original_code=nil)
# Open the pipe if necessary
start unless alive?
begin
# Timeout requests that take too long.
# Invalid MENTOS_TIMEOUT results in just using default.
timeout_time = Integer(ENV["MENTOS_TIMEOUT"]) rescue 8
Timeout::timeout(timeout_time) do
# For sanity checking on both sides of the pipe when highlighting, we prepend and
# append an id. mentos checks that these are 8 character ids and that they match.
# It then returns the id's back to Rubyland.
id = (0...8).map{65.+(rand(25)).chr}.join
code = add_ids(original_code, id) if original_code
# Add metadata to the header and generate it.
if code
bytesize = code.bytesize
else
bytesize = 0
end
kwargs.freeze
kwargs = kwargs.merge("fd" => @out.to_i, "id" => id, "bytes" => bytesize)
out_header = MultiJson.dump(:method => method, :args => args, :kwargs => kwargs)
# Get the size of the header itself and write that.
bits = get_fixed_bits_from_header(out_header)
@in.write(bits)
# mentos is now waiting for the header, and, potentially, code.
write_data(out_header, code)
check_for_error
# mentos will now return data to us. First it sends the header.
header = get_header
# Now handle the header, any read any more data required.
res = handle_header_and_return(header, id)
# Finally, return what we got.
return_result(res, method)
end
rescue Timeout::Error
# If we timeout, we need to clear out the pipe and start over.
@log.error "Timeout on a mentos #{method} call"
stop "Timeout on mentos #{method} call."
end
rescue Errno::EPIPE, EOFError
stop "EPIPE"
raise MentosError, "EPIPE"
end | ruby | {
"resource": ""
} |
q18009 | Pygments.Popen.handle_header_and_return | train | def handle_header_and_return(header, id)
if header
header = header_to_json(header)
bytes = header[:bytes]
# Read more bytes (the actual response body)
res = @out.read(bytes.to_i)
if header[:method] == "highlight"
# Make sure we have a result back; else consider this an error.
if res.nil?
@log.warn "No highlight result back from mentos."
stop "No highlight result back from mentos."
raise MentosError, "No highlight result back from mentos."
end
# Remove the newline from Python
res = res[0..-2]
@log.info "Highlight in process."
# Get the id's
start_id = res[0..7]
end_id = res[-8..-1]
# Sanity check.
if not (start_id == id and end_id == id)
@log.error "ID's did not match. Aborting."
stop "ID's did not match. Aborting."
raise MentosError, "ID's did not match. Aborting."
else
# We're good. Remove the padding
res = res[10..-11]
@log.info "Highlighting complete."
res
end
end
res
else
@log.error "No header data back."
stop "No header data back."
raise MentosError, "No header received back."
end
end | ruby | {
"resource": ""
} |
q18010 | Pygments.Popen.get_header | train | def get_header
begin
size = @out.read(33)
size = size[0..-2]
# Sanity check the size
if not size_check(size)
@log.error "Size returned from mentos.py invalid."
stop "Size returned from mentos.py invalid."
raise MentosError, "Size returned from mentos.py invalid."
end
# Read the amount of bytes we should be expecting. We first
# convert the string of bits into an integer.
header_bytes = size.to_s.to_i(2) + 1
@log.info "Size in: #{size.to_s} (#{header_bytes.to_s})"
@out.read(header_bytes)
rescue
@log.error "Failed to get header."
stop "Failed to get header."
raise MentosError, "Failed to get header."
end
end | ruby | {
"resource": ""
} |
q18011 | Pygments.Popen.return_result | train | def return_result(res, method)
unless method == :lexer_name_for || method == :highlight || method == :css
res = MultiJson.load(res, :symbolize_keys => true)
end
res = res.rstrip if res.class == String
res
end | ruby | {
"resource": ""
} |
q18012 | Pygments.Popen.header_to_json | train | def header_to_json(header)
@log.info "[In header: #{header} "
header = MultiJson.load(header, :symbolize_keys => true)
if header[:error]
# Raise this as a Ruby exception of the MentosError class.
# Stop so we don't leave the pipe in an inconsistent state.
@log.error "Failed to convert header to JSON."
stop header[:error]
raise MentosError, header[:error]
else
header
end
end | ruby | {
"resource": ""
} |
q18013 | FlagShihTzu.ClassMethods.sql_in_for_flag | train | def sql_in_for_flag(flag, colmn)
val = flag_mapping[colmn][flag]
flag_value_range_for_column(colmn).select { |bits| bits & val == val }
end | ruby | {
"resource": ""
} |
q18014 | Dynflow.Action::Format.input_format | train | def input_format(&block)
case
when block && !@input_format_block
@input_format_block = block
when !block && @input_format_block
return @input_format ||= Apipie::Params::Description.define(&@input_format_block)
when block && @input_format_block
raise "The input_format has already been defined in #{self.class}"
when !block && !@input_format_block
if superclass.respond_to? :input_format
superclass.input_format
else
raise "The input_format has not been defined yet in #{self.class}"
end
end
end | ruby | {
"resource": ""
} |
q18015 | Dynflow.Serializable.recursive_to_hash | train | def recursive_to_hash(*values)
if values.size == 1
value = values.first
case value
when String, Numeric, Symbol, TrueClass, FalseClass, NilClass, Time
value
when Hash
value.inject({}) { |h, (k, v)| h.update k => recursive_to_hash(v) }
when Array
value.map { |v| recursive_to_hash v }
else
value.to_hash
end
else
values.all? { |v| Type! v, Hash, NilClass }
recursive_to_hash(values.compact.reduce { |h, v| h.merge v })
end
end | ruby | {
"resource": ""
} |
q18016 | Dynflow.Action::WithSubPlans.trigger | train | def trigger(action_class, *args)
if uses_concurrency_control
trigger_with_concurrency_control(action_class, *args)
else
world.trigger { world.plan_with_options(action_class: action_class, args: args, caller_action: self) }
end
end | ruby | {
"resource": ""
} |
q18017 | Dynflow.Action::WithBulkSubPlans.current_batch | train | def current_batch
start_position = output[:planned_count]
size = start_position + batch_size > total_count ? total_count - start_position : batch_size
batch(start_position, size)
end | ruby | {
"resource": ""
} |
q18018 | Dynflow.ExecutionPlan::DependencyGraph.add_dependencies | train | def add_dependencies(step, action)
action.required_step_ids.each do |required_step_id|
@graph[step.id] << required_step_id
end
end | ruby | {
"resource": ""
} |
q18019 | Dynflow.World.reload! | train | def reload!
# TODO what happens with newly loaded classes
@action_classes = @action_classes.map do |klass|
begin
Utils.constantize(klass.to_s)
rescue NameError
nil # ignore missing classes
end
end.compact
middleware.clear_cache!
calculate_subscription_index
end | ruby | {
"resource": ""
} |
q18020 | Dynflow.Action::Rescue.rescue_strategy | train | def rescue_strategy
suggested_strategies = []
if self.steps.compact.any? { |step| step.state == :error }
suggested_strategies << SuggestedStrategy[self, rescue_strategy_for_self]
end
self.planned_actions.each do |planned_action|
rescue_strategy = rescue_strategy_for_planned_action(planned_action)
next unless rescue_strategy # ignore actions that have no say in the rescue strategy
suggested_strategies << SuggestedStrategy[planned_action, rescue_strategy]
end
combine_suggested_strategies(suggested_strategies)
end | ruby | {
"resource": ""
} |
q18021 | Dynflow.Action::Rescue.combine_suggested_strategies | train | def combine_suggested_strategies(suggested_strategies)
if suggested_strategies.empty?
nil
else
# TODO: Find the safest rescue strategy among the suggested ones
if suggested_strategies.all? { |suggested_strategy| suggested_strategy.strategy == Skip }
return Skip
elsif suggested_strategies.all? { |suggested_strategy| suggested_strategy.strategy == Fail }
return Fail
else
return Pause # We don't know how to handle this case, so we'll just pause
end
end
end | ruby | {
"resource": ""
} |
q18022 | Csvlint.ErrorCollector.build_errors | train | def build_errors(type, category = nil, row = nil, column = nil, content = nil, constraints = {})
@errors << Csvlint::ErrorMessage.new(type, category, row, column, content, constraints)
end | ruby | {
"resource": ""
} |
q18023 | Csvlint.Validator.parse_contents | train | def parse_contents(stream, line = nil)
# parse_contents will parse one line and apply headers, formats methods and error handle as appropriate
current_line = line.present? ? line : 1
all_errors = []
@csv_options[:encoding] = @encoding
begin
row = LineCSV.parse_line(stream, @csv_options)
rescue LineCSV::MalformedCSVError => e
build_exception_messages(e, stream, current_line)
end
if row
if current_line <= 1 && @csv_header
# this conditional should be refactored somewhere
row = row.reject { |col| col.nil? || col.empty? }
validate_header(row)
@col_counts << row.size
else
build_formats(row)
@col_counts << row.reject { |col| col.nil? || col.empty? }.size
@expected_columns = row.size unless @expected_columns != 0
build_errors(:blank_rows, :structure, current_line, nil, stream.to_s) if row.reject { |c| c.nil? || c.empty? }.size == 0
# Builds errors and warnings related to the provided schema file
if @schema
@schema.validate_row(row, current_line, all_errors, @source, @validate)
@errors += @schema.errors
all_errors += @schema.errors
@warnings += @schema.warnings
else
build_errors(:ragged_rows, :structure, current_line, nil, stream.to_s) if !row.empty? && row.size != @expected_columns
end
end
end
@data << row
end | ruby | {
"resource": ""
} |
q18024 | AmazonPay.Client.create_order_reference_for_id | train | def create_order_reference_for_id(
id,
id_type,
inherit_shipping_address: nil,
confirm_now: nil,
amount: nil,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
store_name: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CreateOrderReferenceForId',
'SellerId' => merchant_id,
'Id' => id,
'IdType' => id_type
}
optional = {
'InheritShippingAddress' => inherit_shipping_address,
'ConfirmNow' => confirm_now,
'OrderReferenceAttributes.OrderTotal.Amount' => amount,
'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code,
'OrderReferenceAttributes.PlatformId' => platform_id,
'OrderReferenceAttributes.SellerNote' => seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18025 | AmazonPay.Client.get_billing_agreement_details | train | def get_billing_agreement_details(
amazon_billing_agreement_id,
address_consent_token: nil,
access_token: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetBillingAgreementDetails',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
# Preseving address_consent_token for backwards compatibility
# AccessToken returns all data in AddressConsentToken plus new data
# You cannot pass both address_consent_token and access_token in
# the same call or you will encounter a 400/"AmbiguousToken" error
'AccessToken' => access_token,
'AddressConsentToken' => address_consent_token,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18026 | AmazonPay.Client.set_billing_agreement_details | train | def set_billing_agreement_details(
amazon_billing_agreement_id,
platform_id: nil,
seller_note: nil,
seller_billing_agreement_id: nil,
custom_information: nil,
store_name: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetBillingAgreementDetails',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'BillingAgreementAttributes.PlatformId' => platform_id,
'BillingAgreementAttributes.SellerNote' => seller_note,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.SellerBillingAgreementId' => seller_billing_agreement_id,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation' => custom_information,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName' => store_name,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18027 | AmazonPay.Client.confirm_billing_agreement | train | def confirm_billing_agreement(
amazon_billing_agreement_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ConfirmBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18028 | AmazonPay.Client.validate_billing_agreement | train | def validate_billing_agreement(
amazon_billing_agreement_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ValidateBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18029 | AmazonPay.Client.close_billing_agreement | train | def close_billing_agreement(
amazon_billing_agreement_id,
closure_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CloseBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'ClosureReason' => closure_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18030 | AmazonPay.Client.list_order_reference | train | def list_order_reference(
query_id,
query_id_type,
created_time_range_start: nil,
created_time_range_end: nil,
sort_order: nil,
page_size: nil,
order_reference_status_list_filter: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
payment_domain = payment_domain_hash[@region]
parameters = {
'Action' => 'ListOrderReference',
'SellerId' => merchant_id,
'QueryId' => query_id,
'QueryIdType' => query_id_type
}
optional = {
'CreatedTimeRange.StartTime' => created_time_range_start,
'CreatedTimeRange.EndTime' => created_time_range_end,
'SortOrder' => sort_order,
'PageSize' => page_size,
'PaymentDomain' => payment_domain,
'MWSAuthToken' => mws_auth_token
}
if order_reference_status_list_filter
order_reference_status_list_filter.each_with_index do |val, index|
optional_key = "OrderReferenceStatusListFilter.OrderReferenceStatus.#{index + 1}"
optional[optional_key] = val
end
end
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18031 | AmazonPay.Client.get_merchant_account_status | train | def get_merchant_account_status(
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetMerchantAccountStatus',
'SellerId' => merchant_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18032 | AmazonPay.Client.get_order_reference_details | train | def get_order_reference_details(
amazon_order_reference_id,
address_consent_token: nil,
access_token: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetOrderReferenceDetails',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
# Preseving address_consent_token for backwards compatibility
# AccessToken returns all data in AddressConsentToken plus new data
'AccessToken' => access_token || address_consent_token,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18033 | AmazonPay.Client.set_order_reference_details | train | def set_order_reference_details(
amazon_order_reference_id,
amount,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
request_payment_authorization: nil,
store_name: nil,
order_item_categories: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetOrderReferenceDetails',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id,
'OrderReferenceAttributes.OrderTotal.Amount' => amount,
'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code
}
optional = {
'OrderReferenceAttributes.PlatformId' => platform_id,
'OrderReferenceAttributes.RequestPaymentAuthorization' => request_payment_authorization,
'OrderReferenceAttributes.SellerNote' => seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
if order_item_categories
optional.merge!(
get_categories_list(
'OrderReferenceAttributes',
order_item_categories
)
)
end
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18034 | AmazonPay.Client.set_order_attributes | train | def set_order_attributes(
amazon_order_reference_id,
amount: nil,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
payment_service_provider_id: nil,
payment_service_provider_order_id: nil,
request_payment_authorization: nil,
store_name: nil,
order_item_categories: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetOrderAttributes',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'OrderAttributes.OrderTotal.Amount' => amount,
'OrderAttributes.OrderTotal.CurrencyCode' => currency_code,
'OrderAttributes.PlatformId' => platform_id,
'OrderAttributes.SellerNote' => seller_note,
'OrderAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId' => payment_service_provider_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId' => payment_service_provider_order_id,
'OrderAttributes.RequestPaymentAuthorization' => request_payment_authorization,
'OrderAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
optional['OrderAttributes.OrderTotal.CurrencyCode'] = nil if amount.nil?
if order_item_categories
optional.merge!(
get_categories_list(
'OrderAttributes',
order_item_categories
)
)
end
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18035 | AmazonPay.Client.confirm_order_reference | train | def confirm_order_reference(
amazon_order_reference_id,
success_url: nil,
failure_url: nil,
authorization_amount: nil,
currency_code: @currency_code,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ConfirmOrderReference',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'SuccessUrl' => success_url,
'FailureUrl' => failure_url,
'AuthorizationAmount.Amount' => authorization_amount,
'AuthorizationAmount.CurrencyCode' => currency_code,
'MWSAuthToken' => mws_auth_token
}
optional['AuthorizationAmount.CurrencyCode'] = nil if authorization_amount.nil?
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18036 | AmazonPay.Client.cancel_order_reference | train | def cancel_order_reference(
amazon_order_reference_id,
cancelation_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CancelOrderReference',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'CancelationReason' => cancelation_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18037 | AmazonPay.Client.get_authorization_details | train | def get_authorization_details(
amazon_authorization_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetAuthorizationDetails',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18038 | AmazonPay.Client.capture | train | def capture(
amazon_authorization_id,
capture_reference_id,
amount,
currency_code: @currency_code,
seller_capture_note: nil,
soft_descriptor: nil,
provider_credit_details: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'Capture',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id,
'CaptureReferenceId' => capture_reference_id,
'CaptureAmount.Amount' => amount,
'CaptureAmount.CurrencyCode' => currency_code
}
optional = {
'SellerCaptureNote' => seller_capture_note,
'SoftDescriptor' => soft_descriptor,
'MWSAuthToken' => mws_auth_token
}
optional.merge!(set_provider_credit_details(provider_credit_details)) if provider_credit_details
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18039 | AmazonPay.Client.get_capture_details | train | def get_capture_details(
amazon_capture_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetCaptureDetails',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18040 | AmazonPay.Client.refund | train | def refund(
amazon_capture_id,
refund_reference_id,
amount,
currency_code: @currency_code,
seller_refund_note: nil,
soft_descriptor: nil,
provider_credit_reversal_details: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'Refund',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id,
'RefundReferenceId' => refund_reference_id,
'RefundAmount.Amount' => amount,
'RefundAmount.CurrencyCode' => currency_code
}
optional = {
'SellerRefundNote' => seller_refund_note,
'SoftDescriptor' => soft_descriptor,
'MWSAuthToken' => mws_auth_token
}
optional.merge!(set_provider_credit_reversal_details(provider_credit_reversal_details)) if provider_credit_reversal_details
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18041 | AmazonPay.Client.get_refund_details | train | def get_refund_details(
amazon_refund_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetRefundDetails',
'SellerId' => merchant_id,
'AmazonRefundId' => amazon_refund_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18042 | AmazonPay.Client.close_authorization | train | def close_authorization(
amazon_authorization_id,
closure_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CloseAuthorization',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id
}
optional = {
'ClosureReason' => closure_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | {
"resource": ""
} |
q18043 | AmazonPay.Client.set_provider_credit_details | train | def set_provider_credit_details(provider_credit_details)
member_details = {}
provider_credit_details.each_with_index do |val, index|
member = index + 1
member_details["ProviderCreditList.member.#{member}.ProviderId"] = val[:provider_id]
member_details["ProviderCreditList.member.#{member}.CreditAmount.Amount"] = val[:amount]
member_details["ProviderCreditList.member.#{member}.CreditAmount.CurrencyCode"] = val[:currency_code]
end
member_details
end | ruby | {
"resource": ""
} |
q18044 | AmazonPay.Client.set_provider_credit_reversal_details | train | def set_provider_credit_reversal_details(provider_credit_reversal_details)
member_details = {}
provider_credit_reversal_details.each_with_index do |val, index|
member = index + 1
member_details["ProviderCreditReversalList.member.#{member}.ProviderId"] = val[:provider_id]
member_details["ProviderCreditReversalList.member.#{member}.CreditReversalAmount.Amount"] = val[:amount]
member_details["ProviderCreditReversalList.member.#{member}.CreditReversalAmount.CurrencyCode"] = val[:currency_code]
end
member_details
end | ruby | {
"resource": ""
} |
q18045 | AmazonPay.Request.build_post_url | train | def build_post_url
@optional.map { |k, v| @parameters[k] = v unless v.nil? }
@parameters['Timestamp'] = Time.now.utc.iso8601 unless @parameters.key?('Timestamp')
@parameters = @default_hash.merge(@parameters)
post_url = @parameters.sort.map { |k, v| "#{k}=#{custom_escape(v)}" }.join('&')
post_body = ['POST', @mws_endpoint.to_s, "/#{@sandbox_str}/#{AmazonPay::API_VERSION}", post_url].join("\n")
post_url += '&Signature=' + sign(post_body)
if @log_enabled
data = AmazonPay::Sanitize.new(post_url)
@logger.debug("request/Post: #{data.sanitize_request_data}")
end
post_url
end | ruby | {
"resource": ""
} |
q18046 | AmazonPay.Request.sign | train | def sign(post_body)
custom_escape(Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, @secret_key, post_body)))
end | ruby | {
"resource": ""
} |
q18047 | AmazonPay.Request.post | train | def post(mws_endpoint, sandbox_str, post_url)
uri = URI("https://#{mws_endpoint}/#{sandbox_str}/#{AmazonPay::API_VERSION}")
https = Net::HTTP.new(uri.host, uri.port, @proxy_addr, @proxy_port, @proxy_user, @proxy_pass)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
user_agent = { 'User-Agent' => "#{AmazonPay::SDK_NAME}/#{AmazonPay::VERSION}; (#{@application_name + '/' if @application_name}#{@application_version.to_s + ';' if @application_version} #{RUBY_VERSION}; #{RUBY_PLATFORM})" }
tries = 0
begin
response = https.post(uri.path, post_url, user_agent)
if @log_enabled
data = AmazonPay::Sanitize.new(response.body)
@logger.debug("response: #{data.sanitize_response_data}")
end
if @throttle.eql?(true)
raise 'InternalServerError' if response.code.eql?('500')
raise 'ServiceUnavailable or RequestThrottled' if response.code.eql?('503')
end
AmazonPay::Response.new(response)
rescue StandardError => error
tries += 1
sleep(get_seconds_for_try_count(tries))
retry if tries <= MAX_RETRIES
raise error.message
end
end | ruby | {
"resource": ""
} |
q18048 | AmazonPay.Client.charge | train | def charge(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code: @currency_code,
charge_note: nil,
charge_order_id: nil,
store_name: nil,
custom_information: nil,
soft_descriptor: nil,
platform_id: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
if order_reference?(amazon_reference_id)
call_order_reference_api(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code,
charge_note,
charge_order_id,
store_name,
custom_information,
soft_descriptor,
platform_id,
merchant_id,
mws_auth_token
)
elsif billing_agreement?(amazon_reference_id)
call_billing_agreement_api(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code,
charge_note,
charge_order_id,
store_name,
custom_information,
soft_descriptor,
platform_id,
merchant_id,
mws_auth_token
)
end
end | ruby | {
"resource": ""
} |
q18049 | Flame.Router.add | train | def add(routes_refine)
routes.deep_merge! routes_refine.routes
reverse_routes.merge! routes_refine.reverse_routes
end | ruby | {
"resource": ""
} |
q18050 | Flame.Router.find_nearest_route | train | def find_nearest_route(path)
path_parts = path.parts.dup
loop do
route = routes.navigate(*path_parts)&.values&.grep(Route)&.first
break route if route || path_parts.pop.nil?
end
end | ruby | {
"resource": ""
} |
q18051 | Flame.Router.path_of | train | def path_of(route_or_controller, action = nil)
if route_or_controller.is_a?(Flame::Router::Route)
route = route_or_controller
controller = route.controller
action = route.action
else
controller = route_or_controller
end
reverse_routes.dig(controller.to_s, action)
end | ruby | {
"resource": ""
} |
q18052 | Flame.Render.render | train | def render(cache: true, &block)
@cache = cache
## Compile Tilt to instance hash
return unless @filename
tilt = compile_file
## Render Tilt from instance hash with new options
layout_render tilt.render(@scope, @locals, &block)
end | ruby | {
"resource": ""
} |
q18053 | Flame.Render.compile_file | train | def compile_file(filename = @filename)
cached = @controller.cached_tilts[filename]
return cached if @cache && cached
compiled = Tilt.new(filename, nil, @tilt_options)
@controller.cached_tilts[filename] ||= compiled if @cache
compiled
end | ruby | {
"resource": ""
} |
q18054 | Flame.Render.find_file | train | def find_file(path)
caller_path = caller_locations(4..4).first.path
caller_dir =
begin
File.dirname(caller_path).sub(views_dir, '') if Tilt[caller_path]
rescue LoadError
nil
end
find_files(path, controller_dirs | Array(caller_dir))
.find { |file| Tilt[file] }
end | ruby | {
"resource": ""
} |
q18055 | Flame.Render.find_layouts | train | def find_layouts(path)
find_files(path, layout_dirs)
.select { |file| Tilt[file] }
.sort! { |a, b| b.split('/').size <=> a.split('/').size }
end | ruby | {
"resource": ""
} |
q18056 | Flame.Render.controller_dirs | train | def controller_dirs
parts = @controller.class.underscore.split('/').map do |part|
%w[_controller _ctrl]
.find { |suffix| part.chomp! suffix }
part
## Alternative, but slower by ~50%:
# part.sub(/_(controller|ctrl)$/, '')
end
combine_parts(parts).map! { |path| path.join('/') }
end | ruby | {
"resource": ""
} |
q18057 | Flame.Render.combine_parts | train | def combine_parts(parts)
parts.size.downto(1).with_object([]) do |i, arr|
arr.push(*parts.combination(i).to_a)
end
# variants.uniq!.reject!(&:empty?)
end | ruby | {
"resource": ""
} |
q18058 | Flame.Render.layout_render | train | def layout_render(content)
return content unless @layout
layout_files = find_layouts(@layout)
return content if layout_files.empty?
layout_files.each_with_object(content.dup) do |layout_file, result|
layout = compile_file(layout_file)
result.replace layout.render(@scope, @locals) { result }
end
end | ruby | {
"resource": ""
} |
q18059 | Flame.Path.adapt | train | def adapt(ctrl, action)
parameters = ctrl.instance_method(action).parameters
parameters.map! do |parameter|
parameter_type, parameter_name = parameter
path_part = self.class::Part.new parameter_name, arg: parameter_type
path_part unless parts.include? path_part
end
self.class.new @path.empty? ? "/#{action}" : self, *parameters.compact
end | ruby | {
"resource": ""
} |
q18060 | Flame.Path.to_routes_with_endpoint | train | def to_routes_with_endpoint
endpoint =
parts.reduce(result = Flame::Router::Routes.new) do |hash, part|
hash[part] ||= Flame::Router::Routes.new
end
[result, endpoint]
end | ruby | {
"resource": ""
} |
q18061 | Flame.Path.assign_argument | train | def assign_argument(part, args = {})
## Not argument
return part unless part.arg?
## Not required argument
return args.delete(part[2..-1].to_sym) if part.opt_arg?
## Required argument
param = args.delete(part[1..-1].to_sym)
## Required argument is nil
error = Errors::ArgumentNotAssignedError.new(@path, part)
raise error if param.nil?
## All is ok
param
end | ruby | {
"resource": ""
} |
q18062 | Flame.Dispatcher.status | train | def status(value = nil)
response.status ||= 200
response.headers['X-Cascade'] = 'pass' if value == 404
value ? response.status = value : response.status
end | ruby | {
"resource": ""
} |
q18063 | Flame.Dispatcher.params | train | def params
@params ||=
begin
request.params.symbolize_keys(deep: true)
rescue ArgumentError => e
raise unless e.message.include?('invalid %-encoding')
{}
end
end | ruby | {
"resource": ""
} |
q18064 | Flame.Dispatcher.dump_error | train | def dump_error(error)
error_message = [
"#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} - " \
"#{error.class} - #{error.message}:",
*error.backtrace
].join("\n\t")
@env[Rack::RACK_ERRORS].puts(error_message)
end | ruby | {
"resource": ""
} |
q18065 | Flame.Dispatcher.try_options | train | def try_options
return unless request.http_method == :OPTIONS
allow = available_endpoint&.allow
halt 404 unless allow
response.headers['Allow'] = allow
end | ruby | {
"resource": ""
} |
q18066 | Flame.Controller.redirect | train | def redirect(*args)
args[0] = args.first.to_s if args.first.is_a? URI
unless args.first.is_a? String
path_to_args_range = 0..(args.last.is_a?(Integer) ? -2 : -1)
args[path_to_args_range] = path_to(*args[path_to_args_range])
end
response.redirect(*args)
status
end | ruby | {
"resource": ""
} |
q18067 | Flame.Controller.attachment | train | def attachment(filename = nil, disposition = :attachment)
content_dis = 'Content-Disposition'
response[content_dis] = disposition.to_s
return unless filename
response[content_dis] << "; filename=\"#{File.basename(filename)}\""
ext = File.extname(filename)
response.content_type = ext unless ext.empty?
end | ruby | {
"resource": ""
} |
q18068 | Flame.Controller.reroute | train | def reroute(*args)
add_controller_class(args)
ctrl, action = args[0..1]
ctrl_object = ctrl == self.class ? self : ctrl.new(@dispatcher)
ctrl_object.send :execute, action
body
end | ruby | {
"resource": ""
} |
q18069 | Flame.Application.call | train | def call(env)
@app.call(env) if @app.respond_to? :call
Flame::Dispatcher.new(self.class, env).run!
end | ruby | {
"resource": ""
} |
q18070 | Redd.Client.request | train | def request(verb, path, options = {})
# puts "#{verb.to_s.upcase} #{path}", ' ' + options.inspect
response = connection.request(verb, path, **options)
Response.new(response.status.code, response.headers, response.body.to_s)
end | ruby | {
"resource": ""
} |
q18071 | Redd.Middleware.redirect_to_reddit! | train | def redirect_to_reddit!
state = SecureRandom.urlsafe_base64
url = Redd.url(
client_id: @client_id,
redirect_uri: @redirect_uri,
scope: @scope,
duration: @duration,
state: state
)
@request.session[:redd_state] = state
[302, { 'Location' => url }, []]
end | ruby | {
"resource": ""
} |
q18072 | Redd.Middleware.after_call | train | def after_call
env_session = @request.env['redd.session']
if env_session && env_session.client.access
# Make sure to flush any changes made to the Session client to the browser.
@request.session[:redd_session] = env_session.client.access.to_h
else
# Clear the session if the app explicitly set 'redd.session' to nil.
@request.session.delete(:redd_session)
end
end | ruby | {
"resource": ""
} |
q18073 | Redd.Middleware.handle_token_error | train | def handle_token_error
message = nil
message = 'invalid_state' if @request.GET['state'] != @request.session[:redd_state]
message = @request.GET['error'] if @request.GET['error']
raise Errors::TokenRetrievalError, message if message
end | ruby | {
"resource": ""
} |
q18074 | Redd.Middleware.create_session! | train | def create_session!
# Skip authorizing if there was an error from the authorization.
handle_token_error
# Try to get a code (the rescue block will also prevent crazy crashes)
access = @strategy.authenticate(@request.GET['code'])
@request.session[:redd_session] = access.to_h
rescue Errors::TokenRetrievalError, Errors::ResponseError => error
@request.env['redd.error'] = error
end | ruby | {
"resource": ""
} |
q18075 | Redd.APIClient.request | train | def request(verb, path, raw: false, params: {}, **options)
# Make sure @access is populated by a valid access
ensure_access_is_valid
# Setup base API params and make request
api_params = { api_type: 'json', raw_json: 1 }.merge(params)
# This loop is retried @max_retries number of times until it succeeds
handle_retryable_errors do
response = @rate_limiter.after_limit { super(verb, path, params: api_params, **options) }
# Raise errors if encountered at the API level.
response_error = @error_handler.check_error(response, raw: raw)
raise response_error unless response_error.nil?
# All done, return the response
response
end
end | ruby | {
"resource": ""
} |
q18076 | AnsibleTowerClient.HashModel.hash_to_model | train | def hash_to_model(klass_name, hash)
model_klass =
if self.class.const_defined?("#{self.class}::#{klass_name}")
self.class.const_get(klass_name)
else
self.class.const_set(klass_name, Class.new(HashModel))
end
model_klass.new(hash)
end | ruby | {
"resource": ""
} |
q18077 | Roma.Mkconfig.save_data | train | def save_data(res)
if res.key?("storage")
case res["storage"].value
when "Ruby Hash"
req = "rh_storage"
storage = "RubyHashStorage"
when "Tokyo Cabinet"
req = "tc_storage"
storage = "TCStorage"
bnum = Calculate.get_bnum(res)
bnum = 5000000 if bnum < 5000000
xmsiz = Calculate.get_xmsize_max(res)
when "Groonga"
req = "groonga_storage"
storage = "GroongaStorage"
bnum = Calculate.get_bnum(res)
bnum = 5000000 if bnum < 5000000
xmsiz = Calculate.get_xmsize_max(res)
end
end
if res.key?("language")
fd = Calculate.get_fd(res)
print "\r\nPlease set FileDescriptor bigger than #{fd}.\r\n\r\n"
end
body = ""
open(CONFIG_TEMPLATE_PATH, "r") do |f|
body = f.read
end
if req
body = ch_assign(body, "require", " ", "roma\/storage\/#{req}")
body = ch_assign(body, "STORAGE_CLASS", "Roma::Storage::#{storage}")
case req
when "rh_storage"
body = ch_assign(body, "STORAGE_OPTION","")
when /^(tc_storage|groonga_storage)$/
body = ch_assign(body, "STORAGE_OPTION", "bnum=#{bnum}\#xmsiz=#{xmsiz}\#opts=d#dfunit=10")
end
end
if res.key?("plugin")
body = ch_assign(body, "PLUGIN_FILES", res["plugin"].value)
end
open(CONFIG_OUT_PATH, "w") do |f|
f.flock(File::LOCK_EX)
f.puts body
f.truncate(f.tell)
f.flock(File::LOCK_UN)
end
puts "Before"
Box.print_with_box(@defaults)
re_require(CONFIG_OUT_PATH, Config)
results = load_config([:STORAGE_CLASS, :STORAGE_OPTION, :PLUGIN_FILES])
print "\r\nAfter\r\n"
Box.print_with_box(results)
print "\r\nMkconfig is finish.\r\n"
print "\r\nIf you need, change directory path about LOG, RTTABLE, STORAGE, WB and other setting.\r\n\r\n"
end | ruby | {
"resource": ""
} |
q18078 | AnsibleTowerClient.BaseModel.update_attributes! | train | def update_attributes!(attributes)
@api.patch(url, attributes.to_json)
attributes.each do |method_name, value|
invoke_name = "#{override_raw_attributes[method_name] || method_name}="
if respond_to?(invoke_name)
send(invoke_name, value)
else
AnsibleTowerClient.logger.warn("Unknown attribute/method: #{invoke_name}. Skip updating it ...")
end
end
true
end | ruby | {
"resource": ""
} |
q18079 | AnsibleTowerClient.BaseModel.hash_to_model | train | def hash_to_model(klass_name, hash)
model_klass =
if self.class.const_defined?(klass_name, false)
self.class.const_get(klass_name)
else
self.class.const_set(klass_name, Class.new(BaseModel))
end
model_klass.new(api, hash)
end | ruby | {
"resource": ""
} |
q18080 | MLBStatsAPI.Stats.stats | train | def stats(options = {})
raise ArgumentError, '#stats requires a stats arg' unless options[:stats]
raise ArgumentError, '#stats requires a group arg' unless options[:group]
get '/stats', options
end | ruby | {
"resource": ""
} |
q18081 | MLBStatsAPI.Standings.standings | train | def standings(options = {})
options[:hydrate] = 'team' unless options.key?(:hydrate)
if options[:leagues] && !options[:leagueId]
league_ids = Leagues::LEAGUES.values_at(*options.delete(:leagues))
options[:leagueId] = league_ids
end
options[:leagueId] = [103, 104] unless Array(options[:leagueId])&.any?
get '/standings', options
end | ruby | {
"resource": ""
} |
q18082 | MLBStatsAPI.Leagues.all_star_ballot | train | def all_star_ballot(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarBallot", options
end | ruby | {
"resource": ""
} |
q18083 | MLBStatsAPI.Leagues.all_star_write_ins | train | def all_star_write_ins(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarWriteIns", options
end | ruby | {
"resource": ""
} |
q18084 | MLBStatsAPI.Leagues.all_star_final_vote | train | def all_star_final_vote(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarFinalVote", options
end | ruby | {
"resource": ""
} |
q18085 | MLBStatsAPI.People.person | train | def person(person_ids, options = {})
ids = Array(person_ids)
result = get('/people', options.merge(personIds: ids)).dig('people')
return result.first if ids.length == 1
result
end | ruby | {
"resource": ""
} |
q18086 | Gemika.RSpec.run_specs | train | def run_specs(options = nil)
options ||= {}
files = options.fetch(:files, 'spec')
rspec_options = options.fetch(:options, '--color')
# We need to override the gemfile explicitely, since we have a default Gemfile in the project root
gemfile = options.fetch(:gemfile, Gemika::Env.gemfile)
fatal = options.fetch(:fatal, true)
runner = binary(:gemfile => gemfile)
bundle_exec = options.fetch(:bundle_exec) ? 'bundle exec' : nil
command = [bundle_exec, runner, rspec_options, files].compact.join(' ')
result = shell_out(command)
if result
true
elsif fatal
raise RSpecFailed, "RSpec failed: #{command}"
else
false
end
end | ruby | {
"resource": ""
} |
q18087 | Gemika.RSpec.configure_should_syntax | train | def configure_should_syntax
if Env.gem?('rspec', '>= 2.11')
configure do |config|
config.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }
config.mock_with(:rspec) { |c| c.syntax = [:should, :expect] }
end
else
# We have an old RSpec that only understands should syntax
end
end | ruby | {
"resource": ""
} |
q18088 | Gemika.Database.adapter_config | train | def adapter_config
default_config = {}
default_config['database'] = guess_database_name
if Env.gem?('pg')
default_config['adapter'] = 'postgresql'
default_config['username'] = 'postgres' if Env.travis?
default_config['password'] = ''
user_config = @yaml_config['postgresql'] || @yaml_config['postgres'] || @yaml_config['pg'] || {}
elsif Env.gem?('mysql2')
default_config['adapter'] = 'mysql2'
default_config['username'] = 'travis' if Env.travis?
default_config['encoding'] = 'utf8'
user_config = (@yaml_config['mysql'] || @yaml_config['mysql2']) || {}
elsif Env.gem?('sqlite3')
default_config['adapter'] = 'sqlite3'
default_config['database'] = ':memory:'
user_config = (@yaml_config['sqlite'] || @yaml_config['sqlite3']) || {}
else
raise UnknownAdapter, "Unknown database type. Either 'pg', 'mysql2', or 'sqlite3' gem should be in your current bundle."
end
default_config.merge(user_config)
end | ruby | {
"resource": ""
} |
q18089 | Gemika.Matrix.each | train | def each(&block)
@all_passed = true
rows.each do |row|
gemfile = row.gemfile
if row.compatible_with_ruby?(current_ruby)
@compatible_count += 1
print_title gemfile
gemfile_passed = Env.with_gemfile(gemfile, row, &block)
@all_passed &= gemfile_passed
if gemfile_passed
@results[row] = tint('Success', COLOR_SUCCESS)
else
@results[row] = tint('Failed', COLOR_FAILURE)
end
else
@results[row] = tint("Skipped", COLOR_WARNING)
end
end
print_summary
end | ruby | {
"resource": ""
} |
q18090 | Gemika.Env.with_gemfile | train | def with_gemfile(path, *args, &block)
# Make sure that if block calls #gemfile we still return the gemfile for this
# process, regardless of what's in ENV temporarily
@gemfile_changed = true
@process_gemfile = ENV['BUNDLE_GEMFILE']
Bundler.with_clean_env do
ENV['BUNDLE_GEMFILE'] = path
block.call(*args)
end
ensure
@gemfile_changed = false
ENV['BUNDLE_GEMFILE'] = @process_gemfile
end | ruby | {
"resource": ""
} |
q18091 | Gemika.Env.gem? | train | def gem?(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
name, requirement_string = args
if options[:gemfile] && !process_gemfile?(options[:gemfile])
gem_in_gemfile?(options[:gemfile], name, requirement_string)
else
gem_activated?(name, requirement_string)
end
end | ruby | {
"resource": ""
} |
q18092 | FetcheableOnApi.Filterable.predicates | train | def predicates(predicate, collection, klass, column_name, value)
case predicate
when :between
klass.arel_table[column_name].between(value.first..value.last)
when :does_not_match
klass.arel_table[column_name].does_not_match("%#{value}%")
when :does_not_match_all
klass.arel_table[column_name].does_not_match_all(value)
when :does_not_match_any
klass.arel_table[column_name].does_not_match_any(value)
when :eq
klass.arel_table[column_name].eq(value)
when :eq_all
klass.arel_table[column_name].eq_all(value)
when :eq_any
klass.arel_table[column_name].eq_any(value)
when :gt
klass.arel_table[column_name].gt(value)
when :gt_all
klass.arel_table[column_name].gt_all(value)
when :gt_any
klass.arel_table[column_name].gt_any(value)
when :gteq
klass.arel_table[column_name].gteq(value)
when :gteq_all
klass.arel_table[column_name].gteq_all(value)
when :gteq_any
klass.arel_table[column_name].gteq_any(value)
when :in
klass.arel_table[column_name].in(value)
when :in_all
klass.arel_table[column_name].in_all(value)
when :in_any
klass.arel_table[column_name].in_any(value)
when :lt
klass.arel_table[column_name].lt(value)
when :lt_all
klass.arel_table[column_name].lt_all(value)
when :lt_any
klass.arel_table[column_name].lt_any(value)
when :lteq
klass.arel_table[column_name].lteq(value)
when :lteq_all
klass.arel_table[column_name].lteq_all(value)
when :lteq_any
klass.arel_table[column_name].lteq_any(value)
when :ilike
klass.arel_table[column_name].matches("%#{value}%")
when :matches
klass.arel_table[column_name].matches(value)
when :matches_all
klass.arel_table[column_name].matches_all(value)
when :matches_any
klass.arel_table[column_name].matches_any(value)
when :not_between
klass.arel_table[column_name].not_between(value.first..value.last)
when :not_eq
klass.arel_table[column_name].not_eq(value)
when :not_eq_all
klass.arel_table[column_name].not_eq_all(value)
when :not_eq_any
klass.arel_table[column_name].not_eq_any(value)
when :not_in
klass.arel_table[column_name].not_in(value)
when :not_in_all
klass.arel_table[column_name].not_in_all(value)
when :not_in_any
klass.arel_table[column_name].not_in_any(value)
else
unless predicate.respond_to?(:call)
raise ArgumentError,
"unsupported predicate `#{predicate}`"
end
predicate.call(collection, value)
end
end | ruby | {
"resource": ""
} |
q18093 | Systemd.JournalEntry.catalog | train | def catalog(opts = {})
return nil unless catalog?
opts[:replace] = true unless opts.key?(:replace)
cat = Systemd::Journal.catalog_for(self[:message_id])
# catalog_for does not do field substitution for us, so we do it here
# if requested
opts[:replace] ? field_substitute(cat) : cat
end | ruby | {
"resource": ""
} |
q18094 | Systemd.Journal.query_unique | train | def query_unique(field)
results = []
Native.sd_journal_restart_unique(@ptr)
rc = Native.sd_journal_query_unique(@ptr, field.to_s.upcase)
raise JournalError, rc if rc < 0
while (kvpair = enumerate_helper(:sd_journal_enumerate_unique))
results << kvpair.last
end
results
end | ruby | {
"resource": ""
} |
q18095 | Systemd.Journal.data_threshold | train | def data_threshold
size_ptr = FFI::MemoryPointer.new(:size_t, 1)
if (rc = Native.sd_journal_get_data_threshold(@ptr, size_ptr)) < 0
raise JournalError, rc
end
size_ptr.read_size_t
end | ruby | {
"resource": ""
} |
q18096 | CloudCrowd.Action.download | train | def download(url, path)
if url.match(FILE_URL)
FileUtils.cp(url.sub(FILE_URL, ''), path)
else
File.open(path, 'w+') do |file|
Net::HTTP.get_response(URI(url)) do |response|
response.read_body do |chunk|
file.write chunk
end
end
end
end
path
end | ruby | {
"resource": ""
} |
q18097 | CloudCrowd.Action.` | train | def `(command)
result = super(command)
exit_code = $?.to_i
raise Error::CommandFailed.new(result, exit_code) unless exit_code == 0
result
end | ruby | {
"resource": ""
} |
q18098 | CloudCrowd.Action.safe_filename | train | def safe_filename(url)
url = url.sub(/\?.*\Z/, '')
ext = File.extname(url)
name = URI.unescape(File.basename(url)).gsub(/[^a-zA-Z0-9_\-.]/, '-').gsub(/-+/, '-')
File.basename(name, ext).gsub('.', '-') + ext
end | ruby | {
"resource": ""
} |
q18099 | CloudCrowd.Action.download_input | train | def download_input
return unless input_is_url?
Dir.chdir(@work_directory) do
@input_path = File.join(@work_directory, safe_filename(@input))
@file_name = File.basename(@input_path, File.extname(@input_path))
download(@input, @input_path)
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.