_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q9300
SycLink.Formatter.print_horizontal_line
train
def print_horizontal_line(line, separator, widths) puts widths.map { |width| line * width }.join(separator) end
ruby
{ "resource": "" }
q9301
SycLink.Formatter.print_table
train
def print_table(columns, formatter) columns.transpose.each { |row| puts sprintf(formatter, *row) } end
ruby
{ "resource": "" }
q9302
CollectionSpace.Helpers.all
train
def all(path, options = {}, &block) all = [] list_type, list_item = get_list_types(path) result = request('GET', path, options) raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil? total = result.parsed[list_type]['totalItems'].to_i ite...
ruby
{ "resource": "" }
q9303
CollectionSpace.Helpers.post_blob_url
train
def post_blob_url(url) raise ArgumentError.new("Invalid blob URL #{url}") unless URI.parse(url).scheme =~ /^https?/ request 'POST', "blobs", { query: { "blobUri" => url }, } end
ruby
{ "resource": "" }
q9304
CollectionSpace.Helpers.to_object
train
def to_object(record, attribute_map, stringify_keys = false) attributes = {} attribute_map.each do |map| map = map.inject({}) { |memo,(k,v)| memo[k.to_s] = v; memo} if stringify_keys if map["with"] as = deep_find(record, map["key"], map["nested_key"]) values = [] ...
ruby
{ "resource": "" }
q9305
Ponder.Channel.topic
train
def topic if @topic @topic else connected do fiber = Fiber.current callbacks = {} [331, 332, 403, 442].each do |numeric| callbacks[numeric] = @thaum.on(numeric) do |event_data| topic = event_data[:params].match(':(.*)').captures.first ...
ruby
{ "resource": "" }
q9306
Scrapula.Page.search!
train
def search! query, operations = [], &block result = @agent_page.search query # FIXME on every object result = operations.reduce(result) do |tmp, op| tmp.__send__ op end if result yield result if block_given? result end
ruby
{ "resource": "" }
q9307
Guard.HamlCoffee.get_output
train
def get_output(file) file_dir = File.dirname(file) file_name = File.basename(file).split('.')[0..-2].join('.') file_name = "#{file_name}.js" if file_name.match("\.js").nil? file_dir = file_dir.gsub(Regexp.new("#{@options[:input]}(\/){0,1}"), '') if @options[:input] file_dir = File.join(@...
ruby
{ "resource": "" }
q9308
Redstruct.SortedSet.slice
train
def slice(**options) defaults = { lower: nil, upper: nil, exclusive: false, lex: @lex } self.class::Slice.new(self, **defaults.merge(options)) end
ruby
{ "resource": "" }
q9309
Redstruct.SortedSet.to_enum
train
def to_enum(match: '*', count: 10, with_scores: false) enumerator = self.connection.zscan_each(@key, match: match, count: count) return enumerator if with_scores return Enumerator.new do |yielder| loop do item, = enumerator.next yielder << item end end end
ruby
{ "resource": "" }
q9310
Scalaroid.ReplicatedDHT.delete
train
def delete(key, timeout = 2000) result_raw = @conn.call(:delete, [key, timeout]) result = @conn.class.process_result_delete(result_raw) @lastDeleteResult = result[:results] if result[:success] == true return result[:ok] elsif result[:success] == :timeout raise TimeoutError....
ruby
{ "resource": "" }
q9311
Rokko.Rokko.prettify
train
def prettify(blocks) docs_blocks, code_blocks = blocks # Combine all docs blocks into a single big markdown document with section # dividers and run through the Markdown processor. Then split it back out # into separate sections rendered_html = self.class.renderer.render(docs_blocks.join(...
ruby
{ "resource": "" }
q9312
DomainNeutral.SymbolizedClass.method_missing
train
def method_missing(method, *args) if method.to_s =~ /^(\w+)\?$/ v = self.class.find_by_symbol($1) raise NameError unless v other = v.to_sym self.class.class_eval { define_method(method) { self.to_sym == other }} return self.to_sym == other end super end
ruby
{ "resource": "" }
q9313
DomainNeutral.SymbolizedClass.flush_cache
train
def flush_cache Rails.cache.delete([self.class.name, symbol_was.to_s]) Rails.cache.delete([self.class.name, id]) end
ruby
{ "resource": "" }
q9314
Technologist.GitRepository.find_blob
train
def find_blob(blob_name, current_tree = root_tree, &block) blob = current_tree[blob_name] if blob blob = repository.lookup(blob[:oid]) if !block_given? || yield(blob) return blob end end # recurse current_tree.each_tree do |sub_tree| blob = find_...
ruby
{ "resource": "" }
q9315
Scram.Target.conditions_hash_validations
train
def conditions_hash_validations conditions.each do |comparator, mappings| errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a...
ruby
{ "resource": "" }
q9316
DataPaths.Methods.register_data_path
train
def register_data_path(path) path = File.expand_path(path) DataPaths.register(path) data_paths << path unless data_paths.include?(path) return path end
ruby
{ "resource": "" }
q9317
DataPaths.Methods.unregister_data_path
train
def unregister_data_path(path) path = File.expand_path(path) self.data_paths.delete(path) return DataPaths.unregister!(path) end
ruby
{ "resource": "" }
q9318
DataPaths.Methods.unregister_data_paths
train
def unregister_data_paths data_paths.each { |path| DataPaths.unregister!(path) } data_paths.clear return true end
ruby
{ "resource": "" }
q9319
ActiveRecord.IdentityMap.reinit_with
train
def reinit_with(coder) @attributes_cache = {} dirty = @changed_attributes.keys attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty)) @attributes.update(attributes) @changed_attributes.update(coder['attributes'].slice(*dirty)) @changed_attributes.delet...
ruby
{ "resource": "" }
q9320
DiscourseMountableSso.DiscourseSsoController.sso
train
def sso require "discourse_mountable_sso/single_sign_on" sso = DiscourseMountableSso::SingleSignOn.parse( ((session[:discourse_mountable_sso] || {}).delete(:query_string).presence || request.query_string), @config.secret ) discourse_data = send @config.discourse_data_meth...
ruby
{ "resource": "" }
q9321
Meme.Info.followers
train
def followers(count=10) count = 0 if count.is_a?(Symbol) && count == :all query = "SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'" parse = Request.parse(query) if parse results = parse['query']['results'] results.nil? ? nil : results['meme'].map {|m| Info....
ruby
{ "resource": "" }
q9322
Meme.Info.posts
train
def posts(quantity=0) query = "SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';" parse = Request.parse(query) if parse results = parse['query']['results'] results.nil? ? nil : results['post'].map {|m| Post.new(m)} else parse.error! end end
ruby
{ "resource": "" }
q9323
SycLink.Designer.add_links_from_file
train
def add_links_from_file(file) File.foreach(file) do |line| next if line.chomp.empty? url, name, description, tag = line.chomp.split(';') website.add_link(Link.new(url, { name: name, description: description, ...
ruby
{ "resource": "" }
q9324
SycLink.Designer.export
train
def export(format) message = "to_#{format.downcase}" if website.respond_to? message website.send(message) else raise "cannot export to #{format}" end end
ruby
{ "resource": "" }
q9325
SycLink.Designer.update_links_from_file
train
def update_links_from_file(file) File.foreach(file) do |line| next if line.chomp.empty? url, name, description, tag = line.chomp.split(';') website.find_links(url).first.update({ name: name, description: description, ...
ruby
{ "resource": "" }
q9326
SycLink.Designer.remove_links
train
def remove_links(urls) urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link| website.remove_link(link) end end
ruby
{ "resource": "" }
q9327
SycLink.Designer.remove_links_from_file
train
def remove_links_from_file(file) urls = File.foreach(file).map { |url| url.chomp unless url.empty? } remove_links(urls) end
ruby
{ "resource": "" }
q9328
SycLink.Designer.save_website
train
def save_website(directory) File.open(yaml_file(directory, website.title), 'w') do |f| YAML.dump(website, f) end end
ruby
{ "resource": "" }
q9329
SycLink.Designer.delete_website
train
def delete_website(directory) if File.exists? yaml_file(directory, website.title) FileUtils.rm(yaml_file(directory, website.title)) end end
ruby
{ "resource": "" }
q9330
Blueprint.CSSParser.parse
train
def parse(data = nil) data ||= @raw_data # wrapper array holding hashes of css tags/rules css_out = [] # clear initial spaces data.strip_side_space!.strip_space! # split on end of assignments data.split('}').each_with_index do |assignments, index| # split agai...
ruby
{ "resource": "" }
q9331
Bender.CLI.load_enviroment
train
def load_enviroment(file = nil) file ||= "." if File.directory?(file) && File.exists?(File.expand_path("#{file}/config/environment.rb")) require 'rails' require File.expand_path("#{file}/config/environment.rb") if defined?(::Rails) && ::Rails.respond_to?(:application) ...
ruby
{ "resource": "" }
q9332
MaRuKu.MDElement.each_element
train
def each_element(e_node_type=nil, &block) @children.each do |c| if c.kind_of? MDElement if (not e_node_type) || (e_node_type == c.node_type) block.call c end c.each_element(e_node_type, &block) end end end
ruby
{ "resource": "" }
q9333
MaRuKu.MDElement.replace_each_string
train
def replace_each_string(&block) for c in @children if c.kind_of? MDElement c.replace_each_string(&block) end end processed = [] until @children.empty? c = @children.shift if c.kind_of? String result = block.call(c) [*result].each do |e| processed << e end else processed << c e...
ruby
{ "resource": "" }
q9334
RSpecProxies.Proxies.and_before_calling_original
train
def and_before_calling_original self.and_wrap_original do |m, *args, &block| yield *args m.call(*args, &block) end end
ruby
{ "resource": "" }
q9335
RSpecProxies.Proxies.and_after_calling_original
train
def and_after_calling_original self.and_wrap_original do |m, *args, &block| result = m.call(*args, &block) yield result result end end
ruby
{ "resource": "" }
q9336
ActsAsIntegerInfinitable.ClassMethods.acts_as_integer_infinitable
train
def acts_as_integer_infinitable(fields, options = {}) options[:infinity_value] = -1 unless options.key? :infinity_value fields.each do |field| define_method("#{field}=") do |value| int_value = value == Float::INFINITY ? options[:infinity_value] : value write_attribute(field, int...
ruby
{ "resource": "" }
q9337
CaRuby.PersistenceService.query
train
def query(template_or_hql, *path) String === template_or_hql ? query_hql(template_or_hql) : query_template(template_or_hql, path) end
ruby
{ "resource": "" }
q9338
CaRuby.PersistenceService.query_hql
train
def query_hql(hql) logger.debug { "Building HQLCriteria..." } criteria = HQLCriteria.new(hql) target = hql[/from\s+(\S+)/i, 1] raise DatabaseError.new("HQL does not contain a FROM clause: #{hql}") unless target logger.debug { "Submitting search on target class #{target} with the following ...
ruby
{ "resource": "" }
q9339
CaRuby.PersistenceService.query_association_post_caCORE_v4
train
def query_association_post_caCORE_v4(obj, attribute) assn = obj.class.association(attribute) begin result = dispatch { |svc| svc.association(obj, assn) } rescue Exception => e logger.error("Error fetching association #{obj} - #{e}") raise end end
ruby
{ "resource": "" }
q9340
Guard.Yardstick.run_partially
train
def run_partially(paths) return if paths.empty? displayed_paths = paths.map { |path| smart_path(path) } UI.info "Inspecting Yarddocs: #{displayed_paths.join(' ')}" inspect_with_yardstick(path: paths) end
ruby
{ "resource": "" }
q9341
Guard.Yardstick.inspect_with_yardstick
train
def inspect_with_yardstick(yardstick_options = {}) config = ::Yardstick::Config.coerce(yardstick_config(yardstick_options)) measurements = ::Yardstick.measure(config) measurements.puts rescue StandardError => error UI.error 'The following exception occurred while running ' \ "...
ruby
{ "resource": "" }
q9342
Guard.Yardstick.yardstick_config
train
def yardstick_config(extra_options = {}) return options unless options[:config] yardstick_options = YAML.load_file(options[:config]) yardstick_options.merge(extra_options) end
ruby
{ "resource": "" }
q9343
Domain.API.domain_error!
train
def domain_error!(first, *args) first = [first]+args unless args.empty? raise TypeError, "Can't convert `#{first.inspect}` into #{self}", caller end
ruby
{ "resource": "" }
q9344
Checkdin.UserBridge.login_url
train
def login_url options email = options.delete(:email) or raise ArgumentError.new("No :email passed for user") user_identifier = options.delete(:user_identifier) or raise ArgumentError.new("No :user_identifier passed for user") authenticated_parameters = build_authentica...
ruby
{ "resource": "" }
q9345
MeserOngkir.Api.call
train
def call url = URI(api_url) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE url.query = URI.encode_www_form(@params) if @params request = Net::HTTP::Get.new(url) request['key'] = ENV['MESER_ONGKIR_API_KEY'] http....
ruby
{ "resource": "" }
q9346
Spec.Matchers.method_missing
train
def method_missing(sym, *args, &block) # :nodoc:\ matchers = natural_language.keywords['matchers'] be_word = matchers['be'] if matchers sym = be_to_english(sym, be_word) return Matchers::BePredicate.new(sym, *args, &block) if be_predicate?(sym) return Matchers::Has.new(sym, *args, &block) ...
ruby
{ "resource": "" }
q9347
Taxonifi::Export.SpeciesFile.tblRefs
train
def tblRefs sql = [] @headers = %w{RefID ActualYear Title PubID Verbatim} @name_collection.ref_collection.collection.each_with_index do |r,i| # Assumes the 0 "null" pub id is there pub_id = @pub_collection[r.publication] ? @pub_collection[r.publication] : 0 # Build a note base...
ruby
{ "resource": "" }
q9348
Taxonifi::Export.SpeciesFile.tblPubs
train
def tblPubs sql = [] @headers = %w{PubID PrefID PubType ShortName FullName Note LastUpdate ModifiedBy Publisher PlacePublished PubRegID Status StartYear EndYear BHL} # Hackish should build this elsewhere, but degrades OK pubs = @name_collection.ref_collection.collection.collect{|r| r.publicatio...
ruby
{ "resource": "" }
q9349
Taxonifi::Export.SpeciesFile.tblPeople
train
def tblPeople @headers = %w{PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy} sql = [] @name_collection.ref_collection.all_authors.each do |a| cols = { PersonID: a.id, FamilyName: (a.last_name.length > 0 ? a.last_name : "Unknown"), ...
ruby
{ "resource": "" }
q9350
Taxonifi::Export.SpeciesFile.tblRefAuthors
train
def tblRefAuthors @headers = %w{RefID PersonID SeqNum AuthorCount LastUpdate ModifiedBy} sql = [] @name_collection.ref_collection.collection.each do |r| r.authors.each_with_index do |x, i| cols = { RefID: r.id, PersonID: x.id, SeqNum: i + 1, ...
ruby
{ "resource": "" }
q9351
Taxonifi::Export.SpeciesFile.tblCites
train
def tblCites @headers = %w{TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus} sql = [] @name_collection.citations.keys.each do |name_id| seq_num = 1 @name_...
ruby
{ "resource": "" }
q9352
Taxonifi::Export.SpeciesFile.tblTypeSpecies
train
def tblTypeSpecies @headers = %w{GenusNameID SpeciesNameID Reason AuthorityRefID FirstFamGrpNameID LastUpdate ModifiedBy NewID} sql = [] names = @name_collection.names_at_rank('genus') + @name_collection.names_at_rank('subgenus') names.each do |n| if n.properties[:type_species_id] ...
ruby
{ "resource": "" }
q9353
Taxonifi::Export.SpeciesFile.tblNomenclator
train
def tblNomenclator @headers = %w{NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind} sql = [] i = 1 # Ugh, move build from here @name_collection.nomenclators.keys.each do ...
ruby
{ "resource": "" }
q9354
ExcelToCsv.ExcelFile.empty_row?
train
def empty_row?(row) is_empty = true row.each do |item| is_empty = false if item && !item.empty? end is_empty end
ruby
{ "resource": "" }
q9355
ExcelToCsv.ExcelFile.truncate_decimal
train
def truncate_decimal(a_cell) if(a_cell.is_a?(Numeric)) a_cell = truncate_decimal_to_string(a_cell, 3) # Truncate zeros (unless there is only 1 decimal place) # eg. 12.10 => 12.1 # 12.0 => 12.0 a_cell = BigDecimal.new(a_cell).to_s("F") end a_cell end
ruby
{ "resource": "" }
q9356
ExcelToCsv.ExcelFile.clean_int_value
train
def clean_int_value(a_cell) if(a_cell.match(/\.[0]+$/)) cary = a_cell.split(".") a_cell = cary[0] end a_cell end
ruby
{ "resource": "" }
q9357
Fuelcell.Cli.parse
train
def parse(raw_args) cmd_args = cmd_args_extractor.call(raw_args) cmd = root.locate(cmd_args, raw_args) root.add_global_options(cmd) begin parser.call(cmd, cmd_args, raw_args) rescue => e shell.error e.message shell.failure_exit end end
ruby
{ "resource": "" }
q9358
Fuelcell.Cli.execute
train
def execute(context) cmd = context[:cmd] opts = context[:opts] || {} args = context[:args] || [] cmd_args = context[:cmd_args] cli_shell = context[:shell] || shell unless cmd.callable? return root['help'].call(opts, cmd_args, shell) end cmd = ha...
ruby
{ "resource": "" }
q9359
StreamBot.OAuth.get_access_token
train
def get_access_token # get saved access token if ::File.exists?(ACCESS_TOKEN) @access_token = ::YAML.load_file(ACCESS_TOKEN) end # if access token is nil, # then get a new initial token if @access_token.nil? get_initial_token ::File.open(ACCESS_TOKEN, 'w') do ...
ruby
{ "resource": "" }
q9360
StreamBot.OAuth.get_initial_token
train
def get_initial_token @request_token = get_request_token puts "Place \"#{@request_token.authorize_url}\" in your browser" print "Enter the number they give you: " pin = STDIN.readline.chomp @access_token = @request_token.get_access_token(:oauth_verifier => pin) end
ruby
{ "resource": "" }
q9361
Rsxml.Sexp.traverse
train
def traverse(sexp, visitor, context=Visitor::Context.new) element_name, attrs, children = decompose_sexp(sexp) non_ns_attrs, ns_bindings = Namespace::non_ns_attrs_ns_bindings(context.ns_stack, element_name, attrs) context.ns_stack.push(ns_bindings) eelement_name = Namespace::explode_qna...
ruby
{ "resource": "" }
q9362
Errship.Rescuers.errship_standard
train
def errship_standard(errship_scope = false) flash[:error] ||= I18n.t('errship.standard') render :template => '/errship/standard.html.erb', :layout => 'application', :locals => { :status_code => 500, :errship_scope => errship_scope }, :status => (Errship.status_co...
ruby
{ "resource": "" }
q9363
Errship.Rescuers.flashback
train
def flashback(error_message, exception = nil) airbrake_class.send(:notify, exception) if airbrake_class flash[:error] = error_message begin redirect_to :back rescue ActionController::RedirectBackError redirect_to error_path end end
ruby
{ "resource": "" }
q9364
SDBTools.Operation.each
train
def each Transaction.open(":#{method} operation") do |t| next_token = starting_token begin args = @args.dup args << next_token results = @sdb.send(@method, *args) yield(results, self) next_token = results[:next_token] end while next_token ...
ruby
{ "resource": "" }
q9365
ActionController.RequestForgeryProtection.form_authenticity_token
train
def form_authenticity_token raise 'CSRF token secret must be defined' if CSRF_TOKEN_SECRET.nil? || CSRF_TOKEN_SECRET.empty? if request.session_options[:id].nil? || request.session_options[:id].empty? original_form_authenticity_token else Digest::SHA1.hexdigest("#{CSRF_TOKEN_S...
ruby
{ "resource": "" }
q9366
Putio.Configurable.reset!
train
def reset! Putio::Configurable.keys.each do |key| public_send("#{key}=".to_sym, Putio::Defaults.options[key]) end self end
ruby
{ "resource": "" }
q9367
Machined.Context.add_machined_helpers
train
def add_machined_helpers # :nodoc: machined.context_helpers.each do |helper| case helper when Proc instance_eval &helper when Module extend helper end end end
ruby
{ "resource": "" }
q9368
Crisp.Shell.run
train
def run runtime = Runtime.new buffer = '' while (line = Readline.readline(buffer.empty? ? ">> " : "?> ", true)) begin buffer << line ast = Parser.new.parse(buffer) puts "=> " + runtime.run(ast).to_s buffer = '' rescue Crisp::SyntaxError => e ...
ruby
{ "resource": "" }
q9369
ZergGemPlugin.Manager.load
train
def load(needs = {}) needs = needs.merge({"zergrush" => INCLUDE}) Gem::Specification.each { |gem| # don't load gems more than once next if @gems.has_key? gem.name check = needs.dup # rolls through the depends and...
ruby
{ "resource": "" }
q9370
Rufus.Cloche.put
train
def put(doc, opts={}) opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h } doc = Rufus::Json.dup(doc) unless opts['update_rev'] # work with a copy, don't touch original type, key = doc['type'], doc['_id'] raise( ArgumentError.new("missing values for keys 'type' and/or '_id...
ruby
{ "resource": "" }
q9371
Rufus.Cloche.get_many
train
def get_many(type, regex=nil, opts={}) opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h } d = dir_for(type) return (opts['count'] ? 0 : []) unless File.exist?(d) regexes = regex ? Array(regex) : nil docs = [] skipped = 0 limit = opts['limit'] skip = opts['skip'...
ruby
{ "resource": "" }
q9372
JqueryDatepick.FormHelper.datepicker
train
def datepicker(object_name, method, options = {}, timepicker = false) input_tag = JqueryDatepick::Tags.new(object_name, method, self, options) dp_options, tf_options = input_tag.split_options(options) tf_options[:value] = input_tag.format_date(tf_options[:value], String.new(dp_options[:dateFormat]))...
ruby
{ "resource": "" }
q9373
Twat.Options.default=
train
def default=(value) value = value.to_sym unless config.accounts.include?(value) raise NoSuchAccount end config[:default] = value config.save! end
ruby
{ "resource": "" }
q9374
ActiveHarmony.Queue.queue_push
train
def queue_push(object) queue_item = QueueItem.new( :kind => "push", :object_type => object.class.name, :object_local_id => object.id, :state => "new" ) queue_item.save end
ruby
{ "resource": "" }
q9375
ActiveHarmony.Queue.queue_pull
train
def queue_pull(object_class, remote_id) queue_item = QueueItem.new( :kind => "pull", :object_type => object_class.name, :object_remote_id => remote_id, :state => "new" ) queue_item.save end
ruby
{ "resource": "" }
q9376
Organismo.ElementCollection.elements_by_source
train
def elements_by_source source_items.map.with_index do |source_item, index| Organismo::Element.new(source_item, index).create end end
ruby
{ "resource": "" }
q9377
PutText.POEntry.to_s
train
def to_s str = String.new('') # Add comments str = add_comment(str, ':', @references.join(' ')) if references? str = add_comment(str, ',', @flags.join("\n")) if flags? # Add id and context str = add_string(str, 'msgctxt', @msgctxt) if @msgctxt str = add_string(str, 'msgid', @...
ruby
{ "resource": "" }
q9378
TF2R.Raffle.info
train
def info @info ||= {link_snippet: @link_snippet, title: title, description: description, start_time: start_time, end_time: end_time, win_chance: win_chance, current_entries: current_entries, max_entries: max_entries, is_done: is_done} end
ruby
{ "resource": "" }
q9379
TF2R.Raffle.populate_raffle_info
train
def populate_raffle_info threads = [] threads << Thread.new do @api_info = API.raffle_info(@link_snippet) end threads << Thread.new do page = @scraper.fetch(raffle_link(@link_snippet)) @scraper_info = @scraper.scrape_raffle(page) end threads.each { |t| t.join...
ruby
{ "resource": "" }
q9380
TF2R.Raffle.normalize_entries
train
def normalize_entries(entries) entries.map do |entry| entry[:steam_id] = extract_steam_id entry.delete('link') entry[:username] = entry.delete('name') entry[:color] = entry.delete('color').downcase.strip entry[:avatar_link] = entry.delete('avatar') end entries end
ruby
{ "resource": "" }
q9381
Andromeda.Spot.post_to
train
def post_to(track, data, tags_in = {}) tags_in = (here.tags.identical_copy.update(tags_in) rescue tags_in) if here plan.post_data self, track, data, tags_in self end
ruby
{ "resource": "" }
q9382
FentonShell.Organization.organization_create
train
def organization_create(global_options, options) result = Excon.post( "#{global_options[:fenton_server_url]}/organizations.json", body: organization_json(options), headers: { 'Content-Type' => 'application/json' } ) [result.status, JSON.parse(result.body)] end
ruby
{ "resource": "" }
q9383
Drafter.Creation.save_draft
train
def save_draft(parent_draft=nil, parent_association_name=nil) if valid? do_create_draft(parent_draft, parent_association_name) create_subdrafts end return self.draft.reload if self.draft end
ruby
{ "resource": "" }
q9384
Drafter.Creation.build_draft_uploads
train
def build_draft_uploads self.attributes.keys.each do |key| if (self.respond_to?(key) && self.send(key).is_a?(CarrierWave::Uploader::Base) && self.send(key).file) self.draft.draft_uploads << build_draft_upload(key) end end end
ruby
{ "resource": "" }
q9385
Drafter.Creation.build_draft_upload
train
def build_draft_upload(key) cw_uploader = self.send(key) file = File.new(cw_uploader.file.path) if cw_uploader.file existing_upload = self.draft.draft_uploads.where(:draftable_mount_column => key).first draft_upload = existing_upload.nil? ? DraftUpload.new : existing_upload draft...
ruby
{ "resource": "" }
q9386
EvenBetterNestedSet.NestedSet.root
train
def root(force_reload=nil) @root = nil if force_reload @root ||= transaction do reload_boundaries base_class.roots.find(:first, :conditions => ["#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?", left, right]) end end
ruby
{ "resource": "" }
q9387
EvenBetterNestedSet.NestedSet.family_ids
train
def family_ids(force_reload=false) return @family_ids unless @family_ids.nil? or force_reload transaction do reload_boundaries query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " + "WHERE #{nested_set_column(:left)} >= #{left} AND #{nested...
ruby
{ "resource": "" }
q9388
EvenBetterNestedSet.NestedSet.recalculate_nested_set
train
def recalculate_nested_set(left) #:nodoc: child_left = left + 1 children.each do |child| child_left = child.recalculate_nested_set(child_left) end set_boundaries(left, child_left) save_without_validation! right + 1 end
ruby
{ "resource": "" }
q9389
Lleidasms.Client.send_waplink
train
def send_waplink number, url, message cmd_waplink number, url, message if wait wait_for last_label return false if @response_cmd.eql? 'NOOK' return "#{@response_args[0]}.#{@response_args[1]}".to_f end end
ruby
{ "resource": "" }
q9390
Lleidasms.Client.add_addressee
train
def add_addressee addressees, wait = true @addressees_accepted = false @addressees_rejected = false if addressees.kind_of?(Array) addressees = addressees.join ' ' end cmd_dst addressees while wait && !@addressees_accepted wait_for last_label retur...
ruby
{ "resource": "" }
q9391
Lleidasms.Client.msg
train
def msg message, wait = true cmd_msg message return false unless wait_for(last_label) if wait return @response_args end
ruby
{ "resource": "" }
q9392
Cornerstone.CornerstoneMailer.new_post
train
def new_post(name, email, post, discussion) @post = post @discussion = discussion @name = name mail :to => email, :subject => I18n.t('cornerstone.cornerstone_mailer.new_post.subject', :topic => @discussion.subject) end
ruby
{ "resource": "" }
q9393
Beam.Upload.validate_record
train
def validate_record(errors_count, row_hash, index) record = new(row_hash) unless record.valid? errors_count += 1 [nil, errors_count, log_and_return_validation_error(record, row_hash, index)] else [record, errors_count, nil] end end
ruby
{ "resource": "" }
q9394
Tuiter.Request.create_http_request
train
def create_http_request(http_method, path, *arguments) http_method = http_method.to_sym if [:post, :put].include?(http_method) data = arguments.shift end headers = arguments.first.is_a?(Hash) ? arguments.shift : {} case http_method when :post reques...
ruby
{ "resource": "" }
q9395
Activr.Registry.timeline_entries
train
def timeline_entries @timeline_entries ||= begin result = { } self.timelines.each do |(timeline_kind, timeline_class)| dir_name = Activr::Utils.kind_for_class(timeline_class) dir_path = File.join(Activr.timelines_path, dir_name) if !File.directory?(dir_path) ...
ruby
{ "resource": "" }
q9396
Activr.Registry.class_for_timeline_entry
train
def class_for_timeline_entry(timeline_kind, route_kind) (self.timeline_entries[timeline_kind] && self.timeline_entries[timeline_kind][route_kind]) || Activr::Timeline::Entry end
ruby
{ "resource": "" }
q9397
Activr.Registry.add_entity
train
def add_entity(entity_name, entity_options, activity_klass) entity_name = entity_name.to_sym if @entity_classes[entity_name] && (@entity_classes[entity_name].name != entity_options[:class].name) # otherwise this would break timeline entries deletion mecanism raise "Entity name #{entity_name...
ruby
{ "resource": "" }
q9398
Activr.Registry.activity_entities_for_model
train
def activity_entities_for_model(model_class) @activity_entities_for_model[model_class] ||= begin result = [ ] @entity_classes.each do |entity_name, entity_class| result << entity_name if (entity_class == model_class) end result end end
ruby
{ "resource": "" }
q9399
Activr.Registry.timeline_entities_for_model
train
def timeline_entities_for_model(model_class) @timeline_entities_for_model[model_class] ||= begin result = { } self.timelines.each do |timeline_kind, timeline_class| result[timeline_class] = [ ] timeline_class.routes.each do |route| entities_ary = @activity_entitie...
ruby
{ "resource": "" }