_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q1300
Proxmox.Proxmox.extract_ticket
train
def extract_ticket(response) data = JSON.parse(response.body) ticket = data['data']['ticket'] csrf_prevention_token = data['data']['CSRFPreventionToken'] unless ticket.nil? token = 'PVEAuthCookie=' + ticket.gsub!(/:/, '%3A').gsub!(/=/, '%3D') end @connection_status = 'connected' { CSRFPreventionToken: csrf_prevention_token, cookie: token } end
ruby
{ "resource": "" }
q1301
Proxmox.Proxmox.check_response
train
def check_response(response) if response.code == 200 JSON.parse(response.body)['data'] else 'NOK: error code = ' + response.code.to_s end end
ruby
{ "resource": "" }
q1302
Proxmox.Proxmox.http_action_post
train
def http_action_post(url, data = {}) @site[url].post data, @auth_params do |response, _request, _result, &_block| check_response response end end
ruby
{ "resource": "" }
q1303
Rly.Lex.next
train
def next while @pos < @input.length if self.class.ignores_list[@input[@pos]] ignore_symbol next end m = self.class.token_regexps.match(@input[@pos..-1]) if m && ! m[0].empty? val = nil type = nil resolved_type = nil m.names.each do |n| if m[n] type = n.to_sym resolved_type = (n.start_with?('__anonymous_') ? nil : type) val = m[n] break end end if type tok = build_token(resolved_type, val) @pos += m.end(0) tok = self.class.callables[type].call(tok) if self.class.callables[type] if tok && tok.type return tok else next end end end if self.class.literals_list[@input[@pos]] tok = build_token(@input[@pos], @input[@pos]) matched = true @pos += 1 return tok end if self.class.error_hander pos = @pos tok = build_token(:error, @input[@pos]) tok = self.class.error_hander.call(tok) if pos == @pos raise LexError.new("Illegal character '#{@input[@pos]}' at index #{@pos}") else return tok if tok && tok.type end else raise LexError.new("Illegal character '#{@input[@pos]}' at index #{@pos}") end end return nil end
ruby
{ "resource": "" }
q1304
CarrierWave.Vips.auto_orient
train
def auto_orient manipulate! do |image| o = image.get('exif-Orientation').to_i rescue nil o ||= image.get('exif-ifd0-Orientation').to_i rescue 1 case o when 1 # Do nothing, everything is peachy when 6 image.rot270 when 8 image.rot180 when 3 image.rot90 else raise('Invalid value for Orientation: ' + o.to_s) end image.set_type GObject::GSTR_TYPE, 'exif-Orientation', '' image.set_type GObject::GSTR_TYPE, 'exif-ifd0-Orientation', '' end end
ruby
{ "resource": "" }
q1305
CarrierWave.Vips.convert
train
def convert(f, opts = {}) opts = opts.dup f = f.to_s.downcase allowed = %w(jpeg jpg png) raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f) self.format_override = f == 'jpeg' ? 'jpg' : f opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality) write_opts.merge!(opts) get_image end
ruby
{ "resource": "" }
q1306
CarrierWave.Vips.resize_to_fill
train
def resize_to_fill(new_width, new_height) manipulate! do |image| image = resize_image image, new_width, new_height, :max if image.width > new_width top = 0 left = (image.width - new_width) / 2 elsif image.height > new_height left = 0 top = (image.height - new_height) / 2 else left = 0 top = 0 end # Floating point errors can sometimes chop off an extra pixel # TODO: fix all the universe so that floating point errors never happen again new_height = image.height if image.height < new_height new_width = image.width if image.width < new_width image.extract_area(left, top, new_width, new_height) end end
ruby
{ "resource": "" }
q1307
CarrierWave.Vips.resize_to_limit
train
def resize_to_limit(new_width, new_height) manipulate! do |image| image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height image end end
ruby
{ "resource": "" }
q1308
Jekyll.Convertible.read_yaml
train
def read_yaml(base, name, alt = true) _localization_original_read_yaml(base, name) read_alternate_language_content(base, name) if alt && content.empty? end
ruby
{ "resource": "" }
q1309
Jekyll.Page.destination
train
def destination(dest) # The url needs to be unescaped in order to preserve the correct filename path = File.join(dest, @dir, CGI.unescape(url)) if ext == '.html' && _localization_original_url !~ /\.html\z/ path.sub!(Localization::LANG_END_RE, '') File.join(path, "index#{ext}#{@lang_ext}") else path end end
ruby
{ "resource": "" }
q1310
Jekyll.Page.process
train
def process(name) self.ext = File.extname(name) self.basename = name[0 .. -self.ext.length-1]. sub(Localization::LANG_END_RE, '') end
ruby
{ "resource": "" }
q1311
MidiSmtpServer.Smtpd.stop
train
def stop(wait_seconds_before_close = 2, gracefully = true) # always signal shutdown shutdown if gracefully # wait if some connection(s) need(s) more time to handle shutdown sleep wait_seconds_before_close if connections? # drop tcp_servers while raising SmtpdStopServiceException @connections_mutex.synchronize do @tcp_server_threads.each do |tcp_server_thread| tcp_server_thread.raise SmtpdStopServiceException if tcp_server_thread end end # wait if some connection(s) still need(s) more time to come down sleep wait_seconds_before_close if connections? || !stopped? end
ruby
{ "resource": "" }
q1312
MidiSmtpServer.Smtpd.on_auth_event
train
def on_auth_event(ctx, authorization_id, authentication_id, authentication) # if authentification is used, override this event # and implement your own user management. # otherwise all authentifications are blocked per default logger.debug("Deny access from #{ctx[:server][:remote_ip]}:#{ctx[:server][:remote_port]} for #{authentication_id}" + (authorization_id == '' ? '' : "/#{authorization_id}") + " with #{authentication}") raise Smtpd535Exception end
ruby
{ "resource": "" }
q1313
MidiSmtpServer.Smtpd.serve_service
train
def serve_service raise 'Service was already started' unless stopped? # set flag to signal shutdown by stop / shutdown command @shutdown = false # instantiate the service for alls @hosts and @ports @hosts.each_with_index do |host, index| # instantiate the service for each host and port # if host is empty "" wildcard (all) interfaces are used # otherwise it will be bind to single host ip only # if ports at index is not specified, use last item # of ports array. if multiple ports specified by # item like 2525:3535:4545, then all are instantiated ports_for_host = (index < @ports.length ? @ports[index] : @ports.last).to_s.split(':') # loop all ports for that host ports_for_host.each do |port| serve_service_on_host_and_port(host, port) end end end
ruby
{ "resource": "" }
q1314
MidiSmtpServer.Smtpd.serve_service_on_host_and_port
train
def serve_service_on_host_and_port(host, port) # log information logger.info('Running service on ' + (host == '' ? '<any>' : host) + ':' + port.to_s) # instantiate the service for host and port # if host is empty "" wildcard (all) interfaces are used # otherwise it will be bind to single host ip only tcp_server = TCPServer.new(host, port) # append this server to the list of TCPServers @tcp_servers << tcp_server # run thread until shutdown @tcp_server_threads << Thread.new do begin # always check for shutdown request until shutdown? # get new client and start additional thread # to handle client process client = tcp_server.accept Thread.new(client) do |io| # add to list of connections @connections << Thread.current # handle connection begin # initialize a session storage hash Thread.current[:session] = {} # process smtp service on io socket io = serve_client(Thread.current[:session], io) # save returned io value due to maybe # established ssl io socket rescue SmtpdStopConnectionException # ignore this exception due to service shutdown rescue StandardError => e # log fatal error while handling connection logger.fatal(e.backtrace.join("\n")) ensure begin # always gracefully shutdown connection. # if the io object was overriden by the # result from serve_client() due to ssl # io, the ssl + io socket will be closed io.close rescue StandardError # ignore any exception from here end # remove closed session from connections @connections_mutex.synchronize do # drop this thread from connections @connections.delete(Thread.current) # drop this thread from processings @processings.delete(Thread.current) # signal mutex for next waiting thread @connections_cv.signal end end end end rescue SmtpdStopServiceException # ignore this exception due to service shutdown rescue StandardError => e # log fatal error while starting new thread logger.fatal(e.backtrace.join("\n")) ensure begin # drop the service tcp_server.close # remove from list @tcp_servers.delete(tcp_server) # reset local var tcp_server = nil rescue StandardError # ignor any error from here end if shutdown? # wait for finishing opened connections @connections_mutex.synchronize do @connections_cv.wait(@connections_mutex) until @connections.empty? end else # drop any open session immediately @connections.each { |c| c.raise SmtpdStopConnectionException } end # remove this thread from list @tcp_server_threads.delete(Thread.current) end end end
ruby
{ "resource": "" }
q1315
MidiSmtpServer.Smtpd.process_reset_session
train
def process_reset_session(session, connection_initialize = false) # set active command sequence info session[:cmd_sequence] = connection_initialize ? :CMD_HELO : :CMD_RSET # drop any auth challenge session[:auth_challenge] = {} # test existing of :ctx hash session[:ctx] || session[:ctx] = {} # reset server values (only on connection start) if connection_initialize # create or rebuild :ctx hash session[:ctx].merge!( server: { local_host: '', local_ip: '', local_port: '', local_response: '', remote_host: '', remote_ip: '', remote_port: '', helo: '', helo_response: '', connected: '', exceptions: 0, authorization_id: '', authentication_id: '', authenticated: '', encrypted: '' } ) end # reset envelope values session[:ctx].merge!( envelope: { from: '', to: [], encoding_body: '', encoding_utf8: '' } ) # reset message data session[:ctx].merge!( message: { received: -1, delivered: -1, bytesize: -1, headers: '', crlf: "\r\n", data: '' } ) end
ruby
{ "resource": "" }
q1316
MidiSmtpServer.Smtpd.process_auth_plain
train
def process_auth_plain(session, encoded_auth_response) begin # extract auth id (and password) @auth_values = Base64.decode64(encoded_auth_response).split("\x00") # check for valid credentials parameters raise Smtpd500Exception unless @auth_values.length == 3 # call event function to test credentials return_value = on_auth_event(session[:ctx], @auth_values[0], @auth_values[1], @auth_values[2]) if return_value # overwrite data with returned value as authorization id @auth_values[0] = return_value end # save authentication information to ctx session[:ctx][:server][:authorization_id] = @auth_values[0].to_s.empty? ? @auth_values[1] : @auth_values[0] session[:ctx][:server][:authentication_id] = @auth_values[1] session[:ctx][:server][:authenticated] = Time.now.utc # response code return '235 OK' ensure # whatever happens in this check, reset next sequence session[:cmd_sequence] = :CMD_RSET end end
ruby
{ "resource": "" }
q1317
Danthes.ViewHelpers.subscribe_to
train
def subscribe_to(channel, opts = {}) js_tag = opts.delete(:include_js_tag){ true } subscription = Danthes.subscription(channel: channel) content = raw("if (typeof Danthes != 'undefined') { Danthes.sign(#{subscription.to_json}) }") js_tag ? content_tag('script', content, type: 'text/javascript') : content end
ruby
{ "resource": "" }
q1318
Lacquer.CacheUtils.clear_cache_for
train
def clear_cache_for(*paths) return unless Lacquer.configuration.enable_cache case Lacquer.configuration.job_backend when :delayed_job require 'lacquer/delayed_job_job' Delayed::Job.enqueue(Lacquer::DelayedJobJob.new(paths)) when :resque require 'lacquer/resque_job' Resque.enqueue(Lacquer::ResqueJob, paths) when :sidekiq require 'lacquer/sidekiq_worker' Lacquer::SidekiqWorker.perform_async(paths) when :none Varnish.new.purge(*paths) end end
ruby
{ "resource": "" }
q1319
Danthes.FayeExtension.incoming
train
def incoming(message, callback) if message['channel'] == '/meta/subscribe' authenticate_subscribe(message) elsif message['channel'] !~ %r{^/meta/} authenticate_publish(message) end callback.call(message) end
ruby
{ "resource": "" }
q1320
Lacquer.Varnish.send_command
train
def send_command(command) Lacquer.configuration.varnish_servers.collect do |server| retries = 0 response = nil begin retries += 1 connection = Net::Telnet.new( 'Host' => server[:host], 'Port' => server[:port], 'Timeout' => server[:timeout] || 5) if(server[:secret]) connection.waitfor("Match" => /^107/) do |authentication_request| matchdata = /^107 \d{2}\s*(.{32}).*$/m.match(authentication_request) # Might be a bit ugly regex, but it works great! salt = matchdata[1] if(salt.empty?) raise VarnishError, "Bad authentication request" end digest = OpenSSL::Digest.new('sha256') digest << salt digest << "\n" digest << server[:secret] digest << salt digest << "\n" connection.cmd("String" => "auth #{digest.to_s}", "Match" => /\d{3}/) do |auth_response| if(!(/^200/ =~ auth_response)) raise AuthenticationError, "Could not authenticate" end end end end connection.cmd('String' => command, 'Match' => /\n\n/) {|r| response = r.split("\n").first.strip} connection.close if connection.respond_to?(:close) rescue Exception => e if retries < Lacquer.configuration.retries retry else if Lacquer.configuration.command_error_handler Lacquer.configuration.command_error_handler.call({ :error_class => "Varnish Error, retried #{Lacquer.configuration.retries} times", :error_message => "Error while trying to connect to #{server[:host]}:#{server[:port]}: #{e}", :parameters => server, :response => response }) elsif e.kind_of?(Lacquer::AuthenticationError) raise e else raise VarnishError.new("Error while trying to connect to #{server[:host]}:#{server[:port]} #{e}") end end end response end end
ruby
{ "resource": "" }
q1321
MidiSmtpServer.TlsTransport.start
train
def start(io) # start SSL negotiation ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx) # connect to server socket ssl.accept # make sure to close also the underlying io ssl.sync_close = true # return as new io socket return ssl end
ruby
{ "resource": "" }
q1322
ResponsiveImages.ViewHelpers.responsive_image_tag
train
def responsive_image_tag image, options={} # Merge any options passed with the configured options sizes = ResponsiveImages.options.deep_merge(options) # Let's create a hash of the alternative options for our data attributes data_sizes = alternative_sizes(image, sizes) # Get the image source image_src = src_path(image, sizes) # Return the image tag with our responsive data attributes return image_tag image_src, data_sizes.merge(options) end
ruby
{ "resource": "" }
q1323
ResponsiveImages.ViewHelpers.alternative_sizes
train
def alternative_sizes image, sizes data_sizes = {} sizes[:sizes].each do |size, value| if value.present? data_sizes["data-#{size}-src"] = (value == :default ? image.url : image.send(value)) else false end end data_sizes end
ruby
{ "resource": "" }
q1324
WorldDb.ReaderBase.load_continent_defs
train
def load_continent_defs( name, more_attribs={} ) reader = create_values_reader( name, more_attribs ) reader.each_line do |attribs, values| ## check optional values values.each_with_index do |value, index| logger.warn "unknown type for value >#{value}<" end rec = Continent.find_by_key( attribs[ :key ] ) if rec.present? logger.debug "update Continent #{rec.id}-#{rec.key}:" else logger.debug "create Continent:" rec = Continent.new end logger.debug attribs.to_json rec.update_attributes!( attribs ) end # each lines end
ruby
{ "resource": "" }
q1325
BracketTree.PositionalRelation.all
train
def all if @side if @round seats = by_round @round, @side else side_root = @bracket.root.send(@side) seats = [] @bracket.top_down(side_root) do |node| seats << node end end else if @round seats = by_round(@round, :left) + by_round(@round, :right) else seats = [] @bracket.top_down(@bracket.root) do |node| seats << node end end end seats end
ruby
{ "resource": "" }
q1326
BracketTree.PositionalRelation.by_round
train
def by_round round, side depth = @bracket.depth[side] - (round - 1) seats = [] side_root = @bracket.root.send(side) @bracket.top_down(side_root) do |node| if node.depth == depth seats << node end end seats end
ruby
{ "resource": "" }
q1327
Danger.DangerSlather.configure
train
def configure(xcodeproj_path, scheme, options: {}) require 'slather' @project = Slather::Project.open(xcodeproj_path) @project.scheme = scheme @project.workspace = options[:workspace] @project.build_directory = options[:build_directory] @project.ignore_list = options[:ignore_list] @project.ci_service = options[:ci_service] @project.coverage_access_token = options[:coverage_access_token] @project.coverage_service = options[:coverage_service] || :terminal @project.source_directory = options[:source_directory] @project.output_directory = options[:output_directory] @project.input_format = options[:input_format] @project.binary_file = options[:binary_file] @project.decimals = options[:decimals] @project.configure @project.post if options[:post] end
ruby
{ "resource": "" }
q1328
Danger.DangerSlather.total_coverage
train
def total_coverage unless @project.nil? @total_coverage ||= begin total_project_lines = 0 total_project_lines_tested = 0 @project.coverage_files.each do |coverage_file| total_project_lines_tested += coverage_file.num_lines_tested total_project_lines += coverage_file.num_lines_testable end @total_coverage = (total_project_lines_tested / total_project_lines.to_f) * 100.0 end end end
ruby
{ "resource": "" }
q1329
Danger.DangerSlather.notify_if_coverage_is_less_than
train
def notify_if_coverage_is_less_than(options) minimum_coverage = options[:minimum_coverage] notify_level = options[:notify_level] || :fail if total_coverage < minimum_coverage notify_message = "Total coverage less than #{minimum_coverage}%" if notify_level == :fail fail notify_message else warn notify_message end end end
ruby
{ "resource": "" }
q1330
Danger.DangerSlather.notify_if_modified_file_is_less_than
train
def notify_if_modified_file_is_less_than(options) minimum_coverage = options[:minimum_coverage] notify_level = options[:notify_level] || :fail if all_modified_files_coverage.count > 0 files_to_notify = all_modified_files_coverage.select do |file| file.percentage_lines_tested < minimum_coverage end notify_messages = files_to_notify.map do |file| "#{file.source_file_pathname_relative_to_repo_root} has less than #{minimum_coverage}% code coverage" end notify_messages.each do |message| if notify_level == :fail fail message else warn message end end end end
ruby
{ "resource": "" }
q1331
Danger.DangerSlather.modified_files_coverage_table
train
def modified_files_coverage_table unless @project.nil? line = '' if all_modified_files_coverage.count > 0 line << "File | Coverage\n" line << "-----|-----\n" all_modified_files_coverage.each do |coverage_file| file_name = coverage_file.source_file_pathname_relative_to_repo_root.to_s percentage = @project.decimal_f([coverage_file.percentage_lines_tested]) line << "#{file_name} | **`#{percentage}%`**\n" end end return line end end
ruby
{ "resource": "" }
q1332
Danger.DangerSlather.show_coverage
train
def show_coverage unless @project.nil? line = "## Code coverage\n" line << total_coverage_markdown line << modified_files_coverage_table line << '> Powered by [Slather](https://github.com/SlatherOrg/slather)' markdown line end end
ruby
{ "resource": "" }
q1333
Danger.DangerSlather.all_modified_files_coverage
train
def all_modified_files_coverage unless @project.nil? all_modified_files_coverage ||= begin modified_files = git.modified_files.nil? ? [] : git.modified_files added_files = git.added_files.nil? ? [] : git.added_files all_changed_files = modified_files | added_files @project.coverage_files.select do |file| all_changed_files.include? file.source_file_pathname_relative_to_repo_root.to_s end end all_modified_files_coverage end end
ruby
{ "resource": "" }
q1334
GreenOnion.Compare.diff_iterator
train
def diff_iterator @images.first.height.times do |y| @images.first.row(y).each_with_index do |pixel, x| unless pixel == @images.last[x,y] @diff_index << [x,y] pixel_difference_filter(pixel, x, y) end end end end
ruby
{ "resource": "" }
q1335
GreenOnion.Compare.pixel_difference_filter
train
def pixel_difference_filter(pixel, x, y) chans = [] [:r, :b, :g].each do |chan| chans << channel_difference(chan, pixel, x, y) end @images.last[x,y] = ChunkyPNG::Color.rgb(chans[0], chans[1], chans[2]) end
ruby
{ "resource": "" }
q1336
GreenOnion.Compare.channel_difference
train
def channel_difference(chan, pixel, x, y) ChunkyPNG::Color.send(chan, pixel) + ChunkyPNG::Color.send(chan, @images.last[x,y]) - 2 * [ChunkyPNG::Color.send(chan, pixel), ChunkyPNG::Color.send(chan, @images.last[x,y])].min end
ruby
{ "resource": "" }
q1337
GreenOnion.Compare.percentage_diff
train
def percentage_diff(org, fresh) diff_images(org, fresh) @total_px = @images.first.pixels.length @changed_px = @diff_index.length @percentage_changed = ( (@diff_index.length.to_f / @images.first.pixels.length) * 100 ).round(2) end
ruby
{ "resource": "" }
q1338
GreenOnion.Compare.save_visual_diff
train
def save_visual_diff(org, fresh) x, y = @diff_index.map{ |xy| xy[0] }, @diff_index.map{ |xy| xy[1] } @diffed_image = org.insert(-5, '_diff') begin @images.last.rect(x.min, y.min, x.max, y.max, ChunkyPNG::Color.rgb(0,255,0)) rescue NoMethodError puts "Both skins are the same.".color(:yellow) end @images.last.save(@diffed_image) end
ruby
{ "resource": "" }
q1339
Etcd.Keys.get
train
def get(key, opts = {}) response = api_execute(key_endpoint + key, :get, params: opts) Response.from_http_response(response) end
ruby
{ "resource": "" }
q1340
Etcd.Keys.set
train
def set(key, opts = nil) fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) path = key_endpoint + key payload = {} [:ttl, :value, :dir, :prevExist, :prevValue, :prevIndex].each do |k| payload[k] = opts[k] if opts.key?(k) end response = api_execute(path, :put, params: payload) Response.from_http_response(response) end
ruby
{ "resource": "" }
q1341
Etcd.Keys.compare_and_swap
train
def compare_and_swap(key, opts = {}) fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) fail ArgumentError, 'You must pass prevValue' unless opts.key?(:prevValue) set(key, opts) end
ruby
{ "resource": "" }
q1342
Etcd.Keys.watch
train
def watch(key, opts = {}) params = { wait: true } fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) timeout = opts[:timeout] || @read_timeout index = opts[:waitIndex] || opts[:index] params[:waitIndex] = index unless index.nil? params[:consistent] = opts[:consistent] if opts.key?(:consistent) params[:recursive] = opts[:recursive] if opts.key?(:recursive) response = api_execute( key_endpoint + key, :get, timeout: timeout, params: params ) Response.from_http_response(response) end
ruby
{ "resource": "" }
q1343
GremlinClient.Connection.receive_message
train
def receive_message(msg) response = Oj.load(msg.data) # this check is important in case a request timeout and we make new ones after if response['requestId'] == @request_id if @response.nil? @response = response else @response['result']['data'].concat response['result']['data'] @response['result']['meta'].merge! response['result']['meta'] @response['status'] = response['status'] end end end
ruby
{ "resource": "" }
q1344
GremlinClient.Connection.treat_response
train
def treat_response # note that the partial_content status should be processed differently. # look at http://tinkerpop.apache.org/docs/3.0.1-incubating/ for more info ok_status = [:success, :no_content, :partial_content].map { |st| STATUS[st] } unless ok_status.include?(@response['status']['code']) fail ::GremlinClient::ServerError.new(@response['status']['code'], @response['status']['message']) end @response['result'] end
ruby
{ "resource": "" }
q1345
YandexMoney.ExternalPayment.request_external_payment
train
def request_external_payment(payment_options) payment_options[:instance_id] = @instance_id request = self.class.send_external_payment_request("/api/request-external-payment", payment_options) RecursiveOpenStruct.new request.parsed_response end
ruby
{ "resource": "" }
q1346
YandexMoney.ExternalPayment.process_external_payment
train
def process_external_payment(payment_options) payment_options[:instance_id] = @instance_id request = self.class.send_external_payment_request("/api/process-external-payment", payment_options) RecursiveOpenStruct.new request.parsed_response end
ruby
{ "resource": "" }
q1347
CassandraMigrations.Migration.migrate
train
def migrate(direction) return unless respond_to?(direction) case direction when :up then announce_migration "migrating" when :down then announce_migration "reverting" end time = Benchmark.measure { send(direction) } case direction when :up then announce_migration "migrated (%.4fs)" % time.real; puts when :down then announce_migration "reverted (%.4fs)" % time.real; puts end end
ruby
{ "resource": "" }
q1348
CassandraMigrations.Migration.announce_migration
train
def announce_migration(message) text = "#{name}: #{message}" length = [0, 75 - text.length].max puts "== %s %s" % [text, "=" * length] end
ruby
{ "resource": "" }
q1349
YandexMoney.Wallet.operation_history
train
def operation_history(options=nil) history = RecursiveOpenStruct.new( send_request("/api/operation-history", options).parsed_response ) history.operations = history.operations.map do |operation| RecursiveOpenStruct.new operation end history end
ruby
{ "resource": "" }
q1350
YandexMoney.Wallet.operation_details
train
def operation_details(operation_id) request = send_request("/api/operation-details", operation_id: operation_id) RecursiveOpenStruct.new request.parsed_response end
ruby
{ "resource": "" }
q1351
YandexMoney.Wallet.incoming_transfer_accept
train
def incoming_transfer_accept(operation_id, protection_code = nil) uri = "/api/incoming-transfer-accept" if protection_code request_body = { operation_id: operation_id, protection_code: protection_code } else request_body = { operation_id: operation_id } end RecursiveOpenStruct.new send_request("/api/incoming-transfer-accept", request_body) end
ruby
{ "resource": "" }
q1352
Etcd.Client.api_execute
train
def api_execute(path, method, options = {}) params = options[:params] case method when :get req = build_http_request(Net::HTTP::Get, path, params) when :post req = build_http_request(Net::HTTP::Post, path, nil, params) when :put req = build_http_request(Net::HTTP::Put, path, nil, params) when :delete req = build_http_request(Net::HTTP::Delete, path, params) else fail "Unknown http action: #{method}" end http = Net::HTTP.new(host, port) http.read_timeout = options[:timeout] || read_timeout setup_https(http) req.basic_auth(user_name, password) if [user_name, password].all? Log.debug("Invoking: '#{req.class}' against '#{path}") res = http.request(req) Log.debug("Response code: #{res.code}") Log.debug("Response body: #{res.body}") process_http_request(res) end
ruby
{ "resource": "" }
q1353
Etcd.Client.process_http_request
train
def process_http_request(res) case res when HTTP_SUCCESS Log.debug('Http success') res when HTTP_CLIENT_ERROR fail Error.from_http_response(res) else Log.debug('Http error') Log.debug(res.body) res.error! end end
ruby
{ "resource": "" }
q1354
GitReview.Commands.list
train
def list(reverse = false) requests = server.current_requests_full.reject do |request| # Find only pending (= unmerged) requests and output summary. # Explicitly look for local changes git does not yet know about. # TODO: Isn't this a bit confusing? Maybe display pending pushes? local.merged? request.head.sha end source = local.source if requests.empty? puts "No pending requests for '#{source}'." else puts "Pending requests for '#{source}':" puts "ID Updated Comments Title".pink print_requests(requests, reverse) end end
ruby
{ "resource": "" }
q1355
GitReview.Commands.show
train
def show(number, full = false) request = server.get_request_by_number(number) # Determine whether to show full diff or stats only. option = full ? '' : '--stat ' diff = "diff --color=always #{option}HEAD...#{request.head.sha}" # TODO: Refactor into using Request model. print_request_details request puts git_call(diff) print_request_discussions request end
ruby
{ "resource": "" }
q1356
GitReview.Commands.browse
train
def browse(number) request = server.get_request_by_number(number) # FIXME: Use request.html_url as soon as we are using our Request model. Launchy.open request._links.html.href end
ruby
{ "resource": "" }
q1357
GitReview.Commands.checkout
train
def checkout(number, branch = true) request = server.get_request_by_number(number) puts 'Checking out changes to your local repository.' puts 'To get back to your original state, just run:' puts puts ' git checkout master'.pink puts # Ensure we are looking at the right remote. remote = local.remote_for_request(request) git_call "fetch #{remote}" # Checkout the right branch. branch_name = request.head.ref if branch if local.branch_exists?(:local, branch_name) if local.source_branch == branch_name puts "On branch #{branch_name}." else git_call "checkout #{branch_name}" end else git_call "checkout --track -b #{branch_name} #{remote}/#{branch_name}" end else git_call "checkout #{remote}/#{branch_name}" end end
ruby
{ "resource": "" }
q1358
GitReview.Commands.approve
train
def approve(number) request = server.get_request_by_number(number) repo = server.source_repo # TODO: Make this configurable. comment = 'Reviewed and approved.' response = server.add_comment(repo, request.number, comment) if response[:body] == comment puts 'Successfully approved request.' else puts response[:message] end end
ruby
{ "resource": "" }
q1359
GitReview.Commands.merge
train
def merge(number) request = server.get_request_by_number(number) if request.head.repo message = "Accept request ##{request.number} " + "and merge changes into \"#{local.target}\"" command = "merge -m '#{message}' #{request.head.sha}" puts puts "Request title:" puts " #{request.title}" puts puts "Merge command:" puts " git #{command}" puts puts git_call(command) else print_repo_deleted request end end
ruby
{ "resource": "" }
q1360
GitReview.Commands.close
train
def close(number) request = server.get_request_by_number(number) repo = server.source_repo server.close_issue(repo, request.number) unless server.request_exists?('open', request.number) puts 'Successfully closed request.' end end
ruby
{ "resource": "" }
q1361
GitReview.Commands.create
train
def create(upstream = false) # Prepare original_branch and local_branch. # TODO: Allow to use the same switches and parameters that prepare takes. original_branch, local_branch = prepare # Don't create request with uncommitted changes in current branch. if local.uncommitted_changes? puts 'You have uncommitted changes.' puts 'Please stash or commit before creating the request.' return end if local.new_commits?(upstream) # Feature branch differs from local or upstream master. if server.request_exists_for_branch?(upstream) puts 'A pull request already exists for this branch.' puts 'Please update the request directly using `git push`.' return end # Push latest commits to the remote branch (create if necessary). remote = local.remote_for_branch(local_branch) || 'origin' git_call( "push --set-upstream #{remote} #{local_branch}", debug_mode, true ) server.send_pull_request upstream # Return to the user's original branch. git_call "checkout #{original_branch}" else puts 'Nothing to push to remote yet. Commit something first.' end end
ruby
{ "resource": "" }
q1362
GitReview.Commands.print_repo_deleted
train
def print_repo_deleted(request) user = request.head.user.login url = request.patch_url puts "Sorry, #{user} deleted the source repository." puts "git-review doesn't support this." puts "Tell the contributor not to do this." puts puts "You can still manually patch your repo by running:" puts puts " curl #{url} | git am" puts end
ruby
{ "resource": "" }
q1363
GitReview.Commands.move_local_changes
train
def move_local_changes(original_branch, feature_name) feature_branch = create_feature_name(feature_name) # By checking out the feature branch, the commits on the original branch # are copied over. That way we only need to remove pending (local) commits # from the original branch. git_call "checkout -b #{feature_branch}" if local.source_branch == feature_branch # Save any uncommitted changes, to be able to reapply them later. save_uncommitted_changes = local.uncommitted_changes? git_call('stash') if save_uncommitted_changes # Go back to original branch and get rid of pending (local) commits. git_call("checkout #{original_branch}") remote = local.remote_for_branch(original_branch) remote += '/' if remote git_call("reset --hard #{remote}#{original_branch}") git_call("checkout #{feature_branch}") git_call('stash pop') if save_uncommitted_changes feature_branch end end
ruby
{ "resource": "" }
q1364
CookieJar.Cookie.to_s
train
def to_s(ver = 0, prefix = true) return "#{name}=#{value}" if ver == 0 # we do not need to encode path; the only characters required to be # quoted must be escaped in URI str = prefix ? "$Version=#{version};" : '' str << "#{name}=#{value};$Path=\"#{path}\"" str << ";$Domain=#{domain}" if domain.start_with? '.' str << ";$Port=\"#{ports.join ','}\"" if ports str end
ruby
{ "resource": "" }
q1365
CookieJar.Cookie.to_hash
train
def to_hash result = { name: @name, value: @value, domain: @domain, path: @path, created_at: @created_at } { expiry: @expiry, secure: (true if @secure), http_only: (true if @http_only), version: (@version if version != 0), comment: @comment, comment_url: @comment_url, discard: (true if @discard), ports: @ports }.each do |name, value| result[name] = value if value end result end
ruby
{ "resource": "" }
q1366
CookieJar.Cookie.should_send?
train
def should_send?(request_uri, script) uri = CookieJar::CookieValidation.to_uri request_uri # cookie path must start with the uri, it must not be a secure cookie # being sent over http, and it must not be a http_only cookie sent to # a script path = if uri.path == '' '/' else uri.path end path_match = path.start_with? @path secure_match = !(@secure && uri.scheme == 'http') script_match = !(script && @http_only) expiry_match = !expired? ports_match = ports.nil? || (ports.include? uri.port) path_match && secure_match && script_match && expiry_match && ports_match end
ruby
{ "resource": "" }
q1367
GitReview.Local.remotes_with_urls
train
def remotes_with_urls result = {} git_call('remote -vv').split("\n").each do |line| entries = line.split("\t") remote = entries.first target_entry = entries.last.split(' ') direction = target_entry.last[1..-2].to_sym target_url = target_entry.first result[remote] ||= {} result[remote][direction] = target_url end result end
ruby
{ "resource": "" }
q1368
GitReview.Local.remotes_for_url
train
def remotes_for_url(remote_url) result = remotes_with_urls.collect do |remote, urls| remote if urls.values.all? { |url| url == remote_url } end result.compact end
ruby
{ "resource": "" }
q1369
GitReview.Local.remote_for_request
train
def remote_for_request(request) repo_owner = request.head.repo.owner.login remote_url = server.remote_url_for(repo_owner) remotes = remotes_for_url(remote_url) if remotes.empty? remote = "review_#{repo_owner}" git_call("remote add #{remote} #{remote_url}", debug_mode, true) else remote = remotes.first end remote end
ruby
{ "resource": "" }
q1370
GitReview.Local.clean_remotes
train
def clean_remotes protected_remotes = remotes_for_branches remotes.each do |remote| # Only remove review remotes that aren't referenced by current branches. if remote.index('review_') == 0 && !protected_remotes.include?(remote) git_call "remote remove #{remote}" end end end
ruby
{ "resource": "" }
q1371
GitReview.Local.remotes_for_branches
train
def remotes_for_branches remotes = git_call('branch -lvv').gsub('* ', '').split("\n").map do |line| line.split(' ')[2][1..-2].split('/').first end remotes.uniq end
ruby
{ "resource": "" }
q1372
GitReview.Local.remote_for_branch
train
def remote_for_branch(branch_name) git_call('branch -lvv').gsub('* ', '').split("\n").each do |line| entries = line.split(' ') next unless entries.first == branch_name # Return the remote name or nil for local branches. match = entries[2].match(%r(\[(.*)(\]|:))) return match[1].split('/').first if match end nil end
ruby
{ "resource": "" }
q1373
GitReview.Local.clean_single
train
def clean_single(number, force = false) request = server.pull_request(source_repo, number) if request && request.state == 'closed' # ensure there are no unmerged commits or '--force' flag has been set branch_name = request.head.ref if unmerged_commits?(branch_name) && !force puts "Won't delete branches that contain unmerged commits." puts "Use '--force' to override." else delete_branch(branch_name) end end rescue Octokit::NotFound false end
ruby
{ "resource": "" }
q1374
GitReview.Local.clean_all
train
def clean_all (review_branches - protected_branches).each do |branch_name| # only clean up obsolete branches. delete_branch(branch_name) unless unmerged_commits?(branch_name, false) end end
ruby
{ "resource": "" }
q1375
GitReview.Local.target_repo
train
def target_repo(upstream=false) # TODO: Manually override this and set arbitrary repositories if upstream server.repository(source_repo).parent.full_name else source_repo end end
ruby
{ "resource": "" }
q1376
CookieJar.Jar.set_cookie2
train
def set_cookie2(request_uri, cookie_header_value) cookie = Cookie.from_set_cookie2 request_uri, cookie_header_value add_cookie cookie end
ruby
{ "resource": "" }
q1377
CookieJar.Jar.to_a
train
def to_a result = [] @domains.values.each do |paths| paths.values.each do |cookies| cookies.values.inject result, :<< end end result end
ruby
{ "resource": "" }
q1378
CookieJar.Jar.expire_cookies
train
def expire_cookies(session = false) @domains.delete_if do |_domain, paths| paths.delete_if do |_path, cookies| cookies.delete_if do |_cookie_name, cookie| cookie.expired? || (session && cookie.session?) end cookies.empty? end paths.empty? end end
ruby
{ "resource": "" }
q1379
CookieJar.Jar.get_cookies
train
def get_cookies(request_uri, opts = {}) uri = to_uri request_uri hosts = Cookie.compute_search_domains uri return [] if hosts.nil? path = if uri.path == '' '/' else uri.path end results = [] hosts.each do |host| domain = find_domain host domain.each do |apath, cookies| next unless path.start_with? apath results += cookies.values.select do |cookie| cookie.should_send? uri, opts[:script] end end end # Sort by path length, longest first results.sort do |lhs, rhs| rhs.path.length <=> lhs.path.length end end
ruby
{ "resource": "" }
q1380
CookieJar.Jar.get_cookie_header
train
def get_cookie_header(request_uri, opts = {}) cookies = get_cookies request_uri, opts ver = [[], []] cookies.each do |cookie| ver[cookie.version] << cookie end if ver[1].empty? # can do a netscape-style cookie header, relish the opportunity cookies.map(&:to_s).join ';' else # build a RFC 2965-style cookie header. Split the cookies into # version 0 and 1 groups so that we can reuse the '$Version' header result = '' unless ver[0].empty? result << '$Version=0;' result << ver[0].map do |cookie| (cookie.to_s 1, false) end.join(';') # separate version 0 and 1 with a comma result << ',' end result << '$Version=1;' ver[1].map do |cookie| result << (cookie.to_s 1, false) end result end end
ruby
{ "resource": "" }
q1381
Memoizable.Memory.[]=
train
def []=(name, value) memoized = true @memory.compute_if_absent(name) do memoized = false value end fail ArgumentError, "The method #{name} is already memoized" if memoized end
ruby
{ "resource": "" }
q1382
Jsonify.Builder.attributes!
train
def attributes!(object, *attrs) attrs.each do |attr| method_missing attr, object.send(attr) end end
ruby
{ "resource": "" }
q1383
Jsonify.Builder.array!
train
def array!(args) __array args.each do |arg| @level += 1 yield arg @level -= 1 value = @stack.pop # If the object created was an array with a single value # assume that just the value should be added if (JsonArray === value && value.values.length <= 1) value = value.values.first end @stack[@level].add value end end
ruby
{ "resource": "" }
q1384
Semrush.Report.error
train
def error(text = "") e = /ERROR\s(\d+)\s::\s(.*)/.match(text) || {} name = (e[2] || "UnknownError").titleize code = e[1] || -1 error_class = name.gsub(/\s/, "") if error_class == "NothingFound" [] else begin raise Semrush::Exception.const_get(error_class).new(self, "#{name} (#{code})") rescue raise Semrush::Exception::Base.new(self, "#{name} (#{code}) *** error_class=#{error_class} not implemented ***") end end end
ruby
{ "resource": "" }
q1385
Astrolabe.Node.each_ancestor
train
def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_ancestors(&block) else visit_ancestors_with_types(types, &block) end self end
ruby
{ "resource": "" }
q1386
Astrolabe.Node.each_child_node
train
def each_child_node(*types) return to_enum(__method__, *types) unless block_given? types.flatten! children.each do |child| next unless child.is_a?(Node) yield child if types.empty? || types.include?(child.type) end self end
ruby
{ "resource": "" }
q1387
Astrolabe.Node.each_descendant
train
def each_descendant(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
ruby
{ "resource": "" }
q1388
Astrolabe.Node.each_node
train
def each_node(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! yield self if types.empty? || types.include?(type) if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
ruby
{ "resource": "" }
q1389
AvatarsForRails.ActiveRecord.acts_as_avatarable
train
def acts_as_avatarable(options = {}) options[:styles] ||= AvatarsForRails.avatarable_styles cattr_accessor :avatarable_options self.avatarable_options = options include AvatarsForRails::Avatarable end
ruby
{ "resource": "" }
q1390
Memoizable.MethodBuilder.create_memoized_method
train
def create_memoized_method name, method, freezer = @method_name, @original_method, @freezer @descendant.module_eval do define_method(name) do |&block| fail BlockNotAllowedError.new(self.class, name) if block memoized_method_cache.fetch(name) do freezer.call(method.bind(self).call) end end end end
ruby
{ "resource": "" }
q1391
Lol.ChampionMasteryRequest.all
train
def all summoner_id: result = perform_request api_url "champion-masteries/by-summoner/#{summoner_id}" result.map { |c| DynamicModel.new c } end
ruby
{ "resource": "" }
q1392
Lol.ChampionRequest.all
train
def all free_to_play: false result = perform_request api_url("champions", "freeToPlay" => free_to_play) result["champions"].map { |c| DynamicModel.new c } end
ruby
{ "resource": "" }
q1393
Zuora.Response.symbolize_key
train
def symbolize_key(key) return key unless key.respond_to?(:split) key.split(':').last.underscore.to_sym end
ruby
{ "resource": "" }
q1394
Zuora.Response.symbolize_keys_deep
train
def symbolize_keys_deep(hash) return hash unless hash.is_a?(Hash) Hash[hash.map do |key, value| # if value is array, loop each element and recursively symbolize keys if value.is_a? Array value = value.map { |element| symbolize_keys_deep(element) } # if value is hash, recursively symbolize keys elsif value.is_a? Hash value = symbolize_keys_deep(value) end [symbolize_key(key), value] end] end
ruby
{ "resource": "" }
q1395
Zuora.Client.to_s
train
def to_s public_vars = instance_variables.reject do |var| INSTANCE_VARIABLE_LOG_BLACKLIST.include? var end public_vars.map! do |var| "#{var}=\"#{instance_variable_get(var)}\"" end public_vars = public_vars.join(' ') "<##{self.class}:#{object_id.to_s(8)} #{public_vars}>" end
ruby
{ "resource": "" }
q1396
Lol.TournamentRequest.create_tournament
train
def create_tournament provider_id:, name: nil body = { "providerId" => provider_id, "name" => name }.delete_if do |k, v| v.nil? end perform_request api_url("tournaments"), :post, body end
ruby
{ "resource": "" }
q1397
Lol.TournamentRequest.create_codes
train
def create_codes tournament_id:, count: nil, allowed_participants: nil, map_type: "SUMMONERS_RIFT", metadata: nil, team_size: 5, pick_type: "TOURNAMENT_DRAFT", spectator_type: "ALL" body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "metadata" => metadata, "pickType" => pick_type, "spectatorType" => spectator_type, "teamSize" => team_size }.compact uri_params = { "tournamentId" => tournament_id, "count" => count }.compact perform_request api_url("codes", uri_params), :post, body end
ruby
{ "resource": "" }
q1398
Lol.TournamentRequest.update_code
train
def update_code tournament_code, allowed_participants: nil, map_type: nil, pick_type: nil, spectator_type: nil body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "pickType" => pick_type, "spectatorType" => spectator_type }.compact perform_request api_url("codes/#{tournament_code}"), :put, body end
ruby
{ "resource": "" }
q1399
Lol.TournamentRequest.all_lobby_events
train
def all_lobby_events tournament_code: result = perform_request api_url "lobby-events/by-code/#{tournament_code}" result["eventList"].map { |e| DynamicModel.new e } end
ruby
{ "resource": "" }