_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 items = result.parsed[list_type]['itemsInPage'].to_i return all if total == 0 pages = (total / config.page_size) + 1 (0 .. pages - 1).each do |i| options[:query][:pgNum] = i result = request('GET', path, options) raise RequestError.new result.status if result.status_code != 200 list_items = result.parsed[list_type][list_item] list_items = [ list_items ] if items == 1 list_items.each { |item| yield item if block_given? } all.concat list_items end all end
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 = [] if as.is_a? Array values = as.map { |a| strip_refname( deep_find(a, map["with"]) ) } elsif as.is_a? Hash and as[ map["with"] ] values = as[ map["with"] ].is_a?(Array) ? as[ map["with"] ].map { |a| strip_refname(a) } : [ strip_refname(as[ map["with"] ]) ] end attributes[map["field"]] = values else attributes[map["field"]] = deep_find(record, map["key"], map["nested_key"]) end end attributes end
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 fiber.resume topic end end raw "TOPIC #{@name}" @topic = Fiber.yield callbacks.each do |type, callback| @thaum.callbacks[type].delete(callback) end @topic end end end
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(@options[:output], file_dir) if @options[:output] if file_dir == '' file_name else File.join(file_dir, file_name) end end
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.new(result_raw) else raise UnknownError.new(result_raw) end end
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("\n\n##### DIVIDER\n\n")) rendered_html = ' ' if rendered_html == '' # ''.split() won't return anything useful docs_html = rendered_html.split(/\n*<h5>DIVIDER<\/h5>\n*/m) docs_html.zip(code_blocks) end
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_blob(blob_name, repository.lookup(sub_tree[:oid]), &block) break blob if blob end end
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? Hash end end
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.delete_if{|k,v| v.eql? @attributes[k]} run_callbacks :find self end
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_method discourse_data.each_pair {|k,v| sso.send("#{ k }=", v) } sso.sso_secret = @config.secret yield sso if block_given? redirect_to sso.to_url("#{@config.discourse_url}/session/sso_login") end
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.new(m)} else parse.error! end end
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, tag: tag })) end end
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, tag: tag }) end end
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 again to separate tags from rules tags, styles = assignments.split('{').map{|a| a.strip_side_space!} unless styles.blank? # clean up tags and apply namespaces as needed tags.strip_selector_space! tags.gsub!(/\./, ".#{namespace}") unless namespace.blank? # split on semicolon to iterate through each rule rules = [] styles.split(';').each do |key_val_pair| unless key_val_pair.nil? # split by property/val and append to rules array with correct declaration property, value = key_val_pair.split(':', 2).map{|kv| kv.strip_side_space!} break unless property && value rules << "#{property}:#{value};" end end # now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9) css_out << {:tags => tags, :rules => rules.join, :idx => index} unless tags.blank? || rules.to_s.blank? end end css_out end
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) # Rails 3 ::Rails.application.eager_load! elsif defined?(::Rails::Initializer) # Rails 2.3 $rails_rake_task = false ::Rails::Initializer.run :load_application_classes end elsif File.file?(file) require File.expand_path(file) end end
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 end end @children = processed end
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_value) end define_method("#{field}") do value = read_attribute(field) value == options[:infinity_value] ? Float::INFINITY : value end end end
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 HQL:\n #{hql}" } begin dispatch { |svc| svc.query(criteria, target) } rescue Exception => e logger.error("Error querying on HQL - #{$!}:\n#{hql}") raise e end end
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 ' \ "guard-yardstick: #{error.backtrace.first} " \ "#{error.message} (#{error.class.name})" end
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_authenticated_parameters(email, user_identifier, options) [checkdin_landing_url, authenticated_parameters.to_query].join end
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.request(request) end
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) if have_predicate?(sym) end
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 based on "unused" properties note = [] if r.properties r.properties.keys.each do |k| note.push "#{k}: #{r.properties[k]}" if r.properties[k] && r.properties.length > 0 end end note = note.join("; ") note = @empty_quotes if note.length == 0 cols = { RefID: r.id, ContainingRefID: 0, Title: (r.title.nil? ? @empty_quotes : r.title), PubID: pub_id, Series: @empty_quotes, Volume: (r.volume ? r.volume : @empty_quotes), Issue: (r.number ? r.number : @empty_quotes), RefPages: r.page_string, # always a strings ActualYear: (r.year ? r.year : @empty_quotes), StatedYear: @empty_quotes, AccessCode: 0, Flags: 0, Note: note, LastUpdate: @time, LinkID: 0, ModifiedBy: @authorized_user_id, CiteDataStatus: 0, Verbatim: (r.full_citation ? r.full_citation : @empty_quotes) } sql << sql_insert_statement('tblRefs', cols) end sql.join("\n") end
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.publication}.compact.uniq pubs.each_with_index do |p, i| cols = { PubID: i + 1, PrefID: 0, PubType: 1, ShortName: "unknown_#{i}", # Unique constraint FullName: p, Note: @empty_quotes, LastUpdate: @time, ModifiedBy: @authorized_user_id, Publisher: @empty_quotes, PlacePublished: @empty_quotes, PubRegID: 0, Status: 0, StartYear: 0, EndYear: 0, BHL: 0 } @pub_collection.merge!(p => i + 1) sql << sql_insert_statement('tblPubs', cols) end sql.join("\n") end
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"), GivenNames: a.first_name || @empty_quotes, GivenInitials: a.initials_string || @empty_quotes, Suffix: a.suffix || @empty_quotes, Role: 1, # authors LastUpdate: @time, ModifiedBy: @authorized_user_id } sql << sql_insert_statement('tblPeople', cols) end sql.join("\n") end
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, AuthorCount: r.authors.size + 1, LastUpdate: @time, ModifiedBy: @authorized_user_id } sql << sql_insert_statement('tblRefAuthors', cols) end end sql.join("\n") end
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_collection.citations[name_id].each do |ref_id, nomenclator_index, properties| cols = { TaxonNameID: name_id, SeqNum: seq_num, RefID: ref_id, NomenclatorID: nomenclator_index, LastUpdate: @time, ModifiedBy: @authorized_user_id, CitePages: (properties[:cite_pages] ? properties[:cite_pages] : @empty_quotes), NewNameStatus: 0, Note: (properties[:note] ? properties[:note] : @empty_quotes), TypeClarification: 0, # We might derive more data from this CurrentConcept: (properties[:current_concept] == true ? 1 : 0), # Boolean, right? ConceptChange: 0, # Unspecified InfoFlags: 0, # InfoFlagStatus: 1, # 1 => needs review PolynomialStatus: 0 } sql << sql_insert_statement('tblCites', cols) seq_num += 1 end end sql.join("\n") end
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] ref = get_ref(n) # ref = @by_author_reference_index[n.author_year_index] next if ref.nil? cols = { GenusNameID: n.id , SpeciesNameID: n.properties[:type_species_id], Reason: 0 , AuthorityRefID: 0 , FirstFamGrpNameID: 0 , LastUpdate: @time , ModifiedBy: @authorized_user_id , NewID: 0 # What is this? } sql << sql_insert_statement('tblTypeSpecies', cols) end end sql.join("\n") end
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 |i| name = @name_collection.nomenclators[i] genus_id = @genus_names[name[0]] genus_id ||= 0 subgenus_id = @genus_names[name[1]] subgenus_id ||= 0 species_id = @species_names[name[2]] species_id ||= 0 subspecies_id = @species_names[name[3]] subspecies_id ||= 0 variety_id = @species_names[name[4]] variety_id ||= 0 cols = { NomenclatorID: i, GenusNameID: genus_id, SubgenusNameID: subgenus_id, SpeciesNameID: species_id, SubspeciesNameID: subspecies_id, InfrasubspeciesNameID: variety_id, InfrasubKind: (variety_id == 0 ? 0 : 2), LastUpdate: @time, ModifiedBy: @authorized_user_id, SuitableForGenus: 0, # Set in SF w test SuitableForSpecies: 0 # Set in SF w test } i += 1 sql << sql_insert_statement('tblNomenclator', cols) end sql.join("\n") end
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 = handle_callable_option(root, cmd) cmd.call(opts, args, cli_shell) end
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 |out| YAML.dump(@access_token, out) end end end
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_qname(context.ns_stack, element_name) eattrs = Namespace::explode_attr_qnames(context.ns_stack, non_ns_attrs) begin visitor.element(context, eelement_name, eattrs, ns_bindings) do children.each_with_index do |child, i| if child.is_a?(Array) traverse(child, visitor, context) else visitor.text(context, child) end end end ensure context.ns_stack.pop end visitor end
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_code_success ? 200 : 500) end
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 end end
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_SECRET}#{request.session_options[:id]}#{request.subdomain}") end end
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 # noop end end end
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 inverts anything it finds gem.dependencies.each do |dep| # this will fail if a gem is depended more than once if check.has_key? dep.name check[dep.name] = !check[dep.name] end end # now since excluded gems start as true, inverting them # makes them false so we'll skip this gem if any excludes are found if (check.select {|name,test| !test}).length == 0 # looks like no needs were set to false, so it's good if gem.metadata["zergrushplugin"] != nil require File.join(gem.gem_dir, "lib", gem.name, "init.rb") @gems[gem.name] = gem.gem_dir end end } return nil end
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'") ) if type.nil? || key.nil? rev = (doc['_rev'] ||= -1) raise( ArgumentError.new("values for '_rev' must be positive integers") ) if rev.class != Fixnum && rev.class != Bignum r = lock(rev == -1 ? :create : :write, type, key) do |file| cur = do_get(file) return cur if cur && cur['_rev'] != doc['_rev'] return true if cur.nil? && doc['_rev'] != -1 doc['_rev'] += 1 File.open(file.path, 'wb') { |io| io.write(Rufus::Json.encode(doc)) } end r == false ? true : nil end
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'] count = opts['count'] ? 0 : nil files = Dir[File.join(d, '**', '*.json')].sort_by { |f| File.basename(f) } files = files.reverse if opts['descending'] files.each do |fn| key = File.basename(fn, '.json') if regexes.nil? or match?(key, regexes) skipped = skipped + 1 next if skip and skipped <= skip doc = get(type, key) next unless doc if count count = count + 1 else docs << doc end break if limit and docs.size >= limit end end # WARNING : there is a twist here, the filenames may have a different # sort order from actual _ids... #docs.sort { |doc0, doc1| doc0['_id'] <=> doc1['_id'] } # let's trust filename order count ? count : docs end
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])) if tf_options[:value] && !tf_options[:value].empty? && dp_options.has_key?(:dateFormat) html = input_tag.render method = timepicker ? "datetimepicker" : "datepicker" html += javascript_tag("jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)["id"]}').#{method}(#{dp_options.to_json})});") html.html_safe end
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', @msgid) str = add_string(str, 'msgid_plural', @msgid_plural) if plural? str = add_translations(str) str end
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 } end
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_upload.file_data = file draft_upload.draftable_mount_column = key draft_upload end
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_set_column(:right)} <= #{right} " + "ORDER BY #{nested_set_column(:left)}" @family_ids = base_class.connection.select_values(query).map(&:to_i) end end
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 return false if !add_addressee_results end end
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 request = Net::HTTP::Post.new(path,headers) request["Content-Length"] = 0 # Default to 0 when :put request = Net::HTTP::Put.new(path,headers) request["Content-Length"] = 0 # Default to 0 when :get request = Net::HTTP::Get.new(path,headers) when :delete request = Net::HTTP::Delete.new(path,headers) else raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}" end # handling basic http auth request.basic_auth @config[:username], @config[:password] if data.is_a?(Hash) request.set_form_data(data) elsif data request.body = data.to_s request["Content-Length"] = request.body.length end request end
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) dir_name = Activr::Utils.kind_for_class(timeline_class, 'timeline') dir_path = File.join(Activr.timelines_path, dir_name) end if File.directory?(dir_path) result[timeline_kind] = { } Dir["#{dir_path}/*.rb"].sort.inject(result[timeline_kind]) do |memo, file_path| base_name = File.basename(file_path, '.rb') # skip base class if (base_name != "base_timeline_entry") klass = "#{timeline_class.name}::#{base_name.camelize}".constantize route_kind = if (match_data = base_name.match(/(.+)_timeline_entry$/)) match_data[1] else base_name end route = timeline_class.routes.find do |timeline_route| timeline_route.kind == route_kind end raise "Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}" unless route memo[route_kind] = klass end memo end end end result end end
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} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}" end # class for entity @entity_classes[entity_name] = entity_options[:class] # entities for activity @activity_entities[activity_klass] ||= [ ] @activity_entities[activity_klass] << entity_name # entities @entities ||= { } @entities[entity_name] ||= { } if !@entities[entity_name][activity_klass].blank? raise "Entity name #{entity_name} already used for activity: #{activity_klass}" end @entities[entity_name][activity_klass] = entity_options end
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_entities[route.activity_class] (entities_ary || [ ]).each do |entity_name| result[timeline_class] << entity_name if (@entity_classes[entity_name] == model_class) end end result[timeline_class].uniq! end result end end
ruby
{ "resource": "" }