_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q24200 | Wavefront.ApiCaller.post | train | def post(path, body = nil, ctype = 'text/plain')
body = body.to_json unless body.is_a?(String)
make_call(mk_conn(path, 'Content-Type': ctype,
'Accept': 'application/json'),
:post, nil, body)
end | ruby | {
"resource": ""
} |
q24201 | Wavefront.ApiCaller.put | train | def put(path, body = nil, ctype = 'application/json')
make_call(mk_conn(path, 'Content-Type': ctype,
'Accept': 'application/json'),
:put, nil, body.to_json)
end | ruby | {
"resource": ""
} |
q24202 | Wavefront.ApiCaller.verbosity | train | def verbosity(conn, method, *args)
return unless noop || verbose
log format('uri: %s %s', method.upcase, conn.url_prefix)
return unless args.last && !args.last.empty?
log method == :get ? "params: #{args.last}" : "body: #{args.last}"
end | ruby | {
"resource": ""
} |
q24203 | CucumberAnalytics.Outline.to_s | train | def to_s
text = ''
text << tag_output_string + "\n" unless tags.empty?
text << "Scenario Outline:#{name_output_string}"
text << "\n" + description_output_string unless description_text.empty?
text << "\n" unless steps.empty? || description_text.empty?
text << "\n" + steps_output_string unless steps.empty?
text << "\n\n" + examples_output_string unless examples.empty?
text
end | ruby | {
"resource": ""
} |
q24204 | Wavefront.MetricHelper.dist | train | def dist(path, interval, value, tags = nil)
key = [path, interval, tags]
@buf[:dists][key] += [value].flatten
end | ruby | {
"resource": ""
} |
q24205 | Wavefront.MetricHelper.flush_gauges | train | def flush_gauges(gauges)
return if gauges.empty?
to_flush = gauges.dup
@buf[:gauges] = empty_gauges
writer.write(gauges_to_wf(gauges)).tap do |resp|
@buf[:gauges] += to_flush unless resp.ok?
end
end | ruby | {
"resource": ""
} |
q24206 | Wavefront.MetricHelper.replay_counters | train | def replay_counters(buffer)
buffer.each { |k, v| counter(k[0], v, k[1]) }
end | ruby | {
"resource": ""
} |
q24207 | Hornetseye.Malloc.+ | train | def +( offset )
if offset > @size
raise "Offset must not be more than #{@size} (but was #{offset})"
end
mark, size = self, @size - offset
retval = orig_plus offset
retval.instance_eval { @mark, @size = mark, size }
retval
end | ruby | {
"resource": ""
} |
q24208 | Hornetseye.Malloc.write | train | def write( data )
if data.is_a? Malloc
if data.size > @size
raise "Must not write more than #{@size} bytes of memory " +
"(illegal attempt to write #{data.size} bytes)"
end
orig_write data, data.size
else
if data.bytesize > @size
raise "Must not write more than #{@size} bytes of memory " +
"(illegal attempt to write #{data.bytesize} bytes)"
end
orig_write data
end
end | ruby | {
"resource": ""
} |
q24209 | CucumberAnalytics.Example.to_s | train | def to_s
text = ''
text << tag_output_string + "\n" unless tags.empty?
text << "Examples:#{name_output_string}"
text << "\n" + description_output_string unless description_text.empty?
text << "\n" unless description_text.empty?
text << "\n" + parameters_output_string
text << "\n" + rows_output_string unless rows.empty?
text
end | ruby | {
"resource": ""
} |
q24210 | Wavefront.CoreApi.time_to_ms | train | def time_to_ms(time)
return false unless time.is_a?(Integer)
return time if time.to_s.size == 13
(time.to_f * 1000).round
end | ruby | {
"resource": ""
} |
q24211 | BoxGrinder.FSMonitor.capture | train | def capture(*observers, &block)
@lock_a.synchronize do
add_observers(observers)
_capture(&block)
if block_given?
yield
_stop
end
end
end | ruby | {
"resource": ""
} |
q24212 | BoxGrinder.FSMonitor.alias_and_capture | train | def alias_and_capture(klazz, m_sym, flag, &blk)
alias_m_sym = "__alias_#{m_sym}"
klazz.class_eval do
alias_method alias_m_sym, m_sym
define_method(m_sym) do |*args, &blx|
response = send(alias_m_sym, *args, &blx)
blk.call(self, *args) if flag.get_set
response
end
end
end | ruby | {
"resource": ""
} |
q24213 | BoxGrinder.RPMVersion.newest | train | def newest(versions)
versions.sort { |x,y| compare(x,y) }.last
end | ruby | {
"resource": ""
} |
q24214 | BoxGrinder.LinuxHelper.partition_mount_points | train | def partition_mount_points(partitions)
partitions.keys.sort do |a, b|
a_count = a.count('/')
b_count = b.count('/')
if a_count > b_count
v = 1
else
if a_count < b_count
v = -1
else
if a.length == b.length
v = a <=> b
else
v = a.length <=> b.length
end
end
end
# This forces having swap partition at the end of the disk
v = 1 if a_count == 0
v = -1 if b_count == 0
v
end
end | ruby | {
"resource": ""
} |
q24215 | Consular.Terminator.process! | train | def process!
windows = @termfile[:windows]
default = windows.delete('default')
execute_window(default, :default => true) unless default[:tabs].empty?
windows.each_pair { |_, cont| execute_window(cont) }
end | ruby | {
"resource": ""
} |
q24216 | HasTrolleyControllerHelpersOverrides.UrlFor.url_for_trolley | train | def url_for_trolley(options = { })
return url_for_dc_identifier(@purchasable_item) if @purchasable_item && params[:action] == 'create'
user = options.delete(:user)
trolley = options[:trolley] || @trolley || user.trolley
if trolley.blank?
user = @user
else
user = trolley.user
end
options[:user_id] = user.id
options[:controller] = 'trolleys'
options[:action] = 'show'
options[:urlified_name] = Basket.site_basket.urlified_name
url = url_for(options) # .split(".%23%")[0]
end | ruby | {
"resource": ""
} |
q24217 | HasTrolleyControllerHelpersOverrides.UrlFor.url_for_order | train | def url_for_order(options = { })
trolley = options.delete(:trolley) || @trolley
trolley = @order.trolley if @order
order = options.delete(:order) || @order || trolley.selected_order
options[:id] = order
options[:controller] = 'orders'
options[:action] = 'show'
options[:urlified_name] = Basket.site_basket.urlified_name
url_for options
end | ruby | {
"resource": ""
} |
q24218 | EbayTrader.SessionID.sign_in_url | train | def sign_in_url(ruparams = {})
url = []
url << EbayTrader.configuration.production? ? 'https://signin.ebay.com' : 'https://signin.sandbox.ebay.com'
url << '/ws/eBayISAPI.dll?SignIn'
url << "&runame=#{url_encode ru_name}"
url << "&SessID=#{url_encode id}"
if ruparams && ruparams.is_a?(Hash) && !ruparams.empty?
params = []
ruparams.each_pair { |key, value| params << "#{key}=#{value}" }
url << "&ruparams=#{url_encode(params.join('&'))}"
end
url.join
end | ruby | {
"resource": ""
} |
q24219 | JMX.MBean.method_missing | train | def method_missing(method, *args, &block) #:nodoc:
method_in_snake_case = method.to_s.snake_case # this way Java/JRuby styles are compatible
if @operations.keys.include?(method_in_snake_case)
op_name, param_types = @operations[method_in_snake_case]
@connection.invoke @object_name,
op_name,
args.to_java(:Object),
param_types.to_java(:String)
else
super
end
end | ruby | {
"resource": ""
} |
q24220 | GitHub.PullRequest.create | train | def create(base, head, title, body)
logger.info { "Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}." }
begin
return sym_hash_JSON(client.create_pull_request(repo, base, head, title, body))
rescue Octokit::UnprocessableEntity => exp
pull = pull_requests.find { |p| p[:head][:ref] == head and p[:base][:ref] == base }
if pull
logger.warn { "Pull request already exists. See #{pull[:html_url]}" }
else
logger.warn { "UnprocessableEntity: #{exp}" }
end
return pull
end
end | ruby | {
"resource": ""
} |
q24221 | Vagalume.Song.remove_title | train | def remove_title(lyric)
lines = lyric.lines
lines.shift
lines = remove_empty_lines_from_beginning(lines)
lines.join
end | ruby | {
"resource": ""
} |
q24222 | InlineForms.InlineFormsGenerator.set_some_flags | train | def set_some_flags
@flag_not_accessible_through_html = true
@flag_create_migration = true
@flag_create_model = true
@create_id = true
for attribute in attributes
@flag_not_accessible_through_html = false if attribute.name == '_enabled'
@flag_create_migration = false if attribute.name == '_no_migration'
@flag_create_model = false if attribute.name == '_no_model'
@create_id = false if attribute.name == "_id" && attribute.type == :false
end
@flag_create_controller = @flag_create_model
@flag_create_resource_route = @flag_create_model
end | ruby | {
"resource": ""
} |
q24223 | RackCASRails.ActionControllerBaseAdditions.login_url | train | def login_url(service_url=request.url)
url = URI(Rails.application.cas_server_url)
url.path = "/login"
url.query = "service=#{service_url || request.url}"
url.to_s
end | ruby | {
"resource": ""
} |
q24224 | EbayTrader.SaxHandler.format_key | train | def format_key(key)
key = key.to_s
key = key.gsub('PayPal', 'Paypal')
key = key.gsub('eBay', 'Ebay')
key = key.gsub('EBay', 'Ebay')
key.underscore.to_sym
end | ruby | {
"resource": ""
} |
q24225 | GitProc.GitLib.push_to_server | train | def push_to_server(local_branch, remote_branch, opts = {})
if opts[:local]
logger.debug('Not pushing to the server because the user selected local-only.')
elsif not has_a_remote?
logger.debug('Not pushing to the server because there is no remote.')
elsif local_branch == config.master_branch
logger.warn('Not pushing to the server because the current branch is the mainline branch.')
else
opts[:prepush].call if opts[:prepush]
push(remote.name, local_branch, remote_branch, :force => opts[:force])
opts[:postpush].call if opts[:postpush]
end
end | ruby | {
"resource": ""
} |
q24226 | GitProc.GitLib.branch | train | def branch(branch_name, opts = {})
if branch_name
if opts[:delete]
return delete_branch(branch_name, opts[:force])
elsif opts[:rename]
return rename_branch(branch_name, opts[:rename])
elsif opts[:upstream]
return set_upstream_branch(branch_name, opts[:upstream])
else
base_branch = opts[:base_branch] || 'master'
if opts[:force]
return change_branch(branch_name, base_branch)
else
return create_branch(branch_name, base_branch)
end
end
else
#list_branches(opts)
return list_branches(opts[:all], opts[:remote], opts[:no_color])
end
end | ruby | {
"resource": ""
} |
q24227 | GitProc.GitLib.remove | train | def remove(files, opts = {})
args = []
args << '-f' if opts[:force]
args << [*files]
command(:rm, args)
end | ruby | {
"resource": ""
} |
q24228 | GitProc.GitLib.write_sync_control_file | train | def write_sync_control_file(branch_name)
latest_sha = rev_parse(branch_name)
filename = sync_control_filename(branch_name)
logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" }
File.open(filename, 'w') { |f| f.puts latest_sha }
end | ruby | {
"resource": ""
} |
q24229 | GitProc.GitLib.delete_sync_control_file! | train | def delete_sync_control_file!(branch_name)
filename = sync_control_filename(branch_name)
logger.debug { "Deleting sync control file, #{filename}" }
# on some systems, especially Windows, the file may be locked. wait for it to unlock
counter = 10
while counter > 0
begin
File.delete(filename)
counter = 0
rescue
counter = counter - 1
sleep(0.25)
end
end
end | ruby | {
"resource": ""
} |
q24230 | GitProc.GitLib.create_git_command | train | def create_git_command(cmd, opts, redirect)
opts = [opts].flatten.map { |s| escape(s) }.join(' ')
return "git #{cmd} #{opts} #{redirect} 2>&1"
end | ruby | {
"resource": ""
} |
q24231 | Metasploit::Model::Search::With.ClassMethods.search_with | train | def search_with(operator_class, options={})
merged_operations = options.merge(
:klass => self
)
operator = operator_class.new(merged_operations)
operator.valid!
search_with_operator_by_name[operator.name] = operator
end | ruby | {
"resource": ""
} |
q24232 | Philtre.PlaceHolder.to_s_append | train | def to_s_append( ds, s )
s << '$' << name.to_s
s << ':' << sql_field.to_s if sql_field
s << '/*' << small_source << '*/'
end | ruby | {
"resource": ""
} |
q24233 | Philtre.Filter.call | train | def call( dataset )
# mainly for Sequel::Model
dataset = dataset.dataset if dataset.respond_to? :dataset
# clone here so later order! calls don't mess with a Model's default dataset
dataset = expressions.inject(dataset.clone) do |dataset, filter_expr|
dataset.filter( filter_expr )
end
# preserve existing order if we don't have one.
if order_clause.empty?
dataset
else
# There might be multiple orderings in the order_clause
dataset.order *order_clause
end
end | ruby | {
"resource": ""
} |
q24234 | Philtre.Filter.valued_parameters | train | def valued_parameters
@valued_parameters ||= filter_parameters.select do |key,value|
# :order is special, it must always be excluded
key.to_sym != :order && valued_parameter?(key,value)
end
end | ruby | {
"resource": ""
} |
q24235 | Philtre.Filter.to_h | train | def to_h(all=false)
filter_parameters.select{|k,v| all || !v.blank?}
end | ruby | {
"resource": ""
} |
q24236 | Philtre.Filter.expr_hash | train | def expr_hash
vary = valued_parameters.map do |key, value|
[ key, to_expr(key, value) ]
end
Hash[ vary ]
end | ruby | {
"resource": ""
} |
q24237 | Jserializer.Base.serializable_hash | train | def serializable_hash
return serializable_collection if collection?
self.class._attributes.each_with_object({}) do |(name, option), hash|
if _include_from_options?(name) && public_send(option[:include_method])
hash[option[:key] || name] = _set_value(name, option)
end
end
end | ruby | {
"resource": ""
} |
q24238 | GitProc.GitBranch.delete! | train | def delete!(force = false)
if local?
@lib.branch(@name, :force => force, :delete => true)
else
@lib.push(Process.server_name, nil, nil, :delete => @name)
end
end | ruby | {
"resource": ""
} |
q24239 | Metasploit::Model::Search.ClassMethods.search_operator_by_name | train | def search_operator_by_name
unless instance_variable_defined? :@search_operator_by_name
@search_operator_by_name = {}
search_with_operator_by_name.each_value do |operator|
@search_operator_by_name[operator.name] = operator
end
search_association_operators.each do |operator|
@search_operator_by_name[operator.name] = operator
end
end
@search_operator_by_name
end | ruby | {
"resource": ""
} |
q24240 | EbayTrader.XMLBuilder.root | train | def root(name, *args, &block)
set_context(&block)
node(name, args, &block)
end | ruby | {
"resource": ""
} |
q24241 | EbayTrader.XMLBuilder.node | train | def node(name, args, &block)
content = get_node_content(args)
options = format_node_attributes(get_node_attributes(args))
@_segments ||= []
@_segments << "#{indent_new_line}<#{name}#{options}>#{content}"
if block_given?
@depth += 1
instance_eval(&block)
@depth -= 1
@_segments << indent_new_line
end
@_segments << "</#{name}>"
@xml = @_segments.join('').strip
end | ruby | {
"resource": ""
} |
q24242 | EbayTrader.XMLBuilder.get_node_content | train | def get_node_content(args)
return nil if block_given?
content = nil
args.each do |arg|
case arg
when Hash
next
when Time
# eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
when DateTime
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
break
else
content = arg.to_s
break
end
end
content
end | ruby | {
"resource": ""
} |
q24243 | EbayTrader.XMLBuilder.format_node_attributes | train | def format_node_attributes(options)
options.collect { |key, value|
value = value.to_s.gsub('"', '\"')
" #{key}=\"#{value}\""
}.join('')
end | ruby | {
"resource": ""
} |
q24244 | Mailigen.Api.call | train | def call method, params = {}
url = "#{api_url}&method=#{method}"
params = {apikey: self.api_key}.merge params
resp = post_api(url, params)
begin
return JSON.parse(resp)
rescue
return resp.tr('"','')
end
end | ruby | {
"resource": ""
} |
q24245 | Mailigen.Api.post_api | train | def post_api url, params
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = self.secure
form_params = params.to_query
res = http.post(uri.request_uri, form_params)
res.body
end | ruby | {
"resource": ""
} |
q24246 | ApiExplorer.ApiController.read_file | train | def read_file
json_string = ''
if ApiExplorer::use_file
json_path = ApiExplorer::json_path
json_string = File.read(json_path)
else
json_string = ApiExplorer::json_string
end
@methods = JSON.parse(json_string)["methods"]
end | ruby | {
"resource": ""
} |
q24247 | Phoney.Formatter.format | train | def format(input, pattern, options={})
fill = options[:fill]
intl_prefix = options[:intl_prefix]||''
trunk_prefix = options[:trunk_prefix]||''
slots = pattern.count(PLACEHOLDER_CHAR)
# Return original input if it is too long
return input if (fill.nil? && input.length > slots)
# Pad and clone the string if necessary.
source = (fill.nil? || fill.empty?) ? input : input.ljust(slots, fill)
result = ''
slot = 0
has_open = had_c = had_n = false
pattern.split('').each_with_index do |chr, index|
case chr
when 'c'
had_c = true
result << intl_prefix
when 'n'
had_n = true
result << trunk_prefix
when '#'
if slot < source.length
result << source[slot]
slot += 1
else
result << ' ' if has_open
end
when '('
if slot < source.length
has_open = true
result << chr
end
when ')'
if (slot < source.length || has_open)
has_open = false
result << chr
end
else
# Don't show space after n if no trunk prefix or after c if no intl prefix
next if (chr == ' ' && pattern[index-1] == 'n' && trunk_prefix.empty?)
next if (chr == ' ' && pattern[index-1] == 'c' && intl_prefix.empty?)
result << chr if (slot < source.length)
end
end
# Not all format strings have a 'c' or 'n' in them.
# If we have an international prefix or a trunk prefix but the format string
# doesn't explictly say where to put it then simply add it to the beginning.
result.prepend trunk_prefix if (!had_n && !trunk_prefix.empty?)
result.prepend "#{intl_prefix} " if (!had_c && !intl_prefix.empty?)
result.strip
end | ruby | {
"resource": ""
} |
q24248 | GitHubService.Configuration.configure_octokit | train | def configure_octokit(opts = {})
base_url = opts[:base_url] || base_github_api_url_for_remote
Octokit.configure do |c|
c.api_endpoint = api_endpoint(base_url)
c.web_endpoint = web_endpoint(base_url)
end
if logger.level < ::GitProc::GitLogger::INFO
Octokit.middleware = Faraday::RackBuilder.new do |builder|
builder.response :logger, logger
builder.use Octokit::Response::RaiseError
builder.adapter Faraday.default_adapter
end
end
end | ruby | {
"resource": ""
} |
q24249 | GitHubService.Configuration.create_pw_client | train | def create_pw_client(opts = {})
usr = opts[:user] || user()
pw = opts[:password] || password()
remote = opts[:remote_name] || self.remote_name
logger.info("Authorizing #{usr} to work with #{remote}.")
configure_octokit(opts)
Octokit::Client.new(:login => usr, :password => pw)
end | ruby | {
"resource": ""
} |
q24250 | GitHubService.Configuration.unprocessable_authorization | train | def unprocessable_authorization(exp)
errors = exp.errors
if not (errors.nil? or errors.empty?)
error_hash = errors[0]
if error_hash[:resource] == 'OauthAccess'
# error_hash[:code]
return ask_about_resetting_authorization
else
raise exp
end
else
raise exp
end
end | ruby | {
"resource": ""
} |
q24251 | Metasploit::Model::Association.ClassMethods.association | train | def association(name, options={})
association = Metasploit::Model::Association::Reflection.new(
:model => self,
:name => name.to_sym,
:class_name => options[:class_name]
)
association.valid!
association_by_name[association.name] = association
end | ruby | {
"resource": ""
} |
q24252 | Annex.ViewHelpers.annex_block | train | def annex_block(identifier, opts = {})
opts[:route] ||= current_route
case Annex::config[:adapter]
when :activerecord
doc = Annex::Block.where(route: "#{opts[:route]}_#{identifier}").first_or_create
content = doc.content
when :mongoid
doc = Annex::Block.where(route: opts[:route]).first_or_create
content = doc.content.try(:[], identifier.to_s)
end
render partial: 'annex/block', locals: { content: content || opts[:default], identifier: identifier, opts: opts }
end | ruby | {
"resource": ""
} |
q24253 | GitProc.GitRemote.repo_name | train | def repo_name
unless @repo_name
url = config["remote.#{name}.url"]
raise GitProcessError.new("There is no #{name} url set up.") if url.nil? or url.empty?
uri = Addressable::URI.parse(url)
@repo_name = uri.path.sub(/\.git/, '').sub(/^\//, '')
end
@repo_name
end | ruby | {
"resource": ""
} |
q24254 | GitProc.GitRemote.remote_name | train | def remote_name
unless @remote_name
@remote_name = config['gitProcess.remoteName']
if @remote_name.nil? or @remote_name.empty?
remotes = self.remote_names
if remotes.empty?
@remote_name = nil
else
@remote_name = remotes[0]
raise "remote name is not a String: #{@remote_name.inspect}" unless @remote_name.is_a? String
end
end
logger.debug { "Using remote name of '#{@remote_name}'" }
end
@remote_name
end | ruby | {
"resource": ""
} |
q24255 | GitProc.GitRemote.expanded_url | train | def expanded_url(server_name = 'origin', raw_url = nil, opts = {})
if raw_url.nil?
raise ArgumentError.new('Need server_name') unless server_name
conf_key = "remote.#{server_name}.url"
url = config[conf_key]
raise GitHubService::NoRemoteRepository.new("There is no value set for '#{conf_key}'") if url.nil? or url.empty?
else
raise GitHubService::NoRemoteRepository.new("There is no value set for '#{raw_url}'") if raw_url.nil? or raw_url.empty?
url = raw_url
end
if /^\S+@/ =~ url
url.sub(/^(\S+@\S+?):(.*)$/, "ssh://\\1/\\2")
else
uri = URI.parse(url)
host = uri.host
scheme = uri.scheme
raise URI::InvalidURIError.new("Need a scheme in URI: '#{url}'") unless scheme
if scheme == 'file'
url
elsif host.nil?
# assume that the 'scheme' is the named configuration in ~/.ssh/config
rv = GitRemote.hostname_and_user_from_ssh_config(scheme, opts[:ssh_config_file] ||= "#{ENV['HOME']}/.ssh/config")
raise GitHubService::NoRemoteRepository.new("Could not determine a host from #{url}") if rv.nil?
host = rv[0]
user = rv[1]
url.sub(/^\S+:(\S+)$/, "ssh://#{user}@#{host}/\\1")
else
url
end
end
end | ruby | {
"resource": ""
} |
q24256 | EbayTrader.Request.to_s | train | def to_s(indent = xml_tab_width)
xml = ''
if defined? Ox
ox_doc = Ox.parse(xml_response)
xml = Ox.dump(ox_doc, indent: indent)
else
rexml_doc = REXML::Document.new(xml_response)
rexml_doc.write(xml, indent)
end
xml
end | ruby | {
"resource": ""
} |
q24257 | EbayTrader.Request.submit | train | def submit
raise EbayTraderError, 'Cannot post an eBay API request before application keys have been set' unless EbayTrader.configuration.has_keys_set?
uri = EbayTrader.configuration.uri
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = http_timeout
if uri.port == 443
# http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
http.use_ssl = true
verify = EbayTrader.configuration.ssl_verify
if verify
if verify.is_a?(String)
pem = File.read(verify)
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(pem)
end
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
post = Net::HTTP::Post.new(uri.path, headers)
post.body = xml_request
begin
response = http.start { |http| http.request(post) }
rescue OpenSSL::SSL::SSLError => e
# SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
raise EbayTraderError, e
rescue Net::ReadTimeout
raise EbayTraderTimeoutError, "Failed to complete #{call_name} in #{http_timeout} seconds"
rescue Exception => e
raise EbayTraderError, e
ensure
EbayTrader.configuration.counter_callback.call if EbayTrader.configuration.has_counter?
end
@http_response_code = response.code.to_i.freeze
# If the call was successful it should have a response code starting with '2'
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
raise EbayTraderError, "HTTP Response Code: #{http_response_code}" unless http_response_code.between?(200, 299)
if response['Content-Encoding'] == 'gzip'
@xml_response = ActiveSupport::Gzip.decompress(response.body)
else
@xml_response = response.body
end
end | ruby | {
"resource": ""
} |
q24258 | WebPurify.Blacklist.add_to_blacklist | train | def add_to_blacklist(word, deep_search=0)
params = {
:method => WebPurify::Constants.methods[:add_to_blacklist],
:word => word,
:ds => deep_search
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
return parsed[:success]=='1'
end | ruby | {
"resource": ""
} |
q24259 | WebPurify.Blacklist.remove_from_blacklist | train | def remove_from_blacklist(word)
params = {
:method => WebPurify::Constants.methods[:remove_from_blacklist],
:word => word
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
return parsed[:success]=='1'
end | ruby | {
"resource": ""
} |
q24260 | WebPurify.Blacklist.get_blacklist | train | def get_blacklist
params = {
:method => WebPurify::Constants.methods[:get_blacklist]
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
if parsed[:word]
return [] << parsed[:word]
else
return []
end
end | ruby | {
"resource": ""
} |
q24261 | Expectacle.ThrowerBase.write_and_logging | train | def write_and_logging(message, command, secret = false)
logging_message = secret ? message : message + command
@logger.info logging_message
if @writer.closed?
@logger.error "Try to write #{command}, but writer closed"
@commands.clear
else
@writer.puts command
end
end | ruby | {
"resource": ""
} |
q24262 | Expectacle.ThrowerBase.default_io_logger | train | def default_io_logger(logger_io, progname)
logger = Logger.new(logger_io)
logger.progname = progname
logger.datetime_format = '%Y-%m-%d %H:%M:%D %Z'
logger
end | ruby | {
"resource": ""
} |
q24263 | Expectacle.ThrowerBase.load_yaml_file | train | def load_yaml_file(file_type, file_name)
YAML.load_file file_name
rescue StandardError => error
@logger.error "Cannot load #{file_type}: #{file_name}"
raise error
end | ruby | {
"resource": ""
} |
q24264 | TrickBag.Validations.nil_instance_vars | train | def nil_instance_vars(object, vars)
vars = Array(vars)
vars.select { |var| object.instance_variable_get(var).nil? }
end | ruby | {
"resource": ""
} |
q24265 | TrickBag.Validations.raise_on_nil_instance_vars | train | def raise_on_nil_instance_vars(object, vars)
nil_vars = nil_instance_vars(object, vars)
unless nil_vars.empty?
raise ObjectValidationError.new("The following instance variables were nil: #{nil_vars.join(', ')}.")
end
end | ruby | {
"resource": ""
} |
q24266 | Rudy::CLI.CommandBase.print_header | train | def print_header
# Send The Huxtables the global values again because they could be
# updated after initialization but before the command was executed
Rudy::Huxtable.update_global @global
li Rudy::CLI.generate_header(@@global, @@config) if @@global.print_header
unless @@global.quiet
if @@global.environment == "prod"
msg = "YOU ARE PLAYING WITH PRODUCTION"
li Rudy::Utils.banner(msg, :normal), $/
end
end
end | ruby | {
"resource": ""
} |
q24267 | Rudy.Utils.bell | train | def bell(chimes=1, logger=nil)
chimes ||= 0
return unless logger
chimed = chimes.to_i
logger.print "\a"*chimes if chimes > 0 && logger
true # be like Rudy.bug()
end | ruby | {
"resource": ""
} |
q24268 | Rudy.Utils.bug | train | def bug(bugid, logger=STDERR)
logger.puts "You have found a bug! If you want, you can email".color(:red)
logger.puts 'rudy@solutious.com'.color(:red).bright << " about it. It's bug ##{bugid}.".color(:red)
logger.puts "Continuing...".color(:red)
true # so we can string it together like: bug('1') && next if ...
end | ruby | {
"resource": ""
} |
q24269 | Rudy.Utils.known_type? | train | def known_type?(key)
return false unless key
key &&= key.to_s.to_sym
Rudy::ID_MAP.has_key?(key)
end | ruby | {
"resource": ""
} |
q24270 | Rudy.Utils.identifier | train | def identifier(key)
key &&= key.to_sym
return unless Rudy::ID_MAP.has_key?(key)
Rudy::ID_MAP[key]
end | ruby | {
"resource": ""
} |
q24271 | Rudy.Utils.capture | train | def capture(stream)
#raise "We can only capture STDOUT or STDERR" unless stream == :stdout || stream == :stderr
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").read
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end | ruby | {
"resource": ""
} |
q24272 | Rudy.Utils.write_to_file | train | def write_to_file(filename, content, mode, chmod=600)
mode = (mode == :append) ? 'a' : 'w'
f = File.open(filename,mode)
f.puts content
f.close
return unless Rudy.sysinfo.os == :unix
raise "Provided chmod is not a Fixnum (#{chmod})" unless chmod.is_a?(Fixnum)
File.chmod(chmod, filename)
end | ruby | {
"resource": ""
} |
q24273 | Rudy.Metadata.refresh! | train | def refresh!
raise UnknownObject, self.name unless self.exists?
h = Rudy::Metadata.get self.name
return false if h.nil? || h.empty?
obj = self.from_hash(h)
obj.postprocess
obj
end | ruby | {
"resource": ""
} |
q24274 | TrickBag.Operators.multi_eq | train | def multi_eq(*values)
# If there is only 1 arg, it must be an array of at least 2 elements.
values = values.first if values.first.is_a?(Array) && values.size == 1
raise ArgumentError.new("Must be called with at least 2 parameters; was: #{values.inspect}") if values.size < 2
values[1..-1].all? { |value| value == values.first }
end | ruby | {
"resource": ""
} |
q24275 | Rudy.Machines.exists? | train | def exists?(pos=nil)
machines = pos.nil? ? list : get(pos)
!machines.nil?
end | ruby | {
"resource": ""
} |
q24276 | Rudy.Machines.running? | train | def running?(pos=nil)
group = pos.nil? ? list : [get(pos)].compact
return false if group.nil? || group.empty?
group.collect! { |m| m.instance_running? }
!group.member?(false)
end | ruby | {
"resource": ""
} |
q24277 | DEVp2p.RLPxSession.create_auth_message | train | def create_auth_message(remote_pubkey, ephemeral_privkey=nil, nonce=nil)
raise RLPxSessionError, 'must be initiator' unless initiator?
raise InvalidKeyError, 'invalid remote pubkey' unless Crypto::ECCx.valid_key?(remote_pubkey)
@remote_pubkey = remote_pubkey
token = @ecc.get_ecdh_key remote_pubkey
flag = 0x0
@initiator_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256)))
raise RLPxSessionError, 'invalid nonce length' unless @initiator_nonce.size == 32
token_xor_nonce = Utils.sxor token, @initiator_nonce
raise RLPxSessionError, 'invalid token xor nonce length' unless token_xor_nonce.size == 32
ephemeral_pubkey = @ephemeral_ecc.raw_pubkey
raise InvalidKeyError, 'invalid ephemeral pubkey' unless ephemeral_pubkey.size == 512 / 8 && Crypto::ECCx.valid_key?(ephemeral_pubkey)
sig = @ephemeral_ecc.sign token_xor_nonce
raise RLPxSessionError, 'invalid signature' unless sig.size == 65
auth_message = "#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}"
raise RLPxSessionError, 'invalid auth message length' unless auth_message.size == 194
auth_message
end | ruby | {
"resource": ""
} |
q24278 | DEVp2p.RLPxSession.create_auth_ack_message | train | def create_auth_ack_message(ephemeral_pubkey=nil, nonce=nil, version=SUPPORTED_RLPX_VERSION, eip8=false)
raise RLPxSessionError, 'must not be initiator' if initiator?
ephemeral_pubkey = ephemeral_pubkey || @ephemeral_ecc.raw_pubkey
@responder_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256)))
if eip8 || @got_eip8_auth
msg = create_eip8_auth_ack_message ephemeral_pubkey, @responder_nonce, version
raise RLPxSessionError, 'invalid msg size' unless msg.size > 97
else
msg = "#{ephemeral_pubkey}#{@responder_nonce}\x00"
raise RLPxSessionError, 'invalid msg size' unless msg.size == 97
end
msg
end | ruby | {
"resource": ""
} |
q24279 | DEVp2p.RLPxSession.setup_cipher | train | def setup_cipher
raise RLPxSessionError, 'missing responder nonce' unless @responder_nonce
raise RLPxSessionError, 'missing initiator_nonce' unless @initiator_nonce
raise RLPxSessionError, 'missing auth_init' unless @auth_init
raise RLPxSessionError, 'missing auth_ack' unless @auth_ack
raise RLPxSessionError, 'missing remote ephemeral pubkey' unless @remote_ephemeral_pubkey
raise InvalidKeyError, 'invalid remote ephemeral pubkey' unless Crypto::ECCx.valid_key?(@remote_ephemeral_pubkey)
# derive base secrets from ephemeral key agreement
# ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk)
@ecdhe_shared_secret = @ephemeral_ecc.get_ecdh_key(@remote_ephemeral_pubkey)
@shared_secret = Crypto.keccak256("#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}")
@token = Crypto.keccak256 @shared_secret
@aes_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@shared_secret}"
@mac_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@aes_secret}"
mac1 = keccak256 "#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}"
mac2 = keccak256 "#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}"
if initiator?
@egress_mac, @ingress_mac = mac1, mac2
else
@egress_mac, @ingress_mac = mac2, mac1
end
iv = "\x00" * 16
@aes_enc = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c|
c.encrypt
c.iv = iv
c.key = @aes_secret
end
@aes_dec = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c|
c.decrypt
c.iv = iv
c.key = @aes_secret
end
@mac_enc = OpenSSL::Cipher.new(MAC_CIPHER).tap do |c|
c.encrypt
c.key = @mac_secret
end
@ready = true
end | ruby | {
"resource": ""
} |
q24280 | DEVp2p.RLPxSession.decode_auth_plain | train | def decode_auth_plain(ciphertext)
message = begin
@ecc.ecies_decrypt ciphertext[0,307]
rescue
raise AuthenticationError, $!
end
raise RLPxSessionError, 'invalid message length' unless message.size == 194
sig = message[0,65]
pubkey = message[65+32,64]
raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey)
nonce = message[65+32+64,32]
flag = message[(65+32+64+32)..-1].ord
raise RLPxSessionError, 'invalid flag' unless flag == 0
[307, sig, pubkey, nonce, 4]
end | ruby | {
"resource": ""
} |
q24281 | DEVp2p.RLPxSession.decode_auth_eip8 | train | def decode_auth_eip8(ciphertext)
size = ciphertext[0,2].unpack('S>').first + 2
raise RLPxSessionError, 'invalid ciphertext size' unless ciphertext.size >= size
message = begin
@ecc.ecies_decrypt ciphertext[2...size], ciphertext[0,2]
rescue
raise AuthenticationError, $!
end
values = RLP.decode message, sedes: eip8_auth_sedes, strict: false
raise RLPxSessionError, 'invalid values size' unless values.size >= 4
[size] + values[0,4]
end | ruby | {
"resource": ""
} |
q24282 | DEVp2p.RLPxSession.decode_ack_plain | train | def decode_ack_plain(ciphertext)
message = begin
@ecc.ecies_decrypt ciphertext[0,210]
rescue
raise AuthenticationError, $!
end
raise RLPxSessionError, 'invalid message length' unless message.size == 64+32+1
ephemeral_pubkey = message[0,64]
nonce = message[64,32]
known = message[-1].ord
raise RLPxSessionError, 'invalid known byte' unless known == 0
[210, ephemeral_pubkey, nonce, 4]
end | ruby | {
"resource": ""
} |
q24283 | DEVp2p.RLPxSession.decode_ack_eip8 | train | def decode_ack_eip8(ciphertext)
size = ciphertext[0,2].unpack('S>').first + 2
raise RLPxSessionError, 'invalid ciphertext length' unless ciphertext.size == size
message = begin
@ecc.ecies_decrypt(ciphertext[2...size], ciphertext[0,2])
rescue
raise AuthenticationError, $!
end
values = RLP.decode message, sedes: eip8_ack_sedes, strict: false
raise RLPxSessionError, 'invalid values length' unless values.size >= 3
[size] + values[0,3]
end | ruby | {
"resource": ""
} |
q24284 | Rudy.Global.apply_system_defaults | train | def apply_system_defaults
if @region.nil? && @zone.nil?
@region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE
elsif @region.nil?
@region = @zone.to_s.gsub(/[a-z]$/, '').to_sym
elsif @zone.nil?
@zone = "#{@region}b".to_sym
end
@environment ||= Rudy::DEFAULT_ENVIRONMENT
@role ||= Rudy::DEFAULT_ROLE
@localhost ||= Rudy.sysinfo.hostname || 'localhost'
@auto = false if @auto.nil?
end | ruby | {
"resource": ""
} |
q24285 | Rudy.Global.clear_system_defaults | train | def clear_system_defaults
@region = nil if @region == Rudy::DEFAULT_REGION
@zone = nil if @zone == Rudy::DEFAULT_ZONE
@environment = nil if @environment == Rudy::DEFAULT_ENVIRONMENT
@role = nil if @role == Rudy::DEFAULT_ROLE
@localhost = nil if @localhost == (Rudy.sysinfo.hostname || 'localhost')
@auto = nil if @auto == false
end | ruby | {
"resource": ""
} |
q24286 | Rudy::Routines::Handlers.RyeTools.print_command | train | def print_command(user, host, cmd)
#return if @@global.parallel
cmd ||= ""
cmd, user = cmd.to_s, user.to_s
prompt = user == "root" ? "#" : "$"
li ("%s@%s%s %s" % [user, host, prompt, cmd.bright])
end | ruby | {
"resource": ""
} |
q24287 | CircleciArtifact.Fetcher.parse | train | def parse(artifacts:, queries:)
raise ArgumentError, 'Error: Must have artifacts' if artifacts.nil?
raise ArgumentError, 'Error: Must have queries' unless queries.is_a?(Array)
# Example
# [
# {
# node_index: 0,
# path: "/tmp/circle-artifacts.NHQxLku/cherry-pie.png",
# pretty_path: "$CIRCLE_ARTIFACTS/cherry-pie.png",
# url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/cherry-pie.png"
# },
# {
# node_index: 0,
# path: "/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png",
# pretty_path: "$CIRCLE_ARTIFACTS/rhubarb-pie.png",
# url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png"
# }
# ]
results = ResultSet.new
artifacts.body.each do |artifact|
url = artifact['url']
if url.nil?
STDERR.puts "Warning: No URL found on #{artifact}"
next
end
query = queries.find { |q| url.include?(q.url_substring) }
next if query.nil?
result = Result.new(query: query, url: url)
results.add_result(result)
end
results
end | ruby | {
"resource": ""
} |
q24288 | Crunchbase.Client.get | train | def get(permalink, kclass_name, relationship_name = nil)
case kclass_name
when 'Person'
person(permalink, relationship_name)
when 'Organization'
organization(permalink, relationship_name)
end
end | ruby | {
"resource": ""
} |
q24289 | Scrapifier.Methods.scrapify | train | def scrapify(options = {})
uri, meta = find_uri(options[:which]), {}
return meta if uri.nil?
if !(uri =~ sf_regex(:image))
meta = sf_eval_uri(uri, options[:images])
elsif !sf_check_img_ext(uri, options[:images]).empty?
[:title, :description, :uri, :images].each { |k| meta[k] = uri }
end
meta
end | ruby | {
"resource": ""
} |
q24290 | Scrapifier.Methods.find_uri | train | def find_uri(which = 0)
which = scan(sf_regex(:uri))[which.to_i][0]
which =~ sf_regex(:protocol) ? which : "http://#{which}"
rescue NoMethodError
nil
end | ruby | {
"resource": ""
} |
q24291 | Expectacle.Thrower.previewed_host_param | train | def previewed_host_param
host_param = @host_param.dup
enable_mode = @enable_mode
@enable_mode = false
host_param[:username] = embed_user_name
host_param[:password] = embed_password
host_param[:ipaddr] = embed_ipaddr
@enable_mode = true
host_param[:enable] = embed_password
@enable_mode = enable_mode
host_param
end | ruby | {
"resource": ""
} |
q24292 | ActsAsLearnable.InstanceMethods.reset | train | def reset
self.repetitions = 0
self.interval = 0
self.due = Date.today
self.studied_at = Date.today
save
end | ruby | {
"resource": ""
} |
q24293 | HandBrake.CLI.output | train | def output(filename, options={})
options = options.dup
overwrite = options.delete :overwrite
case overwrite
when true, nil
# no special behavior
when false
raise FileExistsError, filename if File.exist?(filename)
when :ignore
if File.exist?(filename)
trace "Ignoring transcode to #{filename.inspect} because it already exists"
return
end
else
raise "Unsupported value for :overwrite: #{overwrite.inspect}"
end
atomic = options.delete :atomic
interim_filename =
case atomic
when true
partial_filename(filename)
when String
partial_filename(File.join(atomic, File.basename(filename)))
when false, nil
filename
else
fail "Unsupported value for :atomic: #{atomic.inspect}"
end
unless options.empty?
raise "Unknown options for output: #{options.keys.inspect}"
end
FileUtils.mkdir_p(File.dirname(interim_filename), fileutils_options)
run('--output', interim_filename)
if filename != interim_filename
replace =
if File.exist?(filename)
trace "#{filename.inspect} showed up during transcode"
case overwrite
when false
raise FileExistsError, filename
when :ignore
trace "- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it"
false
else
trace '- will replace with new transcode'
true
end
else
true
end
FileUtils.mkdir_p(File.dirname(filename), fileutils_options)
FileUtils.mv(interim_filename, filename, fileutils_options) if replace
end
end | ruby | {
"resource": ""
} |
q24294 | HandBrake.CLI.preset_list | train | def preset_list
result = run('--preset-list')
result.output.scan(%r{\< (.*?)\n(.*?)\>}m).inject({}) { |h1, (cat, block)|
h1[cat.strip] = block.scan(/\+(.*?):(.*?)\n/).inject({}) { |h2, (name, args)|
h2[name.strip] = args.strip
h2
}
h1
}
end | ruby | {
"resource": ""
} |
q24295 | HandBrake.CLI.method_missing | train | def method_missing(name, *args)
copy = self.dup
copy.instance_eval { @args << [name, *(args.collect { |a| a.to_s })] }
copy
end | ruby | {
"resource": ""
} |
q24296 | TrickBag.Timing.retry_until_true_or_timeout | train | def retry_until_true_or_timeout(
sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil)
test_preconditions = -> do
# Method signature has changed from:
# (predicate, sleep_interval, timeout_secs, output_stream = $stdout)
# to:
# (sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil)
#
# Test to see that when old signature is used, a descriptive error is raised.
#
# This test should be removed when we go to version 1.0.
if sleep_interval.respond_to?(:call)
raise ArgumentError.new('Sorry, method signature has changed to: ' \
'(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).' \
' Also a code block can now be provided instead of a lambda.')
end
if block_given? && predicate
raise ArgumentError.new('Both a predicate lambda and a code block were specified.' \
' Please specify one or the other but not both.')
end
end
test_preconditions.()
success = false
start_time = Time.now
end_time = start_time + timeout_secs
text_generator = ->() do
now = Time.now
elapsed = now - start_time
to_go = end_time - now
'%9.3f %9.3f' % [elapsed, to_go]
end
status_updater = ::TrickBag::Io::TextModeStatusUpdater.new(text_generator, output_stream)
loop do
break if Time.now >= end_time
success = !! (block_given? ? yield : predicate.())
break if success
status_updater.print
sleep(sleep_interval)
end
output_stream.print "\n"
success
end | ruby | {
"resource": ""
} |
q24297 | TrickBag.Timing.benchmark | train | def benchmark(caption, out_stream = $stdout, &block)
return_value = nil
bm = Benchmark.measure { return_value = block.call }
out_stream << bm.to_s.chomp << ": #{caption}\n"
return_value
end | ruby | {
"resource": ""
} |
q24298 | TrickBag.Timing.try_with_timeout | train | def try_with_timeout(max_seconds, check_interval_in_secs, &block)
raise "Must pass block to this method" unless block_given?
end_time = Time.now + max_seconds
block_return_value = nil
thread = Thread.new { block_return_value = block.call }
while Time.now < end_time
unless thread.alive?
return [true, block_return_value]
end
sleep(check_interval_in_secs)
end
thread.kill
[false, nil]
end | ruby | {
"resource": ""
} |
q24299 | DEVp2p.Command.create | train | def create(proto, *args)
options = args.last.is_a?(Hash) ? args.pop : {}
raise ArgumentError, "proto #{proto} must be protocol" unless proto.is_a?(Protocol)
raise ArgumentError, "command structure mismatch" if !options.empty? && structure.instance_of?(RLP::Sedes::CountableList)
options.empty? ? args : options
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.