_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q8300
Mongolicious.Storage.cleanup
train
def cleanup(bucket, prefix, versions) objects = @con.get_bucket(bucket, :prefix => prefix).body['Contents'] return if objects.size <= versions objects[0...(objects.size - versions)].each do |o| Mongolicious.logger.info("Removing outdated version #{o['Key']}") @con.delete_object(bucket,...
ruby
{ "resource": "" }
q8301
Twat::Subcommands.Base.format
train
def format(twt, idx = nil) idx = pad(idx) if idx text = deentitize(twt.text) if config.colors? buf = idx ? "#{idx.cyan}:" : "" if twt.as_user == config.account_name.to_s buf += "#{twt.as_user.bold.blue}: #{text}" elsif text.mentions?(config.account_name) buf...
ruby
{ "resource": "" }
q8302
Scalaroid.Transaction.write
train
def write(key, value, binary = false) result = req_list(new_req_list().add_write(key, value, binary))[0] _process_result_commit(result) end
ruby
{ "resource": "" }
q8303
Scalaroid.Transaction.add_del_on_list
train
def add_del_on_list(key, to_add, to_remove) result = req_list(new_req_list().add_add_del_on_list(key, to_add, to_remove))[0] process_result_add_del_on_list(result) end
ruby
{ "resource": "" }
q8304
Scalaroid.Transaction.add_on_nr
train
def add_on_nr(key, to_add) result = req_list(new_req_list().add_add_on_nr(key, to_add))[0] process_result_add_on_nr(result) end
ruby
{ "resource": "" }
q8305
RandomOutcome.Simulator.outcome
train
def outcome num = random_float_including_zero_and_excluding_one # don't inline @probability_range_to_outcome.detect { |probability_range, _| num.in? probability_range }.last end
ruby
{ "resource": "" }
q8306
RestlessRouter.Routes.add_route
train
def add_route(route) raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) @routes << route unless route_exists?(route) end
ruby
{ "resource": "" }
q8307
RestlessRouter.Routes.add_route!
train
def add_route!(route) # Raise exception if the route is existing, too raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) raise ExistingRouteError.new(("Route already exists for %s" % [route.name])) if route_exists?(route) @routes << route end
ruby
{ "resource": "" }
q8308
RestlessRouter.Routes.route_for
train
def route_for(name) name = name.to_s @routes.select { |entry| entry.name == name }.first end
ruby
{ "resource": "" }
q8309
RestlessRouter.Routes.route_for!
train
def route_for!(name) route = route_for(name) raise RouteNotFoundError.new(("Route not found for %s" % [name])) if route.nil? route end
ruby
{ "resource": "" }
q8310
Auditing.Base.audit_enabled
train
def audit_enabled(opts={}) include InstanceMethods class_attribute :auditing_fields has_many :audits, :as => :auditable, :order => 'created_at DESC, id DESC' self.auditing_fields = gather_fields_for_auditing(opts[:fields]) after_create :log_creation after_update :log_update e...
ruby
{ "resource": "" }
q8311
Institutions.Util.method_missing
train
def method_missing(method, *args, &block) instance_variable = instance_variablize(method) if respond_to_missing?(method) and instance_variable_defined?(instance_variable) self.class.send :attr_reader, method.to_sym instance_variable_get instance_variable else super end ...
ruby
{ "resource": "" }
q8312
Institutions.Util.respond_to_missing?
train
def respond_to_missing?(method, include_private = false) # Short circuit if we have invalid instance variable name, # otherwise we get an exception that we don't need. return super unless valid_instance_variable? method if instance_variable_defined? instance_variablize(method) true ...
ruby
{ "resource": "" }
q8313
MapKit.Point.in?
train
def in?(bounding_box) top, left, bottom, right = bounding_box.coords (left..right) === @lng && (top..bottom) === @lat end
ruby
{ "resource": "" }
q8314
MapKit.Point.pixel
train
def pixel(bounding_box) x, y = MapKit.latlng2pixel(@lat, @lng, bounding_box.zoom) tile_x, tile_y = MapKit.latlng2pixel(bounding_box.top, bounding_box.left, bounding_box.zoom) [x-tile_x, y-tile_y] end
ruby
{ "resource": "" }
q8315
MapKit.BoundingBox.grow!
train
def grow!(percent) lng = ((100.0 + percent) * (width / 2.0 / 100.0)) / 2.0 lat = ((100.0 + percent) * (height / 2.0 / 100.0)) / 2.0 @top += lat @left -= lng @bottom -= lat @right += lng end
ruby
{ "resource": "" }
q8316
LatoBlog.Interface::Fields.blog__sync_config_post_fields_with_db_post_fields
train
def blog__sync_config_post_fields_with_db_post_fields posts = LatoBlog::Post.all # create / update fields on database posts.map { |p| blog__sync_config_post_fields_with_db_post_fields_for_post(p) } end
ruby
{ "resource": "" }
q8317
LatoBlog.Interface::Fields.blog__sync_config_post_fields_with_db_post_fields_for_post
train
def blog__sync_config_post_fields_with_db_post_fields_for_post(post) # save or update post fields from config post_fields = CONFIGS[:lato_blog][:post_fields] post_fields.map { |key, content| blog__sync_config_post_field(post, key, content) } # remove old post fields db_post_fields = post.p...
ruby
{ "resource": "" }
q8318
LatoBlog.Interface::Fields.blog__sync_config_post_field
train
def blog__sync_config_post_field(post, key, content) db_post_field = LatoBlog::PostField.find_by( key: key, lato_blog_post_id: post.id, lato_blog_post_field_id: nil ) # check if post field can be created for the post if content[:categories] && !content[:categories].empty?...
ruby
{ "resource": "" }
q8319
LatoBlog.Interface::Fields.blog__sync_db_post_field
train
def blog__sync_db_post_field(post, db_post_field) post_fields = CONFIGS[:lato_blog][:post_fields] # search db post field on config file content = post_fields[db_post_field.key] db_post_field.update(meta_visible: false) && return unless content # check category of post field is accepted ...
ruby
{ "resource": "" }
q8320
LatoBlog.Interface::Fields.blog__update_db_post_field
train
def blog__update_db_post_field(db_post_field, content, post_field_parent = nil) # run minimum updates db_post_field.update( position: content[:position], meta_visible: true ) # run custom update for type case db_post_field.typology when 'text' update_db_post_f...
ruby
{ "resource": "" }
q8321
AuthNetReceiver.RawTransaction.json_data
train
def json_data begin return JSON.parse(self.data) rescue JSON::ParserError, TypeError => e logger.warn "Error while parsing raw transaction data: #{e.message}" return {} end end
ruby
{ "resource": "" }
q8322
AuthNetReceiver.RawTransaction.md5_hash_is_valid?
train
def md5_hash_is_valid?(json) if AuthNetReceiver.config.hash_value.nil? || AuthNetReceiver.config.gateway_login.nil? raise StandardError, 'AuthNetReceiver hash_value and gateway_login cannot be nil!' end parts = [] parts << AuthNetReceiver.config.hash_value parts << AuthNetReceiver....
ruby
{ "resource": "" }
q8323
SimpleFormDojo.FormBuilder.button
train
def button(type, *args, &block) # set options to value if first arg is a Hash options = args.extract_options! button_type = 'dijit/form/Button' button_type = 'dojox/form/BusyButton' if options[:busy] options.reverse_merge!(:'data-dojo-type' => button_type) content = '' if valu...
ruby
{ "resource": "" }
q8324
SimpleFormDojo.FormBuilder.button_default_value
train
def button_default_value obj = object.respond_to?(:to_model) ? object.to_model : object key = obj ? (obj.persisted? ? :edit : :new) : :submit model = if obj.class.respond_to?(:model_name) obj.class.model_name.human else object_name.to_s.humanize end defaults = [] ...
ruby
{ "resource": "" }
q8325
OpenDirectoryUtils.Connection.run
train
def run(command:, params:, output: nil) answer = {} params[:format] = output # just in case clear record_name and calculate later params[:record_name] = nil ssh_cmds = send(command, params, dir_info) # pp ssh_cmds results = send_cmds_to_od_server(ssh_cmds) # pp results ...
ruby
{ "resource": "" }
q8326
Octo.Counter.local_count
train
def local_count(duration, type) aggr = {} Octo::Enterprise.each do |enterprise| args = { enterprise_id: enterprise.id, ts: duration, type: type } aggr[enterprise.id.to_s] = {} unless aggr.has_key?(enterprise.id.to_s) results = where(args) ...
ruby
{ "resource": "" }
q8327
Ichiban.ScriptRunner.script_file_changed
train
def script_file_changed(path) Ichiban.logger.script_run(path) script = Ichiban::Script.new(path).run end
ruby
{ "resource": "" }
q8328
Tumble.Blog.reblog_post
train
def reblog_post(id, reblog_key, options={}) @connection.post("/blog/#{name}/post/reblog", options.merge('id' => id, 'reblog_key' => reblog_key)).response end
ruby
{ "resource": "" }
q8329
FileBlobs.ActiveRecordMigrationExtensions.create_file_blobs_table
train
def create_file_blobs_table(table_name = :file_blobs, options = {}, &block) blob_limit = options[:blob_limit] || 1.megabyte create_table table_name, id: false do |t| t.primary_key :id, :string, null: false, limit: 48 t.binary :data, null: false, limit: blob_limit # Block capturing and callin...
ruby
{ "resource": "" }
q8330
S3Asset.ActsAsS3Asset.crop_resized
train
def crop_resized(image, size, gravity = "Center") size =~ /(\d+)x(\d+)/ width = $1.to_i height = $2.to_i # Grab the width and height of the current image in one go. cols, rows = image[:dimensions] # Only do anything if needs be. Who knows, maybe it's already the exact # dimen...
ruby
{ "resource": "" }
q8331
Megam.RestAdapter.megam_rest
train
def megam_rest options = { :email => email, :api_key => api_key, :org_id => org_id, :password_hash => password_hash, :master_key => master_key, :host => host } if headers options[:header...
ruby
{ "resource": "" }
q8332
Attribution.ClassMethods.add_attribute
train
def add_attribute(name, type, metadata={}) attr_reader name attributes << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
ruby
{ "resource": "" }
q8333
Attribution.ClassMethods.string
train
def string(attr, metadata={}) add_attribute(attr, :string, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_s) end end
ruby
{ "resource": "" }
q8334
Attribution.ClassMethods.boolean
train
def boolean(attr, metadata={}) add_attribute(attr, :boolean, metadata) define_method("#{attr}=") do |arg| v = case arg when String then BOOLEAN_TRUE_STRINGS.include?(arg.downcase) when Numeric then arg == 1 when nil then nil else !!arg end instance_var...
ruby
{ "resource": "" }
q8335
Attribution.ClassMethods.integer
train
def integer(attr, metadata={}) add_attribute(attr, :integer, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_i) end end
ruby
{ "resource": "" }
q8336
Attribution.ClassMethods.float
train
def float(attr, metadata={}) add_attribute(attr, :float, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_f) end end
ruby
{ "resource": "" }
q8337
Attribution.ClassMethods.decimal
train
def decimal(attr, metadata={}) add_attribute(attr, :decimal, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : BigDecimal.new(arg.to_s)) end end
ruby
{ "resource": "" }
q8338
Attribution.ClassMethods.date
train
def date(attr, metadata={}) add_attribute(attr, :date, metadata) define_method("#{attr}=") do |arg| v = case arg when Date then arg when Time, DateTime then arg.to_date when String then Date.parse(arg) when Hash args = Util.extract_values(arg, :year, :month,...
ruby
{ "resource": "" }
q8339
Attribution.ClassMethods.array
train
def array(attr, metadata={}) add_attribute(attr, :array, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", Array(arg)) end end
ruby
{ "resource": "" }
q8340
Attribution.ClassMethods.add_association
train
def add_association(name, type, metadata={}) associations << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
ruby
{ "resource": "" }
q8341
Attribution.ClassMethods.has_many
train
def has_many(association_name, metadata={}) add_association association_name, :has_many, metadata association_class_name = metadata.try(:fetch, :class_name, [name.split('::')[0..-2].join('::'), association_name.to_s.classify].reject(&:blank?).join('::')) # foos define_method(association_name)...
ruby
{ "resource": "" }
q8342
Ponytail.Configuration.update_schema
train
def update_schema config.update_schema = config.update_schema.call if config.update_schema.respond_to?(:call) config.update_schema end
ruby
{ "resource": "" }
q8343
QuartzTorrent.TorrentDataDelegate.to_h
train
def to_h result = {} ## Extra fields added by this method: # Length of the torrent result[:dataLength] = @info ? @info.dataLength : 0 # Percent complete pct = withCurrentAndTotalBytes{ |cur, total| (cur.to_f / total.to_f * 100.0).round 1 } result[:percentComplete] = pct ...
ruby
{ "resource": "" }
q8344
Dreck.Result.list
train
def list(type, sym, count: nil) if count raise BadCountError unless count.positive? end @expected << [:list, type, sym, count] end
ruby
{ "resource": "" }
q8345
Dreck.Result.parse!
train
def parse! check_absorption! @expected.each do |type, *rest| case type when :list parse_list!(*rest) else parse_type!(type, *rest) end end self end
ruby
{ "resource": "" }
q8346
Dreck.Result.check_absorption!
train
def check_absorption! count, greedy = count_expected return unless strict? raise GreedyAbsorptionError.new(count, @args.size) if count >= @args.size && greedy raise AbsorptionError.new(count, @args.size) if count != @args.size && !greedy end
ruby
{ "resource": "" }
q8347
Dreck.Result.count_expected
train
def count_expected count = @expected.inject(0) do |n, exp| case exp.first when :list # if the list is greedy, all arguments have to be absorbed return [n, true] unless exp[3] n + exp[3] else n + 1 end end [count, false] end
ruby
{ "resource": "" }
q8348
Dreck.Result.parse_list!
train
def parse_list!(type, sym, count) args = if count @args.shift count else @args end @results[sym] = Parser.parse_list type, args end
ruby
{ "resource": "" }
q8349
Ean3.Hotels.getReservation
train
def getReservation response = conncetion.post do |req| req.url "res", options end return_error_or_body(response, response.body) end
ruby
{ "resource": "" }
q8350
Ean3.Hotels.getAlternateProperties
train
def getAlternateProperties response = conncetion.get do |req| req.url "altProps", options end return_error_or_body(response, response.body) end
ruby
{ "resource": "" }
q8351
Gricer.DashboardController.index
train
def index @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) end
ruby
{ "resource": "" }
q8352
Gricer.DashboardController.overview
train
def overview @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) render partial: 'overview', formats: [:html], locals: {sessions: @sessions, requests: @requests} end
ruby
{ "resource": "" }
q8353
Enumeration.Collection.[]
train
def [](key) if self.map? && @data.has_key?(key) @data[key] elsif (self.map? && @data.has_value?(key)) || (self.list? && @data.include?(key)) key else nil end end
ruby
{ "resource": "" }
q8354
Enumeration.Collection.key
train
def key(value) if self.map? && @data.has_value?(value) @data.invert[value] elsif (self.map? && @data.has_key?(value)) || (self.list? && @data.include?(value)) value else nil end end
ruby
{ "resource": "" }
q8355
Loco.Observable.initialize_bindings
train
def initialize_bindings bindings = self.class.get_class_bindings bindings.each do |binding| binding[:proc].observed_properties.each do |key_path| register_observer(self, key_path) do new_value = binding[:proc].call(self) if binding[:name] self.s...
ruby
{ "resource": "" }
q8356
TinyAtom.Feed.add_entry
train
def add_entry(id, title, updated, link, options={}) entries << { :id => id, :title => title, :updated => updated, :link => link }.merge(options) end
ruby
{ "resource": "" }
q8357
Machined.SpecHelpers.machined
train
def machined(config = {}) @machined = nil if config.delete(:reload) @machined ||= Machined::Environment.new(config.reverse_merge(:skip_bundle => true, :skip_autoloading => true)) end
ruby
{ "resource": "" }
q8358
Machined.SpecHelpers.build_context
train
def build_context(logical_path = 'application.js', options = {}) pathname = options[:pathname] || Pathname.new('assets').join(logical_path).expand_path env = options[:env] || machined.assets env.context_class.new env, logical_path, pathname end
ruby
{ "resource": "" }
q8359
Machined.SpecHelpers.machined_cli
train
def machined_cli(args, silence = true) capture(:stdout) { Machined::CLI.start args.split(' ') } end
ruby
{ "resource": "" }
q8360
Machined.SpecHelpers.modify
train
def modify(file, content = nil) Pathname.new(file).tap do |file| file.open('w') { |f| f.write(content) } if content future = Time.now + 60 file.utime future, future end end
ruby
{ "resource": "" }
q8361
Osheet.WorkbookElement::PartialSet.verify
train
def verify(partial) unless partial.kind_of?(Partial) raise ArgumentError, 'you can only push Osheet::Partial objs to the partial set' end pkey = partial_key(partial) self[pkey] ||= nil pkey end
ruby
{ "resource": "" }
q8362
Osheet.WorkbookElement::TemplateSet.verify
train
def verify(template) unless template.kind_of?(Template) raise ArgumentError, 'you can only push Osheet::Template objs to the template set' end key = template_key(template) self[key.first] ||= {} self[key.first][key.last] ||= nil key end
ruby
{ "resource": "" }
q8363
FaviconParty.HTTPClient.get
train
def get(url) stdin, stdout, stderr, t = Open3.popen3(curl_get_cmd(url)) output = encode_utf8(stdout.read).strip error = encode_utf8(stderr.read).strip if !error.nil? && !error.empty? if error.include? "SSL" raise FaviconParty::Curl::SSLError.new(error) elsif error.inclu...
ruby
{ "resource": "" }
q8364
Plangrade.OAuth2Client.exchange_auth_code_for_token
train
def exchange_auth_code_for_token(opts={}) unless (opts[:params] && opts[:params][:code]) raise ArgumentError.new("You must include an authorization code as a parameter") end opts[:authenticate] ||= :body code = opts[:params].delete(:code) authorization_code.get_token(code, opts) ...
ruby
{ "resource": "" }
q8365
Sem4rSoap.SoapDumper.dump_soap_options
train
def dump_soap_options(options) @soap_dump = true @soap_dump_log = nil if options[:directory] @soap_dump_dir = options[:directory] else @soap_dump_log = File.open(options[:file], "w") end @soap_dump_format = false || options[:format] @soap_dump_interceptor ...
ruby
{ "resource": "" }
q8366
Deas.BaseLogging.call!
train
def call!(env) env['rack.logger'] = @logger status, headers, body = nil, nil, nil benchmark = Benchmark.measure do status, headers, body = @app.call(env) end log_error(env['deas.error']) env['deas.time_taken'] = RoundedTime.new(benchmark.real) [status, headers, body] ...
ruby
{ "resource": "" }
q8367
Deas.VerboseLogging.call!
train
def call!(env) log "===== Received request =====" Rack::Request.new(env).tap do |request| log " Method: #{request.request_method.inspect}" log " Path: #{request.path.inspect}" end env['deas.logging'] = Proc.new{ |msg| log(msg) } status, headers, body = super(env) ...
ruby
{ "resource": "" }
q8368
Deas.SummaryLogging.call!
train
def call!(env) env['deas.logging'] = Proc.new{ |msg| } # no-op status, headers, body = super(env) request = Rack::Request.new(env) line_attrs = { 'method' => request.request_method, 'path' => request.path, 'params' => env['deas.params'], 'splat' => env['dea...
ruby
{ "resource": "" }
q8369
Wafflemix.Asset.to_jq_upload
train
def to_jq_upload { "name" => read_attribute(:asset_name), "size" => asset_size, "url" => asset_url, "thumbnail_url" => asset.thumb('80x80#').url, "delete_url" => Wafflemix::Engine::routes.url_helpers.admin_asset_path(:id => id), "delete_type" => "DELETE" } ...
ruby
{ "resource": "" }
q8370
Bumbleworks.User.claim
train
def claim(task, force = false) raise UnauthorizedClaimAttempt unless has_role?(task.role) release!(task) if force task.claim(claim_token) end
ruby
{ "resource": "" }
q8371
Bumbleworks.User.release
train
def release(task, force = false) return unless task.claimed? raise UnauthorizedReleaseAttempt unless force || task.claimant == claim_token task.release end
ruby
{ "resource": "" }
q8372
Blueprint.Validator.validate
train
def validate java_path = `which java`.rstrip raise "You do not have a Java installed, but it is required." if java_path.blank? output_header Blueprint::CSS_FILES.keys.each do |file_name| css_output_path = File.join(Blueprint::BLUEPRINT_ROOT_PATH, file_name) puts "\n\n ...
ruby
{ "resource": "" }
q8373
Cyclical.Schedule.occurrences_between
train
def occurrences_between(t1, t2) return ((start_time < t1 || @start_time >= t2) ? [] : [start_time]) if @occurrence.nil? @occurrence.occurrences_between(t1, t2) end
ruby
{ "resource": "" }
q8374
CrateAPI.Crate.destroy
train
def destroy response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % ["#{self.id}"]}", :post)) raise CrateDestroyError, response["message"] unless response["status"] != "failure" end
ruby
{ "resource": "" }
q8375
CrateAPI.Crate.rename
train
def rename(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % ["#{self.id}"]}", :post, {:body => {:name => name}})) raise CrateRenameError, response["message"] unless response["status"] != "failure" end
ruby
{ "resource": "" }
q8376
CrateAPI.Crate.add_file
train
def add_file(path) file = File.new(path) response = CrateAPI::Base.call("#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}", :post, {:body => {:file => file, :crate_id => @id}}) raise CrateFileAlreadyExistsError, response["message"] unless response["status"] != "failure" ...
ruby
{ "resource": "" }
q8377
Humpyard.Element.last_modified
train
def last_modified rails_root_mtime = Time.zone.at(::File.new("#{Rails.root}").mtime) timestamps = [rails_root_mtime, self.updated_at] timestamps.sort.last end
ruby
{ "resource": "" }
q8378
BoxGrinder.ApplianceConfigHelper.substitute
train
def substitute(init, value, depth) if depth > VAR_SUBSTITUTION_MAX_DEPTH raise SystemStackError, "Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping." end original = value.clone value.gsub!(/(#(.*?)#)...
ruby
{ "resource": "" }
q8379
BoxGrinder.ApplianceConfigHelper.merge_partitions
train
def merge_partitions partitions = {} merge_field('hardware.partitions') do |parts| parts.each do |root, partition| if partitions.keys.include?(root) partitions[root]['size'] = partition['size'] if partitions[root]['size'] < partition['size'] unless partition['type...
ruby
{ "resource": "" }
q8380
Logsly::Logging182::Appenders.RollingFile.copy_truncate
train
def copy_truncate return unless ::File.exist?(@fn) FileUtils.concat @fn, @fn_copy @io.truncate 0 # touch the age file if needed if @age FileUtils.touch @age_fn @age_fn_mtime = nil end @roller.roll = true end
ruby
{ "resource": "" }
q8381
Diff::Display.Unified::Generator.inline_diff
train
def inline_diff(line, start, ending) if start != 0 || ending != 0 last = ending + line.length str = line[0...start] + '\0' + line[start...last] + '\1' + line[last...line.length] end str || line end
ruby
{ "resource": "" }
q8382
GSL.ScatterInterp.function
train
def function(vec1, vec2) case @func when :linear return normalized_radius(vec1, vec2) when :cubic_alt return normalized_radius(vec1, vec2)**(1.5) when :thin_plate_splines return 0.0 if radius(vec1, vec2) == 0.0 return normalized_radius(vec1, vec2)**2.0 * Math.log(normalized_radius(vec1, vec2)) whe...
ruby
{ "resource": "" }
q8383
GSL.ScatterInterp.eval
train
def eval(*pars) raise ArgumentError("wrong number of points") if pars.size != @dim # p vals pars = GSL::Vector.alloc(pars) return @npoints.times.inject(0.0) do |sum, i| # sum + function(radius(vals, @gridpoints.row(i)))*@weights[i] sum + function(pars, @gridpoints.row(i))*@weights[i] end end
ruby
{ "resource": "" }
q8384
GSL.ScatterInterp.gaussian_smooth_eval
train
def gaussian_smooth_eval(*vals, sigma_vec) npix = 7 raise "npix must be odd" if npix%2==0 case vals.size when 2 # delt0 = 3.0*0.999999*sigma_vec[0] / (npix-1) # delt1 = 3.0*0.999999*sigma_vec[1] / (npix-1) # sig3 = 3.0*sigma vals0 = GSL::Vector.linspace(vals[0] - 3.0* sigma_vec[0], vals[0] + 3.0* si...
ruby
{ "resource": "" }
q8385
GSL.Contour.graphkit
train
def graphkit(*args) if args.size == 0 conts = @last_contours else conts = contours(*args) end graphs = conts.map do |val, cons| unless cons[0] nil else (cons.map do |con| # p con contour = con.transpose kit = CodeRunner::GraphKit.autocreate({x: {data: contour[0]}, y: {data: co...
ruby
{ "resource": "" }
q8386
Citero.CSF.method_missing
train
def method_missing(meth, *args, &block) # Check to see if it can be evaluated if(matches? meth) #Defines the method and caches it to the class self.class.send(:define_method, meth) do # Splits the method and parameter. See formatize and directionize @csf::config()::getStr...
ruby
{ "resource": "" }
q8387
Analysand.Http.set_credentials
train
def set_credentials(req, creds) return unless creds if String === creds req.add_field('Cookie', creds) elsif creds[:username] && creds[:password] req.basic_auth(creds[:username], creds[:password]) end end
ruby
{ "resource": "" }
q8388
ZTK.Parallel.wait
train
def wait(flags=0) config.ui.logger.debug { "wait" } config.ui.logger.debug { "forks(#{@forks.inspect})" } return nil if @forks.count <= 0 pid, status = (Process.wait2(-1, Process::WUNTRACED) rescue nil) if !pid.nil? && !status.nil? && !(fork = @forks.select{ |f| f[:pid] == pid }.first)....
ruby
{ "resource": "" }
q8389
ZTK.Parallel.signal_all
train
def signal_all(signal="KILL") signaled = 0 if (!@forks.nil? && (@forks.count > 0)) @forks.each do |fork| begin Process.kill(signal, fork[:pid]) signaled += 1 rescue nil end end end signaled end
ruby
{ "resource": "" }
q8390
Vli.Registry.register
train
def register(key, value=nil, &block) block = lambda { value } if value @actions[key] = block end
ruby
{ "resource": "" }
q8391
Vli.Registry.get
train
def get(key) return nil if !@actions.has_key?(key) return @results_cache[key] if @results_cache.has_key?(key) @results_cache[key] = @actions[key].call end
ruby
{ "resource": "" }
q8392
Tay.SpecificationValidator.check_file_presence
train
def check_file_presence spec.icons.values.each do |path| fail_if_not_exist "Icon", path end if spec.browser_action fail_if_not_exist "Browser action popup", spec.browser_action.popup fail_if_not_exist "Browser action icon", spec.browser_action.icon end if spec.pag...
ruby
{ "resource": "" }
q8393
BlipTV.Request.set
train
def set(container, &declarations) struct = OpenStruct.new declarations.call(struct) send("#{container}=", struct.table) end
ruby
{ "resource": "" }
q8394
BlipTV.Request.run
train
def run(&block) if block_given? set(:params, &block) end if post? and multipart? put_multipart_params_into_body else put_params_into_url end request = RestClient::Request.execute( :method => http_method, :url => url, :h...
ruby
{ "resource": "" }
q8395
Pwl.Locker.authenticate
train
def authenticate begin @backend.transaction(true){ raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created] check_salt! } rescue OpenSSL::Cipher::CipherError raise WrongMasterPasswordError e...
ruby
{ "resource": "" }
q8396
Pwl.Locker.get
train
def get(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_accessed) value = @backend[:user][encrypt(key)] raise KeyNotFoundError.new(key) unless value EntryMapper.from_json(decrypt(value)) } end
ruby
{ "resource": "" }
q8397
Pwl.Locker.add
train
def add(entry_or_key, value = nil) if value.nil? and entry_or_key.is_a?(Entry) # treat as entry entry = entry_or_key else entry = Entry.new(entry_or_key) entry.password = value end entry.validate! @backend.transaction{ timestamp!(:last_modified) @b...
ruby
{ "resource": "" }
q8398
Pwl.Locker.delete
train
def delete(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_modified) old_value = @backend[:user].delete(encrypt(key)) raise KeyNotFoundError.new(key) unless old_value EntryMapper.from_json(decrypt(old_value)) } end
ruby
{ "resource": "" }
q8399
Pwl.Locker.all
train
def all result = [] @backend.transaction(true){ @backend[:user].each{|k,v| result << EntryMapper.from_json(decrypt(v))} } result end
ruby
{ "resource": "" }