_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, o['Key'])
end
end
|
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 += "#{twt.as_user.bold.red}: #{text}"
else
buf += "#{twt.as_user.bold.cyan}: #{text}"
end
buf.colorise!
else
buf = idx ? "#{idx}: " : ""
buf += "#{twt.as_user}: #{text}"
end
end
|
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
end
|
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
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
else
super
end
end
|
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.post_fields.visibles.roots
db_post_fields.map { |dbpf| blog__sync_db_post_field(post, dbpf) }
end
|
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?
db_categories = LatoBlog::Category.where(meta_permalink: content[:categories])
return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty?
end
# run correct action for field
if db_post_field
blog__update_db_post_field(db_post_field, content)
else
blog__create_db_post_field(post, key, content)
end
end
|
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
if content[:categories] && !content[:categories].empty?
db_categories = LatoBlog::Category.where(meta_permalink: content[:categories])
db_post_field.update(meta_visible: false) && return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty?
end
end
|
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_field_text(db_post_field, content, post_field_parent)
when 'textarea'
update_db_post_field_textarea(db_post_field, content, post_field_parent)
when 'datetime'
update_db_post_field_datetime(db_post_field, content, post_field_parent)
when 'editor'
update_db_post_field_editor(db_post_field, content, post_field_parent)
when 'geolocalization'
update_db_post_field_geolocalization(db_post_field, content, post_field_parent)
when 'image'
update_db_post_field_image(db_post_field, content, post_field_parent)
when 'gallery'
update_db_post_field_gallery(db_post_field, content, post_field_parent)
when 'youtube'
update_db_post_field_youtube(db_post_field, content, post_field_parent)
when 'composed'
update_db_post_field_composed(db_post_field, content, post_field_parent)
when 'relay'
update_db_post_field_relay(db_post_field, content, post_field_parent)
end
end
|
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.config.gateway_login if json['x_subscription_id'].blank?
parts << json['x_trans_id']
parts << json['x_amount']
hash = Digest::MD5.hexdigest(parts.join()).upcase
return hash == json['x_MD5_Hash']
end
|
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 value = options.delete(:value)
content = value.html_safe
else
content = button_default_value
end
options.reverse_merge!({ :type => type, :value => content })
dojo_props = {}
dojo_props.merge!(options[:dojo_html]) if options.include?(:dojo_html)
options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(dojo_props)
options[:class] = "button #{options[:class]}".strip
template.content_tag(:button, content, *(args << options), &block)
end
|
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 = []
defaults << "helpers.submit.#{object_name}.#{key}"
defaults << "#{key.to_s.humanize} #{model}"
I18n.t(defaults.shift, :default => defaults)
end
|
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
answer = process_results(results, command, params, ssh_cmds )
params[:value] = nil
return answer
rescue ArgumentError, NoMethodError => error
format_results(error.message, command, params, ssh_cmds, 'error')
end
|
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)
results_group = results.group_by { |x| x.uid }
results_group.each do |uid, counters|
_sum = counters.inject(0) do |sum, counter|
sum + counter.count
end
aggr[enterprise.id.to_s][uid] = _sum
end
end
aggr
end
|
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 calling is a bit slower than using yield. This is
# not a concern because migrations aren't run in tight loops.
block.call t
end
end
|
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
# dimensions we're looking for.
if(width != cols && height != rows)
image.combine_options do |c|
# Scale the image down to the widest dimension.
if(width != cols || height != rows)
scale = [width / cols.to_f, height / rows.to_f].max * 100
c.resize("#{scale}%")
end
# Align how things will be cropped.
c.gravity(gravity)
# Crop the image to size.
c.crop("#{width}x#{height}+0+0")
end
end
end
|
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[:headers] = headers
end
Megam::API.new(options)
end
|
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_variable_set("@#{attr}", v)
end
alias_method "#{attr}?", attr
end
|
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, :day)
args.present? ? Date.new(*args.map(&:to_i)) : nil
when nil then nil
else raise ArgumentError.new("can't convert #{arg.class} to Date")
end
instance_variable_set("@#{attr}", v)
end
end
|
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) do |*query|
association_class = association_class_name.constantize
# TODO: Support a more generic version of lazy-loading
if query.empty? # Ex: Books.all, so we want to cache it.
ivar = "@#{association_name}"
if instance_variable_defined?(ivar)
instance_variable_get(ivar)
elsif self.class.autoload_associations? && association_class.respond_to?(:all)
instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id)))
else
[]
end
else # Ex: Book.all(:name => "The..."), so we do not want to cache it
if self.class.autoload_associations? && association_class.respond_to?(:all)
Array(association_class.all({"#{self.class.name.demodulize.underscore}_id" => id}.merge(query.first)))
end
end
end
# foos=
define_method("#{association_name}=") do |arg|
association_class = association_class_name.constantize
attr_name = self.class.name.demodulize.underscore
objs = (arg.is_a?(Hash) ? arg.values : Array(arg)).map do |obj|
o = association_class.cast(obj)
if o.respond_to?("#{attr_name}=")
o.send("#{attr_name}=", self)
end
if o.respond_to?("#{attr_name}_id=") && respond_to?(:id)
o.send("#{attr_name}_id=", id)
end
o
end
instance_variable_set("@#{association_name}", objs)
end
end
|
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
# Time left
secondsLeft = withCurrentAndTotalBytes do |cur, total|
if @downloadRateDataOnly && @downloadRateDataOnly > 0
(total.to_f - cur.to_f) / @downloadRateDataOnly
else
0
end
end
# Cap estimated time at 9999 hours
secondsLeft = 35996400 if secondsLeft > 35996400
result[:timeLeft] = Formatter.formatTime(secondsLeft)
## Regular fields
result[:info] = @info ? @info.to_h : nil
result[:infoHash] = @infoHash
result[:recommendedName] = @recommendedName
result[:downloadRate] = @downloadRate
result[:uploadRate] = @uploadRate
result[:downloadRateDataOnly] = @downloadRateDataOnly
result[:uploadRateDataOnly] = @uploadRateDataOnly
result[:completedBytes] = @completedBytes
result[:peers] = @peers.collect{ |p| p.to_h }
result[:state] = @state
#result[:completePieceBitfield] = @completePieceBitfield
result[:metainfoLength] = @metainfoLength
result[:metainfoCompletedLength] = @metainfoCompletedLength
result[:paused] = @paused
result[:queued] = @queued
result[:uploadRateLimit] = @uploadRateLimit
result[:downloadRateLimit] = @downloadRateLimit
result[:ratio] = @ratio
result[:uploadDuration] = @uploadDuration
result[:bytesUploaded] = @bytesUploaded
result[:bytesDownloaded] = @bytesDownloaded
result[:alarms] = @alarms.collect{ |a| a.to_h }
result
end
|
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.setValue(new_value, forKey:binding[:name])
end
end
end
end
end
|
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.include? "Couldn't resolve host"
raise FaviconParty::Curl::DNSError.new(error)
else
raise FaviconParty::CurlError.new(error)
end
end
output
end
|
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)
end
|
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 = options[:interceptor] if options[:interceptor]
end
|
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]
end
|
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)
log " Redir: #{headers['Location']}" if headers.key?('Location')
log "===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) ====="
[status, headers, body]
end
|
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['deas.splat'],
'time' => env['deas.time_taken'],
'status' => status
}
if env['deas.handler_class']
line_attrs['handler'] = env['deas.handler_class'].name
end
if headers.key?('Location')
line_attrs['redir'] = headers['Location']
end
log SummaryLine.new(line_attrs)
[status, headers, body]
end
|
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"
}
end
|
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 Testing #{css_output_path}"
puts " Output ============================================================\n\n"
@error_count += 1 if !system("#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'")
end
output_footer
end
|
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"
end
|
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!(/(#(.*?)#)+?/) do
# 1. Match pre-defined variable, or variable defined in appliance definition.
next @appliance_config.variables[$2] if @appliance_config.variables.has_key?($2)
# 2. Match from environment variables.
next ENV[$2] unless ENV[$2].nil?
# 3. No match, replace the original string.
$1
end
substitute(init, value, depth+1) unless original == value
end
|
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'].nil?
partitions[root].delete('options') if partitions[root]['type'] != partition['type']
partitions[root]['type'] = partition['type']
else
partitions[root]['type'] = @appliance_config.default_filesystem_type
end
else
partitions[root] = {}
partitions[root]['size'] = partition['size']
unless partition['type'].nil?
partitions[root]['type'] = partition['type']
else
partitions[root]['type'] = @appliance_config.default_filesystem_type
end
end
partitions[root]['passphrase'] = partition['passphrase'] unless partition['passphrase'].nil?
partitions[root]['options'] = partition['options'] unless partition['options'].nil?
end
end
# https://bugzilla.redhat.com/show_bug.cgi?id=466275
partitions['/boot'] = {'type' => 'ext3', 'size' => 0.1} if partitions['/boot'].nil? and (@appliance_config.os.name == 'sl' or @appliance_config.os.name == 'centos' or @appliance_config.os.name == 'rhel') and @appliance_config.os.version == '5'
@appliance_config.hardware.partitions = partitions
end
|
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))
when :thin_plate_splines_alt
rnorm = ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0))
return rnorm * Math.log(rnorm)
when :multiquadratic
# return Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum))
(@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0)
when :inverse_multiquadratic
1.0 / ((@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0))
when :cubic
((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0))**(1.5)
# invs = ((vec1-vec2).square + @r0.square).sqrt**(-1)
# invs.sum
# p @ro
# return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum))
# when :inverse_multiquadratic
# # p @ro
# return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum))
else
raise ArgumentError.new("Bad radial basis function: #{@func}")
end
end
|
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* sigma_vec[0], npix)
vals1 = GSL::Vector.linspace(vals[1] - 3.0* sigma_vec[1], vals[1] + 3.0* sigma_vec[1], npix)
mat = GSL::Matrix.alloc(vals0.size, vals1.size)
for i in 0...vals0.size
for j in 0...vals1.size
mat[i,j] = eval(vals0[i], vals1[j])
end
end
mat.gaussian_smooth(*sigma_vec.to_a)
cent = (npix - 1) / 2
return mat[cent, cent]
else
raise 'Not supported for this number of dimensions yet'
end
end
|
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: contour[1], title: val.to_s}})
kit.data[0].with = "l"
kit
end).sum
end
end
graphs.compact.reverse.sum
end
|
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()::getStringArray(meth.to_s.to_java_name).to_a
end
# calls the method
send meth, *args, &block
else
super
end
end
|
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).nil?
data = nil
begin
data = Marshal.load(Zlib::Inflate.inflate(Base64.decode64(fork[:reader].read).to_s))
rescue Zlib::BufError
config.ui.logger.fatal { "Encountered Zlib::BufError when reading child pipe." }
end
config.ui.logger.debug { "read(#{data.inspect})" }
data = process_data(data)
!data.nil? and @results.push(data)
fork[:reader].close
fork[:writer].close
@forks -= [fork]
return [pid, status, data]
end
nil
end
|
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.page_action
fail_if_not_exist "Page action popup", spec.page_action.popup
fail_if_not_exist "Page action icon", spec.page_action.icon
end
if spec.packaged_app
fail_if_not_exist "App launch page", spec.packaged_app.page
end
spec.content_scripts.each do |content_script|
content_script.javascripts.each do |script_path|
fail_if_not_exist "Content script javascript", script_path
end
content_script.stylesheets.each do |style_path|
fail_if_not_exist "Content script style", style_path
end
end
spec.background_scripts.each do |script_path|
fail_if_not_exist "Background script style", script_path
end
fail_if_not_exist "Background page", spec.background_page
fail_if_not_exist "Options page", spec.options_page
spec.web_intents.each do |web_intent|
fail_if_not_exist "Web intent href", web_intent.href
end
spec.nacl_modules.each do |nacl_module|
fail_if_not_exist "NaCl module", nacl_module.path
end
spec.web_accessible_resources.each do |path|
fail_if_not_exist "Web accessible resource", path
end
end
|
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,
:headers => headers,
:payload => body
)
self.response = parse_response(request)
end
|
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
end
end
|
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)
@backend[:user][encrypt(entry.name)] = encrypt(EntryMapper.to_json(entry))
}
end
|
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": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.