_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q1400
Lol.SummonerRequest.find_by_name
train
def find_by_name name name = CGI.escape name.downcase.gsub(/\s/, '') DynamicModel.new perform_request api_url "summoners/by-name/#{name}" end
ruby
{ "resource": "" }
q1401
Scriptster.Configuration.apply
train
def apply Logger.set_name @name if @name Logger.set_verbosity @verbosity if @verbosity Logger.set_file @file if @file Logger.set_format @log_format if @log_format if @colours.is_a? Proc @colours.call else ColourThemes.send @colours.to_sym end end
ruby
{ "resource": "" }
q1402
Lol.Request.api_url
train
def api_url path, params = {} url = File.join File.join(api_base_url, api_base_path), path "#{url}?#{api_query_string params}" end
ruby
{ "resource": "" }
q1403
Lol.Request.clean_url
train
def clean_url(url) uri = URI.parse(url) uri.query = CGI.parse(uri.query || '').reject { |k| k == 'api_key' }.to_query uri.to_s end
ruby
{ "resource": "" }
q1404
Lol.Request.perform_request
train
def perform_request url, verb = :get, body = nil, options = {} options_id = options.inspect can_cache = [:post, :put].include?(verb) ? false : cached? if can_cache && result = store.get("#{clean_url(url)}#{options_id}") return JSON.parse(result) end response = perform_rate_limited_request(url, verb, body, options) store.setex "#{clean_url(url)}#{options_id}", ttl, response.to_json if can_cache response end
ruby
{ "resource": "" }
q1405
Scriptster.ShellCmd.run
train
def run Open3.popen3(@cmd) do |stdin, stdout, stderr, wait_thr| stdin.close # leaving stdin open when we don't use it can cause some commands to hang stdout_buffer="" stderr_buffer="" streams = [stdout, stderr] while streams.length > 0 IO.select(streams).flatten.compact.each do |io| if io.eof? streams.delete io next end stdout_buffer += io.readpartial(1) if io.fileno == stdout.fileno stderr_buffer += io.readpartial(1) if io.fileno == stderr.fileno end # Remove and process all the finished lines from the output buffer stdout_buffer.sub!(/.*\n/m) do @out += $& if @show_out $&.strip.split("\n").each do |line| line = @tag.style("cmd") + " " + line if @tag log(@out_level, line) end end '' end # Remove and process all the finished lines from the error buffer stderr_buffer.sub!(/.*\n/m) do @err += $& if @show_err $&.strip.split("\n").each do |line| line = @tag.style("cmd") + " " + line if @tag log(:err, line) end end '' end end @status = wait_thr.value end if (@expect.is_a?(Array) && !@expect.include?(@status.exitstatus)) || (@expect.is_a?(Integer) && @status.exitstatus != @expect) unless @show_err err_lines = @err.split "\n" err_lines.each do |l| l = @tag.style("cmd") + " " + l if @tag log(:err, l.chomp) end end raise "'#{@cmd}' failed!" if @raise end end
ruby
{ "resource": "" }
q1406
Lol.MasteriesRequest.by_summoner_id
train
def by_summoner_id summoner_id result = perform_request api_url "masteries/by-summoner/#{summoner_id}" result["pages"].map { |p| DynamicModel.new p } end
ruby
{ "resource": "" }
q1407
SchemaModel.ClassMethods.define_writer!
train
def define_writer!(k, definition) define_method("#{k}=") do |value| # Recursively convert hash and array of hash to schematized objects value = ensure_schema value, definition[:schema] # Initial value instance_variable_set "@#{k}", value # Dirty tracking self.changed_attributes ||= Set.new self.changed_attributes << k end end
ruby
{ "resource": "" }
q1408
SchemaModel.InstanceMethods.check_children
train
def check_children(child_schema, value) return unless child_schema && value.present? if value.is_a? Array value.map(&:errors).reject(&:empty?) else value.errors end end
ruby
{ "resource": "" }
q1409
SchemaModel.InstanceMethods.check_validation
train
def check_validation(valid, value) return unless valid && value passes_validation = begin valid.call(value) rescue StandardError false end passes_validation ? nil : 'is invalid' end
ruby
{ "resource": "" }
q1410
SchemaModel.InstanceMethods.append!
train
def append!(errors, attr, key, val) return unless val.present? errors ||= {} errors[attr] ||= {} errors[attr][key] = val end
ruby
{ "resource": "" }
q1411
Delighted.Resource.to_hash
train
def to_hash serialized_attributes = attributes.dup self.class.expandable_attributes.each_pair.select do |attribute_name, expanded_class| if expanded_class === attributes[attribute_name] serialized_attributes[attribute_name] = serialized_attributes[attribute_name].id end end serialized_attributes end
ruby
{ "resource": "" }
q1412
Mailgun.Webhook.update
train
def update(id, url=default_webhook_url) params = {:url => url} Mailgun.submit :put, webhook_url(id), params end
ruby
{ "resource": "" }
q1413
Mailgun.MailingList.update
train
def update(address, new_address, options={}) params = {:address => new_address} Mailgun.submit :put, list_url(address), params.merge(options) end
ruby
{ "resource": "" }
q1414
EncryptedStrings.AsymmetricCipher.encrypt
train
def encrypt(data) raise NoPublicKeyError, "Public key file: #{public_key_file}" unless public? encrypted_data = public_rsa.public_encrypt(data) [encrypted_data].pack('m') end
ruby
{ "resource": "" }
q1415
EncryptedStrings.AsymmetricCipher.decrypt
train
def decrypt(data) raise NoPrivateKeyError, "Private key file: #{private_key_file}" unless private? decrypted_data = data.unpack('m')[0] private_rsa.private_decrypt(decrypted_data) end
ruby
{ "resource": "" }
q1416
EncryptedStrings.AsymmetricCipher.private_rsa
train
def private_rsa if password options = {:password => password} options[:algorithm] = algorithm if algorithm private_key = @private_key.decrypt(:symmetric, options) OpenSSL::PKey::RSA.new(private_key) else @private_rsa ||= OpenSSL::PKey::RSA.new(@private_key) end end
ruby
{ "resource": "" }
q1417
EncryptedStrings.ShaCipher.encrypt
train
def encrypt(data) Digest::const_get(algorithm.upcase).hexdigest(build(data, salt)) end
ruby
{ "resource": "" }
q1418
EncryptedStrings.ShaCipher.build
train
def build(data, salt) if builder.is_a?(Proc) builder.call(data, salt) else builder.send(:build, data, salt) end end
ruby
{ "resource": "" }
q1419
Mailgun.Secure.check_request_auth
train
def check_request_auth(timestamp, token, signature, offset=-5) if offset != 0 offset = Time.now.to_i + offset * 60 return false if timestamp < offset end return signature == OpenSSL::HMAC.hexdigest( OpenSSL::Digest::Digest.new('sha256'), Mailgun.api_key, '%s%s' % [timestamp, token]) end
ruby
{ "resource": "" }
q1420
Res.IR.json
train
def json hash = { :started => @started, :finished => @finished, :results => @results, :type => @type } # Merge in the world information if it's available hash[:world] = world if world hash[:hive_job_id] = hive_job_id if hive_job_id JSON.pretty_generate( hash ) end
ruby
{ "resource": "" }
q1421
EncryptedStrings.SymmetricCipher.decrypt
train
def decrypt(data) cipher = build_cipher(:decrypt) cipher.update(data.unpack('m')[0]) + cipher.final end
ruby
{ "resource": "" }
q1422
EncryptedStrings.SymmetricCipher.encrypt
train
def encrypt(data) cipher = build_cipher(:encrypt) [cipher.update(data) + cipher.final].pack('m') end
ruby
{ "resource": "" }
q1423
Mailgun.Domain.create
train
def create(domain, opts = {}) opts = {name: domain}.merge(opts) Mailgun.submit :post, domain_url, opts end
ruby
{ "resource": "" }
q1424
Perlin.GradientTable.index
train
def index(*coords) s = coords.last coords.reverse[1..-1].each do |c| s = perm(s) + c end perm(s) end
ruby
{ "resource": "" }
q1425
Mailgun.MailingList::Member.add
train
def add(member_address, options={}) params = {:address => member_address} Mailgun.submit :post, list_member_url, params.merge(options) end
ruby
{ "resource": "" }
q1426
Mailgun.MailingList::Member.update
train
def update(member_address, options={}) params = {:address => member_address} Mailgun.submit :put, list_member_url(member_address), params.merge(options) end
ruby
{ "resource": "" }
q1427
BLE.Device.cancel_pairing
train
def cancel_pairing block_given? ? @o_dev[I_DEVICE].CancelPairing(&Proc.new) : @o_dev[I_DEVICE].CancelPairing() true rescue DBus::Error => e case e.name when E_DOES_NOT_EXIST then true when E_FAILED then false else raise ScriptError end end
ruby
{ "resource": "" }
q1428
BLE.Device.is_paired?
train
def is_paired? @o_dev[I_DEVICE]['Paired'] rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject else raise ScriptError end end
ruby
{ "resource": "" }
q1429
BLE.Device.trusted=
train
def trusted=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Trusted'] = val end
ruby
{ "resource": "" }
q1430
BLE.Device.blocked=
train
def blocked=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Blocked'] = val end
ruby
{ "resource": "" }
q1431
BLE.Device.refresh!
train
def refresh! _require_connection! max_wait ||= 1.5 # Use ||= due to the retry @services = Hash[@o_dev.subnodes.map {|p_srv| p_srv = [@o_dev.path, p_srv].join '/' o_srv = BLUEZ.object(p_srv) o_srv.introspect srv = o_srv.GetAll(I_GATT_SERVICE).first char = Hash[o_srv.subnodes.map {|char| p_char = [o_srv.path, char].join '/' o_char = BLUEZ.object(p_char) o_char.introspect uuid = o_char[I_GATT_CHARACTERISTIC]['UUID' ].downcase flags = o_char[I_GATT_CHARACTERISTIC]['Flags'] [ uuid, Characteristic.new({ :uuid => uuid, :flags => flags, :obj => o_char }) ] }] uuid = srv['UUID'].downcase [ uuid, { :uuid => uuid, :primary => srv['Primary'], :characteristics => char } ] }] self rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject when E_INVALID_ARGS # That's probably because all the bluez information # haven't been collected yet on dbus for GattServices if max_wait > 0 sleep(0.25) ; max_wait -= 0.25 ; retry end raise NotReady else raise ScriptError end end
ruby
{ "resource": "" }
q1432
PMScreenModule.ClassMethods.action_bar
train
def action_bar(show_action_bar, opts={}) @action_bar_options = ({show:true, back: true, icon: false}).merge(opts).merge({show: show_action_bar}) end
ruby
{ "resource": "" }
q1433
Mixpanel.Tracker.escape_object_for_js
train
def escape_object_for_js(object, i = 0) if object.kind_of? Hash # Recursive case Hash.new.tap do |h| object.each do |k, v| h[escape_object_for_js(k, i + 1)] = escape_object_for_js(v, i + 1) end end elsif object.kind_of? Enumerable # Recursive case object.map do |elt| escape_object_for_js(elt, i + 1) end elsif object.respond_to? :iso8601 # Base case - safe object object.iso8601 elsif object.kind_of?(Numeric) # Base case - safe object object elsif [true, false, nil].member?(object) # Base case - safe object object else # Base case - use string sanitizer from ActiveSupport escape_javascript(object.to_s) end end
ruby
{ "resource": "" }
q1434
HerokuExternalDb.Configuration.db_configuration
train
def db_configuration(opts) return {} unless opts raise "ca_path for #{opts.inspect} cannot be determined from Rails root; please set it explicitly" unless ca_path config = {} [ :sslca, # Needed when using X.509 :sslcert, :sslkey, ].each do |k| if value = opts[k] filepath = File.join(ca_path, value) raise "File #{filepath.inspect} does not exist!" unless File.exists?(filepath) config[k] = filepath end end return config end
ruby
{ "resource": "" }
q1435
HerokuExternalDb.Configuration.db_config
train
def db_config @db_config ||= begin raise "ENV['#{env_prefix}_DATABASE_URL'] expected but not found!" unless ENV["#{env_prefix}_DATABASE_URL"] config = parse_db_uri(ENV["#{env_prefix}_DATABASE_URL"]) if ENV["#{env_prefix}_DATABASE_CA"] config.merge!(db_configuration({ :sslca => ENV["#{env_prefix}_DATABASE_CA"], :sslcert => ENV["#{env_prefix}_DATABASE_CERT"], :sslkey => ENV["#{env_prefix}_DATABASE_KEY"], })) end config end end
ruby
{ "resource": "" }
q1436
BLE.Notifications.start_notify!
train
def start_notify!(service, characteristic) char= _find_characteristic(service, characteristic) if char.flag?('notify') char.notify! else raise OperationNotSupportedError.new("No notifications available for characteristic #{characteristic}") end end
ruby
{ "resource": "" }
q1437
BLE.Notifications.on_notification
train
def on_notification(service, characteristic, raw: false, &callback) _require_connection! char= _find_characteristic(service, characteristic) if char.flag?('notify') char.on_change(raw: raw) { |val| callback.call(val) } elsif char.flag?('encrypt-read') || char.flag?('encrypt-authenticated-read') raise NotYetImplemented else raise AccessUnavailable end end
ruby
{ "resource": "" }
q1438
Steam.Client.get
train
def get(resource, params: {}, key: Steam.apikey) params[:key] = key response = @conn.get resource, params JSON.parse(response.body) rescue JSON::ParserError # If the steam web api returns an error it's virtually never in json, so # lets pretend that we're getting some sort of consistant response # for errors. { error: '500 Internal Server Error' } end
ruby
{ "resource": "" }
q1439
NdrUi.BootstrapHelper.bootstrap_tab_nav_tag
train
def bootstrap_tab_nav_tag(title, linkto, active = false) content_tag('li', link_to(title, linkto, "data-toggle": 'tab'), active ? { class: 'active' } : {}) end
ruby
{ "resource": "" }
q1440
NdrUi.BootstrapHelper.bootstrap_list_badge_and_link_to
train
def bootstrap_list_badge_and_link_to(type, count, name, path) html = content_tag(:div, bootstrap_badge_tag(type, count), class: 'pull-right') + name bootstrap_list_link_to(html, path) end
ruby
{ "resource": "" }
q1441
NdrUi.BootstrapHelper.bootstrap_progressbar_tag
train
def bootstrap_progressbar_tag(*args) percentage = args[0].to_i options = args[1] || {} options.stringify_keys! options['title'] ||= "#{percentage}%" classes = ['progress'] classes << options.delete('class') classes << 'progress-striped' type = options.delete('type').to_s type = " progress-bar-#{type}" unless type.blank? # Animate the progress bar unless something has broken: classes << 'active' unless type == 'danger' inner = content_tag(:div, '', class: "progress-bar#{type}", style: "width:#{percentage}%") options['class'] = classes.compact.join(' ') content_tag(:div, inner, options) end
ruby
{ "resource": "" }
q1442
NdrUi.BootstrapHelper.description_list_name_value_pair
train
def description_list_name_value_pair(name, value, blank_value_placeholder = nil) # SECURE: TPG 2013-08-07: The output is sanitised by content_tag return unless value.present? || blank_value_placeholder.present? content_tag(:dt, name) + content_tag(:dd, value || content_tag(:span, blank_value_placeholder, class: 'text-muted')) end
ruby
{ "resource": "" }
q1443
NdrUi.BootstrapHelper.details_link
train
def details_link(path, options = {}) return unless ndr_can?(:read, path) link_to_with_icon({ icon: 'share-alt', title: 'Details', path: path }.merge(options)) end
ruby
{ "resource": "" }
q1444
NdrUi.BootstrapHelper.edit_link
train
def edit_link(path, options = {}) return unless ndr_can?(:edit, path) path = edit_polymorphic_path(path) if path.is_a?(ActiveRecord::Base) link_to_with_icon({ icon: 'pencil', title: 'Edit', path: path }.merge(options)) end
ruby
{ "resource": "" }
q1445
NdrUi.BootstrapHelper.delete_link
train
def delete_link(path, options = {}) return unless ndr_can?(:delete, path) defaults = { icon: 'trash icon-white', title: 'Delete', path: path, class: 'btn btn-xs btn-danger', method: :delete, 'data-confirm': I18n.translate(:'ndr_ui.confirm_delete', locale: options[:locale]) } link_to_with_icon(defaults.merge(options)) end
ruby
{ "resource": "" }
q1446
NdrUi.BootstrapHelper.link_to_with_icon
train
def link_to_with_icon(options = {}) options[:class] ||= 'btn btn-default btn-xs' icon = bootstrap_icon_tag(options.delete(:icon)) content = options.delete(:text) ? icon + ' ' + options[:title] : icon link_to content, options.delete(:path), options end
ruby
{ "resource": "" }
q1447
AsciiCharts.Chart.round_value
train
def round_value(val) remainder = val % self.step_size unprecised = if (remainder * 2) >= self.step_size (val - remainder) + self.step_size else val - remainder end if self.step_size < 1 precision = -Math.log10(self.step_size).floor (unprecised * (10 ** precision)).to_i.to_f / (10 ** precision) else unprecised end end
ruby
{ "resource": "" }
q1448
BLE.Characteristic._deserialize_value
train
def _deserialize_value(val, raw: false) val = val.pack('C*') val = @desc.post_process(val) if !raw && @desc.read_processors? val end
ruby
{ "resource": "" }
q1449
NdrUi.CssHelper.css_class_options_merge
train
def css_class_options_merge(options, css_classes = [], &block) options.symbolize_keys! css_classes += options[:class].split(' ') if options.include?(:class) yield(css_classes) if block_given? options[:class] = css_classes.join(' ') unless css_classes.empty? unless css_classes == css_classes.uniq fail "Multiple css class definitions: #{css_classes.inspect}" end options end
ruby
{ "resource": "" }
q1450
BLE.Adapter.filter
train
def filter(uuids, rssi: nil, pathloss: nil, transport: :le) unless [:auto, :bredr, :le].include?(transport) raise ArgumentError, "transport must be one of :auto, :bredr, :le" end filter = { } unless uuids.nil? || uuids.empty? filter['UUIDs' ] = DBus.variant('as', uuids) end unless rssi.nil? filter['RSSI' ] = DBus.variant('n', rssi) end unless pathloss.nil? filter['Pathloss' ] = DBus.variant('q', pathloss) end unless transport.nil? filter['Transport'] = DBus.variant('s', transport.to_s) end @o_adapter[I_ADAPTER].SetDiscoveryFilter(filter) self end
ruby
{ "resource": "" }
q1451
ServiceMock.Server.stub_with_file
train
def stub_with_file(filename) return if ::ServiceMock.disable_stubs yield self if block_given? content = File.open(filename, 'rb') { |file| file.read } stub(content) end
ruby
{ "resource": "" }
q1452
ServiceMock.Server.stub_with_erb
train
def stub_with_erb(filename, hsh={}) return if ::ServiceMock.disable_stubs yield self if block_given? template = File.open(filename, 'rb') { |file| file.read } erb_content = ERB.new(template).result(data_binding(hsh)) stub(erb_content) end
ruby
{ "resource": "" }
q1453
ServiceMock.Server.count
train
def count(request_criteria) return if ::ServiceMock.disable_stubs yield self if block_given? JSON.parse(http.post('/__admin/requests/count', request_criteria).body)['count'] end
ruby
{ "resource": "" }
q1454
ServiceMock.Server.count_with_file
train
def count_with_file(filename) return if ::ServiceMock.disable_stubs yield self if block_given? content = File.open(filename, 'rb') { |file| file.read } count(content) end
ruby
{ "resource": "" }
q1455
ServiceMock.Server.count_with_erb
train
def count_with_erb(filename, hsh={}) return if ::ServiceMock.disable_stubs yield self if block_given? template = File.open(filename, 'rb') { |file| file.read } erb_content = ERB.new(template).result(data_binding(hsh)) count(erb_content) end
ruby
{ "resource": "" }
q1456
Ashton.Texture.clear
train
def clear(options = {}) options = { color: [0.0, 0.0, 0.0, 0.0], }.merge! options color = options[:color] color = color.to_opengl if color.is_a? Gosu::Color Gl.glBindFramebufferEXT Gl::GL_FRAMEBUFFER_EXT, fbo_id unless rendering? Gl.glDisable Gl::GL_BLEND # Need to replace the alpha too. Gl.glClearColor(*color) Gl.glClear Gl::GL_COLOR_BUFFER_BIT | Gl::GL_DEPTH_BUFFER_BIT Gl.glEnable Gl::GL_BLEND Gl.glBindFramebufferEXT Gl::GL_FRAMEBUFFER_EXT, 0 unless rendering? nil end
ruby
{ "resource": "" }
q1457
VLC.Connection.write
train
def write(data, fire_and_forget = true) raise NotConnectedError, "no connection to server" unless connected? @socket.puts(data) @socket.flush return true if fire_and_forget read rescue Errno::EPIPE disconnect raise BrokenConnectionError, "the connection to the server is lost" end
ruby
{ "resource": "" }
q1458
VLC.Connection.read
train
def read(timeout=nil) timeout = read_timeout if timeout.nil? raw_data = nil Timeout.timeout(timeout) do raw_data = @socket.gets.chomp end if (data = parse_raw_data(raw_data)) data[1] else raise VLC::ProtocolError, "could not interpret the playload: #{raw_data}" end rescue Timeout::Error raise VLC::ReadTimeoutError, "read timeout" end
ruby
{ "resource": "" }
q1459
Gosu.Window.post_process
train
def post_process(*shaders) raise ArgumentError, "Block required" unless block_given? raise TypeError, "Can only process with Shaders" unless shaders.all? {|s| s.is_a? Ashton::Shader } # In case no shaders are passed, just run the contents of the block. unless shaders.size > 0 yield return end buffer1 = primary_buffer buffer1.clear # Allow user to draw into a buffer, rather than the window. buffer1.render do yield end if shaders.size > 1 buffer2 = secondary_buffer # Don't need to clear, since we will :replace. # Draw into alternating buffers, applying each shader in turn. shaders[0...-1].each do |shader| buffer1, buffer2 = buffer2, buffer1 buffer1.render do buffer2.draw 0, 0, nil, shader: shader, mode: :replace end end end # Draw the buffer directly onto the window, utilising the (last) shader. buffer1.draw 0, 0, nil, shader: shaders.last end
ruby
{ "resource": "" }
q1460
Spidey.AbstractSpider.each_url
train
def each_url(&_block) index = 0 while index < urls.count # urls grows dynamically, don't use &:each url = urls[index] next unless url yield url, handlers[url].first, handlers[url].last index += 1 end end
ruby
{ "resource": "" }
q1461
Gosu.Image.draw_as_points
train
def draw_as_points(points, z, options = {}) color = options[:color] || DEFAULT_DRAW_COLOR scale = options[:scale] || 1.0 shader = options[:shader] mode = options[:mode] || :default if shader shader.enable z $window.gl z do shader.image = self shader.color = color end end begin points.each do |x, y| draw_rot_without_hash x, y, z, 0, 0.5, 0.5, scale, scale, color, mode end ensure shader.disable z if shader end end
ruby
{ "resource": "" }
q1462
Ashton.SignedDistanceField.sample_distance
train
def sample_distance(x, y) x = [[x, width - 1].min, 0].max y = [[y, height - 1].min, 0].max # Could be checking any of red/blue/green. @field.red((x / @scale).round, (y / @scale).round) - ZERO_DISTANCE end
ruby
{ "resource": "" }
q1463
Ashton.SignedDistanceField.sample_gradient
train
def sample_gradient(x, y) d0 = sample_distance x, y - 1 d1 = sample_distance x - 1, y d2 = sample_distance x + 1, y d3 = sample_distance x, y + 1 [(d2 - d1) / @scale, (d3 - d0) / @scale] end
ruby
{ "resource": "" }
q1464
Ashton.SignedDistanceField.sample_normal
train
def sample_normal(x, y) gradient_x, gradient_y = sample_gradient x, y length = Gosu::distance 0, 0, gradient_x, gradient_y if length == 0 [0, 0] # This could be NaN in edge cases. else [gradient_x / length, gradient_y / length] end end
ruby
{ "resource": "" }
q1465
Ashton.SignedDistanceField.line_of_sight_blocked_at
train
def line_of_sight_blocked_at(x1, y1, x2, y2) distance_to_travel = Gosu::distance x1, y1, x2, y2 distance_x, distance_y = x2 - x1, y2 - y1 distance_travelled = 0 x, y = x1, y1 loop do distance = sample_distance x, y # Blocked? return [x, y] if distance <= 0 distance_travelled += distance # Got to destination in the clear. return nil if distance_travelled >= distance_to_travel lerp = distance_travelled.fdiv distance_to_travel x = x1 + distance_x * lerp y = y1 + distance_y * lerp end end
ruby
{ "resource": "" }
q1466
Ashton.SignedDistanceField.render_field
train
def render_field raise ArgumentError, "Block required" unless block_given? @mask.render do @mask.clear $window.scale 1.0 / @scale do yield self end end @shader.enable do @field.render do @mask.draw 0, 0, 0 end end nil end
ruby
{ "resource": "" }
q1467
Ashton.SignedDistanceField.draw
train
def draw(x, y, z, options = {}) options = { mode: :add, }.merge! options $window.scale @scale do @field.draw x, y, z, options end nil end
ruby
{ "resource": "" }
q1468
Ashton.SignedDistanceField.to_a
train
def to_a width.times.map do |x| height.times.map do |y| sample_distance x, y end end end
ruby
{ "resource": "" }
q1469
VLC.Server.start
train
def start(detached = false) return @pid if running? detached ? @deamon = true : setup_traps @pid = RUBY_VERSION >= '1.9' ? process_spawn(detached) : process_spawn_ruby_1_8(detached) end
ruby
{ "resource": "" }
q1470
VLC.Server.process_spawn_ruby_1_8
train
def process_spawn_ruby_1_8(detached) rd, wr = IO.pipe if Process.fork #parent wr.close pid = rd.read.to_i rd.close return pid else #child rd.close detach if detached #daemonization wr.write(Process.pid) wr.close STDIN.reopen "/dev/null" STDOUT.reopen "/dev/null", "a" STDERR.reopen "/dev/null", "a" Kernel.exec "#{headless? ? 'cvlc' : 'vlc'} --extraintf rc --rc-host #{@host}:#{@port}" end end
ruby
{ "resource": "" }
q1471
Furoshiki.Configuration.merge_config
train
def merge_config(config) defaults = { name: 'Ruby App', version: '0.0.0', release: 'Rookie', ignore: 'pkg', # TODO: Establish these default icons and paths. These would be # default icons for generic Ruby apps. icons: { #osx: 'path/to/default/App.icns', #gtk: 'path/to/default/app.png', #win32: 'path/to/default/App.ico', }, template_urls: { jar_app: JAR_APP_TEMPLATE_URL, }, validator: Furoshiki::Validator, warbler_extensions: Furoshiki::WarblerExtensions, working_dir: Dir.pwd, } @config = merge_with_symbolized_keys(defaults, config) end
ruby
{ "resource": "" }
q1472
Ashton.WindowBuffer.capture
train
def capture Gl.glBindTexture Gl::GL_TEXTURE_2D, id Gl.glCopyTexImage2D Gl::GL_TEXTURE_2D, 0, Gl::GL_RGBA8, 0, 0, width, height, 0 self end
ruby
{ "resource": "" }
q1473
Ashton.Shader.[]=
train
def []=(uniform, value) uniform = uniform_name_from_symbol(uniform) if uniform.is_a? Symbol # Ensure that the program is current before setting values. needs_use = !current? enable if needs_use set_uniform uniform_location(uniform), value disable if needs_use value end
ruby
{ "resource": "" }
q1474
Ashton.Shader.set_uniform
train
def set_uniform(location, value) raise ShaderUniformError, "Shader uniform #{location.inspect} could not be set, since shader is not current" unless current? return if location == INVALID_LOCATION # Not for end-users :) case value when true, Gl::GL_TRUE Gl.glUniform1i location, 1 when false, Gl::GL_FALSE Gl.glUniform1i location, 0 when Float begin Gl.glUniform1f location, value rescue Gl.glUniform1i location, value.to_i end when Integer begin Gl.glUniform1i location, value rescue Gl.glUniform1f location, value.to_f end when Gosu::Color Gl.glUniform4f location, *value.to_opengl when Array size = value.size raise ArgumentError, "Empty array not supported for uniform data" if size.zero? # raise ArgumentError, "Only support uniforms up to 4 elements" if size > 4 case value[0] when Float begin Gl.send "glUniform#{size}f", location, *value.map(&:to_f) rescue Gl.send "glUniform#{size}i", location, *value.map(&:to_i) end when Integer begin Gl.send "glUniform#{size}i", location, *value.map(&:to_i) rescue Gl.send "glUniform#{size}f", location, *value.map(&:to_f) end when Gosu::Color GL.send "glUniform4fv", location, value.map(&:to_opengl).flatten else raise ArgumentError, "Uniform data type not supported for element of type: #{value[0].class}" end else raise ArgumentError, "Uniform data type not supported for type: #{value.class}" end value end
ruby
{ "resource": "" }
q1475
Ashton.Shader.process_source
train
def process_source(shader, extension) source = if shader.is_a? Symbol file = File.expand_path "#{shader}#{extension}", BUILT_IN_SHADER_PATH unless File.exist? file raise ShaderLoadError, "Failed to load built-in shader: #{shader.inspect}" end File.read file elsif File.exist? shader File.read shader else shader end replace_include source end
ruby
{ "resource": "" }
q1476
Furoshiki.Util.deep_set_symbol_key
train
def deep_set_symbol_key(hash, key, value) if value.kind_of? Hash hash[key.to_sym] = value.inject({}) { |inner_hash, (inner_key, inner_value)| deep_set_symbol_key(inner_hash, inner_key, inner_value) } else hash[key.to_sym] = value end hash end
ruby
{ "resource": "" }
q1477
Furoshiki.Util.merge_with_symbolized_keys
train
def merge_with_symbolized_keys(defaults, hash) hash.inject(defaults) { |symbolized, (k, v)| deep_set_symbol_key(symbolized, k, v) } end
ruby
{ "resource": "" }
q1478
RubyExpect.Expect.expect
train
def expect *patterns, &block @logger.debug("Expecting: #{patterns.inspect}") if @logger.debug? patterns = pattern_escape(*patterns) @end_time = 0 if (@timeout != 0) @end_time = Time.now + @timeout end @before = '' matched_index = nil while (@end_time == 0 || Time.now < @end_time) raise ClosedError.new("Read filehandle is closed") if (@read_fh.closed?) break unless (read_proc) @last_match = nil patterns.each_index do |i| if (match = patterns[i].match(@buffer)) log_buffer(true) @logger.debug(" Matched: #{match}") if @logger.debug? @last_match = match @before = @buffer.slice!(0...match.begin(0)) @match = @buffer.slice!(0...match.to_s.length) matched_index = i break end end unless (@last_match.nil?) unless (block.nil?) instance_eval(&block) end return matched_index end end @logger.debug("Timeout") return nil end
ruby
{ "resource": "" }
q1479
RubyExpect.Expect.pattern_escape
train
def pattern_escape *patterns escaped_patterns = [] patterns.each do |pattern| if (pattern.is_a?(String)) pattern = Regexp.new(Regexp.escape(pattern)) elsif (! pattern.is_a?(Regexp)) raise "Don't know how to match on a #{pattern.class}" end escaped_patterns.push(pattern) end escaped_patterns end
ruby
{ "resource": "" }
q1480
Filemaker.Server.serialize_args
train
def serialize_args(args) return {} if args.nil? args.each do |key, value| case value when DateTime, Time args[key] = value.strftime('%m/%d/%Y %H:%M:%S') when Date args[key] = value.strftime('%m/%d/%Y') else # Especially for range operator (...), we want to output as String args[key] = value.to_s end end args end
ruby
{ "resource": "" }
q1481
C.NodeList.match?
train
def match?(arr, parser=nil) arr = arr.to_a return false if arr.length != self.length each_with_index do |node, i| node.match?(arr[i], parser) or return false end return true end
ruby
{ "resource": "" }
q1482
C.Node.assert_invariants
train
def assert_invariants(testcase) fields.each do |field| if val = send(field.reader) assert_same(self, node.parent, "field.reader is #{field.reader}") if field.child? assert_same(field, val.instance_variable_get(:@parent_field), "field.reader is #{field.reader}") end end end end
ruby
{ "resource": "" }
q1483
C.Node.each
train
def each(&blk) fields.each do |field| if field.child? val = self.send(field.reader) yield val unless val.nil? end end return self end
ruby
{ "resource": "" }
q1484
C.Node.swap_with
train
def swap_with node return self if node.equal? self if self.attached? if node.attached? # both attached -- use placeholder placeholder = Default.new my_parent = @parent my_parent.replace_node(self, placeholder) node.parent.replace_node(node, self) my_parent.replace_node(placeholder, node) else # only `self' attached @parent.replace_node(self, node) end else if node.attached? # only `node' attached node.parent.replace_node(node, self) else # neither attached -- nothing to do end end return self end
ruby
{ "resource": "" }
q1485
C.Node.node_before
train
def node_before(node) node.parent.equal? self or raise ArgumentError, "node is not a child" fields = self.fields i = node.instance_variable_get(:@parent_field).index - 1 i.downto(0) do |i| f = fields[i] if f.child? && (val = self.send(f.reader)) return val end end return nil end
ruby
{ "resource": "" }
q1486
C.Node.remove_node
train
def remove_node(node) node.parent.equal? self or raise ArgumentError, "node is not a child" field = node.instance_variable_get(:@parent_field) node.instance_variable_set(:@parent, nil) node.instance_variable_set(:@parent_field, nil) self.instance_variable_set(field.var, nil) return self end
ruby
{ "resource": "" }
q1487
C.Node.replace_node
train
def replace_node(node, newnode=nil) node.parent.equal? self or raise ArgumentError, "node is not a child" field = node.instance_variable_get(:@parent_field) self.send(field.writer, newnode) return self end
ruby
{ "resource": "" }
q1488
C.NodeChain.link_
train
def link_(a, nodes, b) if nodes.empty? if a.nil? @first = b else a.instance_variable_set(:@next, b) end if b.nil? @last = a else b.instance_variable_set(:@prev, a) end else # connect `a' and `b' first = nodes.first if a.nil? @first = first else a.instance_variable_set(:@next, first) end last = nodes.last if b.nil? @last = last else b.instance_variable_set(:@prev, last) end # connect `nodes' if nodes.length == 1 node = nodes[0] node.instance_variable_set(:@prev, a) node.instance_variable_set(:@next, b) else first.instance_variable_set(:@next, nodes[ 1]) first.instance_variable_set(:@prev, a) last. instance_variable_set(:@prev, nodes[-2]) last. instance_variable_set(:@next, b) (1...nodes.length-1).each do |i| n = nodes[i] n.instance_variable_set(:@prev, nodes[i-1]) n.instance_variable_set(:@next, nodes[i+1]) end end end end
ruby
{ "resource": "" }
q1489
C.NodeChain.link2_
train
def link2_(a, b) if a.nil? @first = b else a.instance_variable_set(:@next, b) unless a.nil? end if b.nil? @last = a else b.instance_variable_set(:@prev, a) unless b.nil? end end
ruby
{ "resource": "" }
q1490
C.NodeChain.get_
train
def get_(i) # return a Node if i < (@length >> 1) # go from the beginning node = @first i.times{node = node.next} else # go from the end node = @last (@length - 1 - i).times{node = node.prev} end return node end
ruby
{ "resource": "" }
q1491
Resqued.Listener.exec
train
def exec socket_fd = @socket.to_i ENV['RESQUED_SOCKET'] = socket_fd.to_s ENV['RESQUED_CONFIG_PATH'] = @config_paths.join(':') ENV['RESQUED_STATE'] = (@old_workers.map { |r| "#{r[:pid]}|#{r[:queue]}" }.join('||')) ENV['RESQUED_LISTENER_ID'] = @listener_id.to_s ENV['RESQUED_MASTER_VERSION'] = Resqued::VERSION log "exec: #{Resqued::START_CTX['$0']} listener" exec_opts = {socket_fd => socket_fd} # Ruby 2.0 needs to be told to keep the file descriptor open during exec. if start_pwd = Resqued::START_CTX['pwd'] exec_opts[:chdir] = start_pwd end procline_buf = ' ' * 256 # make room for setproctitle Kernel.exec(Resqued::START_CTX['$0'], 'listener', procline_buf, exec_opts) end
ruby
{ "resource": "" }
q1492
ChemistryKit.Chemist.method_missing
train
def method_missing(name, *arguments) value = arguments[0] name = name.to_s if name[-1, 1] == '=' key = name[/(.+)\s?=/, 1] @data[key.to_sym] = value unless instance_variables.include? "@#{key}".to_sym else @data[name.to_sym] end end
ruby
{ "resource": "" }
q1493
Placemaker.Client.fetch!
train
def fetch! fields = POST_FIELDS.reject{|f| @options[f].nil? }.map do |f| # Change ruby-form fields to url type, e.g., document_content => documentContent cgi_param = f.to_s.gsub(/\_(.)/) {|s| s.upcase}.gsub('_', '').sub(/url/i, 'URL') Curl::PostField.content(cgi_param, @options[f]) end res = Curl::Easy.http_post('http://wherein.yahooapis.com/v1/document', *fields) @xml_parser = Placemaker::XmlParser.new(res.body_str) end
ruby
{ "resource": "" }
q1494
EffectiveEmailTemplates.LiquidResolver.decorate
train
def decorate(templates, path_info, details, locals) templates.each do |t| t.locals = locals end end
ruby
{ "resource": "" }
q1495
MentionSystem.MentionProcessor.extract_handles_from_mentioner
train
def extract_handles_from_mentioner(mentioner) content = extract_mentioner_content(mentioner) handles = content.scan(handle_regexp).map { |handle| handle.gsub("#{mention_prefix}","") } end
ruby
{ "resource": "" }
q1496
MentionSystem.MentionProcessor.process_after_callbacks
train
def process_after_callbacks(mentioner, mentionee) result = true @callbacks[:after].each do |callback| unless callback.call(mentioner, mentionee) result = false break end end result end
ruby
{ "resource": "" }
q1497
Ebayr.Request.headers
train
def headers { 'X-EBAY-API-COMPATIBILITY-LEVEL' => @compatability_level.to_s, 'X-EBAY-API-DEV-NAME' => dev_id.to_s, 'X-EBAY-API-APP-NAME' => app_id.to_s, 'X-EBAY-API-CERT-NAME' => cert_id.to_s, 'X-EBAY-API-CALL-NAME' => @command.to_s, 'X-EBAY-API-SITEID' => @site_id.to_s, 'Content-Type' => 'text/xml' } end
ruby
{ "resource": "" }
q1498
Ebayr.Request.http
train
def http(&block) http = Net::HTTP.new(@uri.host, @uri.port) if @uri.port == 443 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end return http.start(&block) if block_given? http end
ruby
{ "resource": "" }
q1499
RightApi.Client.retry_request
train
def retry_request(is_read_only = false) attempts = 0 begin yield rescue OpenSSL::SSL::SSLError => e raise e unless @enable_retry # These errors pertain to the SSL handshake. Since no data has been # exchanged its always safe to retry raise e if attempts >= @max_attempts attempts += 1 retry rescue Errno::ECONNRESET, RestClient::ServerBrokeConnection, RestClient::RequestTimeout => e raise e unless @enable_retry # Packetloss related. # There are two timeouts on the ssl negotiation and data read with different # times. Unfortunately the standard timeout class is used for both and the # exceptions are caught and reraised so you can't distinguish between them. # Unfortunate since ssl negotiation timeouts should always be retryable # whereas data may not. if is_read_only raise e if attempts >= @max_attempts attempts += 1 retry else raise e end rescue ApiError => e if re_login?(e) # Session is expired or invalid login() retry else raise e end end end
ruby
{ "resource": "" }