_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q100 | StompParser.Frame.content_encoding | train | def content_encoding
if content_type = headers["content-type"]
mime_type, charset = content_type.split(SEMICOLON, 2)
charset = charset[CHARSET_OFFSET] if charset
charset ||= EMPTY
if charset.empty? and mime_type.start_with?("text/")
Encoding::UTF_8
elsif charset.... | ruby | {
"resource": ""
} |
q101 | StompParser.Frame.write_header | train | def write_header(key, value)
# @see http://stomp.github.io/stomp-specification-1.2.html#Repeated_Header_Entries
key = decode_header(key)
@headers[key] = decode_header(value) unless @headers.has_key?(key)
end | ruby | {
"resource": ""
} |
q102 | Citibike.Client.stations | train | def stations
resp = self.connection.request(
:get,
Citibike::Station.path
)
return resp if @options[:unwrapped]
Citibike::Responses::Station.new(resp)
end | ruby | {
"resource": ""
} |
q103 | MessageDriver.Broker.find_destination | train | def find_destination(destination_name)
destination = @destinations[destination_name]
if destination.nil?
raise MessageDriver::NoSuchDestinationError, "no destination #{destination_name} has been configured"
end
destination
end | ruby | {
"resource": ""
} |
q104 | Slodown.Formatter.extract_metadata | train | def extract_metadata
@metadata = {}
convert do |current|
current.each_line.drop_while do |line|
next false if line !~ /^#\+([a-z_]+): (.*)/
key, value = $1, $2
@metadata[key.to_sym] = value
end.join('')
end
end | ruby | {
"resource": ""
} |
q105 | Slodown.Formatter.embed_transformer | train | def embed_transformer
lambda do |env|
node = env[:node]
node_name = env[:node_name]
# We're fine with a bunch of stuff -- but not <iframe> and <embed> tags.
return if env[:is_whitelisted] || !env[:node].element?
return unless %w[iframe embed].include? env[:node_name]
... | ruby | {
"resource": ""
} |
q106 | Tenanfy.Helpers.append_tenant_theme_to_assets | train | def append_tenant_theme_to_assets(*assets)
assets.map! do |asset|
if should_add_tenant_theme_to_asset?(asset) && current_tenant
"#{current_tenant.themes.first}/#{asset}"
else
asset
end
end
assets
end | ruby | {
"resource": ""
} |
q107 | YourMembership.Session.authenticate | train | def authenticate(user_name, password)
options = {}
options[:Username] = user_name
options[:Password] = password
response = self.class.post('/', :body => self.class.build_XML_request('Auth.Authenticate', self, options))
self.class.response_valid? response
if response['YourMembership... | ruby | {
"resource": ""
} |
q108 | Xcflushd.Authorizer.sorted_metrics | train | def sorted_metrics(metrics, hierarchy)
# 'hierarchy' is a hash where the keys are metric names and the values
# are arrays with the names of the children metrics. Only metrics with
# children and with at least one usage limit appear as keys.
parent_metrics = hierarchy.keys
child_metrics = ... | ruby | {
"resource": ""
} |
q109 | Citibike.Response.all_near | train | def all_near(obj, dist)
@data.select do |d|
if d.id == obj.id
false
else
d.distance_from(obj.latitude, obj.longitude) < dist
end
end
end | ruby | {
"resource": ""
} |
q110 | Citibike.Response.method_missing | train | def method_missing(sym, *args, &block)
if self.data.respond_to?(sym)
return self.data.send(sym, *args, &block)
end
super
end | ruby | {
"resource": ""
} |
q111 | Chimp.QueueWorker.run | train | def run
while @never_exit
work_item = ChimpQueue.instance.shift()
begin
if work_item != nil
job_uuid = work_item.job_uuid
group = work_item.group.group_id
work_item.retry_count = @retry_count
work_item.owner = Thread.current.object_id
... | ruby | {
"resource": ""
} |
q112 | WinGui.DefApi.enforce_count | train | def enforce_count(args, params, diff = 0)
num_args = args.size
num_params = params == 'V' ? 0 : params.size + diff
if num_args != num_params
raise ArgumentError, "wrong number of parameters: expected #{num_params}, got #{num_args}"
end
end | ruby | {
"resource": ""
} |
q113 | WinGui.DefApi.return_enum | train | def return_enum
lambda do |api, *args, &block|
WinGui.enforce_count( args, api.prototype, -1)
handles = []
cb = if block
callback('LP', 'I', &block)
else
callback('LP', 'I') do |handle, message|
handles << handle
true
end
... | ruby | {
"resource": ""
} |
q114 | Oulipo.StringExtensions.alliterativity | train | def alliterativity
words = self.downcase.gsub(/[^a-z\s]/, '').split
leading_letters = words.map(&:chr)
# { 'a' => 3, 'b' => 1, ... }
leading_letter_counts = leading_letters.inject({}) do |result, letter|
result[letter] ||= 0
result[letter] += 1
result
end
... | ruby | {
"resource": ""
} |
q115 | Oulipo.StringExtensions.n_plus | train | def n_plus(places, word_list)
analysis = Analysis.new(self, :nouns => word_list)
substitutor = Substitutor.new(analysis)
substitutor.replace(:nouns).increment(places)
end | ruby | {
"resource": ""
} |
q116 | Oulipo.StringExtensions.snowball? | train | def snowball?
words = self.split
self.chaterism? && words.first.length < words.last.length
end | ruby | {
"resource": ""
} |
q117 | Oulipo.StringExtensions.chaterism? | train | def chaterism?
words = self.gsub(/[^a-z\s]/i, '').split
# Find the direction we're traveling
flen, llen = words.first.length, words.last.length
direction = flen > llen ? :downto : :upto
# Compare the pattern of word lengths against a range-turned-array of expected word lengths
... | ruby | {
"resource": ""
} |
q118 | MiniReadline.EditWindow.sync_window | train | def sync_window(edit_buffer, edit_posn)
unless check_margins(edit_buffer.length, edit_posn)
window_buffer.clear
@show_prompt = true
end
image = build_screen_image(edit_buffer)
update_screen(image)
@window_buffer = image
end | ruby | {
"resource": ""
} |
q119 | MiniReadline.EditWindow.build_screen_image | train | def build_screen_image(edit_buffer)
working_region = edit_buffer[left_margin..right_margin]
if (mask = @options[:secret_mask])
mask[0] * working_region.length
else
working_region
end.ljust(active_width)
end | ruby | {
"resource": ""
} |
q120 | MiniReadline.EditWindow.update_screen | train | def update_screen(image)
if @show_prompt
MiniTerm.print("\r#{prompt.text}\r")
@show_prompt = false
end
(0...active_width).each do |index|
if (image_char = image[index]) != window_buffer[index]
MiniTerm.set_posn(column: prompt.length + index)
MiniTe... | ruby | {
"resource": ""
} |
q121 | Mandate.Memoize.__mandate_memoize | train | def __mandate_memoize(method_name)
memoizer = Module.new do
define_method method_name do
@__mandate_memoized_results ||= {}
if @__mandate_memoized_results.include?(method_name)
@__mandate_memoized_results[method_name]
else
@__mandate_memoized_results[... | ruby | {
"resource": ""
} |
q122 | Aw.Fork.call | train | def call(*, **, &block)
pid = fork_and_return_pid(&block)
write.close
result = read.read
Process.wait(pid)
# rubocop:disable MarshalLoad
Marshal.load(result)
# rubocop:enable MarshalLoad
end | ruby | {
"resource": ""
} |
q123 | Boson::Commands::WebCore.Get.get_body | train | def get_body
uri = URI.parse(@url)
@response = get_response(uri)
(@options[:any_response] || @response.code == '200') ? @response.body : nil
rescue
@options[:raise_error] ? raise : puts("Error: GET '#{@url}' -> #{$!.class}: #{$!.message}")
end | ruby | {
"resource": ""
} |
q124 | Boson::Commands::WebCore.Get.parse_body | train | def parse_body(body)
format = determine_format(@options[:parse])
case format
when :json
unless ::Boson::Util.safe_require 'json'
return puts("Install the json gem to parse json: sudo gem install json")
end
JSON.parse body
when :yaml
YAML::load body
... | ruby | {
"resource": ""
} |
q125 | RailsRedshiftReplicator.FileManager.write_csv | train | def write_csv(file_name, records)
line_number = exporter.connection_adapter.write(local_file(file_name), records)
end | ruby | {
"resource": ""
} |
q126 | RailsRedshiftReplicator.FileManager.file_key_in_format | train | def file_key_in_format(file_name, format)
if format == "gzip"
self.class.s3_file_key exporter.source_table, gzipped(file_name)
else
self.class.s3_file_key exporter.source_table, file_name
end
end | ruby | {
"resource": ""
} |
q127 | RailsRedshiftReplicator.FileManager.upload_csv | train | def upload_csv(files)
files.each do |file|
basename = File.basename(file)
next if basename == File.basename(exporter.replication.key)
RailsRedshiftReplicator.logger.info I18n.t(:uploading_notice,
file: file,
... | ruby | {
"resource": ""
} |
q128 | Chimp.Executor.run_with_retry | train | def run_with_retry(&block)
Log.debug "Running job '#{@job_id}' with status '#{@status}'"
# If we are not the first job in this group, wait @delay
ChimpDaemon.instance.semaphore.synchronize do
if @group.started >= @concurrency && @delay.nonzero?
Log.info "[#{@job_uuid}] Sleeping #{@de... | ruby | {
"resource": ""
} |
q129 | CatarsePagarme.PaymentDelegator.transfer_funds | train | def transfer_funds
raise "payment must be paid" if !payment.paid?
bank_account = PagarMe::BankAccount.new(bank_account_attributes.delete(:bank_account))
bank_account.create
raise "unable to create an bank account" unless bank_account.id.present?
transfer = PagarMe::Transfer.new({
... | ruby | {
"resource": ""
} |
q130 | Chimp.Chimp.run | train | def run
queue = ChimpQueue.instance
arguments = []
ARGV.each { |arg| arguments << arg.clone }
self.cli_args=arguments.collect {|param|
param.gsub(/(?<==).*/) do |match|
match='"'+match+'"'
end
}.join(" ")
parse_command_line if @interactive
check_... | ruby | {
"resource": ""
} |
q131 | Chimp.Chimp.check_option_validity | train | def check_option_validity
if @hold && !@array_names.empty?
puts "ERROR: Holding of array objects is not yet supported"
exit 1
end
if @tags.empty? and @array_names.empty? and @deployment_names.empty? and not @chimpd_wait_until_done
puts "ERROR: Please select the objects to oper... | ruby | {
"resource": ""
} |
q132 | Chimp.Chimp.get_servers_by_tag | train | def get_servers_by_tag(tags)
# Take tags and collapse it,
# Default case, tag is AND
if @match_all
t = tags.join("&tag=")
filter = "tag=#{t}"
servers = Connection.instances(filter)
else
t = tags.join(",")
filter = "tag=#{t}"
servers = Connection.in... | ruby | {
"resource": ""
} |
q133 | Chimp.Chimp.verify_tagged_instances | train | def verify_tagged_instances(servers,tags)
array_list = servers
# servers is an array of hashes
# verify that each object contains the tags.
if @match_all
# has to contain BOTH
matching_servers = array_list.select { |instance| (tags - instance['tags']).empty? }
else
... | ruby | {
"resource": ""
} |
q134 | Chimp.Chimp.get_hrefs_for_arrays | train | def get_hrefs_for_arrays(names)
result = []
arrays_hrefs = []
if names.size > 0
names.each do |array_name|
# Find if arrays exist, if not raise warning.
# One API call per array
begin
Log.debug "[#{Chimp.get_job_uuid}] Making API 1.5 call: client.serve... | ruby | {
"resource": ""
} |
q135 | Chimp.Chimp.detect_server_template | train | def detect_server_template(servers)
Log.debug "[#{Chimp.get_job_uuid}] Looking for server template"
st = []
if servers[0].nil?
return (st)
end
st += servers.collect { |s|
[s['href'],s['server_template']]
}.uniq {|a| a[0]}
#
# We return an array of serve... | ruby | {
"resource": ""
} |
q136 | Chimp.Chimp.detect_right_script | train | def detect_right_script(st, script)
Log.debug "[#{Chimp.get_job_uuid}] Looking for rightscript"
executable = nil
# In the event that chimpd find @op_scripts as nil, set it as an array.
if @op_scripts.nil?
@op_scripts = []
end
if st.nil?
return executable
end
... | ruby | {
"resource": ""
} |
q137 | Chimp.Chimp.reduce_to_common_scripts | train | def reduce_to_common_scripts(number_of_st)
counts = Hash.new 0
@op_scripts.each { |s| counts[s[0]] +=1 }
b = @op_scripts.inject({}) do |res, row|
res[row[0]] ||= []
res[row[0]] << row[1]
res
end
b.inject([]) do |res, (key, values)|
res <<... | ruby | {
"resource": ""
} |
q138 | Chimp.Chimp.extract_operational_scripts | train | def extract_operational_scripts(st)
op_scripts = []
size = st.size
st.each do |s|
# Example of s structure
# ["/api/server_templates/351930003",
# {"id"=>351930003,
# "name"=>"RightScale Right_Site - 2015q1",
# "kind"=>"cm#server_template",
# ... | ruby | {
"resource": ""
} |
q139 | Chimp.Chimp.queue_runner | train | def queue_runner(concurrency, delay, retry_count, progress)
queue = ChimpQueue.instance
queue.max_threads = concurrency
queue.delay = delay
queue.retry_count = retry_count
total_queue_size = queue.size
puts "Executing..." unless progress or not quiet
pbar = ProgressBar.new("Ex... | ruby | {
"resource": ""
} |
q140 | Chimp.Chimp.verify_results | train | def verify_results(group = :default)
failed_workers, results_display = get_results(group)
#
# If no workers failed, then we're done.
#
if failed_workers.empty?
@paused = false
return "continue"
end
#
# Some workers failed; offer the user a chance to retry... | ruby | {
"resource": ""
} |
q141 | Chimp.Chimp.get_results | train | def get_results(group_name)
queue = ChimpQueue.instance
Log.debug("getting results for group #{group_name}")
results = queue.group[@group].results()
failed_workers = []
results_display = []
results.each do |result|
next if result == nil
if result[:status] == :error
... | ruby | {
"resource": ""
} |
q142 | Chimp.Chimp.process | train | def process
Chimp.set_failure(false)
Chimp.set_job_uuid(job_uuid)
Log.debug "[#{job_uuid}] Processing task"
# Add to our "processing" counter
Log.debug "[#{job_uuid}] Trying to get array_info" unless Chimp.failure
get_array_info unless Chimp.failure
Log.debug "[#{job_uuid}] ... | ruby | {
"resource": ""
} |
q143 | Chimp.Chimp.chimpd_wait_until_done | train | def chimpd_wait_until_done
local_queue = ChimpQueue.instance
$stdout.print "Waiting for chimpd jobs to complete for group #{@group}..."
begin
while !@dry_run
local_queue = ChimpQueue.instance
#
# load up remote chimpd jobs into the local queue
# this ma... | ruby | {
"resource": ""
} |
q144 | BackgroundBunnies.Bunny.start | train | def start(connection_or_group)
@connection = connection_or_group
@channel = AMQP::Channel.new(@connection)
queue_options = {}
name = queue_name
if queue_type == :broadcast
queue_options[:exclusive] = true
queue_options[:auto_delete] = true
name = "#{Socket.gethostna... | ruby | {
"resource": ""
} |
q145 | WinGui.Window.click | train | def click(id)
h = child(id).handle
rectangle = [0, 0, 0, 0].pack 'LLLL'
get_window_rect h, rectangle
left, top, right, bottom = rectangle.unpack 'LLLL'
center = [(left + right) / 2, (top + bottom) / 2]
set_cursor_pos *center
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mo... | ruby | {
"resource": ""
} |
q146 | Pandora.Song.load_explorer_data | train | def load_explorer_data
document = Nokogiri::XML(Faraday.get(@song_explorer_url).body)
@id = document.search('songExplorer').first['musicId']
end | ruby | {
"resource": ""
} |
q147 | Chimp.Server.run_executable | train | def run_executable(exec, options)
script_href = "right_script_href="+exec.href
# Construct the parameters to pass for the inputs
params=options.collect { |k, v|
"&inputs[][name]=#{k}&inputs[][value]=#{v}" unless k == :ignore_lock
}.join('&')
if options[:ignore_lock]
para... | ruby | {
"resource": ""
} |
q148 | Phaserunner.Cli.main | train | def main
program_desc 'Read values from the Grin PhaseRunner Controller primarily for logging'
version Phaserunner::VERSION
subcommand_option_handling :normal
arguments :strict
sort_help :manually
desc 'Serial (USB) device'
default_value '/dev/ttyUSB0'
arg 'tty'
... | ruby | {
"resource": ""
} |
q149 | RailsRedshiftReplicator.Deleter.handle_delete_propagation | train | def handle_delete_propagation
if replicable.tracking_deleted && has_deleted_ids?
RailsRedshiftReplicator.logger.info propagation_message(:propagating_deletes)
delete_on_target ? purge_deleted : RailsRedshiftReplicator.logger.error(propagation_message(:delete_propagation_error))
end
end | ruby | {
"resource": ""
} |
q150 | RayyanScrapers.NihFulltextScraper.process_list_page | train | def process_list_page(page)
@logger.info("Processing list page with URL: #{page.uri}")
#page.save_as "html/result-list.html"
new_items_found = nil
items = page.links #[0..50] # TODO REMOVE [], getting sample only
items_len = items.length - 1
@total = @total + items_len
# pli... | ruby | {
"resource": ""
} |
q151 | SmsCarrier.LogSubscriber.deliver | train | def deliver(event)
info do
recipients = Array(event.payload[:to]).join(', ')
"\nSent SMS to #{recipients} (#{event.duration.round(1)}ms)"
end
debug { event.payload[:sms] }
end | ruby | {
"resource": ""
} |
q152 | ACTV.Base.to_hash | train | def to_hash
hash = {}
hash["attrs"] = @attrs
self.instance_variables.keep_if { |key| key != :@attrs }.each do |var|
val = self.instance_variable_get(var)
hash["attrs"][var.to_s.delete("@").to_sym] = val.to_hash if val.is_a? ACTV::Base
end
hash["attrs"]
end | ruby | {
"resource": ""
} |
q153 | Attributor.AttributeResolver.check | train | def check(path_prefix, key_path, predicate = nil)
value = query(key_path, path_prefix)
# we have a value, any value, which is good enough given no predicate
return true if !value.nil? && predicate.nil?
case predicate
when ::String, ::Regexp, ::Integer, ::Float, ::DateTime, true, false
... | ruby | {
"resource": ""
} |
q154 | Attributor.Attribute.describe | train | def describe(shallow = true, example: nil)
description = {}
# Clone the common options
TOP_LEVEL_OPTIONS.each do |option_name|
description[option_name] = options[option_name] if options.key? option_name
end
# Make sure this option definition is not mistaken for the real generated ... | ruby | {
"resource": ""
} |
q155 | Attributor.Attribute.validate | train | def validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT)
raise "INVALID CONTEXT!! #{context}" unless context
# Validate any requirements, absolute or conditional, and return.
if object.nil? # == Attributor::UNSET
# With no value, we can only validate whether that is acceptable or not ... | ruby | {
"resource": ""
} |
q156 | Boson.Pipes.sort_pipe | train | def sort_pipe(object, sort)
sort_lambda = lambda {}
if object[0].is_a?(Hash)
if sort.to_s[/^\d+$/]
sort = sort.to_i
elsif object[0].keys.all? {|e| e.is_a?(Symbol) }
sort = sort.to_sym
end
sort_lambda = untouched_sort?(object.map {|e| e[sort] }) ? lambda {|... | ruby | {
"resource": ""
} |
q157 | Boson.Pipes.pipes_pipe | train | def pipes_pipe(obj, arr)
arr.inject(obj) {|acc,e| Boson.full_invoke(e, [acc]) }
end | ruby | {
"resource": ""
} |
q158 | MiniReadline.Readline.readline | train | def readline(options = {})
suppress_warnings
initialize_parms(options)
MiniTerm.raw { @edit.edit_process }
ensure
restore_warnings
puts
end | ruby | {
"resource": ""
} |
q159 | MiniReadline.Readline.set_options | train | def set_options(options)
@options = MiniReadline::BASE_OPTIONS
.merge(instance_options)
.merge(options)
@options[:window_width] = MiniTerm.width - 1
set_prompt(@options[:prompt])
verify_mask(@options[:secret_mask])
end | ruby | {
"resource": ""
} |
q160 | MiniReadline.Readline.set_prompt | train | def set_prompt(prompt)
@options[:base_prompt] = Prompt.new(prompt)
@options[:scroll_prompt] = Prompt.new(@options[:alt_prompt] || prompt)
verify_prompt(@options[:base_prompt])
verify_prompt(@options[:scroll_prompt])
end | ruby | {
"resource": ""
} |
q161 | FormHelper.ActionView::Helpers::FormTagHelper.hd_picker_tag | train | def hd_picker_tag(field_name, value=nil, cls="datepicker", opts={}, locale_format=nil)
draw_ext_input_tag(field_name, value, cls, locale_format, opts)
end | ruby | {
"resource": ""
} |
q162 | Citibike.Api.distance_from | train | def distance_from(lat, long)
dLat = self.degrees_to_radians(lat - self.latitude)
dLon = self.degrees_to_radians(long - self.longitude)
lat1 = self.degrees_to_radians(lat)
lat2 = self.degrees_to_radians(self.latitude)
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon /... | ruby | {
"resource": ""
} |
q163 | Citibike.Api.method_missing | train | def method_missing(sym, *args, &block)
if self.internal_object.key?(sym.to_s)
return self.internal_object[sym.to_s]
end
super
end | ruby | {
"resource": ""
} |
q164 | Xcflushd.Storage.reports_to_flush | train | def reports_to_flush
# The Redis rename command overwrites the key with the new name if it
# exists. This means that if the rename operation fails in a flush cycle,
# and succeeds in a next one, the data that the key had in the first
# flush cycle will be lost.
# For that reason, every tim... | ruby | {
"resource": ""
} |
q165 | ObjectInspector.Scope.join_name | train | def join_name(parts,
separator: ObjectInspector.configuration.name_separator)
the_parts = Array(parts).tap(&:compact!)
the_parts.join(separator) if the_parts.any?
end | ruby | {
"resource": ""
} |
q166 | ObjectInspector.Scope.join_flags | train | def join_flags(flags,
separator: ObjectInspector.configuration.flags_separator)
the_flags = Array(flags).tap(&:compact!)
the_flags.join(separator) if the_flags.any?
end | ruby | {
"resource": ""
} |
q167 | ObjectInspector.Scope.join_issues | train | def join_issues(issues,
separator: ObjectInspector.configuration.issues_separator)
the_issues = Array(issues).tap(&:compact!)
the_issues.join(separator) if the_issues.any?
end | ruby | {
"resource": ""
} |
q168 | ObjectInspector.Scope.join_info | train | def join_info(items,
separator: ObjectInspector.configuration.info_separator)
the_items = Array(items).tap(&:compact!)
the_items.join(separator) if the_items.any?
end | ruby | {
"resource": ""
} |
q169 | FriendlyId.JsonTranslate.execute_with_locale | train | def execute_with_locale(locale = ::I18n.locale, &block)
actual_locale = ::I18n.locale
::I18n.locale = locale
block.call
::I18n.locale = actual_locale
end | ruby | {
"resource": ""
} |
q170 | Brightbox.DatabaseServer.maintenance_window | train | def maintenance_window
return nil if maintenance_weekday.nil?
weekday = Date::DAYNAMES[maintenance_weekday]
sprintf("%s %02d:00 UTC", weekday, maintenance_hour)
end | ruby | {
"resource": ""
} |
q171 | MtGox.Client.ticker | train | def ticker
ticker = get('/api/1/BTCUSD/ticker')
Ticker.instance.buy = value_currency ticker['buy']
Ticker.instance.high = value_currency ticker['high']
Ticker.instance.price = value_currency ticker['last_all']
Ticker.instance.low = value_currency ticker['low']
... | ruby | {
"resource": ""
} |
q172 | MtGox.Client.offers | train | def offers
offers = get('/api/1/BTCUSD/depth/fetch')
asks = offers['asks'].sort_by { |ask| ask['price_int'].to_i }.collect { |ask| Ask.new(self, ask) }
bids = offers['bids'].sort_by { |bid| -bid['price_int'].to_i }.collect { |bid| Bid.new(self, bid) }
{:asks => asks, :bids => bids}
end | ruby | {
"resource": ""
} |
q173 | MtGox.Client.trades | train | def trades(opts = {})
get('/api/1/BTCUSD/trades/fetch', opts).
sort_by { |trade| trade['date'] }.collect do |trade|
Trade.new(trade)
end
end | ruby | {
"resource": ""
} |
q174 | MtGox.Client.order! | train | def order!(type, amount, price)
order = {:type => order_type(type), :amount_int => intify(amount, :btc)}
order[:price_int] = intify(price, :usd) if price != :market
post('/api/1/BTCUSD/order/add', order)
end | ruby | {
"resource": ""
} |
q175 | MtGox.Client.withdraw! | train | def withdraw!(amount, address)
if amount >= 1000
fail(FilthyRichError.new("#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC"))
else
post('/api/1/generic/bitcoin/send_simple', :amount_int => intify(amount, :btc), :address => address)['trx']
end
e... | ruby | {
"resource": ""
} |
q176 | Boson.Pipe.scientist_process | train | def scientist_process(object, global_opt, env={})
@env = env
[:query, :sort, :reverse_sort].each {|e| global_opt.delete(e) } unless object.is_a?(Array)
process_pipes(object, global_opt)
end | ruby | {
"resource": ""
} |
q177 | Boson.Pipe.process_pipes | train | def process_pipes(obj, options)
internal_pipes(options).each {|pipe|
obj = Pipes.send("#{pipe}_pipe", obj, options[pipe]) if options[pipe]
}
process_user_pipes(obj, options)
end | ruby | {
"resource": ""
} |
q178 | Boson.Pipe.process_user_pipes | train | def process_user_pipes(result, global_opt)
pipes_to_process(global_opt).each {|e|
args = [pipe(e)[:pipe], result]
args << global_opt[e] unless pipe(e)[:type] == :boolean
args << get_env(e, global_opt) if pipe(e)[:env]
pipe_result = Boson.invoke(*args)
result = pipe_result i... | ruby | {
"resource": ""
} |
q179 | AIXM.Document.errors | train | def errors
xsd = Nokogiri::XML::Schema(File.open(AIXM.schema(:xsd)))
xsd.validate(Nokogiri::XML(to_xml)).reject do |error|
AIXM.config.ignored_errors && error.message.match?(AIXM.config.ignored_errors)
end
end | ruby | {
"resource": ""
} |
q180 | Boson.Namespacer.full_invoke | train | def full_invoke(cmd, args) #:nodoc:
command, subcommand = cmd.include?(NAMESPACE) ? cmd.split(NAMESPACE, 2) : [cmd, nil]
dispatcher = subcommand ? Boson.invoke(command) : Boson.main_object
dispatcher.send(subcommand || command, *args)
end | ruby | {
"resource": ""
} |
q181 | Unmarkdown.Parser.parse_nodes | train | def parse_nodes(nodes)
output = ''
# Short-circuit if it's empty
return output if !nodes || nodes.empty?
# Loop through nodes
nodes.each do |node|
case node.name
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
level = node.name.match(/\Ah(\d)\Z/)[1].to_i
if @o... | ruby | {
"resource": ""
} |
q182 | Unmarkdown.Parser.parse_content | train | def parse_content(node)
content = if node.children.empty?
node.content
else
parse_nodes(node.children)
end
end | ruby | {
"resource": ""
} |
q183 | AIXM.A.invert | train | def invert
build(precision: precision, deg: (deg + 180) % 360, suffix: SUFFIX_INVERSIONS.fetch(suffix, suffix))
end | ruby | {
"resource": ""
} |
q184 | Xcflushd.Flusher.async_authorization_tasks | train | def async_authorization_tasks(reports)
# Each call to authorizer.authorizations might need to contact 3scale
# several times. The number of calls equals 1 + number of reported
# metrics without limits.
# This is probably good enough for now, but in the future we might want
# to make sure t... | ruby | {
"resource": ""
} |
q185 | Gametel.Navigation.on | train | def on(cls, &block)
@current_screen = @current_page = cls.new
waiting_for = "#{cls} to be active"
wait_until(10, waiting_for) { @current_screen.active? } if @current_screen.respond_to?(:active?)
block.call @current_screen if block
@current_screen
end | ruby | {
"resource": ""
} |
q186 | Prawndown.Interface.markdown | train | def markdown(string, options = {})
text Prawndown::Parser.new(string).to_prawn, options.merge(inline_format: true)
end | ruby | {
"resource": ""
} |
q187 | MiniReadline.Edit.edit_loop | train | def edit_loop
while @working
@edit_window.sync_window(edit_buffer, edit_posn)
@edit_window.sync_cursor(edit_posn)
process_keystroke(MiniTerm.get_mapped_char)
end
edit_buffer
end | ruby | {
"resource": ""
} |
q188 | MiniReadline.Edit.word_right | train | def word_right(_keyboard_args)
if @edit_posn < length
right = @edit_buffer[(@edit_posn+1)..-1]
@edit_posn = (posn = right.index(/\s\S/)) ? @edit_posn+posn+2 : length
else
MiniTerm.beep
end
end | ruby | {
"resource": ""
} |
q189 | UnionStationHooks.RequestReporter.log_view_rendering | train | def log_view_rendering(options)
return do_nothing_on_null(:log_view_rendering) if null?
Utils.require_key(options, :name)
Utils.require_key(options, :begin_time)
Utils.require_key(options, :end_time)
@transaction.log_activity(next_view_rendering_name,
options[:begin_time], options... | ruby | {
"resource": ""
} |
q190 | VersionCompare.Conversions.ComparableVersion | train | def ComparableVersion(value)
case value
when String,
Integer,
Float,
->(val) { val.respond_to?(:to_ary) }
ComparableVersion.new(value)
when ->(val) { val.respond_to?(:to_comparable_version) }
value.to_comparable_version
else
raise TypeErro... | ruby | {
"resource": ""
} |
q191 | Epuber.Compiler.archive | train | def archive(path = nil, configuration_suffix: nil)
path ||= epub_name(configuration_suffix)
epub_path = File.expand_path(path)
Dir.chdir(@file_resolver.destination_path) do
new_paths = @file_resolver.package_files.map(&:pkg_destination_path)
if ::File.exists?(epub_path)
Zi... | ruby | {
"resource": ""
} |
q192 | Epuber.Compiler.epub_name | train | def epub_name(configuration_suffix = nil)
epub_name = if !@book.output_base_name.nil?
@book.output_base_name
elsif @book.from_file?
::File.basename(@book.file_path, ::File.extname(@book.file_path))
else
@book.title
... | ruby | {
"resource": ""
} |
q193 | TinyCI.Scheduler.run_all_commits | train | def run_all_commits
commits = get_commits
until commits.empty? do
commits.each {|c| run_commit(c)}
commits = get_commits
end
end | ruby | {
"resource": ""
} |
q194 | SimpleRecord.ResultsArray.as_json | train | def as_json(options = nil) #:nodoc:
# use encoder as a proxy to call as_json on all elements, to protect from circular references
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
map { |v| encoder.as_json(v) }
end | ruby | {
"resource": ""
} |
q195 | BlueprintClient.AssetsApi.add_asset_to_node | train | def add_asset_to_node(namespace, type, id, asset_type, asset_id, opts = {})
data, _status_code, _headers = add_asset_to_node_with_http_info(namespace, type, id, asset_type, asset_id, opts)
return data
end | ruby | {
"resource": ""
} |
q196 | BlueprintClient.AssetsApi.delete_asset | train | def delete_asset(namespace, asset_id, asset_type, opts = {})
delete_asset_with_http_info(namespace, asset_id, asset_type, opts)
return nil
end | ruby | {
"resource": ""
} |
q197 | BlueprintClient.AssetsApi.get_asset | train | def get_asset(namespace, asset_type, asset_id, opts = {})
data, _status_code, _headers = get_asset_with_http_info(namespace, asset_type, asset_id, opts)
return data
end | ruby | {
"resource": ""
} |
q198 | BlueprintClient.AssetsApi.get_assets_in_node | train | def get_assets_in_node(namespace, type, id, opts = {})
data, _status_code, _headers = get_assets_in_node_with_http_info(namespace, type, id, opts)
return data
end | ruby | {
"resource": ""
} |
q199 | BlueprintClient.AssetsApi.remove_asset_from_node | train | def remove_asset_from_node(namespace, type, id, asset_type, asset_id, opts = {})
remove_asset_from_node_with_http_info(namespace, type, id, asset_type, asset_id, opts)
return nil
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.