_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4900 | GithubPivotalFlow.Configuration.api_token | train | def api_token
api_token = @options[:api_token] || Git.get_config(KEY_API_TOKEN, :inherited)
if api_token.blank?
api_token = ask('Pivotal API Token (found at https://www.pivotaltracker.com/profile): ').strip
Git.set_config(KEY_API_TOKEN, api_token, :local) unless api_token.blank?
puts
end
api_token
end | ruby | {
"resource": ""
} |
q4901 | GithubPivotalFlow.Configuration.project_id | train | def project_id
project_id = @options[:project_id] || Git.get_config(KEY_PROJECT_ID, :inherited)
if project_id.empty?
project_id = choose do |menu|
menu.prompt = 'Choose project associated with this repository: '
PivotalTracker::Project.all.sort_by { |project| project.name }.each do |project|
menu.choice(project.name) { project.id }
end
end
Git.set_config(KEY_PROJECT_ID, project_id, :local)
puts
end
project_id
end | ruby | {
"resource": ""
} |
q4902 | GithubPivotalFlow.Configuration.story | train | def story
return @story if @story
story_id = Git.get_config(KEY_STORY_ID, :branch)
if story_id.blank? && (matchdata = /^[a-z0-9_\-]+\/(\d+)(-[a-z0-9_\-]+)?$/i.match(Git.current_branch))
story_id = matchdata[1]
Git.set_config(KEY_STORY_ID, story_id, :branch) unless story_id.blank?
end
if story_id.blank?
story_id = ask('What Pivotal story ID is this branch associated with?').strip
Git.set_config(KEY_STORY_ID, story_id, :branch) unless story_id.blank?
end
return nil if story_id.blank?
return (@story = Story.new(project, project.stories.find(story_id.to_i), branch_name: Git.current_branch))
end | ruby | {
"resource": ""
} |
q4903 | GithubPivotalFlow.Configuration.ask_github_password | train | def ask_github_password(username = nil)
username ||= github_username
print "Github password for #{username} (never stored): "
if $stdin.tty?
password = askpass
puts ''
password
else
# in testing
$stdin.gets.chomp
end
rescue Interrupt
abort
end | ruby | {
"resource": ""
} |
q4904 | PaynetEasy::PaynetEasyApi.PaymentProcessor.execute_query | train | def execute_query(query_name, payment_transaction)
query = query(query_name)
begin
request = query.create_request payment_transaction
response = make_request request
query.process_response payment_transaction, response
rescue Exception => error
handle_exception error, payment_transaction, response
return
end
handle_query_result payment_transaction, response
response
end | ruby | {
"resource": ""
} |
q4905 | PaynetEasy::PaynetEasyApi.PaymentProcessor.process_paynet_easy_callback | train | def process_paynet_easy_callback(callback_response, payment_transaction)
begin
callback(callback_response.type).process_callback(payment_transaction, callback_response)
rescue Exception => error
handle_exception error, payment_transaction, callback_response
return
end
handle_query_result payment_transaction, callback_response
callback_response
end | ruby | {
"resource": ""
} |
q4906 | InoreaderApi.Api.login | train | def login(un, pw)
response_body = Helper.auth_request un, pw
auth_token = Hash[*response_body.split.collect { |i| i.split('=') }.flatten]['Auth']
raise InoreaderApi::InoreaderApiError.new 'Bad Authentication' if auth_token.nil?
auth_token
rescue => e
raise InoreaderApi::InoreaderApiError.new e.message if auth_token.nil?
end | ruby | {
"resource": ""
} |
q4907 | LibWebSocket.Frame.to_s | train | def to_s
ary = ["\x00", @buffer.dup, "\xff"]
ary.collect{ |s| s.force_encoding('UTF-8') if s.respond_to?(:force_encoding) }
return ary.join
end | ruby | {
"resource": ""
} |
q4908 | Ldaptic.Methods.add | train | def add(dn, attributes)
attributes = normalize_attributes(attributes)
log_dispatch(:add, dn, attributes)
adapter.add(dn, attributes)
end | ruby | {
"resource": ""
} |
q4909 | Ldaptic.Methods.modify | train | def modify(dn, attributes)
if attributes.kind_of?(Hash)
attributes = normalize_attributes(attributes)
else
attributes = attributes.map do |(action, key, values)|
[action, Ldaptic.encode(key), values.respond_to?(:before_type_cast) ? values.before_type_cast : [values].flatten.compact]
end
end
log_dispatch(:modify, dn, attributes)
adapter.modify(dn, attributes) unless attributes.empty?
end | ruby | {
"resource": ""
} |
q4910 | Ldaptic.Methods.rename | train | def rename(dn, new_rdn, delete_old, *args)
log_dispatch(:rename, dn, new_rdn, delete_old, *args)
adapter.rename(dn, new_rdn.to_str, delete_old, *args)
end | ruby | {
"resource": ""
} |
q4911 | Ldaptic.Methods.compare | train | def compare(dn, key, value)
log_dispatch(:compare, dn, key, value)
adapter.compare(dn, Ldaptic.encode(key), Ldaptic.encode(value))
end | ruby | {
"resource": ""
} |
q4912 | Skydrive.Operations.upload | train | def upload folder_path, filename, file, options={}
response = put("/#{folder_path}/files/#{filename}", file.read, options)
end | ruby | {
"resource": ""
} |
q4913 | FreshdeskAPI.Configuration.options | train | def options
{
headers: {
accept: :json,
content_type: :json,
accept_encoding: 'gzip ,deflate',
user_agent: "FreshdeskAPI API #{FreshdeskAPI::VERSION}"
},
read_timeout: nil,
open_timeout: nil,
base_url: @base_url
}.merge(client_options)
end | ruby | {
"resource": ""
} |
q4914 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.create_request | train | def create_request(payment_transaction)
validate_payment_transaction payment_transaction
request = payment_transaction_to_request payment_transaction
request.api_method = @api_method
request.end_point = payment_transaction.query_config.end_point
request.gateway_url = payment_transaction.query_config.gateway_url
request.signature = create_signature payment_transaction
request
rescue Exception => error
payment_transaction.add_error error
payment_transaction.status = PaymentTransaction::STATUS_ERROR
raise error
end | ruby | {
"resource": ""
} |
q4915 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.process_response | train | def process_response(payment_transaction, response)
if response.processing? || response.approved?
validate = :validate_response_on_success
update = :update_payment_transaction_on_success
else
validate = :validate_response_on_error
update = :update_payment_transaction_on_error
end
begin
send validate, payment_transaction, response
rescue Exception => error
payment_transaction.add_error error
payment_transaction.status = PaymentTransaction::STATUS_ERROR
raise error
end
send update, payment_transaction, response
if response.error?
raise response.error
end
response
end | ruby | {
"resource": ""
} |
q4916 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.validate_payment_transaction | train | def validate_payment_transaction(payment_transaction)
validate_query_config payment_transaction
error_message = ''
missed_fields = []
invalid_fields = []
request_fields_definition.each do |field_name, property_path, is_field_required, validation_rule|
field_value = PropertyAccessor.get_value payment_transaction, property_path, false
if field_value
begin
Validator.validate_by_rule field_value, validation_rule
rescue ValidationError => error
invalid_fields << "Field '#{field_name}' from property path '#{property_path}', #{error.message}."
end
elsif is_field_required
missed_fields << "Field '#{field_name}' from property path '#{property_path}' missed or empty."
end
end
unless missed_fields.empty?
error_message << "Some required fields missed or empty in PaymentTransaction: \n#{missed_fields.join "\n"}\n"
end
unless invalid_fields.empty?
error_message << "Some fields invalid in PaymentTransaction: \n#{invalid_fields.join "\n"}\n"
end
unless error_message.empty?
raise ValidationError, error_message
end
end | ruby | {
"resource": ""
} |
q4917 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.payment_transaction_to_request | train | def payment_transaction_to_request(payment_transaction)
request_fields = {}
request_fields_definition.each do |field_name, property_path, _|
field_value = PropertyAccessor.get_value payment_transaction, property_path
if field_value
request_fields[field_name] = field_value
end
end
Request.new request_fields
end | ruby | {
"resource": ""
} |
q4918 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.validate_response_on_success | train | def validate_response_on_success(payment_transaction, response)
if response.type != success_response_type
raise ValidationError, "Response type '#{response.type}' does " +
"not match success response type '#{success_response_type}'"
end
missed_fields = []
response_fields_definition.each do |field_name|
missed_fields << field_name unless response.key? field_name
end
unless missed_fields.empty?
raise ValidationError, "Some required fields missed or empty in Response: #{missed_fields.join ', '}"
end
validate_client_id payment_transaction, response
end | ruby | {
"resource": ""
} |
q4919 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.validate_response_on_error | train | def validate_response_on_error(payment_transaction, response)
unless [success_response_type, 'error', 'validation-error'].include? response.type
raise ValidationError, "Unknown response type '#{response.type}'"
end
validate_client_id payment_transaction, response
end | ruby | {
"resource": ""
} |
q4920 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.update_payment_transaction_on_success | train | def update_payment_transaction_on_success(payment_transaction, response)
payment_transaction.status = response.status
set_paynet_id payment_transaction, response
end | ruby | {
"resource": ""
} |
q4921 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.update_payment_transaction_on_error | train | def update_payment_transaction_on_error(payment_transaction, response)
if response.declined?
payment_transaction.status = response.status
else
payment_transaction.status = PaymentTransaction::STATUS_ERROR
end
payment_transaction.add_error response.error
set_paynet_id payment_transaction, response
end | ruby | {
"resource": ""
} |
q4922 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.validate_query_definition | train | def validate_query_definition
raise RuntimeError, 'You must configure @request_fields_definition' if request_fields_definition.empty?
raise RuntimeError, 'You must configure @signature_definition' if signature_definition.empty?
raise RuntimeError, 'You must configure @response_fields_definition' if response_fields_definition.empty?
raise RuntimeError, 'You must configure @success_response_type' if success_response_type.nil?
end | ruby | {
"resource": ""
} |
q4923 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.validate_client_id | train | def validate_client_id(payment_transaction, response)
payment_id = payment_transaction.payment.client_id
response_id = response.payment_client_id
if response_id && payment_id.to_s != response_id.to_s # Different types with equal values must pass validation
raise ValidationError, "Response client_id '#{response_id}' does not match Payment client_id '#{payment_id}'"
end
end | ruby | {
"resource": ""
} |
q4924 | PaynetEasy::PaynetEasyApi::Query::Prototype.Query.set_paynet_id | train | def set_paynet_id(payment_transaction, response)
if response.payment_paynet_id
payment_transaction.payment.paynet_id = response.payment_paynet_id
end
end | ruby | {
"resource": ""
} |
q4925 | OpenSecrets.Candidate.summary | train | def summary(options = {})
raise ArgumentError, 'You must provide a :cid option' if options[:cid].nil? || options[:cid].empty?
options.merge!({:method => 'candSummary'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4926 | OpenSecrets.Candidate.contributors | train | def contributors(options = {})
raise ArgumentError, 'You must provide a :cid option' if options[:cid].nil? || options[:cid].empty?
options.merge!({:method => 'candContrib'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4927 | OpenSecrets.Candidate.industries | train | def industries(options = {})
raise ArgumentError, 'You must provide a :cid option' if options[:cid].nil? || options[:cid].empty?
options.merge!({:method => 'candIndustry'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4928 | OpenSecrets.Candidate.contributions_by_industry | train | def contributions_by_industry(options = {})
raise ArgumentError, 'You must provide a :cid option' if options[:cid].nil? || options[:cid].empty?
raise ArgumentError, 'You must provide a :ind option' if options[:ind].nil? || options[:ind].empty?
options.merge!({:method => 'CandIndByInd'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4929 | OpenSecrets.Candidate.sector | train | def sector(options = {})
raise ArgumentError, 'You must provide a :cid option' if options[:cid].nil? || options[:cid].empty?
options.merge!({:method => 'candSector'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4930 | OpenSecrets.Committee.by_industry | train | def by_industry(options = {})
raise ArgumentError, 'You must provide a :cmte option' if options[:cmte].nil? || options[:cmte].empty?
raise ArgumentError, 'You must provide a :congno option' if options[:congno].nil? || options[:congno].empty?
raise ArgumentError, 'You must provide a :indus option' if options[:indus].nil? || options[:indus].empty?
options.merge!({:method => 'congCmteIndus'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4931 | OpenSecrets.Organization.get_orgs | train | def get_orgs(options = {})
raise ArgumentError, 'You must provide a :org option' if options[:org].nil? || options[:org].empty?
options.merge!({:method => 'getOrgs'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4932 | OpenSecrets.Organization.org_summary | train | def org_summary(options = {})
raise ArgumentError, 'You must provide a :id option' if options[:id].nil? || options[:id].empty?
options.merge!({:method => 'orgSummary'})
self.class.get("/", :query => options)
end | ruby | {
"resource": ""
} |
q4933 | Massimo.Config.path_for | train | def path_for(resource_name)
if resource_path = send("#{resource_name}_path")
File.expand_path resource_path
else
File.join source_path, resource_name.to_s
end
end | ruby | {
"resource": ""
} |
q4934 | ParseFasta.SeqFile.get_first_char | train | def get_first_char fname
if File.exists? fname
begin
f = Zlib::GzipReader.open fname
rescue Zlib::GzipFile::Error
f = File.open fname
end
begin
first_char = f.each.peek[0]
return first_char
ensure
f.close
end
else
raise ParseFasta::Error::FileNotFoundError,
"No such file or directory -- #{fname}"
end
end | ruby | {
"resource": ""
} |
q4935 | GithubPivotalFlow.GitHubAPI.create_pullrequest | train | def create_pullrequest options
project = options.fetch(:project)
params = {
:base => options.fetch(:base),
:head => options.fetch(:head)
}
if options[:issue]
params[:issue] = options[:issue]
else
params[:title] = options[:title] if options[:title]
params[:body] = options[:body] if options[:body]
end
res = post "https://%s/repos/%s/%s/pulls" %
[api_host(project.host), project.owner, project.name], params
res.error! unless res.success?
res.data
end | ruby | {
"resource": ""
} |
q4936 | Massimo.Watcher.process | train | def process
if config_changed?
Massimo::UI.say 'massimo is reloading your site'
@site.reload
@site.process
Massimo::UI.say 'massimo has built your site', :growl => true
elsif changed?
Massimo::UI.say 'massimo has noticed a change'
@site.process
Massimo::UI.say 'massimo has built your site', :growl => true
end
end | ruby | {
"resource": ""
} |
q4937 | Edgarj.FieldHelper.draw_form_buttons | train | def draw_form_buttons(options = {})
content_tag(:table) do
content_tag(:tr) do
# save button
content_tag(:td) do
#cp_bitset = Edgarj::ModelPermission::FlagsBitset
#create_or_update = cp_bitset::CREATE + cp_bitset::UPDATE
tag(:input, {
type: 'button',
name: 'save',
onClick: '$("#_edgarj_form").submit()',
value: t('edgarj.default.save'),
class: '_edgarj_form_save',})
#disabled: !permitted?(create_or_update)}.merge(options[:save]||{}))
end +
# search button
content_tag(:td) do
button_for_js(t('edgarj.default.search_form'), <<-JS,
$('#edgarj_form').hide();
$('#edgarj_search_form').show();
JS
{class: '_edgarj_form_search'}.merge(options[:search_form] ||{}))
end +
# clear button
content_tag(:td) do
button_to(t('edgarj.default.clear'),
{action: 'clear'},
{
method: :get,
remote: true,
})
end +
# delete button
content_tag(:td) do
button_to(t('edgarj.default.delete'),
if @record.new_record?
url_for('/')
else
url_for({
controller: params[:controller],
action: 'destroy',
id: @record.id})
end,
{
method: :delete,
remote: true,
data: {confirm: t('edgarj.form.delete_confirm')},
disabled: @record.new_record? # || !permitted?(cp_bitset::DELETE),
})
end
end
end
end | ruby | {
"resource": ""
} |
q4938 | Edgarj.FieldHelper.draw_field | train | def draw_field(f, col, options={})
case col.type
when :date
draw_date(f, col, options[:date] || {})
when :datetime
draw_datetime(f, col, options[:datetime] || {})
when :integer
f.text_field(col.name, options[:integer])
else
f.text_field(col.name, options[:text])
end
end | ruby | {
"resource": ""
} |
q4939 | Edgarj.FieldHelper.draw_datetime | train | def draw_datetime(f, col_or_sym, options={})
col_name = get_column_name(col_or_sym)
f.text_field(col_name,
value: datetime_fmt(f.object.send(col_name)))
end | ruby | {
"resource": ""
} |
q4940 | Edgarj.FieldHelper.draw_address | train | def draw_address(f, col_or_sym)
address_name = f.object.class.get_belongs_to_name(col_or_sym)
render('edgarj/address',
f: f,
rec: f.object,
address_name: address_name
)
end | ruby | {
"resource": ""
} |
q4941 | Edgarj.FieldHelper.draw_bitset | train | def draw_bitset(f, col, bitset=nil, options={})
html = ''
bitset = model.const_get(col_name.to_s.camelize + 'Bitset') if !bitset
i = 0
id_array_var = sprintf('%s_%s_var', f.object_name, col.name)
ids = []
for flag in bitset.constants do
checkbox_id = sprintf('%s_%s_%d', f.object_name, col.name, i)
html += draw_checkbox(f, checkbox_id, flag, bitset, id_array_var) +
label_tag(
checkbox_id,
f.object.class.human_const_name(bitset, flag)) +
' '.html_safe
ids << checkbox_id
i += 1
end
# draw hidden field to send sum-up value
html += f.hidden_field(col.name)
# add hidden-field name to ids' last
ids << sprintf("%s_%s", f.object_name, col.name)
# define arrays to calculate flags
html += "<script> var #{id_array_var}=[" +
ids.map{|id| "'" + id + "'"}.join(',') +
"];</script>"
html.html_safe
end | ruby | {
"resource": ""
} |
q4942 | Edgarj.FieldHelper.draw_enum | train | def draw_enum(f, col_or_sym, enum=nil, options={})
col_name = get_column_name(col_or_sym)
enum = model.const_get(col_name.to_s.camelize) if !enum
sorted_elements = enum.constants.sort{|a,b|
enum.const_get(a) <=> enum.const_get(b)}
options_for_select = options.dup
choice_1st = options_for_select.delete(:choice_1st)
class_4_human_const = options_for_select.delete(:class) || f.object.class
f.select(col_name,
(choice_1st ? [choice_1st] : []) +
sorted_elements.map{|member|
[class_4_human_const.human_const_name(enum, member),
enum.const_get(member)]},
options_for_select)
end | ruby | {
"resource": ""
} |
q4943 | Edgarj.FieldHelper.draw_checkbox | train | def draw_checkbox(f, id, flag, bitset, id_array_var)
val = f.object.send(:flags) || 0
flag_val = bitset.const_get(flag)
tag(:input,
type: 'checkbox',
id: id,
name: id,
value: flag_val,
onChange: "Edgarj.sum_bitset(#{id_array_var})",
checked: (val & flag_val) != 0 )
end | ruby | {
"resource": ""
} |
q4944 | Edgarj.FieldHelper.find_col | train | def find_col(rec, sym)
rec.class.columns.detect{|c| c.name == sym.to_s}
end | ruby | {
"resource": ""
} |
q4945 | Edgarj.FieldHelper.button_for_js | train | def button_for_js(label, js, html_options={})
tag(:input, {type: 'button', value: label, onClick: js}.merge(
html_options))
end | ruby | {
"resource": ""
} |
q4946 | TouRETS.Utilities.map_search_params | train | def map_search_params(search_params)
Hash[search_params.map {|k, v| [key_map[k], v] }]
end | ruby | {
"resource": ""
} |
q4947 | TouRETS.Utilities.value_map | train | def value_map(value)
v = case value.class
when Array
value.join(',')
when Range
"#{value.first}-#{value.last}"
when Hash
if value.has_key?(:or)
"|#{value[:or].join(',')}"
elsif value.has_key?(:not)
"~#{value[:not].join(',')}"
end
when TrueClass
"Y" # TODO: figure out if this should be Y or Yes
when FalseClass
"N" # TODO: figure out if this should be N or No
else
value
end
v
end | ruby | {
"resource": ""
} |
q4948 | Edgarj.EnumCache.label | train | def label(rec, attr, enum = nil)
if !enum
enum = rec.class.const_get(attr.to_s.camelize)
raise(NameError, "wrong constant name #{attr}") if !enum
end
if !@enum_map[enum]
@enum_map[enum] = {}
end
value = rec.attributes[attr.to_s]
if label = @enum_map[enum][value]
@hit += 1
label
else
member = enum.constants.detect{|m|
enum.const_get(m) == value
}
@enum_map[enum][value] =
if member
@out += 1
rec.class.human_const_name(enum, member)
else
@out_of_enum += 1
'??'
end
end
end | ruby | {
"resource": ""
} |
q4949 | ROF.CompareRof.rights_equal | train | def rights_equal(rights_attr)
f_rights = Array.wrap(fedora.fetch('rights', {}).fetch(rights_attr, [])).sort
b_rights = Array.wrap(bendo.fetch('rights', {}).fetch(rights_attr, [])).sort
return 0 if f_rights == b_rights
1
end | ruby | {
"resource": ""
} |
q4950 | ROF.CompareRof.compare_everything_else | train | def compare_everything_else
error_count =0
exclude_keys = ['rights', 'rels-ext', 'metadata', 'thumbnail-file']
all_keys_to_check = (bendo.keys + fedora.keys - exclude_keys).uniq
all_keys_to_check.each do |key|
bendo_value = bendo.fetch(key, nil)
fedora_value = fedora.fetch(key, nil)
# Treat an empty hash and an empty array as equal
next if bendo_value.empty? && fedora_value.empty?
next if normalize_value(bendo_value) == normalize_value(fedora_value)
error_count += 1
break
end
error_count
end | ruby | {
"resource": ""
} |
q4951 | ROF.CompareRof.normalize_value | train | def normalize_value(values)
Array.wrap(values).map do |value|
value.is_a?(String) ? value.gsub("\n", "") : value
end
end | ruby | {
"resource": ""
} |
q4952 | Edgarj.SearchPopup.conditions | train | def conditions
return ['1=0'] if !valid?
if @val.blank?
[]
else
# FIXME: assume type is just string
op = '=?'
val = @val
if val =~ /\*$/
op = ' like ?'
val = @val.gsub(/\*/, '%')
end
["#{@col}#{op}", val]
end
end | ruby | {
"resource": ""
} |
q4953 | React.Runner.start | train | def start
puts "== Connected to #{redis.client.id}"
puts "== Waiting for commands from `#{options[:queue]}`"
if options[:daemon]
puts "== Daemonizing..."
Daemons.daemonize
end
loop do
begin
cid = redis.blpop(options[:queue], 10)[1]
if cmd = commands[cid.to_s]
puts "\e[33m[#{Time.now}]\e[0m Reacting for `#{cid}` command"
threads.add(Thread.new { system(cmd) })
end
rescue Interrupt, SystemExit
puts "\nCleaning up..."
return 0
rescue => ex
puts "ERROR: #{ex}"
end
end
end | ruby | {
"resource": ""
} |
q4954 | SvnWc.RepoAccess.set_conf | train | def set_conf(conf)
begin
conf = load_conf(conf)
@svn_user = conf['svn_user']
@svn_pass = conf['svn_pass']
@force_checkout = conf['force_checkout']
@svn_repo_master = conf['svn_repo_master']
@svn_repo_working_copy = conf['svn_repo_working_copy']
@svn_repo_config_path = conf['svn_repo_config_path']
Svn::Core::Config.ensure(@svn_repo_config_path)
rescue Exception => e
raise RepoAccessError, 'errors loading conf file'
end
end | ruby | {
"resource": ""
} |
q4955 | SvnWc.RepoAccess.add | train | def add(files=[], recurse=true, force=false, no_ignore=false)
# TODO make sure args are what is expected for all methods
raise ArgumentError, 'files is empty' unless files
svn_session() do |svn|
begin
files.each do |ef|
svn.add(ef, recurse, force, no_ignore)
end
#rescue Svn::Error::ENTRY_EXISTS,
# Svn::Error::AuthnNoProvider,
# #Svn::Error::WcNotDirectory,
# Svn::Error::SvnError => e
rescue Exception => excp
raise RepoAccessError, "Add Failed: #{excp.message}"
end
end
end | ruby | {
"resource": ""
} |
q4956 | SvnWc.RepoAccess.delete | train | def delete(files=[], recurs=false)
svn_session() do |svn|
begin
svn.delete(files)
#rescue Svn::Error::AuthnNoProvider,
# #Svn::Error::WcNotDirectory,
# Svn::Error::ClientModified,
# Svn::Error::SvnError => e
rescue Exception => err
raise RepoAccessError, "Delete Failed: #{err.message}"
end
end
end | ruby | {
"resource": ""
} |
q4957 | SvnWc.RepoAccess.commit | train | def commit(files=[], msg='')
if files and files.empty? or files.nil? then files = self.svn_repo_working_copy end
rev = ''
svn_session(msg) do |svn|
begin
rev = svn.commit(files).revision
#rescue Svn::Error::AuthnNoProvider,
# #Svn::Error::WcNotDirectory,
# Svn::Error::IllegalTarget,
# #Svn::Error::EntryNotFound => e
# Exception => e
rescue Exception => err
raise RepoAccessError, "Commit Failed: #{err.message}"
end
end
rev
end | ruby | {
"resource": ""
} |
q4958 | SvnWc.RepoAccess._pre_update_entries | train | def _pre_update_entries #:nodoc:
@pre_up_entries = Array.new
@modified_entries = Array.new
list_entries.each do |ent|
##puts "#{ent[:status]} | #{ent[:repo_rev]} | #{ent[:entry_name]}"
e_name = ent[:entry_name]
stat = ent[:status]
if @limit_to_dir_path # limit files returned to this (and subdir's of) dir
fle = File.join(self.svn_repo_working_copy, e_name)
next unless fle.include? @limit_to_dir_path
end
@pre_up_entries.push e_name
## how does it handle deletes?
#if info()[:rev] != ent[:repo_rev]
# puts "changed file: #{File.join(paths, ent[:entry_name])} | #{ent[:status]} "
#end
if stat == 'M' then @modified_entries.push "#{stat}\t#{e_name}" end
end
end | ruby | {
"resource": ""
} |
q4959 | SvnWc.RepoAccess._post_update_entries | train | def _post_update_entries #:nodoc:
post_up_entries = Array.new
list_entries.each { |ent|
if @limit_to_dir_path # limit files returned to this (and subdir's of) dir
fle = File.join(self.svn_repo_working_copy, ent[:entry_name])
next unless fle.include? @limit_to_dir_path
end
post_up_entries.push ent[:entry_name]
}
added = post_up_entries - @pre_up_entries
removed = @pre_up_entries - post_up_entries
#raise "#{post_up_entries}\n#{@pre_up_entries}"
#raise "#{added} - #{removed}"
if added.length > 0
added.each {|e_add| @modified_entries.push "A\t#{e_add}" }
end
if removed.length > 0
removed.each {|e_rm| @modified_entries.push "D\t#{e_rm}" }
end
end | ruby | {
"resource": ""
} |
q4960 | SvnWc.RepoAccess.revert | train | def revert(file_path='')
if file_path.empty? then file_path = self.svn_repo_working_copy end
svn_session() { |svn| svn.revert(file_path) }
end | ruby | {
"resource": ""
} |
q4961 | Massimo.Resource.render | train | def render
extensions.reverse.inject(content) do |output, ext|
if template_type = Tilt[ext]
template_options = Massimo.config.options_for(ext[1..-1])
template = template_type.new(source_path.to_s, @line, template_options) { output }
template.render(template_scope, template_locals)
else
output
end
end
end | ruby | {
"resource": ""
} |
q4962 | Massimo.Resource.process | train | def process
FileUtils.mkdir_p(output_path.dirname)
output_path.open('w') do |f|
f.write render
end
end | ruby | {
"resource": ""
} |
q4963 | WebVideo.Transcoder.convert | train | def convert(destination, options = {}, &block)
options.symbolize_keys!
process(destination, @source.convert_command, options, &block)
end | ruby | {
"resource": ""
} |
q4964 | CheddarGetter.Response.customer_outstanding_invoices | train | def customer_outstanding_invoices(code = nil)
now = Time.now
customer_invoices(code).reject do |i|
i[:paidTransactionId] || i[:billingDatetime] > now
end
end | ruby | {
"resource": ""
} |
q4965 | CheddarGetter.Response.customer_item | train | def customer_item(item_code = nil, code = nil)
sub_item = retrieve_item(customer_subscription(code), :items, item_code)
plan_item = retrieve_item(customer_plan(code), :items, item_code)
return nil unless sub_item && plan_item
item = plan_item.dup
item[:quantity] = sub_item[:quantity]
item
end | ruby | {
"resource": ""
} |
q4966 | CheddarGetter.Response.customer_item_quantity_remaining | train | def customer_item_quantity_remaining(item_code = nil, code = nil)
item = customer_item(item_code, code)
item ? item[:quantityIncluded] - item[:quantity] : 0
end | ruby | {
"resource": ""
} |
q4967 | CheddarGetter.Response.customer_item_quantity_overage | train | def customer_item_quantity_overage(item_code = nil, code = nil)
over = -customer_item_quantity_remaining(item_code, code)
over = 0 if over <= 0
over
end | ruby | {
"resource": ""
} |
q4968 | CheddarGetter.Response.customer_item_quantity_overage_cost | train | def customer_item_quantity_overage_cost(item_code = nil, code = nil)
item = customer_item(item_code, code)
return 0 unless item
overage = customer_item_quantity_overage(item_code, code)
item[:overageAmount] * overage
end | ruby | {
"resource": ""
} |
q4969 | CheddarGetter.Response.customer_active? | train | def customer_active?(code = nil)
subscription = customer_subscription(code)
if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now
false
else
true
end
end | ruby | {
"resource": ""
} |
q4970 | CheddarGetter.Response.customer_waiting_for_paypal? | train | def customer_waiting_for_paypal?(code = nil)
subscription = customer_subscription(code)
if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now && subscription[:cancelType] == 'paypal-wait'
true
else
false
end
end | ruby | {
"resource": ""
} |
q4971 | Jinda.GemHelpers.process_controllers | train | def process_controllers
process_services
modules= Jinda::Module.all
modules.each do |m|
next if controller_exists?(m.code)
puts " Rails generate controller #{m.code}"
end
end | ruby | {
"resource": ""
} |
q4972 | Edgarj.RescueMixin.edgarj_rescue_sub | train | def edgarj_rescue_sub(ex, message)
logger.info(
"#{ex.class} #{ex.message} bactrace:\n " +
ex.backtrace.join("\n "))
respond_to do |format|
format.html {
flash[:error] = message
redirect_to top_path
}
format.js {
flash.now[:error] = message
render 'message_popup'
}
end
end | ruby | {
"resource": ""
} |
q4973 | FreshdeskAPI.Read.find! | train | def find!(client, options = {})
@client = client # so we can use client.logger in rescue
raise ArgumentError, 'No :id given' unless options[:id]
path = api_url(options) + "/#{options[:id]}"
response = client.make_request!(path, :get)
new(@client).tap do |resource|
resource.attributes.merge!(options)
resource.handle_response(response)
end
end | ruby | {
"resource": ""
} |
q4974 | FreshdeskAPI.Read.find | train | def find(client, options = {}, &block)
find!(client, options, &block)
rescue FreshdeskAPI::Error::ClientError
nil
end | ruby | {
"resource": ""
} |
q4975 | ActsAsObfuscated.ClassMethods.deobfuscate | train | def deobfuscate(original, rescue_with_original_id = true)
if original.kind_of?(Array)
return original.map { |value| deobfuscate(value, true) } # Always rescue with original ID
elsif !(original.kind_of?(Integer) || original.kind_of?(String))
return original
end
# Remove any non-digit formatting characters, and only consider the first 10 digits
obfuscated_id = original.to_s.delete('^0-9').first(10)
# 2147483647 is PostgreSQL's Integer Max Value. If we return a value higher than this, we get weird DB errors
revealed = [EffectiveObfuscation.show(obfuscated_id, acts_as_obfuscated_opts[:spin]).to_i, 2147483647].min
if rescue_with_original_id && (revealed >= 2147483647 || revealed > deobfuscated_maximum_id)
original
else
revealed
end
end | ruby | {
"resource": ""
} |
q4976 | CatarseStripe::Payment.StripeController.callback | train | def callback
@stripe_user = current_user
code = params[:code]
@response = @client.auth_code.get_token(code, {
:headers => {'Authorization' => "Bearer(::Configuration['stripe_secret_key'])"} #Platform Secret Key
})
#Save PROJECT owner's new keys
@stripe_user.stripe_access_token = @response.token
@stripe_user.stripe_key = @response.params['stripe_publishable_key']
@stripe_user.stripe_userid = @response.params['stripe_user_id']
@stripe_user.save
return redirect_to payment_stripe_auth_path(@stripe_user)
rescue Stripe::AuthenticationError => e
::Airbrake.notify({ :error_class => "Stripe #Pay Error", :error_message => "Stripe #Pay Error: #{e.inspect}", :parameters => params}) rescue nil
Rails.logger.info "-----> #{e.inspect}"
flash[:error] = e.message
return redirect_to main_app.user_path(@stripe_user)
end | ruby | {
"resource": ""
} |
q4977 | DataMapper.Collection.adjust! | train | def adjust!(attributes = {}, reload = false)
return true if attributes.empty?
reload_conditions = if reload
model_key = model.key(repository.name)
Query.target_conditions(self, model_key, model_key)
end
adjust_attributes = adjust_attributes(attributes)
repository.adjust(adjust_attributes, self)
if reload_conditions
@query.clear
@query.update(:conditions => reload_conditions)
self.reload
end
true
end | ruby | {
"resource": ""
} |
q4978 | Languages.FunctionAbstract.add_parameters | train | def add_parameters(pValue)
unless ((pValue.respond_to?(:has_key?) && pValue.length == 1) ||
pValue.respond_to?(:to_str))
return nil
end
@parameters.push(pValue)
end | ruby | {
"resource": ""
} |
q4979 | Languages.FunctionAbstract.add_conditional | train | def add_conditional(pConditional, pBehaviour = Languages::KEEP_LEVEL)
return nil unless (pConditional.instance_of?Languages::ConditionalData)
add_with_manager(pConditional, 'conditional', pBehaviour)
end | ruby | {
"resource": ""
} |
q4980 | Languages.FunctionAbstract.add_repetition | train | def add_repetition(pRepetition, pBehaviour = Languages::KEEP_LEVEL)
return nil unless (pRepetition.instance_of?Languages::RepetitionData)
add_with_manager(pRepetition, 'repetition', pBehaviour)
end | ruby | {
"resource": ""
} |
q4981 | Languages.FunctionAbstract.add_block | train | def add_block(pBlock, pBehaviour = Languages::KEEP_LEVEL)
return nil unless (pBlock.instance_of?Languages::BlockData)
add_with_manager(pBlock, 'block', pBehaviour)
end | ruby | {
"resource": ""
} |
q4982 | Languages.FunctionAbstract.<< | train | def <<(fromTo)
return nil unless fromTo.is_a?(Languages::FunctionAbstract)
@name = fromTo.name
@parameters = fromTo.parameters
@managerCondLoopAndBlock = fromTo.managerCondLoopAndBlock
@visibility = fromTo.visibility
@comments = fromTo.comments
@type = @type
end | ruby | {
"resource": ""
} |
q4983 | Languages.FunctionAbstract.add_with_manager | train | def add_with_manager(pElementToAdd, pMetaData, pBehaviour)
case pBehaviour
when Languages::KEEP_LEVEL
@managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd)
when Languages::UP_LEVEL
@managerCondLoopAndBlock.decrease_deep_level
@managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd)
when Languages::DOWN_LEVEL
@managerCondLoopAndBlock.increase_deep_level
@managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd)
end
end | ruby | {
"resource": ""
} |
q4984 | NewsScraper.ExtractorsHelpers.http_request | train | def http_request(url)
url = URIParser.new(url).with_scheme
CLI.put_header(url)
CLI.log "Beginning HTTP request for #{url}"
response = HTTParty.get(url, headers: { "User-Agent" => "news-scraper-#{NewsScraper::VERSION}" })
raise ResponseError.new(
error_code: response.code,
message: response.message,
url: url
) unless response.code == 200
CLI.log "#{response.code} - #{response.message}. Request successful for #{url}"
CLI.put_footer
if block_given?
yield response
else
response
end
end | ruby | {
"resource": ""
} |
q4985 | TranslatorText.Client.detect | train | def detect(sentences)
results = post(
'/detect',
body: build_sentences(sentences).to_json
)
results.map { |r| Types::DetectionResult.new(r) }
end | ruby | {
"resource": ""
} |
q4986 | Literati.MarkdownRenderer.determine_markdown_renderer | train | def determine_markdown_renderer
@markdown = if installed?('github/markdown')
GitHubWrapper.new(@content)
elsif installed?('redcarpet/compat')
Markdown.new(@content, :fenced_code, :safelink, :autolink)
elsif installed?('redcarpet')
RedcarpetCompat.new(@content)
elsif installed?('rdiscount')
RDiscount.new(@content)
elsif installed?('maruku')
Maruku.new(@content)
elsif installed?('kramdown')
Kramdown::Document.new(@content)
elsif installed?('bluecloth')
BlueCloth.new(@content)
end
end | ruby | {
"resource": ""
} |
q4987 | Literati.Renderer.to_markdown | train | def to_markdown
lines = @bare_content.split("\n")
markdown = ""
# Using `while` here so we can alter the collection at will
while current_line = lines.shift
# If we got us some of them bird tracks...
if current_line =~ BIRD_TRACKS_REGEX
# Remove the bird tracks from this line
current_line = remove_bird_tracks(current_line)
# Grab the remaining code block
current_line << slurp_remaining_bird_tracks(lines)
# Fence it and add it to the output
markdown << "```haskell\n#{current_line}\n```\n"
else
# No tracks? Just stick it back in the pile.
markdown << current_line + "\n"
end
end
markdown
end | ruby | {
"resource": ""
} |
q4988 | Literati.Renderer.remove_bird_tracks | train | def remove_bird_tracks(line)
tracks = line.scan(BIRD_TRACKS_REGEX)[0]
(tracks.first == " ") ? tracks[1] : tracks.join
end | ruby | {
"resource": ""
} |
q4989 | Literati.Renderer.slurp_remaining_bird_tracks | train | def slurp_remaining_bird_tracks(lines)
tracked_lines = []
while lines.first =~ BIRD_TRACKS_REGEX
tracked_lines << remove_bird_tracks(lines.shift)
end
if tracked_lines.empty?
""
else
"\n" + tracked_lines.join("\n")
end
end | ruby | {
"resource": ""
} |
q4990 | CPU.UsageSampler.sample | train | def sample
total, @usages = nil, {}
timestamp = Time.now
File.foreach('/proc/stat') do |line|
case line
when /^cpu[^\d]/
next
when CPU
times = $~.captures
processor_id = times[0] = times[0].to_i
(1...times.size).each { |i| times[i] = times[i].to_f / USER_HZ }
times << timestamp << timestamp
@usages[processor_id] = Usage.new(self, *times)
else
break
end
end
if @usages.empty?
raise NoSampleDataError, "could not sample measurement data"
end
self
end | ruby | {
"resource": ""
} |
q4991 | Datey.Formatter.include_year_in_dates? | train | def include_year_in_dates?
if @time.year != Date.today.year
# If the year was in the past, always include the year
return true
end
if @time.year == Date.today.year && @time.month < (Date.today.month - 4)
# If the year is this year, include if it happened more than 6 months
# ago.
return true
end
end | ruby | {
"resource": ""
} |
q4992 | PaynetEasy::PaynetEasyApi::Transport.GatewayClient.parse_response | train | def parse_response(response)
unless response.body
raise ResponseError, 'PaynetEasy response is empty'
end
# Change hash format from {'key' => ['value']} to {'key' => 'value'} in map block
response_fields = Hash[CGI.parse(response.body).map {|key, value| [key, value.first]}]
Response.new response_fields
end | ruby | {
"resource": ""
} |
q4993 | GithubPivotalFlow.Finish.run! | train | def run!
raise_error_if_development_or_master
story = @configuration.story
fail("Could not find story associated with branch") unless story
story.can_merge?
commit_message = options[:commit_message]
if story.release?
story.merge_release!(commit_message, @options)
else
story.merge_to_roots!(commit_message, @options)
end
return 0
end | ruby | {
"resource": ""
} |
q4994 | Elk.SMS.reload | train | def reload
response = @client.get("/SMS/#{self.message_id}")
self.set_parameters(Elk::Util.parse_json(response.body))
response.code == 200
end | ruby | {
"resource": ""
} |
q4995 | Cul::Omniauth::Users.ClassMethods.find_for_provider | train | def find_for_provider(token, provider)
return nil unless token['uid']
props = {:uid => token['uid'].downcase, provider: provider.downcase}
user = where(props).first
# create new user if necessary
unless user
user = create!(whitelist(props))
# can we add groups or roles here?
end
user
end | ruby | {
"resource": ""
} |
q4996 | ParseFasta.Record.to_fastq | train | def to_fastq opts = {}
if fastq?
"@#{@header}\n#{@seq}\n+#{@desc}\n#{qual}"
else
qual = opts.fetch :qual, "I"
check_qual qual
desc = opts.fetch :desc, ""
qual_str = make_qual_str qual
"@#{@header}\n#{@seq}\n+#{desc}\n#{qual_str}"
end
end | ruby | {
"resource": ""
} |
q4997 | Tableau.ModuleParser.module_info | train | def module_info
mod, types = parse, Set.new
mod.classes.each { |c| types.add?(c.type) }
return { name: mod.name, code: mod.module_id, types: types }
end | ruby | {
"resource": ""
} |
q4998 | Edgarj.EdgarjController.create | train | def create
upsert do
# NOTE: create!() is not used because assign to @record to draw form.
# Otherwise, @record would be in nil so failure at edgarj/_form rendering.
#
# NOTE2: valid? after create() calls validate_on_update. This is not
# an expected behavior. So, new, valid?, then save.
@record = model.new(permitted_params(:create))
@record_saved = @record # copy for possible later use
on_upsert
#upsert_files
raise ActiveRecord::RecordNotSaved if !@record.valid?
@record.save
# clear @record values for next data-entry
@record = model.new
end
end | ruby | {
"resource": ""
} |
q4999 | Edgarj.EdgarjController.show | train | def show
@record = user_scoped.find(params[:id])
#add_topic_path
respond_to do |format|
format.html {
prepare_list
@search = page_info.record
render :action=>'index'
}
format.js
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.