repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
rightscale/right_chimp
lib/right_chimp/resources/server.rb
Chimp.Server.run_executable
def run_executable(exec, options) script_href = "right_script_href="+exec.href # Construct the parameters to pass for the inputs params=options.collect { |k, v| "&inputs[][name]=#{k}&inputs[][value]=#{v}" unless k == :ignore_lock }.join('&') if options[:ignore_lock] params+="&ignore_lock=true" end # self is the actual Server object Log.debug "[#{Chimp.get_job_uuid}] Running executable" task = self.object.run_executable(script_href + params) return task end
ruby
def run_executable(exec, options) script_href = "right_script_href="+exec.href # Construct the parameters to pass for the inputs params=options.collect { |k, v| "&inputs[][name]=#{k}&inputs[][value]=#{v}" unless k == :ignore_lock }.join('&') if options[:ignore_lock] params+="&ignore_lock=true" end # self is the actual Server object Log.debug "[#{Chimp.get_job_uuid}] Running executable" task = self.object.run_executable(script_href + params) return task end
[ "def", "run_executable", "(", "exec", ",", "options", ")", "script_href", "=", "\"right_script_href=\"", "+", "exec", ".", "href", "params", "=", "options", ".", "collect", "{", "|", "k", ",", "v", "|", "\"&inputs[][name]=#{k}&inputs[][value]=#{v}\"", "unless", "k", "==", ":ignore_lock", "}", ".", "join", "(", "'&'", ")", "if", "options", "[", ":ignore_lock", "]", "params", "+=", "\"&ignore_lock=true\"", "end", "Log", ".", "debug", "\"[#{Chimp.get_job_uuid}] Running executable\"", "task", "=", "self", ".", "object", ".", "run_executable", "(", "script_href", "+", "params", ")", "return", "task", "end" ]
In order to run the task, we need to call run_executable on ourselves
[ "In", "order", "to", "run", "the", "task", "we", "need", "to", "call", "run_executable", "on", "ourselves" ]
290d3e01f7bf4b505722a080cb0abbb0314222f8
https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/resources/server.rb#L63-L77
train
rberger/phaserunner
lib/phaserunner/main.rb
Phaserunner.Cli.main
def main program_desc 'Read values from the Grin PhaseRunner Controller primarily for logging' version Phaserunner::VERSION subcommand_option_handling :normal arguments :strict sort_help :manually desc 'Serial (USB) device' default_value '/dev/ttyUSB0' arg 'tty' flag [:t, :tty] desc 'Serial port baudrate' default_value 115200 arg 'baudrate' flag [:b, :baudrate] desc 'Modbus slave ID' default_value 1 arg 'slave_id' flag [:s, :slave_id] desc 'Path to json file that contains Grin Modbus Dictionary' default_value Modbus.default_file_path arg 'dictionary_file' flag [:d, :dictionary_file] desc 'Loop the command n times' default_value :forever arg 'loop_count', :optional flag [:l, :loop_count] desc 'Do not output to stdout' switch [:q, :quiet] desc 'Read a single or multiple adjacent registers from and address' arg_name 'register_address' command :read_register do |read_register| read_register.desc 'Number of registers to read starting at the Arg Address' read_register.default_value 1 read_register.flag [:c, :count] read_register.arg 'address' read_register.action do |global_options, options, args| address = args[0].to_i count = args[1].to_i node = dict[address] puts modbus.range_address_header(address, count).join(",") unless quiet (0..loop_count).each do |i| puts modbus.read_raw_range(address, count).join(",") unless quiet end end end desc 'Logs interesting Phaserunner registers to stdout and file' long_desc %q(Logs interesting Phaserunner registers to stdout and a CSV file. File name in the form: phaserunner.#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.csv) command :log do |log| log.action do |global_options, options, args| filename = "phaserunner.#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.csv" output_fd = File.open(filename, 'w') header = modbus.bulk_log_header # Generate and output header line hdr = %Q(Timestamp,#{header.join(",")}) puts hdr unless quiet output_fd.puts hdr (0..loop_count).each do |i| data = modbus.bulk_log_data str = %Q(#{Time.now.utc.round(10).iso8601(6)},#{data.join(",")}) puts str unless quiet output_fd.puts str sleep 0.2 end end end pre do |global, command, options, args| # Pre logic here # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only @quiet = global[:quiet] # Handle that loop_count can be :forever or an Integer @loop_count = if global[:loop_count] == :forever Float::INFINITY else global[:loop_count].to_i end @modbus = Modbus.new(global) @dict = @modbus.dict end post do |global,command,options,args| # Post logic here # Use skips_post before a command to skip this # block on that command only end on_error do |exception| # Error logic here # return false to skip default error handling true end exit run(ARGV) end
ruby
def main program_desc 'Read values from the Grin PhaseRunner Controller primarily for logging' version Phaserunner::VERSION subcommand_option_handling :normal arguments :strict sort_help :manually desc 'Serial (USB) device' default_value '/dev/ttyUSB0' arg 'tty' flag [:t, :tty] desc 'Serial port baudrate' default_value 115200 arg 'baudrate' flag [:b, :baudrate] desc 'Modbus slave ID' default_value 1 arg 'slave_id' flag [:s, :slave_id] desc 'Path to json file that contains Grin Modbus Dictionary' default_value Modbus.default_file_path arg 'dictionary_file' flag [:d, :dictionary_file] desc 'Loop the command n times' default_value :forever arg 'loop_count', :optional flag [:l, :loop_count] desc 'Do not output to stdout' switch [:q, :quiet] desc 'Read a single or multiple adjacent registers from and address' arg_name 'register_address' command :read_register do |read_register| read_register.desc 'Number of registers to read starting at the Arg Address' read_register.default_value 1 read_register.flag [:c, :count] read_register.arg 'address' read_register.action do |global_options, options, args| address = args[0].to_i count = args[1].to_i node = dict[address] puts modbus.range_address_header(address, count).join(",") unless quiet (0..loop_count).each do |i| puts modbus.read_raw_range(address, count).join(",") unless quiet end end end desc 'Logs interesting Phaserunner registers to stdout and file' long_desc %q(Logs interesting Phaserunner registers to stdout and a CSV file. File name in the form: phaserunner.#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.csv) command :log do |log| log.action do |global_options, options, args| filename = "phaserunner.#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.csv" output_fd = File.open(filename, 'w') header = modbus.bulk_log_header # Generate and output header line hdr = %Q(Timestamp,#{header.join(",")}) puts hdr unless quiet output_fd.puts hdr (0..loop_count).each do |i| data = modbus.bulk_log_data str = %Q(#{Time.now.utc.round(10).iso8601(6)},#{data.join(",")}) puts str unless quiet output_fd.puts str sleep 0.2 end end end pre do |global, command, options, args| # Pre logic here # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only @quiet = global[:quiet] # Handle that loop_count can be :forever or an Integer @loop_count = if global[:loop_count] == :forever Float::INFINITY else global[:loop_count].to_i end @modbus = Modbus.new(global) @dict = @modbus.dict end post do |global,command,options,args| # Post logic here # Use skips_post before a command to skip this # block on that command only end on_error do |exception| # Error logic here # return false to skip default error handling true end exit run(ARGV) end
[ "def", "main", "program_desc", "'Read values from the Grin PhaseRunner Controller primarily for logging'", "version", "Phaserunner", "::", "VERSION", "subcommand_option_handling", ":normal", "arguments", ":strict", "sort_help", ":manually", "desc", "'Serial (USB) device'", "default_value", "'/dev/ttyUSB0'", "arg", "'tty'", "flag", "[", ":t", ",", ":tty", "]", "desc", "'Serial port baudrate'", "default_value", "115200", "arg", "'baudrate'", "flag", "[", ":b", ",", ":baudrate", "]", "desc", "'Modbus slave ID'", "default_value", "1", "arg", "'slave_id'", "flag", "[", ":s", ",", ":slave_id", "]", "desc", "'Path to json file that contains Grin Modbus Dictionary'", "default_value", "Modbus", ".", "default_file_path", "arg", "'dictionary_file'", "flag", "[", ":d", ",", ":dictionary_file", "]", "desc", "'Loop the command n times'", "default_value", ":forever", "arg", "'loop_count'", ",", ":optional", "flag", "[", ":l", ",", ":loop_count", "]", "desc", "'Do not output to stdout'", "switch", "[", ":q", ",", ":quiet", "]", "desc", "'Read a single or multiple adjacent registers from and address'", "arg_name", "'register_address'", "command", ":read_register", "do", "|", "read_register", "|", "read_register", ".", "desc", "'Number of registers to read starting at the Arg Address'", "read_register", ".", "default_value", "1", "read_register", ".", "flag", "[", ":c", ",", ":count", "]", "read_register", ".", "arg", "'address'", "read_register", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "address", "=", "args", "[", "0", "]", ".", "to_i", "count", "=", "args", "[", "1", "]", ".", "to_i", "node", "=", "dict", "[", "address", "]", "puts", "modbus", ".", "range_address_header", "(", "address", ",", "count", ")", ".", "join", "(", "\",\"", ")", "unless", "quiet", "(", "0", "..", "loop_count", ")", ".", "each", "do", "|", "i", "|", "puts", "modbus", ".", "read_raw_range", "(", "address", ",", "count", ")", ".", "join", "(", "\",\"", ")", "unless", "quiet", "end", "end", "end", "desc", "'Logs interesting Phaserunner registers to stdout and file'", "long_desc", "%q(Logs interesting Phaserunner registers to stdout and a CSV file. File name in the form: phaserunner.#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.csv)", "command", ":log", "do", "|", "log", "|", "log", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "filename", "=", "\"phaserunner.#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.csv\"", "output_fd", "=", "File", ".", "open", "(", "filename", ",", "'w'", ")", "header", "=", "modbus", ".", "bulk_log_header", "hdr", "=", "%Q(Timestamp,#{header.join(\",\")})", "puts", "hdr", "unless", "quiet", "output_fd", ".", "puts", "hdr", "(", "0", "..", "loop_count", ")", ".", "each", "do", "|", "i", "|", "data", "=", "modbus", ".", "bulk_log_data", "str", "=", "%Q(#{Time.now.utc.round(10).iso8601(6)},#{data.join(\",\")})", "puts", "str", "unless", "quiet", "output_fd", ".", "puts", "str", "sleep", "0.2", "end", "end", "end", "pre", "do", "|", "global", ",", "command", ",", "options", ",", "args", "|", "@quiet", "=", "global", "[", ":quiet", "]", "@loop_count", "=", "if", "global", "[", ":loop_count", "]", "==", ":forever", "Float", "::", "INFINITY", "else", "global", "[", ":loop_count", "]", ".", "to_i", "end", "@modbus", "=", "Modbus", ".", "new", "(", "global", ")", "@dict", "=", "@modbus", ".", "dict", "end", "post", "do", "|", "global", ",", "command", ",", "options", ",", "args", "|", "end", "on_error", "do", "|", "exception", "|", "true", "end", "exit", "run", "(", "ARGV", ")", "end" ]
Does all the CLI work
[ "Does", "all", "the", "CLI", "work" ]
bc1d7c94381c1a3547f5badd581c2f40eefdd807
https://github.com/rberger/phaserunner/blob/bc1d7c94381c1a3547f5badd581c2f40eefdd807/lib/phaserunner/main.rb#L22-L131
train
angelim/rails_redshift_replicator
lib/rails_redshift_replicator/deleter.rb
RailsRedshiftReplicator.Deleter.handle_delete_propagation
def handle_delete_propagation if replicable.tracking_deleted && has_deleted_ids? RailsRedshiftReplicator.logger.info propagation_message(:propagating_deletes) delete_on_target ? purge_deleted : RailsRedshiftReplicator.logger.error(propagation_message(:delete_propagation_error)) end end
ruby
def handle_delete_propagation if replicable.tracking_deleted && has_deleted_ids? RailsRedshiftReplicator.logger.info propagation_message(:propagating_deletes) delete_on_target ? purge_deleted : RailsRedshiftReplicator.logger.error(propagation_message(:delete_propagation_error)) end end
[ "def", "handle_delete_propagation", "if", "replicable", ".", "tracking_deleted", "&&", "has_deleted_ids?", "RailsRedshiftReplicator", ".", "logger", ".", "info", "propagation_message", "(", ":propagating_deletes", ")", "delete_on_target", "?", "purge_deleted", ":", "RailsRedshiftReplicator", ".", "logger", ".", "error", "(", "propagation_message", "(", ":delete_propagation_error", ")", ")", "end", "end" ]
Deletes records flagged for deletion on target and then delete the queue from source
[ "Deletes", "records", "flagged", "for", "deletion", "on", "target", "and", "then", "delete", "the", "queue", "from", "source" ]
823f6da36f43a39f340a3ca7eb159df58a86766d
https://github.com/angelim/rails_redshift_replicator/blob/823f6da36f43a39f340a3ca7eb159df58a86766d/lib/rails_redshift_replicator/deleter.rb#L20-L25
train
rayyanqcri/rayyan-scrapers
lib/rayyan-scrapers/nih_fulltext_scraper.rb
RayyanScrapers.NihFulltextScraper.process_list_page
def process_list_page(page) @logger.info("Processing list page with URL: #{page.uri}") #page.save_as "html/result-list.html" new_items_found = nil items = page.links #[0..50] # TODO REMOVE [], getting sample only items_len = items.length - 1 @total = @total + items_len # pline "Found #{items_len} items in page", true items.each do |anchor| next if anchor.text == '../' new_items_found = false if new_items_found.nil? pid = anchor.text.split('.').first link = "#{page.uri}#{anchor.href}" @logger.info "Got result with id #{pid}" # pline " Item #{@curr_property} of #{@total}..." # get detailed info begin article = Article.find_by_url link if article.nil? new_items_found = true article = process_fulltext_detail_page(@agent.get(link), pid) yield article, true else yield article, false end rescue => exception @logger.error "Error processing #{link}:" @logger.error exception @logger.error exception.backtrace.join("\n") end @curr_property = @curr_property + 1 end new_items_found end
ruby
def process_list_page(page) @logger.info("Processing list page with URL: #{page.uri}") #page.save_as "html/result-list.html" new_items_found = nil items = page.links #[0..50] # TODO REMOVE [], getting sample only items_len = items.length - 1 @total = @total + items_len # pline "Found #{items_len} items in page", true items.each do |anchor| next if anchor.text == '../' new_items_found = false if new_items_found.nil? pid = anchor.text.split('.').first link = "#{page.uri}#{anchor.href}" @logger.info "Got result with id #{pid}" # pline " Item #{@curr_property} of #{@total}..." # get detailed info begin article = Article.find_by_url link if article.nil? new_items_found = true article = process_fulltext_detail_page(@agent.get(link), pid) yield article, true else yield article, false end rescue => exception @logger.error "Error processing #{link}:" @logger.error exception @logger.error exception.backtrace.join("\n") end @curr_property = @curr_property + 1 end new_items_found end
[ "def", "process_list_page", "(", "page", ")", "@logger", ".", "info", "(", "\"Processing list page with URL: #{page.uri}\"", ")", "new_items_found", "=", "nil", "items", "=", "page", ".", "links", "items_len", "=", "items", ".", "length", "-", "1", "@total", "=", "@total", "+", "items_len", "items", ".", "each", "do", "|", "anchor", "|", "next", "if", "anchor", ".", "text", "==", "'../'", "new_items_found", "=", "false", "if", "new_items_found", ".", "nil?", "pid", "=", "anchor", ".", "text", ".", "split", "(", "'.'", ")", ".", "first", "link", "=", "\"#{page.uri}#{anchor.href}\"", "@logger", ".", "info", "\"Got result with id #{pid}\"", "begin", "article", "=", "Article", ".", "find_by_url", "link", "if", "article", ".", "nil?", "new_items_found", "=", "true", "article", "=", "process_fulltext_detail_page", "(", "@agent", ".", "get", "(", "link", ")", ",", "pid", ")", "yield", "article", ",", "true", "else", "yield", "article", ",", "false", "end", "rescue", "=>", "exception", "@logger", ".", "error", "\"Error processing #{link}:\"", "@logger", ".", "error", "exception", "@logger", ".", "error", "exception", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "@curr_property", "=", "@curr_property", "+", "1", "end", "new_items_found", "end" ]
NOTUSED by islam
[ "NOTUSED", "by", "islam" ]
63d8b02987790ca08c06121775f95c49ed52c1b4
https://github.com/rayyanqcri/rayyan-scrapers/blob/63d8b02987790ca08c06121775f95c49ed52c1b4/lib/rayyan-scrapers/nih_fulltext_scraper.rb#L54-L94
train
emn178/sms_carrier
lib/sms_carrier/log_subscriber.rb
SmsCarrier.LogSubscriber.deliver
def deliver(event) info do recipients = Array(event.payload[:to]).join(', ') "\nSent SMS to #{recipients} (#{event.duration.round(1)}ms)" end debug { event.payload[:sms] } end
ruby
def deliver(event) info do recipients = Array(event.payload[:to]).join(', ') "\nSent SMS to #{recipients} (#{event.duration.round(1)}ms)" end debug { event.payload[:sms] } end
[ "def", "deliver", "(", "event", ")", "info", "do", "recipients", "=", "Array", "(", "event", ".", "payload", "[", ":to", "]", ")", ".", "join", "(", "', '", ")", "\"\\nSent SMS to #{recipients} (#{event.duration.round(1)}ms)\"", "end", "debug", "{", "event", ".", "payload", "[", ":sms", "]", "}", "end" ]
An SMS was delivered.
[ "An", "SMS", "was", "delivered", "." ]
6aa97b46d8fa6e92db67a8cf5c81076d5ae1f9ad
https://github.com/emn178/sms_carrier/blob/6aa97b46d8fa6e92db67a8cf5c81076d5ae1f9ad/lib/sms_carrier/log_subscriber.rb#L8-L15
train
activenetwork/actv
lib/actv/base.rb
ACTV.Base.to_hash
def to_hash hash = {} hash["attrs"] = @attrs self.instance_variables.keep_if { |key| key != :@attrs }.each do |var| val = self.instance_variable_get(var) hash["attrs"][var.to_s.delete("@").to_sym] = val.to_hash if val.is_a? ACTV::Base end hash["attrs"] end
ruby
def to_hash hash = {} hash["attrs"] = @attrs self.instance_variables.keep_if { |key| key != :@attrs }.each do |var| val = self.instance_variable_get(var) hash["attrs"][var.to_s.delete("@").to_sym] = val.to_hash if val.is_a? ACTV::Base end hash["attrs"] end
[ "def", "to_hash", "hash", "=", "{", "}", "hash", "[", "\"attrs\"", "]", "=", "@attrs", "self", ".", "instance_variables", ".", "keep_if", "{", "|", "key", "|", "key", "!=", ":@attrs", "}", ".", "each", "do", "|", "var", "|", "val", "=", "self", ".", "instance_variable_get", "(", "var", ")", "hash", "[", "\"attrs\"", "]", "[", "var", ".", "to_s", ".", "delete", "(", "\"@\"", ")", ".", "to_sym", "]", "=", "val", ".", "to_hash", "if", "val", ".", "is_a?", "ACTV", "::", "Base", "end", "hash", "[", "\"attrs\"", "]", "end" ]
Creation of object hash when sending request to soap
[ "Creation", "of", "object", "hash", "when", "sending", "request", "to", "soap" ]
861222f5eccf81628221c71af8b8681789171402
https://github.com/activenetwork/actv/blob/861222f5eccf81628221c71af8b8681789171402/lib/actv/base.rb#L125-L135
train
praxis/attributor
lib/attributor/attribute_resolver.rb
Attributor.AttributeResolver.check
def check(path_prefix, key_path, predicate = nil) value = query(key_path, path_prefix) # we have a value, any value, which is good enough given no predicate return true if !value.nil? && predicate.nil? case predicate when ::String, ::Regexp, ::Integer, ::Float, ::DateTime, true, false return predicate === value when ::Proc # Cannot use === here as above due to different behavior in Ruby 1.8 return predicate.call(value) when nil return !value.nil? else raise AttributorException, "predicate not supported: #{predicate.inspect}" end end
ruby
def check(path_prefix, key_path, predicate = nil) value = query(key_path, path_prefix) # we have a value, any value, which is good enough given no predicate return true if !value.nil? && predicate.nil? case predicate when ::String, ::Regexp, ::Integer, ::Float, ::DateTime, true, false return predicate === value when ::Proc # Cannot use === here as above due to different behavior in Ruby 1.8 return predicate.call(value) when nil return !value.nil? else raise AttributorException, "predicate not supported: #{predicate.inspect}" end end
[ "def", "check", "(", "path_prefix", ",", "key_path", ",", "predicate", "=", "nil", ")", "value", "=", "query", "(", "key_path", ",", "path_prefix", ")", "return", "true", "if", "!", "value", ".", "nil?", "&&", "predicate", ".", "nil?", "case", "predicate", "when", "::", "String", ",", "::", "Regexp", ",", "::", "Integer", ",", "::", "Float", ",", "::", "DateTime", ",", "true", ",", "false", "return", "predicate", "===", "value", "when", "::", "Proc", "return", "predicate", ".", "call", "(", "value", ")", "when", "nil", "return", "!", "value", ".", "nil?", "else", "raise", "AttributorException", ",", "\"predicate not supported: #{predicate.inspect}\"", "end", "end" ]
Checks that the the condition is met. This means the attribute identified by path_prefix and key_path satisfies the optional predicate, which when nil simply checks for existence. @param path_prefix [String] @param key_path [String] @param predicate [String|Regexp|Proc|NilClass] @returns [Boolean] True if :required_if condition is met, false otherwise @raise [AttributorException] When an unsupported predicate is passed
[ "Checks", "that", "the", "the", "condition", "is", "met", ".", "This", "means", "the", "attribute", "identified", "by", "path_prefix", "and", "key_path", "satisfies", "the", "optional", "predicate", "which", "when", "nil", "simply", "checks", "for", "existence", "." ]
faebaa0176086e1421cefc54a352d13a5b08d985
https://github.com/praxis/attributor/blob/faebaa0176086e1421cefc54a352d13a5b08d985/lib/attributor/attribute_resolver.rb#L82-L99
train
praxis/attributor
lib/attributor/attribute.rb
Attributor.Attribute.describe
def describe(shallow = true, example: nil) description = {} # Clone the common options TOP_LEVEL_OPTIONS.each do |option_name| description[option_name] = options[option_name] if options.key? option_name end # Make sure this option definition is not mistaken for the real generated example if (ex_def = description.delete(:example)) description[:example_definition] = ex_def end special_options = options.keys - TOP_LEVEL_OPTIONS - INTERNAL_OPTIONS description[:options] = {} unless special_options.empty? special_options.each do |opt_name| description[:options][opt_name] = options[opt_name] end # Change the reference option to the actual class name. if (reference = options[:reference]) description[:options][:reference] = reference.name end description[:type] = type.describe(shallow, example: example) # Move over any example from the type, into the attribute itself if (ex = description[:type].delete(:example)) description[:example] = dump(ex) end description end
ruby
def describe(shallow = true, example: nil) description = {} # Clone the common options TOP_LEVEL_OPTIONS.each do |option_name| description[option_name] = options[option_name] if options.key? option_name end # Make sure this option definition is not mistaken for the real generated example if (ex_def = description.delete(:example)) description[:example_definition] = ex_def end special_options = options.keys - TOP_LEVEL_OPTIONS - INTERNAL_OPTIONS description[:options] = {} unless special_options.empty? special_options.each do |opt_name| description[:options][opt_name] = options[opt_name] end # Change the reference option to the actual class name. if (reference = options[:reference]) description[:options][:reference] = reference.name end description[:type] = type.describe(shallow, example: example) # Move over any example from the type, into the attribute itself if (ex = description[:type].delete(:example)) description[:example] = dump(ex) end description end
[ "def", "describe", "(", "shallow", "=", "true", ",", "example", ":", "nil", ")", "description", "=", "{", "}", "TOP_LEVEL_OPTIONS", ".", "each", "do", "|", "option_name", "|", "description", "[", "option_name", "]", "=", "options", "[", "option_name", "]", "if", "options", ".", "key?", "option_name", "end", "if", "(", "ex_def", "=", "description", ".", "delete", "(", ":example", ")", ")", "description", "[", ":example_definition", "]", "=", "ex_def", "end", "special_options", "=", "options", ".", "keys", "-", "TOP_LEVEL_OPTIONS", "-", "INTERNAL_OPTIONS", "description", "[", ":options", "]", "=", "{", "}", "unless", "special_options", ".", "empty?", "special_options", ".", "each", "do", "|", "opt_name", "|", "description", "[", ":options", "]", "[", "opt_name", "]", "=", "options", "[", "opt_name", "]", "end", "if", "(", "reference", "=", "options", "[", ":reference", "]", ")", "description", "[", ":options", "]", "[", ":reference", "]", "=", "reference", ".", "name", "end", "description", "[", ":type", "]", "=", "type", ".", "describe", "(", "shallow", ",", "example", ":", "example", ")", "if", "(", "ex", "=", "description", "[", ":type", "]", ".", "delete", "(", ":example", ")", ")", "description", "[", ":example", "]", "=", "dump", "(", "ex", ")", "end", "description", "end" ]
Options we don't want to expose when describing attributes
[ "Options", "we", "don", "t", "want", "to", "expose", "when", "describing", "attributes" ]
faebaa0176086e1421cefc54a352d13a5b08d985
https://github.com/praxis/attributor/blob/faebaa0176086e1421cefc54a352d13a5b08d985/lib/attributor/attribute.rb#L97-L126
train
praxis/attributor
lib/attributor/attribute.rb
Attributor.Attribute.validate
def validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT) raise "INVALID CONTEXT!! #{context}" unless context # Validate any requirements, absolute or conditional, and return. if object.nil? # == Attributor::UNSET # With no value, we can only validate whether that is acceptable or not and return. # Beyond that, no further validation should be done. return validate_missing_value(context) end # TODO: support validation for other types of conditional dependencies based on values of other attributes errors = validate_type(object, context) # End validation if we don't even have the proper type to begin with return errors if errors.any? if options[:values] && !options[:values].include?(object) errors << "Attribute #{Attributor.humanize_context(context)}: #{Attributor.errorize_value(object)} is not within the allowed values=#{options[:values].inspect} " end errors + type.validate(object, context, self) end
ruby
def validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT) raise "INVALID CONTEXT!! #{context}" unless context # Validate any requirements, absolute or conditional, and return. if object.nil? # == Attributor::UNSET # With no value, we can only validate whether that is acceptable or not and return. # Beyond that, no further validation should be done. return validate_missing_value(context) end # TODO: support validation for other types of conditional dependencies based on values of other attributes errors = validate_type(object, context) # End validation if we don't even have the proper type to begin with return errors if errors.any? if options[:values] && !options[:values].include?(object) errors << "Attribute #{Attributor.humanize_context(context)}: #{Attributor.errorize_value(object)} is not within the allowed values=#{options[:values].inspect} " end errors + type.validate(object, context, self) end
[ "def", "validate", "(", "object", ",", "context", "=", "Attributor", "::", "DEFAULT_ROOT_CONTEXT", ")", "raise", "\"INVALID CONTEXT!! #{context}\"", "unless", "context", "if", "object", ".", "nil?", "return", "validate_missing_value", "(", "context", ")", "end", "errors", "=", "validate_type", "(", "object", ",", "context", ")", "return", "errors", "if", "errors", ".", "any?", "if", "options", "[", ":values", "]", "&&", "!", "options", "[", ":values", "]", ".", "include?", "(", "object", ")", "errors", "<<", "\"Attribute #{Attributor.humanize_context(context)}: #{Attributor.errorize_value(object)} is not within the allowed values=#{options[:values].inspect} \"", "end", "errors", "+", "type", ".", "validate", "(", "object", ",", "context", ",", "self", ")", "end" ]
Validates stuff and checks dependencies
[ "Validates", "stuff", "and", "checks", "dependencies" ]
faebaa0176086e1421cefc54a352d13a5b08d985
https://github.com/praxis/attributor/blob/faebaa0176086e1421cefc54a352d13a5b08d985/lib/attributor/attribute.rb#L180-L202
train
cldwalker/boson-more
lib/boson/pipes.rb
Boson.Pipes.sort_pipe
def sort_pipe(object, sort) sort_lambda = lambda {} if object[0].is_a?(Hash) if sort.to_s[/^\d+$/] sort = sort.to_i elsif object[0].keys.all? {|e| e.is_a?(Symbol) } sort = sort.to_sym end sort_lambda = untouched_sort?(object.map {|e| e[sort] }) ? lambda {|e| e[sort] } : lambda {|e| e[sort].to_s } else sort_lambda = untouched_sort?(object.map {|e| e.send(sort) }) ? lambda {|e| e.send(sort) || ''} : lambda {|e| e.send(sort).to_s } end object.sort_by &sort_lambda rescue NoMethodError, ArgumentError $stderr.puts "Sort failed with nonexistant method '#{sort}'" end
ruby
def sort_pipe(object, sort) sort_lambda = lambda {} if object[0].is_a?(Hash) if sort.to_s[/^\d+$/] sort = sort.to_i elsif object[0].keys.all? {|e| e.is_a?(Symbol) } sort = sort.to_sym end sort_lambda = untouched_sort?(object.map {|e| e[sort] }) ? lambda {|e| e[sort] } : lambda {|e| e[sort].to_s } else sort_lambda = untouched_sort?(object.map {|e| e.send(sort) }) ? lambda {|e| e.send(sort) || ''} : lambda {|e| e.send(sort).to_s } end object.sort_by &sort_lambda rescue NoMethodError, ArgumentError $stderr.puts "Sort failed with nonexistant method '#{sort}'" end
[ "def", "sort_pipe", "(", "object", ",", "sort", ")", "sort_lambda", "=", "lambda", "{", "}", "if", "object", "[", "0", "]", ".", "is_a?", "(", "Hash", ")", "if", "sort", ".", "to_s", "[", "/", "\\d", "/", "]", "sort", "=", "sort", ".", "to_i", "elsif", "object", "[", "0", "]", ".", "keys", ".", "all?", "{", "|", "e", "|", "e", ".", "is_a?", "(", "Symbol", ")", "}", "sort", "=", "sort", ".", "to_sym", "end", "sort_lambda", "=", "untouched_sort?", "(", "object", ".", "map", "{", "|", "e", "|", "e", "[", "sort", "]", "}", ")", "?", "lambda", "{", "|", "e", "|", "e", "[", "sort", "]", "}", ":", "lambda", "{", "|", "e", "|", "e", "[", "sort", "]", ".", "to_s", "}", "else", "sort_lambda", "=", "untouched_sort?", "(", "object", ".", "map", "{", "|", "e", "|", "e", ".", "send", "(", "sort", ")", "}", ")", "?", "lambda", "{", "|", "e", "|", "e", ".", "send", "(", "sort", ")", "||", "''", "}", ":", "lambda", "{", "|", "e", "|", "e", ".", "send", "(", "sort", ")", ".", "to_s", "}", "end", "object", ".", "sort_by", "&", "sort_lambda", "rescue", "NoMethodError", ",", "ArgumentError", "$stderr", ".", "puts", "\"Sort failed with nonexistant method '#{sort}'\"", "end" ]
Sorts an array of objects or hashes using a sort field. Sort is reversed with reverse_sort set to true.
[ "Sorts", "an", "array", "of", "objects", "or", "hashes", "using", "a", "sort", "field", ".", "Sort", "is", "reversed", "with", "reverse_sort", "set", "to", "true", "." ]
f928ebc18d8641e038891f78896ae7251b97415c
https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/pipes.rb#L43-L59
train
cldwalker/boson-more
lib/boson/pipes.rb
Boson.Pipes.pipes_pipe
def pipes_pipe(obj, arr) arr.inject(obj) {|acc,e| Boson.full_invoke(e, [acc]) } end
ruby
def pipes_pipe(obj, arr) arr.inject(obj) {|acc,e| Boson.full_invoke(e, [acc]) } end
[ "def", "pipes_pipe", "(", "obj", ",", "arr", ")", "arr", ".", "inject", "(", "obj", ")", "{", "|", "acc", ",", "e", "|", "Boson", ".", "full_invoke", "(", "e", ",", "[", "acc", "]", ")", "}", "end" ]
Pipes output of multiple commands recursively, given initial object
[ "Pipes", "output", "of", "multiple", "commands", "recursively", "given", "initial", "object" ]
f928ebc18d8641e038891f78896ae7251b97415c
https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/pipes.rb#L71-L73
train
PeterCamilleri/mini_readline
lib/mini_readline/read_line.rb
MiniReadline.Readline.readline
def readline(options = {}) suppress_warnings initialize_parms(options) MiniTerm.raw { @edit.edit_process } ensure restore_warnings puts end
ruby
def readline(options = {}) suppress_warnings initialize_parms(options) MiniTerm.raw { @edit.edit_process } ensure restore_warnings puts end
[ "def", "readline", "(", "options", "=", "{", "}", ")", "suppress_warnings", "initialize_parms", "(", "options", ")", "MiniTerm", ".", "raw", "{", "@edit", ".", "edit_process", "}", "ensure", "restore_warnings", "puts", "end" ]
Read a line from the console with edit and history.
[ "Read", "a", "line", "from", "the", "console", "with", "edit", "and", "history", "." ]
45175ee01653a184b8ba04b2e8691dce5b26a1b5
https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line.rb#L34-L41
train
PeterCamilleri/mini_readline
lib/mini_readline/read_line.rb
MiniReadline.Readline.set_options
def set_options(options) @options = MiniReadline::BASE_OPTIONS .merge(instance_options) .merge(options) @options[:window_width] = MiniTerm.width - 1 set_prompt(@options[:prompt]) verify_mask(@options[:secret_mask]) end
ruby
def set_options(options) @options = MiniReadline::BASE_OPTIONS .merge(instance_options) .merge(options) @options[:window_width] = MiniTerm.width - 1 set_prompt(@options[:prompt]) verify_mask(@options[:secret_mask]) end
[ "def", "set_options", "(", "options", ")", "@options", "=", "MiniReadline", "::", "BASE_OPTIONS", ".", "merge", "(", "instance_options", ")", ".", "merge", "(", "options", ")", "@options", "[", ":window_width", "]", "=", "MiniTerm", ".", "width", "-", "1", "set_prompt", "(", "@options", "[", ":prompt", "]", ")", "verify_mask", "(", "@options", "[", ":secret_mask", "]", ")", "end" ]
Set up the options
[ "Set", "up", "the", "options" ]
45175ee01653a184b8ba04b2e8691dce5b26a1b5
https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line.rb#L55-L63
train
PeterCamilleri/mini_readline
lib/mini_readline/read_line.rb
MiniReadline.Readline.set_prompt
def set_prompt(prompt) @options[:base_prompt] = Prompt.new(prompt) @options[:scroll_prompt] = Prompt.new(@options[:alt_prompt] || prompt) verify_prompt(@options[:base_prompt]) verify_prompt(@options[:scroll_prompt]) end
ruby
def set_prompt(prompt) @options[:base_prompt] = Prompt.new(prompt) @options[:scroll_prompt] = Prompt.new(@options[:alt_prompt] || prompt) verify_prompt(@options[:base_prompt]) verify_prompt(@options[:scroll_prompt]) end
[ "def", "set_prompt", "(", "prompt", ")", "@options", "[", ":base_prompt", "]", "=", "Prompt", ".", "new", "(", "prompt", ")", "@options", "[", ":scroll_prompt", "]", "=", "Prompt", ".", "new", "(", "@options", "[", ":alt_prompt", "]", "||", "prompt", ")", "verify_prompt", "(", "@options", "[", ":base_prompt", "]", ")", "verify_prompt", "(", "@options", "[", ":scroll_prompt", "]", ")", "end" ]
Set up the prompt.
[ "Set", "up", "the", "prompt", "." ]
45175ee01653a184b8ba04b2e8691dce5b26a1b5
https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line.rb#L66-L72
train
jomalley2112/hot_date_rails
app/helpers/form_helper.rb
FormHelper.ActionView::Helpers::FormTagHelper.hd_picker_tag
def hd_picker_tag(field_name, value=nil, cls="datepicker", opts={}, locale_format=nil) draw_ext_input_tag(field_name, value, cls, locale_format, opts) end
ruby
def hd_picker_tag(field_name, value=nil, cls="datepicker", opts={}, locale_format=nil) draw_ext_input_tag(field_name, value, cls, locale_format, opts) end
[ "def", "hd_picker_tag", "(", "field_name", ",", "value", "=", "nil", ",", "cls", "=", "\"datepicker\"", ",", "opts", "=", "{", "}", ",", "locale_format", "=", "nil", ")", "draw_ext_input_tag", "(", "field_name", ",", "value", ",", "cls", ",", "locale_format", ",", "opts", ")", "end" ]
for when there's no rails form object and you really just need inputs
[ "for", "when", "there", "s", "no", "rails", "form", "object", "and", "you", "really", "just", "need", "inputs" ]
4580d2c2823ba472afca3d38f21b2f8acff954f2
https://github.com/jomalley2112/hot_date_rails/blob/4580d2c2823ba472afca3d38f21b2f8acff954f2/app/helpers/form_helper.rb#L5-L7
train
ejlangev/citibike
lib/citibike/api.rb
Citibike.Api.distance_from
def distance_from(lat, long) dLat = self.degrees_to_radians(lat - self.latitude) dLon = self.degrees_to_radians(long - self.longitude) lat1 = self.degrees_to_radians(lat) lat2 = self.degrees_to_radians(self.latitude) a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) EARTH_RADIUS * c end
ruby
def distance_from(lat, long) dLat = self.degrees_to_radians(lat - self.latitude) dLon = self.degrees_to_radians(long - self.longitude) lat1 = self.degrees_to_radians(lat) lat2 = self.degrees_to_radians(self.latitude) a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) EARTH_RADIUS * c end
[ "def", "distance_from", "(", "lat", ",", "long", ")", "dLat", "=", "self", ".", "degrees_to_radians", "(", "lat", "-", "self", ".", "latitude", ")", "dLon", "=", "self", ".", "degrees_to_radians", "(", "long", "-", "self", ".", "longitude", ")", "lat1", "=", "self", ".", "degrees_to_radians", "(", "lat", ")", "lat2", "=", "self", ".", "degrees_to_radians", "(", "self", ".", "latitude", ")", "a", "=", "Math", ".", "sin", "(", "dLat", "/", "2", ")", "*", "Math", ".", "sin", "(", "dLat", "/", "2", ")", "+", "Math", ".", "sin", "(", "dLon", "/", "2", ")", "*", "Math", ".", "sin", "(", "dLon", "/", "2", ")", "*", "Math", ".", "cos", "(", "lat1", ")", "*", "Math", ".", "cos", "(", "lat2", ")", "c", "=", "2", "*", "Math", ".", "atan2", "(", "Math", ".", "sqrt", "(", "a", ")", ",", "Math", ".", "sqrt", "(", "1", "-", "a", ")", ")", "EARTH_RADIUS", "*", "c", "end" ]
Returns the distance this object is from the given latitude and longitude. Distance is as the crow flies. @param lat [Float] [A latitude position] @param long [Float] [A longitude position] @return [Float] [Distance from the input postion in miles]
[ "Returns", "the", "distance", "this", "object", "is", "from", "the", "given", "latitude", "and", "longitude", ".", "Distance", "is", "as", "the", "crow", "flies", "." ]
40ae300dacb299468985fa9c2fdf5dba7a235c93
https://github.com/ejlangev/citibike/blob/40ae300dacb299468985fa9c2fdf5dba7a235c93/lib/citibike/api.rb#L44-L58
train
ejlangev/citibike
lib/citibike/api.rb
Citibike.Api.method_missing
def method_missing(sym, *args, &block) if self.internal_object.key?(sym.to_s) return self.internal_object[sym.to_s] end super end
ruby
def method_missing(sym, *args, &block) if self.internal_object.key?(sym.to_s) return self.internal_object[sym.to_s] end super end
[ "def", "method_missing", "(", "sym", ",", "*", "args", ",", "&", "block", ")", "if", "self", ".", "internal_object", ".", "key?", "(", "sym", ".", "to_s", ")", "return", "self", ".", "internal_object", "[", "sym", ".", "to_s", "]", "end", "super", "end" ]
Allow hash keys to be used as methods
[ "Allow", "hash", "keys", "to", "be", "used", "as", "methods" ]
40ae300dacb299468985fa9c2fdf5dba7a235c93
https://github.com/ejlangev/citibike/blob/40ae300dacb299468985fa9c2fdf5dba7a235c93/lib/citibike/api.rb#L66-L72
train
3scale/xcflushd
lib/xcflushd/storage.rb
Xcflushd.Storage.reports_to_flush
def reports_to_flush # The Redis rename command overwrites the key with the new name if it # exists. This means that if the rename operation fails in a flush cycle, # and succeeds in a next one, the data that the key had in the first # flush cycle will be lost. # For that reason, every time we need to rename a key, we will use a # unique suffix. This way, when the rename operation fails, the key # will not be overwritten later, and we will be able to recover its # content. suffix = suffix_for_unique_naming report_keys = report_keys_to_flush(suffix) if report_keys.empty? logger.warn "No reports available to flush" report_keys else reports(report_keys, suffix) end end
ruby
def reports_to_flush # The Redis rename command overwrites the key with the new name if it # exists. This means that if the rename operation fails in a flush cycle, # and succeeds in a next one, the data that the key had in the first # flush cycle will be lost. # For that reason, every time we need to rename a key, we will use a # unique suffix. This way, when the rename operation fails, the key # will not be overwritten later, and we will be able to recover its # content. suffix = suffix_for_unique_naming report_keys = report_keys_to_flush(suffix) if report_keys.empty? logger.warn "No reports available to flush" report_keys else reports(report_keys, suffix) end end
[ "def", "reports_to_flush", "suffix", "=", "suffix_for_unique_naming", "report_keys", "=", "report_keys_to_flush", "(", "suffix", ")", "if", "report_keys", ".", "empty?", "logger", ".", "warn", "\"No reports available to flush\"", "report_keys", "else", "reports", "(", "report_keys", ",", "suffix", ")", "end", "end" ]
This performs a cleanup of the reports to be flushed. We can decide later whether it is better to leave this responsibility to the caller of the method. Returns an array of hashes where each of them has a service_id, credentials, and a usage. The usage is another hash where the keys are the metrics and the values are guaranteed to respond to to_i and to_s.
[ "This", "performs", "a", "cleanup", "of", "the", "reports", "to", "be", "flushed", ".", "We", "can", "decide", "later", "whether", "it", "is", "better", "to", "leave", "this", "responsibility", "to", "the", "caller", "of", "the", "method", "." ]
ca29b7674c3cd952a2a50c0604a99f04662bf27d
https://github.com/3scale/xcflushd/blob/ca29b7674c3cd952a2a50c0604a99f04662bf27d/lib/xcflushd/storage.rb#L53-L71
train
pdobb/object_inspector
lib/object_inspector/scope.rb
ObjectInspector.Scope.join_name
def join_name(parts, separator: ObjectInspector.configuration.name_separator) the_parts = Array(parts).tap(&:compact!) the_parts.join(separator) if the_parts.any? end
ruby
def join_name(parts, separator: ObjectInspector.configuration.name_separator) the_parts = Array(parts).tap(&:compact!) the_parts.join(separator) if the_parts.any? end
[ "def", "join_name", "(", "parts", ",", "separator", ":", "ObjectInspector", ".", "configuration", ".", "name_separator", ")", "the_parts", "=", "Array", "(", "parts", ")", ".", "tap", "(", "&", ":compact!", ")", "the_parts", ".", "join", "(", "separator", ")", "if", "the_parts", ".", "any?", "end" ]
Join the passed-in name parts with the passed in separator. @param parts [Array<#to_s>] @param separator [#to_s] (ObjectInspector.configuration.flags_separator)
[ "Join", "the", "passed", "-", "in", "name", "parts", "with", "the", "passed", "in", "separator", "." ]
ce89add5055b195e3a024f3cc98c8fe5cc1d4d94
https://github.com/pdobb/object_inspector/blob/ce89add5055b195e3a024f3cc98c8fe5cc1d4d94/lib/object_inspector/scope.rb#L28-L32
train
pdobb/object_inspector
lib/object_inspector/scope.rb
ObjectInspector.Scope.join_flags
def join_flags(flags, separator: ObjectInspector.configuration.flags_separator) the_flags = Array(flags).tap(&:compact!) the_flags.join(separator) if the_flags.any? end
ruby
def join_flags(flags, separator: ObjectInspector.configuration.flags_separator) the_flags = Array(flags).tap(&:compact!) the_flags.join(separator) if the_flags.any? end
[ "def", "join_flags", "(", "flags", ",", "separator", ":", "ObjectInspector", ".", "configuration", ".", "flags_separator", ")", "the_flags", "=", "Array", "(", "flags", ")", ".", "tap", "(", "&", ":compact!", ")", "the_flags", ".", "join", "(", "separator", ")", "if", "the_flags", ".", "any?", "end" ]
Join the passed-in flags with the passed in separator. @param flags [Array<#to_s>] @param separator [#to_s] (ObjectInspector.configuration.flags_separator)
[ "Join", "the", "passed", "-", "in", "flags", "with", "the", "passed", "in", "separator", "." ]
ce89add5055b195e3a024f3cc98c8fe5cc1d4d94
https://github.com/pdobb/object_inspector/blob/ce89add5055b195e3a024f3cc98c8fe5cc1d4d94/lib/object_inspector/scope.rb#L38-L42
train
pdobb/object_inspector
lib/object_inspector/scope.rb
ObjectInspector.Scope.join_issues
def join_issues(issues, separator: ObjectInspector.configuration.issues_separator) the_issues = Array(issues).tap(&:compact!) the_issues.join(separator) if the_issues.any? end
ruby
def join_issues(issues, separator: ObjectInspector.configuration.issues_separator) the_issues = Array(issues).tap(&:compact!) the_issues.join(separator) if the_issues.any? end
[ "def", "join_issues", "(", "issues", ",", "separator", ":", "ObjectInspector", ".", "configuration", ".", "issues_separator", ")", "the_issues", "=", "Array", "(", "issues", ")", ".", "tap", "(", "&", ":compact!", ")", "the_issues", ".", "join", "(", "separator", ")", "if", "the_issues", ".", "any?", "end" ]
Join the passed-in issues with the passed in separator. @param issues [Array<#to_s>] @param separator [#to_s] (ObjectInspector.configuration.issues_separator)
[ "Join", "the", "passed", "-", "in", "issues", "with", "the", "passed", "in", "separator", "." ]
ce89add5055b195e3a024f3cc98c8fe5cc1d4d94
https://github.com/pdobb/object_inspector/blob/ce89add5055b195e3a024f3cc98c8fe5cc1d4d94/lib/object_inspector/scope.rb#L48-L52
train
pdobb/object_inspector
lib/object_inspector/scope.rb
ObjectInspector.Scope.join_info
def join_info(items, separator: ObjectInspector.configuration.info_separator) the_items = Array(items).tap(&:compact!) the_items.join(separator) if the_items.any? end
ruby
def join_info(items, separator: ObjectInspector.configuration.info_separator) the_items = Array(items).tap(&:compact!) the_items.join(separator) if the_items.any? end
[ "def", "join_info", "(", "items", ",", "separator", ":", "ObjectInspector", ".", "configuration", ".", "info_separator", ")", "the_items", "=", "Array", "(", "items", ")", ".", "tap", "(", "&", ":compact!", ")", "the_items", ".", "join", "(", "separator", ")", "if", "the_items", ".", "any?", "end" ]
Join the passed-in items with the passed in separator. @param items [Array<#to_s>] @param separator [#to_s] (ObjectInspector.configuration.info_separator)
[ "Join", "the", "passed", "-", "in", "items", "with", "the", "passed", "in", "separator", "." ]
ce89add5055b195e3a024f3cc98c8fe5cc1d4d94
https://github.com/pdobb/object_inspector/blob/ce89add5055b195e3a024f3cc98c8fe5cc1d4d94/lib/object_inspector/scope.rb#L58-L62
train
alexandre025/cdx
lib/friendly_id/json_translate.rb
FriendlyId.JsonTranslate.execute_with_locale
def execute_with_locale(locale = ::I18n.locale, &block) actual_locale = ::I18n.locale ::I18n.locale = locale block.call ::I18n.locale = actual_locale end
ruby
def execute_with_locale(locale = ::I18n.locale, &block) actual_locale = ::I18n.locale ::I18n.locale = locale block.call ::I18n.locale = actual_locale end
[ "def", "execute_with_locale", "(", "locale", "=", "::", "I18n", ".", "locale", ",", "&", "block", ")", "actual_locale", "=", "::", "I18n", ".", "locale", "::", "I18n", ".", "locale", "=", "locale", "block", ".", "call", "::", "I18n", ".", "locale", "=", "actual_locale", "end" ]
Auxiliar function to execute a block with other locale set
[ "Auxiliar", "function", "to", "execute", "a", "block", "with", "other", "locale", "set" ]
a689edac06736978956a3d7b952eadab62c8691b
https://github.com/alexandre025/cdx/blob/a689edac06736978956a3d7b952eadab62c8691b/lib/friendly_id/json_translate.rb#L66-L73
train
brightbox/brightbox-cli
lib/brightbox-cli/database_server.rb
Brightbox.DatabaseServer.maintenance_window
def maintenance_window return nil if maintenance_weekday.nil? weekday = Date::DAYNAMES[maintenance_weekday] sprintf("%s %02d:00 UTC", weekday, maintenance_hour) end
ruby
def maintenance_window return nil if maintenance_weekday.nil? weekday = Date::DAYNAMES[maintenance_weekday] sprintf("%s %02d:00 UTC", weekday, maintenance_hour) end
[ "def", "maintenance_window", "return", "nil", "if", "maintenance_weekday", ".", "nil?", "weekday", "=", "Date", "::", "DAYNAMES", "[", "maintenance_weekday", "]", "sprintf", "(", "\"%s %02d:00 UTC\"", ",", "weekday", ",", "maintenance_hour", ")", "end" ]
A more humanised version of the maintenance window
[ "A", "more", "humanised", "version", "of", "the", "maintenance", "window" ]
aba751383197e0484f75c504420ca0f355a57dc1
https://github.com/brightbox/brightbox-cli/blob/aba751383197e0484f75c504420ca0f355a57dc1/lib/brightbox-cli/database_server.rb#L100-L104
train
sferik/mtgox
lib/mtgox/client.rb
MtGox.Client.ticker
def ticker ticker = get('/api/1/BTCUSD/ticker') Ticker.instance.buy = value_currency ticker['buy'] Ticker.instance.high = value_currency ticker['high'] Ticker.instance.price = value_currency ticker['last_all'] Ticker.instance.low = value_currency ticker['low'] Ticker.instance.sell = value_currency ticker['sell'] Ticker.instance.volume = value_bitcoin ticker['vol'] Ticker.instance.vwap = value_currency ticker['vwap'] Ticker.instance.avg = value_currency ticker['avg'] Ticker.instance.last_local = value_currency ticker['last_local'] Ticker.instance end
ruby
def ticker ticker = get('/api/1/BTCUSD/ticker') Ticker.instance.buy = value_currency ticker['buy'] Ticker.instance.high = value_currency ticker['high'] Ticker.instance.price = value_currency ticker['last_all'] Ticker.instance.low = value_currency ticker['low'] Ticker.instance.sell = value_currency ticker['sell'] Ticker.instance.volume = value_bitcoin ticker['vol'] Ticker.instance.vwap = value_currency ticker['vwap'] Ticker.instance.avg = value_currency ticker['avg'] Ticker.instance.last_local = value_currency ticker['last_local'] Ticker.instance end
[ "def", "ticker", "ticker", "=", "get", "(", "'/api/1/BTCUSD/ticker'", ")", "Ticker", ".", "instance", ".", "buy", "=", "value_currency", "ticker", "[", "'buy'", "]", "Ticker", ".", "instance", ".", "high", "=", "value_currency", "ticker", "[", "'high'", "]", "Ticker", ".", "instance", ".", "price", "=", "value_currency", "ticker", "[", "'last_all'", "]", "Ticker", ".", "instance", ".", "low", "=", "value_currency", "ticker", "[", "'low'", "]", "Ticker", ".", "instance", ".", "sell", "=", "value_currency", "ticker", "[", "'sell'", "]", "Ticker", ".", "instance", ".", "volume", "=", "value_bitcoin", "ticker", "[", "'vol'", "]", "Ticker", ".", "instance", ".", "vwap", "=", "value_currency", "ticker", "[", "'vwap'", "]", "Ticker", ".", "instance", ".", "avg", "=", "value_currency", "ticker", "[", "'avg'", "]", "Ticker", ".", "instance", ".", "last_local", "=", "value_currency", "ticker", "[", "'last_local'", "]", "Ticker", ".", "instance", "end" ]
Fetch the latest ticker data @authenticated false @return [MtGox::Ticker] @example MtGox.ticker
[ "Fetch", "the", "latest", "ticker", "data" ]
031308d64fabbcdb0a745a866818fa9235830c51
https://github.com/sferik/mtgox/blob/031308d64fabbcdb0a745a866818fa9235830c51/lib/mtgox/client.rb#L55-L67
train
sferik/mtgox
lib/mtgox/client.rb
MtGox.Client.offers
def offers offers = get('/api/1/BTCUSD/depth/fetch') asks = offers['asks'].sort_by { |ask| ask['price_int'].to_i }.collect { |ask| Ask.new(self, ask) } bids = offers['bids'].sort_by { |bid| -bid['price_int'].to_i }.collect { |bid| Bid.new(self, bid) } {:asks => asks, :bids => bids} end
ruby
def offers offers = get('/api/1/BTCUSD/depth/fetch') asks = offers['asks'].sort_by { |ask| ask['price_int'].to_i }.collect { |ask| Ask.new(self, ask) } bids = offers['bids'].sort_by { |bid| -bid['price_int'].to_i }.collect { |bid| Bid.new(self, bid) } {:asks => asks, :bids => bids} end
[ "def", "offers", "offers", "=", "get", "(", "'/api/1/BTCUSD/depth/fetch'", ")", "asks", "=", "offers", "[", "'asks'", "]", ".", "sort_by", "{", "|", "ask", "|", "ask", "[", "'price_int'", "]", ".", "to_i", "}", ".", "collect", "{", "|", "ask", "|", "Ask", ".", "new", "(", "self", ",", "ask", ")", "}", "bids", "=", "offers", "[", "'bids'", "]", ".", "sort_by", "{", "|", "bid", "|", "-", "bid", "[", "'price_int'", "]", ".", "to_i", "}", ".", "collect", "{", "|", "bid", "|", "Bid", ".", "new", "(", "self", ",", "bid", ")", "}", "{", ":asks", "=>", "asks", ",", ":bids", "=>", "bids", "}", "end" ]
Fetch both bids and asks in one call, for network efficiency @authenticated false @return [Hash] with keys :asks and :bids, which contain arrays as described in {MtGox::Client#asks} and {MtGox::Clients#bids} @example MtGox.offers
[ "Fetch", "both", "bids", "and", "asks", "in", "one", "call", "for", "network", "efficiency" ]
031308d64fabbcdb0a745a866818fa9235830c51
https://github.com/sferik/mtgox/blob/031308d64fabbcdb0a745a866818fa9235830c51/lib/mtgox/client.rb#L88-L93
train
sferik/mtgox
lib/mtgox/client.rb
MtGox.Client.trades
def trades(opts = {}) get('/api/1/BTCUSD/trades/fetch', opts). sort_by { |trade| trade['date'] }.collect do |trade| Trade.new(trade) end end
ruby
def trades(opts = {}) get('/api/1/BTCUSD/trades/fetch', opts). sort_by { |trade| trade['date'] }.collect do |trade| Trade.new(trade) end end
[ "def", "trades", "(", "opts", "=", "{", "}", ")", "get", "(", "'/api/1/BTCUSD/trades/fetch'", ",", "opts", ")", ".", "sort_by", "{", "|", "trade", "|", "trade", "[", "'date'", "]", "}", ".", "collect", "do", "|", "trade", "|", "Trade", ".", "new", "(", "trade", ")", "end", "end" ]
Fetch recent trades @authenticated false @return [Array<MtGox::Trade>] an array of trades, sorted in chronological order @example MtGox.trades MtGox.trades :since => 12341234
[ "Fetch", "recent", "trades" ]
031308d64fabbcdb0a745a866818fa9235830c51
https://github.com/sferik/mtgox/blob/031308d64fabbcdb0a745a866818fa9235830c51/lib/mtgox/client.rb#L142-L147
train
sferik/mtgox
lib/mtgox/client.rb
MtGox.Client.order!
def order!(type, amount, price) order = {:type => order_type(type), :amount_int => intify(amount, :btc)} order[:price_int] = intify(price, :usd) if price != :market post('/api/1/BTCUSD/order/add', order) end
ruby
def order!(type, amount, price) order = {:type => order_type(type), :amount_int => intify(amount, :btc)} order[:price_int] = intify(price, :usd) if price != :market post('/api/1/BTCUSD/order/add', order) end
[ "def", "order!", "(", "type", ",", "amount", ",", "price", ")", "order", "=", "{", ":type", "=>", "order_type", "(", "type", ")", ",", ":amount_int", "=>", "intify", "(", "amount", ",", ":btc", ")", "}", "order", "[", ":price_int", "]", "=", "intify", "(", "price", ",", ":usd", ")", "if", "price", "!=", ":market", "post", "(", "'/api/1/BTCUSD/order/add'", ",", "order", ")", "end" ]
Create a new order @authenticated true @param type [String] the type of order to create, either "buy" or "sell" @param amount [Numberic] the number of bitcoins to buy/sell @param price [Numeric or Symbol] the bid/ask price in USD, or :market if placing a market order @return [String] order ID for the order, can be inspected using order_result @example # Sell one bitcoin for $123 MtGox.add_order! :sell, 1.0, 123.0
[ "Create", "a", "new", "order" ]
031308d64fabbcdb0a745a866818fa9235830c51
https://github.com/sferik/mtgox/blob/031308d64fabbcdb0a745a866818fa9235830c51/lib/mtgox/client.rb#L235-L239
train
sferik/mtgox
lib/mtgox/client.rb
MtGox.Client.withdraw!
def withdraw!(amount, address) if amount >= 1000 fail(FilthyRichError.new("#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC")) else post('/api/1/generic/bitcoin/send_simple', :amount_int => intify(amount, :btc), :address => address)['trx'] end end
ruby
def withdraw!(amount, address) if amount >= 1000 fail(FilthyRichError.new("#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC")) else post('/api/1/generic/bitcoin/send_simple', :amount_int => intify(amount, :btc), :address => address)['trx'] end end
[ "def", "withdraw!", "(", "amount", ",", "address", ")", "if", "amount", ">=", "1000", "fail", "(", "FilthyRichError", ".", "new", "(", "\"#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC\"", ")", ")", "else", "post", "(", "'/api/1/generic/bitcoin/send_simple'", ",", ":amount_int", "=>", "intify", "(", "amount", ",", ":btc", ")", ",", ":address", "=>", "address", ")", "[", "'trx'", "]", "end", "end" ]
Transfer bitcoins from your Mt. Gox account into another account @authenticated true @param amount [Numeric] the number of bitcoins to withdraw @param address [String] the bitcoin address to send to @return [String] Completed Transaction ID @example # Withdraw 1 BTC from your account MtGox.withdraw! 1.0, '1KxSo9bGBfPVFEtWNLpnUK1bfLNNT4q31L'
[ "Transfer", "bitcoins", "from", "your", "Mt", ".", "Gox", "account", "into", "another", "account" ]
031308d64fabbcdb0a745a866818fa9235830c51
https://github.com/sferik/mtgox/blob/031308d64fabbcdb0a745a866818fa9235830c51/lib/mtgox/client.rb#L284-L290
train
cldwalker/boson-more
lib/boson/pipe.rb
Boson.Pipe.scientist_process
def scientist_process(object, global_opt, env={}) @env = env [:query, :sort, :reverse_sort].each {|e| global_opt.delete(e) } unless object.is_a?(Array) process_pipes(object, global_opt) end
ruby
def scientist_process(object, global_opt, env={}) @env = env [:query, :sort, :reverse_sort].each {|e| global_opt.delete(e) } unless object.is_a?(Array) process_pipes(object, global_opt) end
[ "def", "scientist_process", "(", "object", ",", "global_opt", ",", "env", "=", "{", "}", ")", "@env", "=", "env", "[", ":query", ",", ":sort", ",", ":reverse_sort", "]", ".", "each", "{", "|", "e", "|", "global_opt", ".", "delete", "(", "e", ")", "}", "unless", "object", ".", "is_a?", "(", "Array", ")", "process_pipes", "(", "object", ",", "global_opt", ")", "end" ]
Process pipes for Scientist
[ "Process", "pipes", "for", "Scientist" ]
f928ebc18d8641e038891f78896ae7251b97415c
https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/pipe.rb#L77-L81
train
cldwalker/boson-more
lib/boson/pipe.rb
Boson.Pipe.process_pipes
def process_pipes(obj, options) internal_pipes(options).each {|pipe| obj = Pipes.send("#{pipe}_pipe", obj, options[pipe]) if options[pipe] } process_user_pipes(obj, options) end
ruby
def process_pipes(obj, options) internal_pipes(options).each {|pipe| obj = Pipes.send("#{pipe}_pipe", obj, options[pipe]) if options[pipe] } process_user_pipes(obj, options) end
[ "def", "process_pipes", "(", "obj", ",", "options", ")", "internal_pipes", "(", "options", ")", ".", "each", "{", "|", "pipe", "|", "obj", "=", "Pipes", ".", "send", "(", "\"#{pipe}_pipe\"", ",", "obj", ",", "options", "[", "pipe", "]", ")", "if", "options", "[", "pipe", "]", "}", "process_user_pipes", "(", "obj", ",", "options", ")", "end" ]
Main method which processes all pipe commands, both default and user-defined ones.
[ "Main", "method", "which", "processes", "all", "pipe", "commands", "both", "default", "and", "user", "-", "defined", "ones", "." ]
f928ebc18d8641e038891f78896ae7251b97415c
https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/pipe.rb#L84-L89
train
cldwalker/boson-more
lib/boson/pipe.rb
Boson.Pipe.process_user_pipes
def process_user_pipes(result, global_opt) pipes_to_process(global_opt).each {|e| args = [pipe(e)[:pipe], result] args << global_opt[e] unless pipe(e)[:type] == :boolean args << get_env(e, global_opt) if pipe(e)[:env] pipe_result = Boson.invoke(*args) result = pipe_result if pipe(e)[:filter] } result end
ruby
def process_user_pipes(result, global_opt) pipes_to_process(global_opt).each {|e| args = [pipe(e)[:pipe], result] args << global_opt[e] unless pipe(e)[:type] == :boolean args << get_env(e, global_opt) if pipe(e)[:env] pipe_result = Boson.invoke(*args) result = pipe_result if pipe(e)[:filter] } result end
[ "def", "process_user_pipes", "(", "result", ",", "global_opt", ")", "pipes_to_process", "(", "global_opt", ")", ".", "each", "{", "|", "e", "|", "args", "=", "[", "pipe", "(", "e", ")", "[", ":pipe", "]", ",", "result", "]", "args", "<<", "global_opt", "[", "e", "]", "unless", "pipe", "(", "e", ")", "[", ":type", "]", "==", ":boolean", "args", "<<", "get_env", "(", "e", ",", "global_opt", ")", "if", "pipe", "(", "e", ")", "[", ":env", "]", "pipe_result", "=", "Boson", ".", "invoke", "(", "*", "args", ")", "result", "=", "pipe_result", "if", "pipe", "(", "e", ")", "[", ":filter", "]", "}", "result", "end" ]
global_opt can come from Hirb callback or Scientist
[ "global_opt", "can", "come", "from", "Hirb", "callback", "or", "Scientist" ]
f928ebc18d8641e038891f78896ae7251b97415c
https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/pipe.rb#L117-L126
train
svoop/aixm
lib/aixm/document.rb
AIXM.Document.errors
def errors xsd = Nokogiri::XML::Schema(File.open(AIXM.schema(:xsd))) xsd.validate(Nokogiri::XML(to_xml)).reject do |error| AIXM.config.ignored_errors && error.message.match?(AIXM.config.ignored_errors) end end
ruby
def errors xsd = Nokogiri::XML::Schema(File.open(AIXM.schema(:xsd))) xsd.validate(Nokogiri::XML(to_xml)).reject do |error| AIXM.config.ignored_errors && error.message.match?(AIXM.config.ignored_errors) end end
[ "def", "errors", "xsd", "=", "Nokogiri", "::", "XML", "::", "Schema", "(", "File", ".", "open", "(", "AIXM", ".", "schema", "(", ":xsd", ")", ")", ")", "xsd", ".", "validate", "(", "Nokogiri", "::", "XML", "(", "to_xml", ")", ")", ".", "reject", "do", "|", "error", "|", "AIXM", ".", "config", ".", "ignored_errors", "&&", "error", ".", "message", ".", "match?", "(", "AIXM", ".", "config", ".", "ignored_errors", ")", "end", "end" ]
Validate the generated AIXM or OFMX atainst it's XSD and return the errors found. @return [Array<String>] validation errors
[ "Validate", "the", "generated", "AIXM", "or", "OFMX", "atainst", "it", "s", "XSD", "and", "return", "the", "errors", "found", "." ]
4541e6543d4b6fcd023ef3cd2768946a29ec0b9e
https://github.com/svoop/aixm/blob/4541e6543d4b6fcd023ef3cd2768946a29ec0b9e/lib/aixm/document.rb#L74-L79
train
cldwalker/boson-more
lib/boson/namespacer.rb
Boson.Namespacer.full_invoke
def full_invoke(cmd, args) #:nodoc: command, subcommand = cmd.include?(NAMESPACE) ? cmd.split(NAMESPACE, 2) : [cmd, nil] dispatcher = subcommand ? Boson.invoke(command) : Boson.main_object dispatcher.send(subcommand || command, *args) end
ruby
def full_invoke(cmd, args) #:nodoc: command, subcommand = cmd.include?(NAMESPACE) ? cmd.split(NAMESPACE, 2) : [cmd, nil] dispatcher = subcommand ? Boson.invoke(command) : Boson.main_object dispatcher.send(subcommand || command, *args) end
[ "def", "full_invoke", "(", "cmd", ",", "args", ")", "command", ",", "subcommand", "=", "cmd", ".", "include?", "(", "NAMESPACE", ")", "?", "cmd", ".", "split", "(", "NAMESPACE", ",", "2", ")", ":", "[", "cmd", ",", "nil", "]", "dispatcher", "=", "subcommand", "?", "Boson", ".", "invoke", "(", "command", ")", ":", "Boson", ".", "main_object", "dispatcher", ".", "send", "(", "subcommand", "||", "command", ",", "*", "args", ")", "end" ]
Invoke command string even with namespaces
[ "Invoke", "command", "string", "even", "with", "namespaces" ]
f928ebc18d8641e038891f78896ae7251b97415c
https://github.com/cldwalker/boson-more/blob/f928ebc18d8641e038891f78896ae7251b97415c/lib/boson/namespacer.rb#L13-L17
train
soffes/unmarkdown
lib/unmarkdown/parser.rb
Unmarkdown.Parser.parse_nodes
def parse_nodes(nodes) output = '' # Short-circuit if it's empty return output if !nodes || nodes.empty? # Loop through nodes nodes.each do |node| case node.name when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' level = node.name.match(/\Ah(\d)\Z/)[1].to_i if @options[:underline_headers] && level < 3 content = parse_content(node) output << content + "\n" character = level == 1 ? '=' : '-' content.length.times { output << character} else hashes = '' level.times { hashes << '#' } output << "#{hashes} #{parse_content(node)}" end when 'blockquote' parse_content(node).split("\n").each do |line| output << "> #{line}\n" end when 'ul', 'ol' output << "\n\n" if @list.count > 0 if unordered = node.name == 'ul' @list << :unordered else @list << :ordered @list_position << 0 end output << parse_nodes(node.children) @list.pop @list_position.pop unless unordered when 'li' (@list.count - 1).times { output << ' ' } if @list.last == :unordered output << "* #{parse_content(node)}" else num = (@list_position[@list_position.count - 1] += 1) output << "#{num}. #{parse_content(node)}" end when 'pre' content = parse_content(node) if @options[:fenced_code_blocks] output << "```\n#{content}\n```" else content.split("\n").each do |line| output << " #{line}\n" end end when 'hr' output << "---\n\n" when 'a' output << "[#{parse_content(node)}](#{node['href']}#{build_title(node)})" when 'i', 'em' output << "*#{parse_content(node)}*" when 'b', 'strong' output << "**#{parse_content(node)}**" when 'u' output << "_#{parse_content(node)}_" when 'mark' output << "==#{parse_content(node)}==" when 'code' output << "`#{parse_content(node)}`" when 'img' output << "![#{node['alt']}](#{node['src']}#{build_title(node)})" when 'text' content = parse_content(node) # Optionally look for links content.gsub!(AUTOLINK_URL_REGEX, '<\1>') if @options[:autolink] content.gsub!(AUTOLINK_EMAIL_REGEX, '<\1>') if @options[:autolink] output << content when 'script' next unless @options[:allow_scripts] output << node.to_html else # If it's an supported node or a node that just contains text, just get # its content output << parse_content(node) end output << "\n\n" if BLOCK_ELEMENT_NAMES.include?(node.name) end output end
ruby
def parse_nodes(nodes) output = '' # Short-circuit if it's empty return output if !nodes || nodes.empty? # Loop through nodes nodes.each do |node| case node.name when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' level = node.name.match(/\Ah(\d)\Z/)[1].to_i if @options[:underline_headers] && level < 3 content = parse_content(node) output << content + "\n" character = level == 1 ? '=' : '-' content.length.times { output << character} else hashes = '' level.times { hashes << '#' } output << "#{hashes} #{parse_content(node)}" end when 'blockquote' parse_content(node).split("\n").each do |line| output << "> #{line}\n" end when 'ul', 'ol' output << "\n\n" if @list.count > 0 if unordered = node.name == 'ul' @list << :unordered else @list << :ordered @list_position << 0 end output << parse_nodes(node.children) @list.pop @list_position.pop unless unordered when 'li' (@list.count - 1).times { output << ' ' } if @list.last == :unordered output << "* #{parse_content(node)}" else num = (@list_position[@list_position.count - 1] += 1) output << "#{num}. #{parse_content(node)}" end when 'pre' content = parse_content(node) if @options[:fenced_code_blocks] output << "```\n#{content}\n```" else content.split("\n").each do |line| output << " #{line}\n" end end when 'hr' output << "---\n\n" when 'a' output << "[#{parse_content(node)}](#{node['href']}#{build_title(node)})" when 'i', 'em' output << "*#{parse_content(node)}*" when 'b', 'strong' output << "**#{parse_content(node)}**" when 'u' output << "_#{parse_content(node)}_" when 'mark' output << "==#{parse_content(node)}==" when 'code' output << "`#{parse_content(node)}`" when 'img' output << "![#{node['alt']}](#{node['src']}#{build_title(node)})" when 'text' content = parse_content(node) # Optionally look for links content.gsub!(AUTOLINK_URL_REGEX, '<\1>') if @options[:autolink] content.gsub!(AUTOLINK_EMAIL_REGEX, '<\1>') if @options[:autolink] output << content when 'script' next unless @options[:allow_scripts] output << node.to_html else # If it's an supported node or a node that just contains text, just get # its content output << parse_content(node) end output << "\n\n" if BLOCK_ELEMENT_NAMES.include?(node.name) end output end
[ "def", "parse_nodes", "(", "nodes", ")", "output", "=", "''", "return", "output", "if", "!", "nodes", "||", "nodes", ".", "empty?", "nodes", ".", "each", "do", "|", "node", "|", "case", "node", ".", "name", "when", "'h1'", ",", "'h2'", ",", "'h3'", ",", "'h4'", ",", "'h5'", ",", "'h6'", "level", "=", "node", ".", "name", ".", "match", "(", "/", "\\A", "\\d", "\\Z", "/", ")", "[", "1", "]", ".", "to_i", "if", "@options", "[", ":underline_headers", "]", "&&", "level", "<", "3", "content", "=", "parse_content", "(", "node", ")", "output", "<<", "content", "+", "\"\\n\"", "character", "=", "level", "==", "1", "?", "'='", ":", "'-'", "content", ".", "length", ".", "times", "{", "output", "<<", "character", "}", "else", "hashes", "=", "''", "level", ".", "times", "{", "hashes", "<<", "'#'", "}", "output", "<<", "\"#{hashes} #{parse_content(node)}\"", "end", "when", "'blockquote'", "parse_content", "(", "node", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "output", "<<", "\"> #{line}\\n\"", "end", "when", "'ul'", ",", "'ol'", "output", "<<", "\"\\n\\n\"", "if", "@list", ".", "count", ">", "0", "if", "unordered", "=", "node", ".", "name", "==", "'ul'", "@list", "<<", ":unordered", "else", "@list", "<<", ":ordered", "@list_position", "<<", "0", "end", "output", "<<", "parse_nodes", "(", "node", ".", "children", ")", "@list", ".", "pop", "@list_position", ".", "pop", "unless", "unordered", "when", "'li'", "(", "@list", ".", "count", "-", "1", ")", ".", "times", "{", "output", "<<", "' '", "}", "if", "@list", ".", "last", "==", ":unordered", "output", "<<", "\"* #{parse_content(node)}\"", "else", "num", "=", "(", "@list_position", "[", "@list_position", ".", "count", "-", "1", "]", "+=", "1", ")", "output", "<<", "\"#{num}. #{parse_content(node)}\"", "end", "when", "'pre'", "content", "=", "parse_content", "(", "node", ")", "if", "@options", "[", ":fenced_code_blocks", "]", "output", "<<", "\"```\\n#{content}\\n```\"", "else", "content", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "output", "<<", "\" #{line}\\n\"", "end", "end", "when", "'hr'", "output", "<<", "\"---\\n\\n\"", "when", "'a'", "output", "<<", "\"[#{parse_content(node)}](#{node['href']}#{build_title(node)})\"", "when", "'i'", ",", "'em'", "output", "<<", "\"*#{parse_content(node)}*\"", "when", "'b'", ",", "'strong'", "output", "<<", "\"**#{parse_content(node)}**\"", "when", "'u'", "output", "<<", "\"_#{parse_content(node)}_\"", "when", "'mark'", "output", "<<", "\"==#{parse_content(node)}==\"", "when", "'code'", "output", "<<", "\"`#{parse_content(node)}`\"", "when", "'img'", "output", "<<", "\"![#{node['alt']}](#{node['src']}#{build_title(node)})\"", "when", "'text'", "content", "=", "parse_content", "(", "node", ")", "content", ".", "gsub!", "(", "AUTOLINK_URL_REGEX", ",", "'<\\1>'", ")", "if", "@options", "[", ":autolink", "]", "content", ".", "gsub!", "(", "AUTOLINK_EMAIL_REGEX", ",", "'<\\1>'", ")", "if", "@options", "[", ":autolink", "]", "output", "<<", "content", "when", "'script'", "next", "unless", "@options", "[", ":allow_scripts", "]", "output", "<<", "node", ".", "to_html", "else", "output", "<<", "parse_content", "(", "node", ")", "end", "output", "<<", "\"\\n\\n\"", "if", "BLOCK_ELEMENT_NAMES", ".", "include?", "(", "node", ".", "name", ")", "end", "output", "end" ]
Parse the children of a node
[ "Parse", "the", "children", "of", "a", "node" ]
5dac78bc785918e36568b23b087cccb90e288b53
https://github.com/soffes/unmarkdown/blob/5dac78bc785918e36568b23b087cccb90e288b53/lib/unmarkdown/parser.rb#L36-L130
train
soffes/unmarkdown
lib/unmarkdown/parser.rb
Unmarkdown.Parser.parse_content
def parse_content(node) content = if node.children.empty? node.content else parse_nodes(node.children) end end
ruby
def parse_content(node) content = if node.children.empty? node.content else parse_nodes(node.children) end end
[ "def", "parse_content", "(", "node", ")", "content", "=", "if", "node", ".", "children", ".", "empty?", "node", ".", "content", "else", "parse_nodes", "(", "node", ".", "children", ")", "end", "end" ]
Get the content from a node
[ "Get", "the", "content", "from", "a", "node" ]
5dac78bc785918e36568b23b087cccb90e288b53
https://github.com/soffes/unmarkdown/blob/5dac78bc785918e36568b23b087cccb90e288b53/lib/unmarkdown/parser.rb#L133-L139
train
svoop/aixm
lib/aixm/a.rb
AIXM.A.invert
def invert build(precision: precision, deg: (deg + 180) % 360, suffix: SUFFIX_INVERSIONS.fetch(suffix, suffix)) end
ruby
def invert build(precision: precision, deg: (deg + 180) % 360, suffix: SUFFIX_INVERSIONS.fetch(suffix, suffix)) end
[ "def", "invert", "build", "(", "precision", ":", "precision", ",", "deg", ":", "(", "deg", "+", "180", ")", "%", "360", ",", "suffix", ":", "SUFFIX_INVERSIONS", ".", "fetch", "(", "suffix", ",", "suffix", ")", ")", "end" ]
Invert an angle by 180 degrees @example AIXM.a(120).invert # => AIXM.a(300) AIXM.a("34L").invert # => AIXM.a("16R") AIXM.a("33X").invert # => AIXM.a("33X") @return [AIXM::A] inverted angle
[ "Invert", "an", "angle", "by", "180", "degrees" ]
4541e6543d4b6fcd023ef3cd2768946a29ec0b9e
https://github.com/svoop/aixm/blob/4541e6543d4b6fcd023ef3cd2768946a29ec0b9e/lib/aixm/a.rb#L90-L92
train
3scale/xcflushd
lib/xcflushd/flusher.rb
Xcflushd.Flusher.async_authorization_tasks
def async_authorization_tasks(reports) # Each call to authorizer.authorizations might need to contact 3scale # several times. The number of calls equals 1 + number of reported # metrics without limits. # This is probably good enough for now, but in the future we might want # to make sure that we perform concurrent calls to 3scale instead of # authorizer.authorizations. reports.map do |report| task = Concurrent::Future.new(executor: thread_pool) do authorizer.authorizations(report[:service_id], report[:credentials], report[:usage].keys) end [report, task] end.to_h end
ruby
def async_authorization_tasks(reports) # Each call to authorizer.authorizations might need to contact 3scale # several times. The number of calls equals 1 + number of reported # metrics without limits. # This is probably good enough for now, but in the future we might want # to make sure that we perform concurrent calls to 3scale instead of # authorizer.authorizations. reports.map do |report| task = Concurrent::Future.new(executor: thread_pool) do authorizer.authorizations(report[:service_id], report[:credentials], report[:usage].keys) end [report, task] end.to_h end
[ "def", "async_authorization_tasks", "(", "reports", ")", "reports", ".", "map", "do", "|", "report", "|", "task", "=", "Concurrent", "::", "Future", ".", "new", "(", "executor", ":", "thread_pool", ")", "do", "authorizer", ".", "authorizations", "(", "report", "[", ":service_id", "]", ",", "report", "[", ":credentials", "]", ",", "report", "[", ":usage", "]", ".", "keys", ")", "end", "[", "report", ",", "task", "]", "end", ".", "to_h", "end" ]
Returns a Hash. The keys are the reports and the values their associated async authorization tasks.
[ "Returns", "a", "Hash", ".", "The", "keys", "are", "the", "reports", "and", "the", "values", "their", "associated", "async", "authorization", "tasks", "." ]
ca29b7674c3cd952a2a50c0604a99f04662bf27d
https://github.com/3scale/xcflushd/blob/ca29b7674c3cd952a2a50c0604a99f04662bf27d/lib/xcflushd/flusher.rb#L129-L144
train
leandog/gametel
lib/gametel/navigation.rb
Gametel.Navigation.on
def on(cls, &block) @current_screen = @current_page = cls.new waiting_for = "#{cls} to be active" wait_until(10, waiting_for) { @current_screen.active? } if @current_screen.respond_to?(:active?) block.call @current_screen if block @current_screen end
ruby
def on(cls, &block) @current_screen = @current_page = cls.new waiting_for = "#{cls} to be active" wait_until(10, waiting_for) { @current_screen.active? } if @current_screen.respond_to?(:active?) block.call @current_screen if block @current_screen end
[ "def", "on", "(", "cls", ",", "&", "block", ")", "@current_screen", "=", "@current_page", "=", "cls", ".", "new", "waiting_for", "=", "\"#{cls} to be active\"", "wait_until", "(", "10", ",", "waiting_for", ")", "{", "@current_screen", ".", "active?", "}", "if", "@current_screen", ".", "respond_to?", "(", ":active?", ")", "block", ".", "call", "@current_screen", "if", "block", "@current_screen", "end" ]
create a new screen given a class name
[ "create", "a", "new", "screen", "given", "a", "class", "name" ]
fc9468da9a443b5e6ac553b3e445333a0eabfc18
https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/navigation.rb#L15-L21
train
kaspermeyer/prawndown
lib/prawndown.rb
Prawndown.Interface.markdown
def markdown(string, options = {}) text Prawndown::Parser.new(string).to_prawn, options.merge(inline_format: true) end
ruby
def markdown(string, options = {}) text Prawndown::Parser.new(string).to_prawn, options.merge(inline_format: true) end
[ "def", "markdown", "(", "string", ",", "options", "=", "{", "}", ")", "text", "Prawndown", "::", "Parser", ".", "new", "(", "string", ")", ".", "to_prawn", ",", "options", ".", "merge", "(", "inline_format", ":", "true", ")", "end" ]
Renders Markdown in the current document It supports header 1-6, bold text, italic text, strikethrough and links It supports the same options as +Prawn::Document#text+ Prawn::Document.generate('markdown.pdf') do markdown '# Welcome to Prawndown!' markdown '**Important:** We _hope_ you enjoy your stay!' end
[ "Renders", "Markdown", "in", "the", "current", "document" ]
9d9f86f0a2c799a1dedd32a214427d06e1cf3488
https://github.com/kaspermeyer/prawndown/blob/9d9f86f0a2c799a1dedd32a214427d06e1cf3488/lib/prawndown.rb#L17-L19
train
PeterCamilleri/mini_readline
lib/mini_readline/read_line/edit.rb
MiniReadline.Edit.edit_loop
def edit_loop while @working @edit_window.sync_window(edit_buffer, edit_posn) @edit_window.sync_cursor(edit_posn) process_keystroke(MiniTerm.get_mapped_char) end edit_buffer end
ruby
def edit_loop while @working @edit_window.sync_window(edit_buffer, edit_posn) @edit_window.sync_cursor(edit_posn) process_keystroke(MiniTerm.get_mapped_char) end edit_buffer end
[ "def", "edit_loop", "while", "@working", "@edit_window", ".", "sync_window", "(", "edit_buffer", ",", "edit_posn", ")", "@edit_window", ".", "sync_cursor", "(", "edit_posn", ")", "process_keystroke", "(", "MiniTerm", ".", "get_mapped_char", ")", "end", "edit_buffer", "end" ]
The line editor processing loop.
[ "The", "line", "editor", "processing", "loop", "." ]
45175ee01653a184b8ba04b2e8691dce5b26a1b5
https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line/edit.rb#L68-L76
train
PeterCamilleri/mini_readline
lib/mini_readline/read_line/edit/word_right.rb
MiniReadline.Edit.word_right
def word_right(_keyboard_args) if @edit_posn < length right = @edit_buffer[(@edit_posn+1)..-1] @edit_posn = (posn = right.index(/\s\S/)) ? @edit_posn+posn+2 : length else MiniTerm.beep end end
ruby
def word_right(_keyboard_args) if @edit_posn < length right = @edit_buffer[(@edit_posn+1)..-1] @edit_posn = (posn = right.index(/\s\S/)) ? @edit_posn+posn+2 : length else MiniTerm.beep end end
[ "def", "word_right", "(", "_keyboard_args", ")", "if", "@edit_posn", "<", "length", "right", "=", "@edit_buffer", "[", "(", "@edit_posn", "+", "1", ")", "..", "-", "1", "]", "@edit_posn", "=", "(", "posn", "=", "right", ".", "index", "(", "/", "\\s", "\\S", "/", ")", ")", "?", "@edit_posn", "+", "posn", "+", "2", ":", "length", "else", "MiniTerm", ".", "beep", "end", "end" ]
A little more to the right please!
[ "A", "little", "more", "to", "the", "right", "please!" ]
45175ee01653a184b8ba04b2e8691dce5b26a1b5
https://github.com/PeterCamilleri/mini_readline/blob/45175ee01653a184b8ba04b2e8691dce5b26a1b5/lib/mini_readline/read_line/edit/word_right.rb#L10-L17
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/view_rendering.rb
UnionStationHooks.RequestReporter.log_view_rendering
def log_view_rendering(options) return do_nothing_on_null(:log_view_rendering) if null? Utils.require_key(options, :name) Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) @transaction.log_activity(next_view_rendering_name, options[:begin_time], options[:end_time], options[:name], options[:has_error]) end
ruby
def log_view_rendering(options) return do_nothing_on_null(:log_view_rendering) if null? Utils.require_key(options, :name) Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) @transaction.log_activity(next_view_rendering_name, options[:begin_time], options[:end_time], options[:name], options[:has_error]) end
[ "def", "log_view_rendering", "(", "options", ")", "return", "do_nothing_on_null", "(", ":log_view_rendering", ")", "if", "null?", "Utils", ".", "require_key", "(", "options", ",", ":name", ")", "Utils", ".", "require_key", "(", "options", ",", ":begin_time", ")", "Utils", ".", "require_key", "(", "options", ",", ":end_time", ")", "@transaction", ".", "log_activity", "(", "next_view_rendering_name", ",", "options", "[", ":begin_time", "]", ",", "options", "[", ":end_time", "]", ",", "options", "[", ":name", "]", ",", "options", "[", ":has_error", "]", ")", "end" ]
Logs timing information about the rendering of a single view, template or partial. Unlike {#log_view_rendering_block}, this form does not expect a block. However, you are expected to pass timing information to the options hash. The `union_station_hooks_rails` gem automatically calls {#log_view_rendering_block} for you if your application is a Rails app. It will call this on every view or partial rendering. @option options [String] :name Name of the view, template or partial that is being rendered. @option options [TimePoint or Time] :begin_time The time at which this view rendering begun. See {UnionStationHooks.now} to learn more. @option options [TimePoint or Time] :end_time The time at which this view rendering ended. See {UnionStationHooks.now} to learn more. @option options [Boolean] :has_error (optional) Whether an uncaught exception occurred during the view rendering. Default: false.
[ "Logs", "timing", "information", "about", "the", "rendering", "of", "a", "single", "view", "template", "or", "partial", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/view_rendering.rb#L72-L81
train
pdobb/version_compare
lib/version_compare/conversions.rb
VersionCompare.Conversions.ComparableVersion
def ComparableVersion(value) case value when String, Integer, Float, ->(val) { val.respond_to?(:to_ary) } ComparableVersion.new(value) when ->(val) { val.respond_to?(:to_comparable_version) } value.to_comparable_version else raise TypeError, "Cannot convert #{value.inspect} to ComparableVersion" end end
ruby
def ComparableVersion(value) case value when String, Integer, Float, ->(val) { val.respond_to?(:to_ary) } ComparableVersion.new(value) when ->(val) { val.respond_to?(:to_comparable_version) } value.to_comparable_version else raise TypeError, "Cannot convert #{value.inspect} to ComparableVersion" end end
[ "def", "ComparableVersion", "(", "value", ")", "case", "value", "when", "String", ",", "Integer", ",", "Float", ",", "->", "(", "val", ")", "{", "val", ".", "respond_to?", "(", ":to_ary", ")", "}", "ComparableVersion", ".", "new", "(", "value", ")", "when", "->", "(", "val", ")", "{", "val", ".", "respond_to?", "(", ":to_comparable_version", ")", "}", "value", ".", "to_comparable_version", "else", "raise", "TypeError", ",", "\"Cannot convert #{value.inspect} to ComparableVersion\"", "end", "end" ]
Strict conversion method for creating a `ComparableVersion` object out of anything that can be interpreted is a ComparableVersion. @param [Object] value the object to be converted @example ComparableVersion(1) # => #<ComparableVersion @major=1, @minor=nil, @tiny=nil, @patch=nil> ComparableVersion(1.2) # => #<ComparableVersion @major=1, @minor=2, @tiny=nil, @patch=nil> ComparableVersion("1.2.3") # => #<ComparableVersion @major=1, @minor=2, @tiny=3, @patch=nil> ComparableVersion(["1", "2", "3", "4"]) # => #<ComparableVersion @major=1, @minor=2, @tiny=3, @patch=4>
[ "Strict", "conversion", "method", "for", "creating", "a", "ComparableVersion", "object", "out", "of", "anything", "that", "can", "be", "interpreted", "is", "a", "ComparableVersion", "." ]
3da53adbd2cf639c3bb248bb87f33c4bea83d704
https://github.com/pdobb/version_compare/blob/3da53adbd2cf639c3bb248bb87f33c4bea83d704/lib/version_compare/conversions.rb#L25-L37
train
epuber-io/epuber
lib/epuber/compiler.rb
Epuber.Compiler.archive
def archive(path = nil, configuration_suffix: nil) path ||= epub_name(configuration_suffix) epub_path = File.expand_path(path) Dir.chdir(@file_resolver.destination_path) do new_paths = @file_resolver.package_files.map(&:pkg_destination_path) if ::File.exists?(epub_path) Zip::File.open(epub_path, true) do |zip_file| old_paths = zip_file.instance_eval { @entry_set.entries.map(&:name) } diff = old_paths - new_paths diff.each do |file_to_remove| puts "DEBUG: removing file from result EPUB: #{file_to_remove}" if compilation_context.verbose? zip_file.remove(file_to_remove) end end end run_command(%(zip -q0X "#{epub_path}" mimetype)) run_command(%(zip -qXr9D "#{epub_path}" "#{new_paths.join('" "')}" --exclude \\*.DS_Store)) end path end
ruby
def archive(path = nil, configuration_suffix: nil) path ||= epub_name(configuration_suffix) epub_path = File.expand_path(path) Dir.chdir(@file_resolver.destination_path) do new_paths = @file_resolver.package_files.map(&:pkg_destination_path) if ::File.exists?(epub_path) Zip::File.open(epub_path, true) do |zip_file| old_paths = zip_file.instance_eval { @entry_set.entries.map(&:name) } diff = old_paths - new_paths diff.each do |file_to_remove| puts "DEBUG: removing file from result EPUB: #{file_to_remove}" if compilation_context.verbose? zip_file.remove(file_to_remove) end end end run_command(%(zip -q0X "#{epub_path}" mimetype)) run_command(%(zip -qXr9D "#{epub_path}" "#{new_paths.join('" "')}" --exclude \\*.DS_Store)) end path end
[ "def", "archive", "(", "path", "=", "nil", ",", "configuration_suffix", ":", "nil", ")", "path", "||=", "epub_name", "(", "configuration_suffix", ")", "epub_path", "=", "File", ".", "expand_path", "(", "path", ")", "Dir", ".", "chdir", "(", "@file_resolver", ".", "destination_path", ")", "do", "new_paths", "=", "@file_resolver", ".", "package_files", ".", "map", "(", "&", ":pkg_destination_path", ")", "if", "::", "File", ".", "exists?", "(", "epub_path", ")", "Zip", "::", "File", ".", "open", "(", "epub_path", ",", "true", ")", "do", "|", "zip_file", "|", "old_paths", "=", "zip_file", ".", "instance_eval", "{", "@entry_set", ".", "entries", ".", "map", "(", "&", ":name", ")", "}", "diff", "=", "old_paths", "-", "new_paths", "diff", ".", "each", "do", "|", "file_to_remove", "|", "puts", "\"DEBUG: removing file from result EPUB: #{file_to_remove}\"", "if", "compilation_context", ".", "verbose?", "zip_file", ".", "remove", "(", "file_to_remove", ")", "end", "end", "end", "run_command", "(", "%(zip -q0X \"#{epub_path}\" mimetype)", ")", "run_command", "(", "%(zip -qXr9D \"#{epub_path}\" \"#{new_paths.join('\" \"')}\" --exclude \\\\*.DS_Store)", ")", "end", "path", "end" ]
Archives current target files to epub @param path [String] path to created archive @return [String] path
[ "Archives", "current", "target", "files", "to", "epub" ]
4d736deb3f18c034fc93fcb95cfb9bf03b63c252
https://github.com/epuber-io/epuber/blob/4d736deb3f18c034fc93fcb95cfb9bf03b63c252/lib/epuber/compiler.rb#L112-L136
train
epuber-io/epuber
lib/epuber/compiler.rb
Epuber.Compiler.epub_name
def epub_name(configuration_suffix = nil) epub_name = if [email protected]_base_name.nil? @book.output_base_name elsif @book.from_file? ::File.basename(@book.file_path, ::File.extname(@book.file_path)) else @book.title end epub_name += @book.build_version.to_s unless @book.build_version.nil? epub_name += "-#{@target.name}" if @target != @book.default_target epub_name += "-#{configuration_suffix}" unless configuration_suffix.nil? epub_name + '.epub' end
ruby
def epub_name(configuration_suffix = nil) epub_name = if [email protected]_base_name.nil? @book.output_base_name elsif @book.from_file? ::File.basename(@book.file_path, ::File.extname(@book.file_path)) else @book.title end epub_name += @book.build_version.to_s unless @book.build_version.nil? epub_name += "-#{@target.name}" if @target != @book.default_target epub_name += "-#{configuration_suffix}" unless configuration_suffix.nil? epub_name + '.epub' end
[ "def", "epub_name", "(", "configuration_suffix", "=", "nil", ")", "epub_name", "=", "if", "!", "@book", ".", "output_base_name", ".", "nil?", "@book", ".", "output_base_name", "elsif", "@book", ".", "from_file?", "::", "File", ".", "basename", "(", "@book", ".", "file_path", ",", "::", "File", ".", "extname", "(", "@book", ".", "file_path", ")", ")", "else", "@book", ".", "title", "end", "epub_name", "+=", "@book", ".", "build_version", ".", "to_s", "unless", "@book", ".", "build_version", ".", "nil?", "epub_name", "+=", "\"-#{@target.name}\"", "if", "@target", "!=", "@book", ".", "default_target", "epub_name", "+=", "\"-#{configuration_suffix}\"", "unless", "configuration_suffix", ".", "nil?", "epub_name", "+", "'.epub'", "end" ]
Creates name of epub file for current book and current target @return [String] name of result epub file
[ "Creates", "name", "of", "epub", "file", "for", "current", "book", "and", "current", "target" ]
4d736deb3f18c034fc93fcb95cfb9bf03b63c252
https://github.com/epuber-io/epuber/blob/4d736deb3f18c034fc93fcb95cfb9bf03b63c252/lib/epuber/compiler.rb#L142-L155
train
JonnieCache/tinyci
lib/tinyci/scheduler.rb
TinyCI.Scheduler.run_all_commits
def run_all_commits commits = get_commits until commits.empty? do commits.each {|c| run_commit(c)} commits = get_commits end end
ruby
def run_all_commits commits = get_commits until commits.empty? do commits.each {|c| run_commit(c)} commits = get_commits end end
[ "def", "run_all_commits", "commits", "=", "get_commits", "until", "commits", ".", "empty?", "do", "commits", ".", "each", "{", "|", "c", "|", "run_commit", "(", "c", ")", "}", "commits", "=", "get_commits", "end", "end" ]
Repeatedly gets the list of eligable commits and runs TinyCI against them until there are no more remaining
[ "Repeatedly", "gets", "the", "list", "of", "eligable", "commits", "and", "runs", "TinyCI", "against", "them", "until", "there", "are", "no", "more", "remaining" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/scheduler.rb#L96-L104
train
appoxy/simple_record
lib/simple_record/results_array.rb
SimpleRecord.ResultsArray.as_json
def as_json(options = nil) #:nodoc: # use encoder as a proxy to call as_json on all elements, to protect from circular references encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options) map { |v| encoder.as_json(v) } end
ruby
def as_json(options = nil) #:nodoc: # use encoder as a proxy to call as_json on all elements, to protect from circular references encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options) map { |v| encoder.as_json(v) } end
[ "def", "as_json", "(", "options", "=", "nil", ")", "encoder", "=", "options", "&&", "options", "[", ":encoder", "]", "||", "ActiveSupport", "::", "JSON", "::", "Encoding", "::", "Encoder", ".", "new", "(", "options", ")", "map", "{", "|", "v", "|", "encoder", ".", "as_json", "(", "v", ")", "}", "end" ]
A couple json serialization methods copied from active_support
[ "A", "couple", "json", "serialization", "methods", "copied", "from", "active_support" ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/results_array.rb#L219-L223
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/assets_api.rb
BlueprintClient.AssetsApi.add_asset_to_node
def add_asset_to_node(namespace, type, id, asset_type, asset_id, opts = {}) data, _status_code, _headers = add_asset_to_node_with_http_info(namespace, type, id, asset_type, asset_id, opts) return data end
ruby
def add_asset_to_node(namespace, type, id, asset_type, asset_id, opts = {}) data, _status_code, _headers = add_asset_to_node_with_http_info(namespace, type, id, asset_type, asset_id, opts) return data end
[ "def", "add_asset_to_node", "(", "namespace", ",", "type", ",", "id", ",", "asset_type", ",", "asset_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "add_asset_to_node_with_http_info", "(", "namespace", ",", "type", ",", "id", ",", "asset_type", ",", "asset_id", ",", "opts", ")", "return", "data", "end" ]
Add an asset to the node. Body must be empty. Will upsert the asset if it doesn't exist @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param id id identifying a domain model @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param asset_id id of an asset @param [Hash] opts the optional parameters @return [AssetBody]
[ "Add", "an", "asset", "to", "the", "node", ".", "Body", "must", "be", "empty", ".", "Will", "upsert", "the", "asset", "if", "it", "doesn", "t", "exist" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/assets_api.rb#L32-L35
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/assets_api.rb
BlueprintClient.AssetsApi.delete_asset
def delete_asset(namespace, asset_id, asset_type, opts = {}) delete_asset_with_http_info(namespace, asset_id, asset_type, opts) return nil end
ruby
def delete_asset(namespace, asset_id, asset_type, opts = {}) delete_asset_with_http_info(namespace, asset_id, asset_type, opts) return nil end
[ "def", "delete_asset", "(", "namespace", ",", "asset_id", ",", "asset_type", ",", "opts", "=", "{", "}", ")", "delete_asset_with_http_info", "(", "namespace", ",", "asset_id", ",", "asset_type", ",", "opts", ")", "return", "nil", "end" ]
Delete an Asset @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_id id of an asset @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param [Hash] opts the optional parameters @return [nil]
[ "Delete", "an", "Asset" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/assets_api.rb#L135-L138
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/assets_api.rb
BlueprintClient.AssetsApi.get_asset
def get_asset(namespace, asset_type, asset_id, opts = {}) data, _status_code, _headers = get_asset_with_http_info(namespace, asset_type, asset_id, opts) return data end
ruby
def get_asset(namespace, asset_type, asset_id, opts = {}) data, _status_code, _headers = get_asset_with_http_info(namespace, asset_type, asset_id, opts) return data end
[ "def", "get_asset", "(", "namespace", ",", "asset_type", ",", "asset_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_asset_with_http_info", "(", "namespace", ",", "asset_type", ",", "asset_id", ",", "opts", ")", "return", "data", "end" ]
Get details of a given asset @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param asset_id id of an asset @param [Hash] opts the optional parameters @return [AssetBody]
[ "Get", "details", "of", "a", "given", "asset" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/assets_api.rb#L283-L286
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/assets_api.rb
BlueprintClient.AssetsApi.get_assets_in_node
def get_assets_in_node(namespace, type, id, opts = {}) data, _status_code, _headers = get_assets_in_node_with_http_info(namespace, type, id, opts) return data end
ruby
def get_assets_in_node(namespace, type, id, opts = {}) data, _status_code, _headers = get_assets_in_node_with_http_info(namespace, type, id, opts) return data end
[ "def", "get_assets_in_node", "(", "namespace", ",", "type", ",", "id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_assets_in_node_with_http_info", "(", "namespace", ",", "type", ",", "id", ",", "opts", ")", "return", "data", "end" ]
Get for assets in the relevant node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param id id identifying a domain model @param [Hash] opts the optional parameters @option opts [Array<String>] :filter_asset_type type of asset to return. This filters the results by asset type, but returns all the assets associated with the result. @option opts [Float] :offset index to start result set from @option opts [Float] :limit number of records to return @return [AssetResultSet]
[ "Get", "for", "assets", "in", "the", "relevant", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/assets_api.rb#L371-L374
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/assets_api.rb
BlueprintClient.AssetsApi.remove_asset_from_node
def remove_asset_from_node(namespace, type, id, asset_type, asset_id, opts = {}) remove_asset_from_node_with_http_info(namespace, type, id, asset_type, asset_id, opts) return nil end
ruby
def remove_asset_from_node(namespace, type, id, asset_type, asset_id, opts = {}) remove_asset_from_node_with_http_info(namespace, type, id, asset_type, asset_id, opts) return nil end
[ "def", "remove_asset_from_node", "(", "namespace", ",", "type", ",", "id", ",", "asset_type", ",", "asset_id", ",", "opts", "=", "{", "}", ")", "remove_asset_from_node_with_http_info", "(", "namespace", ",", "type", ",", "id", ",", "asset_type", ",", "asset_id", ",", "opts", ")", "return", "nil", "end" ]
Remove an asset from the relevant node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param id id identifying a domain model @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param asset_id id of an asset @param [Hash] opts the optional parameters @return [nil]
[ "Remove", "an", "asset", "from", "the", "relevant", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/assets_api.rb#L482-L485
train
feduxorg/filegen
lib/filegen/erb_generator.rb
Filegen.ErbGenerator.compile
def compile(source, destination) erb = ERB.new(source.read, nil, '-') begin destination.puts erb.result(data.instance_binding) rescue SyntaxError => e raise Exceptions::ErbTemplateHasSyntaxErrors, e.message end end
ruby
def compile(source, destination) erb = ERB.new(source.read, nil, '-') begin destination.puts erb.result(data.instance_binding) rescue SyntaxError => e raise Exceptions::ErbTemplateHasSyntaxErrors, e.message end end
[ "def", "compile", "(", "source", ",", "destination", ")", "erb", "=", "ERB", ".", "new", "(", "source", ".", "read", ",", "nil", ",", "'-'", ")", "begin", "destination", ".", "puts", "erb", ".", "result", "(", "data", ".", "instance_binding", ")", "rescue", "SyntaxError", "=>", "e", "raise", "Exceptions", "::", "ErbTemplateHasSyntaxErrors", ",", "e", ".", "message", "end", "end" ]
Create erb generator @param [Data] data The data class to be used within the template Compile the template @param [IO] source The source template to be used @param [IO] destination The output io handle
[ "Create", "erb", "generator" ]
08c31d3caa7fb7ac61a6544154714b9d79b88985
https://github.com/feduxorg/filegen/blob/08c31d3caa7fb7ac61a6544154714b9d79b88985/lib/filegen/erb_generator.rb#L25-L32
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/instance_methods.rb
ActsAsSolr.InstanceMethods.solr_save
def solr_save return true if indexing_disabled? if evaluate_condition(:if, self) debug "solr_save: #{self.class.name} : #{record_id(self)}" solr_add to_solr_doc solr_commit if configuration[:auto_commit] true else solr_destroy end end
ruby
def solr_save return true if indexing_disabled? if evaluate_condition(:if, self) debug "solr_save: #{self.class.name} : #{record_id(self)}" solr_add to_solr_doc solr_commit if configuration[:auto_commit] true else solr_destroy end end
[ "def", "solr_save", "return", "true", "if", "indexing_disabled?", "if", "evaluate_condition", "(", ":if", ",", "self", ")", "debug", "\"solr_save: #{self.class.name} : #{record_id(self)}\"", "solr_add", "to_solr_doc", "solr_commit", "if", "configuration", "[", ":auto_commit", "]", "true", "else", "solr_destroy", "end", "end" ]
saves to the Solr index
[ "saves", "to", "the", "Solr", "index" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/instance_methods.rb#L11-L21
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/instance_methods.rb
ActsAsSolr.InstanceMethods.to_solr_doc
def to_solr_doc debug "to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}" doc = Solr::Document.new doc.boost = validate_boost(configuration[:boost]) if configuration[:boost] doc << {:id => solr_id, solr_configuration[:type_field] => self.class.name, solr_configuration[:primary_key_field] => record_id(self).to_s} # iterate through the fields and add them to the document, configuration[:solr_fields].each do |field_name, options| next if [self.class.primary_key, "type"].include?(field_name.to_s) field_boost = options[:boost] || solr_configuration[:default_boost] field_type = get_solr_field_type(options[:type]) solr_name = options[:as] || field_name value = self.send("#{field_name}_for_solr") rescue nil next if value.nil? suffix = get_solr_field_type(field_type) value = Array(value).map{ |v| ERB::Util.html_escape(v) } # escape each value value = value.first if value.size == 1 field = Solr::Field.new(:name => "#{solr_name}_#{suffix}", :value => value) processed_boost = validate_boost(field_boost) field.boost = processed_boost doc << field end add_dynamic_attributes(doc) add_includes(doc) add_tags(doc) add_space(doc) debug doc.to_json doc end
ruby
def to_solr_doc debug "to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}" doc = Solr::Document.new doc.boost = validate_boost(configuration[:boost]) if configuration[:boost] doc << {:id => solr_id, solr_configuration[:type_field] => self.class.name, solr_configuration[:primary_key_field] => record_id(self).to_s} # iterate through the fields and add them to the document, configuration[:solr_fields].each do |field_name, options| next if [self.class.primary_key, "type"].include?(field_name.to_s) field_boost = options[:boost] || solr_configuration[:default_boost] field_type = get_solr_field_type(options[:type]) solr_name = options[:as] || field_name value = self.send("#{field_name}_for_solr") rescue nil next if value.nil? suffix = get_solr_field_type(field_type) value = Array(value).map{ |v| ERB::Util.html_escape(v) } # escape each value value = value.first if value.size == 1 field = Solr::Field.new(:name => "#{solr_name}_#{suffix}", :value => value) processed_boost = validate_boost(field_boost) field.boost = processed_boost doc << field end add_dynamic_attributes(doc) add_includes(doc) add_tags(doc) add_space(doc) debug doc.to_json doc end
[ "def", "to_solr_doc", "debug", "\"to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}\"", "doc", "=", "Solr", "::", "Document", ".", "new", "doc", ".", "boost", "=", "validate_boost", "(", "configuration", "[", ":boost", "]", ")", "if", "configuration", "[", ":boost", "]", "doc", "<<", "{", ":id", "=>", "solr_id", ",", "solr_configuration", "[", ":type_field", "]", "=>", "self", ".", "class", ".", "name", ",", "solr_configuration", "[", ":primary_key_field", "]", "=>", "record_id", "(", "self", ")", ".", "to_s", "}", "configuration", "[", ":solr_fields", "]", ".", "each", "do", "|", "field_name", ",", "options", "|", "next", "if", "[", "self", ".", "class", ".", "primary_key", ",", "\"type\"", "]", ".", "include?", "(", "field_name", ".", "to_s", ")", "field_boost", "=", "options", "[", ":boost", "]", "||", "solr_configuration", "[", ":default_boost", "]", "field_type", "=", "get_solr_field_type", "(", "options", "[", ":type", "]", ")", "solr_name", "=", "options", "[", ":as", "]", "||", "field_name", "value", "=", "self", ".", "send", "(", "\"#{field_name}_for_solr\"", ")", "rescue", "nil", "next", "if", "value", ".", "nil?", "suffix", "=", "get_solr_field_type", "(", "field_type", ")", "value", "=", "Array", "(", "value", ")", ".", "map", "{", "|", "v", "|", "ERB", "::", "Util", ".", "html_escape", "(", "v", ")", "}", "value", "=", "value", ".", "first", "if", "value", ".", "size", "==", "1", "field", "=", "Solr", "::", "Field", ".", "new", "(", ":name", "=>", "\"#{solr_name}_#{suffix}\"", ",", ":value", "=>", "value", ")", "processed_boost", "=", "validate_boost", "(", "field_boost", ")", "field", ".", "boost", "=", "processed_boost", "doc", "<<", "field", "end", "add_dynamic_attributes", "(", "doc", ")", "add_includes", "(", "doc", ")", "add_tags", "(", "doc", ")", "add_space", "(", "doc", ")", "debug", "doc", ".", "to_json", "doc", "end" ]
convert instance to Solr document
[ "convert", "instance", "to", "Solr", "document" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/instance_methods.rb#L37-L74
train
stereobooster/typograf
lib/typograf/client.rb
Typograf.Client.send_request
def send_request(text) params = { 'text' => text.encode("cp1251"), } params['xml'] = @xml if @xml request = Net::HTTP::Post.new(@url.path) request.set_form_data(params) begin response = Net::HTTP.new(@url.host, @url.port).start do |http| http.request(request) end rescue StandardError => exception raise NetworkError.new(exception.message, exception.backtrace) end if !response.is_a?(Net::HTTPOK) raise NetworkError, "#{response.code}: #{response.message}" end body = response.body.force_encoding("cp1251").encode("utf-8") # error = "\xCE\xF8\xE8\xE1\xEA\xE0: \xE2\xFB \xE7\xE0\xE1\xFB\xEB\xE8 \xEF\xE5\xF0\xE5\xE4\xE0\xF2\xFC \xF2\xE5\xEA\xF1\xF2" # error.force_encoding("ASCII-8BIT") if error.respond_to?(:force_encoding) if body == "Ошибка: вы забыли передать текст" raise NetworkError, "Ошибка: вы забыли передать текст" end if @options[:symbols] == 2 HTMLEntities.new.decode(body.chomp) else body.chomp end end
ruby
def send_request(text) params = { 'text' => text.encode("cp1251"), } params['xml'] = @xml if @xml request = Net::HTTP::Post.new(@url.path) request.set_form_data(params) begin response = Net::HTTP.new(@url.host, @url.port).start do |http| http.request(request) end rescue StandardError => exception raise NetworkError.new(exception.message, exception.backtrace) end if !response.is_a?(Net::HTTPOK) raise NetworkError, "#{response.code}: #{response.message}" end body = response.body.force_encoding("cp1251").encode("utf-8") # error = "\xCE\xF8\xE8\xE1\xEA\xE0: \xE2\xFB \xE7\xE0\xE1\xFB\xEB\xE8 \xEF\xE5\xF0\xE5\xE4\xE0\xF2\xFC \xF2\xE5\xEA\xF1\xF2" # error.force_encoding("ASCII-8BIT") if error.respond_to?(:force_encoding) if body == "Ошибка: вы забыли передать текст" raise NetworkError, "Ошибка: вы забыли передать текст" end if @options[:symbols] == 2 HTMLEntities.new.decode(body.chomp) else body.chomp end end
[ "def", "send_request", "(", "text", ")", "params", "=", "{", "'text'", "=>", "text", ".", "encode", "(", "\"cp1251\"", ")", ",", "}", "params", "[", "'xml'", "]", "=", "@xml", "if", "@xml", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@url", ".", "path", ")", "request", ".", "set_form_data", "(", "params", ")", "begin", "response", "=", "Net", "::", "HTTP", ".", "new", "(", "@url", ".", "host", ",", "@url", ".", "port", ")", ".", "start", "do", "|", "http", "|", "http", ".", "request", "(", "request", ")", "end", "rescue", "StandardError", "=>", "exception", "raise", "NetworkError", ".", "new", "(", "exception", ".", "message", ",", "exception", ".", "backtrace", ")", "end", "if", "!", "response", ".", "is_a?", "(", "Net", "::", "HTTPOK", ")", "raise", "NetworkError", ",", "\"#{response.code}: #{response.message}\"", "end", "body", "=", "response", ".", "body", ".", "force_encoding", "(", "\"cp1251\"", ")", ".", "encode", "(", "\"utf-8\"", ")", "if", "body", "==", "\"Ошибка: вы забыли передать текст\"", "raise", "NetworkError", ",", "\"Ошибка: вы забыли передать текст\"", "end", "if", "@options", "[", ":symbols", "]", "==", "2", "HTMLEntities", ".", "new", ".", "decode", "(", "body", ".", "chomp", ")", "else", "body", ".", "chomp", "end", "end" ]
Process text with remote web-service
[ "Process", "text", "with", "remote", "web", "-", "service" ]
c2f89dac63361e58a856801e474db55f2fb8a472
https://github.com/stereobooster/typograf/blob/c2f89dac63361e58a856801e474db55f2fb8a472/lib/typograf/client.rb#L118-L151
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/acts_methods.rb
ActsAsSolr.ActsMethods.acts_as_solr
def acts_as_solr(options={}, solr_options={}, &deferred_solr_configuration) $solr_indexed_models << self extend ClassMethods include InstanceMethods include CommonMethods include ParserMethods define_solr_configuration_methods acts_as_taggable_on :tags if options[:taggable] has_many :dynamic_attributes, :as => "dynamicable" if options[:dynamic_attributes] has_one :local, :as => "localizable" if options[:spatial] after_save :solr_save after_destroy :solr_destroy if deferred_solr_configuration self.deferred_solr_configuration = deferred_solr_configuration else process_acts_as_solr(options, solr_options) end end
ruby
def acts_as_solr(options={}, solr_options={}, &deferred_solr_configuration) $solr_indexed_models << self extend ClassMethods include InstanceMethods include CommonMethods include ParserMethods define_solr_configuration_methods acts_as_taggable_on :tags if options[:taggable] has_many :dynamic_attributes, :as => "dynamicable" if options[:dynamic_attributes] has_one :local, :as => "localizable" if options[:spatial] after_save :solr_save after_destroy :solr_destroy if deferred_solr_configuration self.deferred_solr_configuration = deferred_solr_configuration else process_acts_as_solr(options, solr_options) end end
[ "def", "acts_as_solr", "(", "options", "=", "{", "}", ",", "solr_options", "=", "{", "}", ",", "&", "deferred_solr_configuration", ")", "$solr_indexed_models", "<<", "self", "extend", "ClassMethods", "include", "InstanceMethods", "include", "CommonMethods", "include", "ParserMethods", "define_solr_configuration_methods", "acts_as_taggable_on", ":tags", "if", "options", "[", ":taggable", "]", "has_many", ":dynamic_attributes", ",", ":as", "=>", "\"dynamicable\"", "if", "options", "[", ":dynamic_attributes", "]", "has_one", ":local", ",", ":as", "=>", "\"localizable\"", "if", "options", "[", ":spatial", "]", "after_save", ":solr_save", "after_destroy", ":solr_destroy", "if", "deferred_solr_configuration", "self", ".", "deferred_solr_configuration", "=", "deferred_solr_configuration", "else", "process_acts_as_solr", "(", "options", ",", "solr_options", ")", "end", "end" ]
declares a class as solr-searchable ==== options: fields:: This option can be used to specify only the fields you'd like to index. If not given, all the attributes from the class will be indexed. You can also use this option to include methods that should be indexed as fields class Movie < ActiveRecord::Base acts_as_solr :fields => [:name, :description, :current_time] def current_time Time.now.to_s end end Each field passed can also be a hash with the value being a field type class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => :range_float}] def current_time Time.now end end The field types accepted are: :float:: Index the field value as a float (ie.: 12.87) :integer:: Index the field value as an integer (ie.: 31) :boolean:: Index the field value as a boolean (ie.: true/false) :date:: Index the field value as a date (ie.: Wed Nov 15 23:13:03 PST 2006) :string:: Index the field value as a text string, not applying the same indexing filters as a regular text field :range_integer:: Index the field value for integer range queries (ie.:[5 TO 20]) :range_float:: Index the field value for float range queries (ie.:[14.56 TO 19.99]) Setting the field type preserves its original type when indexed The field may also be passed with a hash value containing options class Author < ActiveRecord::Base acts_as_solr :fields => [{:full_name => {:type => :text, :as => :name}}] def full_name self.first_name + ' ' + self.last_name end end The options accepted are: :type:: Index the field using the specified type :as:: Index the field using the specified field name additional_fields:: This option takes fields to be include in the index in addition to those derived from the database. You can also use this option to include custom fields derived from methods you define. This option will be ignored if the :fields option is given. It also accepts the same field types as the option above class Movie < ActiveRecord::Base acts_as_solr :additional_fields => [:current_time] def current_time Time.now.to_s end end exclude_fields:: This option taks an array of fields that should be ignored from indexing: class User < ActiveRecord::Base acts_as_solr :exclude_fields => [:password, :login, :credit_card_number] end include:: This option can be used for association indexing, which means you can include any :has_one, :has_many, :belongs_to and :has_and_belongs_to_many association to be indexed: class Category < ActiveRecord::Base has_many :books acts_as_solr :include => [:books] end Each association may also be specified as a hash with an option hash as a value class Book < ActiveRecord::Base belongs_to :author has_many :distribution_companies has_many :copyright_dates has_many :media_types acts_as_solr( :fields => [:name, :description], :include => [ {:author => {:using => :fullname, :as => :name}}, {:media_types => {:using => lambda{|media| type_lookup(media.id)}}} {:distribution_companies => {:as => :distributor, :multivalued => true}}, {:copyright_dates => {:as => :copyright, :type => :date}} ] ] The options accepted are: :type:: Index the associated objects using the specified type :as:: Index the associated objects using the specified field name :using:: Index the associated objects using the value returned by the specified method or proc. If a method symbol is supplied, it will be sent to each object to look up the value to index; if a proc is supplied, it will be called once for each object with the object as the only argument :multivalued:: Index the associated objects using one field for each object rather than joining them all into a single field facets:: This option can be used to specify the fields you'd like to index as facet fields class Electronic < ActiveRecord::Base acts_as_solr :facets => [:category, :manufacturer] end boost:: You can pass a boost (float) value that will be used to boost the document and/or a field. To specify a more boost for the document, you can either pass a block or a symbol. The block will be called with the record as an argument, a symbol will result in the according method being called: class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => {:boost => 5.0}}], :boost => 10.0 end class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => {:boost => 5.0}}], :boost => proc {|record| record.id + 120*37} end class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => {:boost => :price_rating}}], :boost => 10.0 end if:: Only indexes the record if the condition evaluated is true. The argument has to be either a symbol, string (to be eval'ed), proc/method, or class implementing a static validation method. It behaves the same way as ActiveRecord's :if option. class Electronic < ActiveRecord::Base acts_as_solr :if => proc{|record| record.is_active?} end offline:: Assumes that your using an outside mechanism to explicitly trigger indexing records, e.g. you only want to update your index through some asynchronous mechanism. Will accept either a boolean or a block that will be evaluated before actually contacting the index for saving or destroying a document. Defaults to false. It doesn't refer to the mechanism of an offline index in general, but just to get a centralized point where you can control indexing. Note: This is only enabled for saving records. acts_as_solr doesn't always like it, if you have a different number of results coming from the database and the index. This might be rectified in another patch to support lazy loading. class Electronic < ActiveRecord::Base acts_as_solr :offline => proc {|record| record.automatic_indexing_disabled?} end auto_commit:: The commit command will be sent to Solr only if its value is set to true: class Author < ActiveRecord::Base acts_as_solr :auto_commit => false end dynamic_attributes: Default false. When true, requires a has_many relationship to a DynamicAttribute (:name, :value) model. Then, all dynamic attributes will be mapped as normal attributes in Solr, so you can filter like this: Model.find_by_solr "#{dynamic_attribute.name}:Lorem" taggable: Default false. When true, indexes tags with field name tag. Tags are taken from taggings.tag spatial: Default false. When true, indexes model.local.latitude and model.local.longitude as coordinates.
[ "declares", "a", "class", "as", "solr", "-", "searchable" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/acts_methods.rb#L172-L195
train
alphasights/json-api-client
lib/json_api_client/mapper.rb
JsonApiClient.Mapper.build_linked_resources_map
def build_linked_resources_map(data) data["linked"].each_with_object({}) do |(type, resources), obj| obj[type] ||= {} resources.each do |linked_resource| obj[type][linked_resource["id"]] = linked_resource end end end
ruby
def build_linked_resources_map(data) data["linked"].each_with_object({}) do |(type, resources), obj| obj[type] ||= {} resources.each do |linked_resource| obj[type][linked_resource["id"]] = linked_resource end end end
[ "def", "build_linked_resources_map", "(", "data", ")", "data", "[", "\"linked\"", "]", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "type", ",", "resources", ")", ",", "obj", "|", "obj", "[", "type", "]", "||=", "{", "}", "resources", ".", "each", "do", "|", "linked_resource", "|", "obj", "[", "type", "]", "[", "linked_resource", "[", "\"id\"", "]", "]", "=", "linked_resource", "end", "end", "end" ]
Builds a map to enable getting references by type and id eg. { "users" => { "1" => { "id" => "1", "name" => "John" }, "5" => { "id" => "5", "name" => "Walter" }, } }
[ "Builds", "a", "map", "to", "enable", "getting", "references", "by", "type", "and", "id" ]
00598445ea200f5db352fd50ce3a7e5ae3a37b9e
https://github.com/alphasights/json-api-client/blob/00598445ea200f5db352fd50ce3a7e5ae3a37b9e/lib/json_api_client/mapper.rb#L72-L79
train
alphasights/json-api-client
lib/json_api_client/mapper.rb
JsonApiClient.Mapper.build_link_type_map
def build_link_type_map(data) data["links"].each_with_object({}) do |(key, value), obj| association = key.split(".").last obj[association] = value["type"].pluralize end end
ruby
def build_link_type_map(data) data["links"].each_with_object({}) do |(key, value), obj| association = key.split(".").last obj[association] = value["type"].pluralize end end
[ "def", "build_link_type_map", "(", "data", ")", "data", "[", "\"links\"", "]", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "obj", "|", "association", "=", "key", ".", "split", "(", "\".\"", ")", ".", "last", "obj", "[", "association", "]", "=", "value", "[", "\"type\"", "]", ".", "pluralize", "end", "end" ]
Builds a map to translate references to types eg. { "author" => "users", "comments" => "comments" }
[ "Builds", "a", "map", "to", "translate", "references", "to", "types" ]
00598445ea200f5db352fd50ce3a7e5ae3a37b9e
https://github.com/alphasights/json-api-client/blob/00598445ea200f5db352fd50ce3a7e5ae3a37b9e/lib/json_api_client/mapper.rb#L85-L90
train
redding/dk
lib/dk/tree_runner.rb
Dk.TreeRunner.build_and_run_task
def build_and_run_task(task_class, params = nil) task_run = TaskRun.new(task_class, params) @task_run_stack.last.runs << task_run @task_run_stack.push(task_run) task = super(task_class, params) @task_run_stack.pop task end
ruby
def build_and_run_task(task_class, params = nil) task_run = TaskRun.new(task_class, params) @task_run_stack.last.runs << task_run @task_run_stack.push(task_run) task = super(task_class, params) @task_run_stack.pop task end
[ "def", "build_and_run_task", "(", "task_class", ",", "params", "=", "nil", ")", "task_run", "=", "TaskRun", ".", "new", "(", "task_class", ",", "params", ")", "@task_run_stack", ".", "last", ".", "runs", "<<", "task_run", "@task_run_stack", ".", "push", "(", "task_run", ")", "task", "=", "super", "(", "task_class", ",", "params", ")", "@task_run_stack", ".", "pop", "task", "end" ]
track all task runs
[ "track", "all", "task", "runs" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/tree_runner.rb#L41-L49
train
JonnieCache/tinyci
lib/tinyci/runner.rb
TinyCI.Runner.run!
def run! begin ensure_path target_path setup_log log_info "Commit: #{@commit}" log_info "Cleaning..." clean log_info "Exporting..." ensure_path export_path export begin load_config rescue ConfigMissingError => e log_error e.message log_error 'Removing export...' clean return false end @builder ||= instantiate_builder @tester ||= instantiate_tester @hooker ||= instantiate_hooker log_info "Building..." run_hook! :before_build begin @builder.build rescue => e run_hook! :after_build_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_build_success ensure run_hook! :after_build end log_info "Testing..." run_hook! :before_test begin @tester.test rescue => e run_hook! :after_test_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_test_success ensure run_hook! :after_test end log_info "Finished #{@commit}" rescue => e raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false end true end
ruby
def run! begin ensure_path target_path setup_log log_info "Commit: #{@commit}" log_info "Cleaning..." clean log_info "Exporting..." ensure_path export_path export begin load_config rescue ConfigMissingError => e log_error e.message log_error 'Removing export...' clean return false end @builder ||= instantiate_builder @tester ||= instantiate_tester @hooker ||= instantiate_hooker log_info "Building..." run_hook! :before_build begin @builder.build rescue => e run_hook! :after_build_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_build_success ensure run_hook! :after_build end log_info "Testing..." run_hook! :before_test begin @tester.test rescue => e run_hook! :after_test_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_test_success ensure run_hook! :after_test end log_info "Finished #{@commit}" rescue => e raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false end true end
[ "def", "run!", "begin", "ensure_path", "target_path", "setup_log", "log_info", "\"Commit: #{@commit}\"", "log_info", "\"Cleaning...\"", "clean", "log_info", "\"Exporting...\"", "ensure_path", "export_path", "export", "begin", "load_config", "rescue", "ConfigMissingError", "=>", "e", "log_error", "e", ".", "message", "log_error", "'Removing export...'", "clean", "return", "false", "end", "@builder", "||=", "instantiate_builder", "@tester", "||=", "instantiate_tester", "@hooker", "||=", "instantiate_hooker", "log_info", "\"Building...\"", "run_hook!", ":before_build", "begin", "@builder", ".", "build", "rescue", "=>", "e", "run_hook!", ":after_build_failure", "raise", "e", "if", "ENV", "[", "'TINYCI_ENV'", "]", "==", "'test'", "log_error", "e", "log_debug", "e", ".", "backtrace", "return", "false", "else", "run_hook!", ":after_build_success", "ensure", "run_hook!", ":after_build", "end", "log_info", "\"Testing...\"", "run_hook!", ":before_test", "begin", "@tester", ".", "test", "rescue", "=>", "e", "run_hook!", ":after_test_failure", "raise", "e", "if", "ENV", "[", "'TINYCI_ENV'", "]", "==", "'test'", "log_error", "e", "log_debug", "e", ".", "backtrace", "return", "false", "else", "run_hook!", ":after_test_success", "ensure", "run_hook!", ":after_test", "end", "log_info", "\"Finished #{@commit}\"", "rescue", "=>", "e", "raise", "e", "if", "ENV", "[", "'TINYCI_ENV'", "]", "==", "'test'", "log_error", "e", "log_debug", "e", ".", "backtrace", "return", "false", "end", "true", "end" ]
Constructor, allows injection of generic configuration params. @param working_dir [String] The working directory to execute against. @param commit [String] SHA1 of git object to run against @param logger [Logger] Logger object @param time [Time] Override time of object creation. Used solely for testing at this time. @param config [Hash] Override TinyCI config object, normally loaded from `.tinyci` file. Used solely for testing at this time. Runs the TinyCI system against the single git object referenced in `@commit`. @return [Boolean] `true` if the commit was built and tested successfully, `false` otherwise
[ "Constructor", "allows", "injection", "of", "generic", "configuration", "params", "." ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/runner.rb#L48-L126
train
JonnieCache/tinyci
lib/tinyci/runner.rb
TinyCI.Runner.instantiate_builder
def instantiate_builder klass = TinyCI::Builders.const_get(@config[:builder][:class]) klass.new(@config[:builder][:config].merge(target: export_path), logger: @logger) end
ruby
def instantiate_builder klass = TinyCI::Builders.const_get(@config[:builder][:class]) klass.new(@config[:builder][:config].merge(target: export_path), logger: @logger) end
[ "def", "instantiate_builder", "klass", "=", "TinyCI", "::", "Builders", ".", "const_get", "(", "@config", "[", ":builder", "]", "[", ":class", "]", ")", "klass", ".", "new", "(", "@config", "[", ":builder", "]", "[", ":config", "]", ".", "merge", "(", "target", ":", "export_path", ")", ",", "logger", ":", "@logger", ")", "end" ]
Instantiate the Builder object according to the class named in the config
[ "Instantiate", "the", "Builder", "object", "according", "to", "the", "class", "named", "in", "the", "config" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/runner.rb#L158-L161
train
JonnieCache/tinyci
lib/tinyci/runner.rb
TinyCI.Runner.instantiate_hooker
def instantiate_hooker return nil unless @config[:hooker].is_a? Hash klass = TinyCI::Hookers.const_get(@config[:hooker][:class]) klass.new(@config[:hooker][:config].merge(target: export_path), logger: @logger) end
ruby
def instantiate_hooker return nil unless @config[:hooker].is_a? Hash klass = TinyCI::Hookers.const_get(@config[:hooker][:class]) klass.new(@config[:hooker][:config].merge(target: export_path), logger: @logger) end
[ "def", "instantiate_hooker", "return", "nil", "unless", "@config", "[", ":hooker", "]", ".", "is_a?", "Hash", "klass", "=", "TinyCI", "::", "Hookers", ".", "const_get", "(", "@config", "[", ":hooker", "]", "[", ":class", "]", ")", "klass", ".", "new", "(", "@config", "[", ":hooker", "]", "[", ":config", "]", ".", "merge", "(", "target", ":", "export_path", ")", ",", "logger", ":", "@logger", ")", "end" ]
Instantiate the Hooker object according to the class named in the config
[ "Instantiate", "the", "Hooker", "object", "according", "to", "the", "class", "named", "in", "the", "config" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/runner.rb#L170-L175
train
sosedoff/grooveshark
lib/grooveshark/playlist.rb
Grooveshark.Playlist.load_songs
def load_songs @songs = [] playlist = @client.request('getPlaylistByID', playlistID: @id) @songs = playlist['songs'].map! do |s| Song.new(s) end if playlist.key?('songs') @songs end
ruby
def load_songs @songs = [] playlist = @client.request('getPlaylistByID', playlistID: @id) @songs = playlist['songs'].map! do |s| Song.new(s) end if playlist.key?('songs') @songs end
[ "def", "load_songs", "@songs", "=", "[", "]", "playlist", "=", "@client", ".", "request", "(", "'getPlaylistByID'", ",", "playlistID", ":", "@id", ")", "@songs", "=", "playlist", "[", "'songs'", "]", ".", "map!", "do", "|", "s", "|", "Song", ".", "new", "(", "s", ")", "end", "if", "playlist", ".", "key?", "(", "'songs'", ")", "@songs", "end" ]
Fetch playlist songs
[ "Fetch", "playlist", "songs" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/playlist.rb#L24-L31
train
PRX/audio_monster
lib/audio_monster/monster.rb
AudioMonster.Monster.create_wav_wrapped_mpeg
def create_wav_wrapped_mpeg(mpeg_path, result_path, options={}) options.to_options! start_at = get_datetime_for_option(options[:start_at]) end_at = get_datetime_for_option(options[:end_at]) wav_wrapped_mpeg = NuWav::WaveFile.from_mpeg(mpeg_path) cart = wav_wrapped_mpeg.chunks[:cart] cart.title = options[:title] || File.basename(mpeg_path) cart.artist = options[:artist] cart.cut_id = options[:cut_id] cart.producer_app_id = options[:producer_app_id] if options[:producer_app_id] cart.start_date = start_at.strftime(PRSS_DATE_FORMAT) cart.start_time = start_at.strftime(AES46_2002_TIME_FORMAT) cart.end_date = end_at.strftime(PRSS_DATE_FORMAT) cart.end_time = end_at.strftime(AES46_2002_TIME_FORMAT) # pass in the options used by NuWav - # :no_pad_byte - when true, will not add the pad byte to the data chunk nu_wav_options = options.slice(:no_pad_byte) wav_wrapped_mpeg.to_file(result_path, nu_wav_options) check_local_file(result_path) return true end
ruby
def create_wav_wrapped_mpeg(mpeg_path, result_path, options={}) options.to_options! start_at = get_datetime_for_option(options[:start_at]) end_at = get_datetime_for_option(options[:end_at]) wav_wrapped_mpeg = NuWav::WaveFile.from_mpeg(mpeg_path) cart = wav_wrapped_mpeg.chunks[:cart] cart.title = options[:title] || File.basename(mpeg_path) cart.artist = options[:artist] cart.cut_id = options[:cut_id] cart.producer_app_id = options[:producer_app_id] if options[:producer_app_id] cart.start_date = start_at.strftime(PRSS_DATE_FORMAT) cart.start_time = start_at.strftime(AES46_2002_TIME_FORMAT) cart.end_date = end_at.strftime(PRSS_DATE_FORMAT) cart.end_time = end_at.strftime(AES46_2002_TIME_FORMAT) # pass in the options used by NuWav - # :no_pad_byte - when true, will not add the pad byte to the data chunk nu_wav_options = options.slice(:no_pad_byte) wav_wrapped_mpeg.to_file(result_path, nu_wav_options) check_local_file(result_path) return true end
[ "def", "create_wav_wrapped_mpeg", "(", "mpeg_path", ",", "result_path", ",", "options", "=", "{", "}", ")", "options", ".", "to_options!", "start_at", "=", "get_datetime_for_option", "(", "options", "[", ":start_at", "]", ")", "end_at", "=", "get_datetime_for_option", "(", "options", "[", ":end_at", "]", ")", "wav_wrapped_mpeg", "=", "NuWav", "::", "WaveFile", ".", "from_mpeg", "(", "mpeg_path", ")", "cart", "=", "wav_wrapped_mpeg", ".", "chunks", "[", ":cart", "]", "cart", ".", "title", "=", "options", "[", ":title", "]", "||", "File", ".", "basename", "(", "mpeg_path", ")", "cart", ".", "artist", "=", "options", "[", ":artist", "]", "cart", ".", "cut_id", "=", "options", "[", ":cut_id", "]", "cart", ".", "producer_app_id", "=", "options", "[", ":producer_app_id", "]", "if", "options", "[", ":producer_app_id", "]", "cart", ".", "start_date", "=", "start_at", ".", "strftime", "(", "PRSS_DATE_FORMAT", ")", "cart", ".", "start_time", "=", "start_at", ".", "strftime", "(", "AES46_2002_TIME_FORMAT", ")", "cart", ".", "end_date", "=", "end_at", ".", "strftime", "(", "PRSS_DATE_FORMAT", ")", "cart", ".", "end_time", "=", "end_at", ".", "strftime", "(", "AES46_2002_TIME_FORMAT", ")", "nu_wav_options", "=", "options", ".", "slice", "(", ":no_pad_byte", ")", "wav_wrapped_mpeg", ".", "to_file", "(", "result_path", ",", "nu_wav_options", ")", "check_local_file", "(", "result_path", ")", "return", "true", "end" ]
need start_at, ends_on
[ "need", "start_at", "ends_on" ]
51654ec0937258902c0c7af1f7d230c5cd2c932b
https://github.com/PRX/audio_monster/blob/51654ec0937258902c0c7af1f7d230c5cd2c932b/lib/audio_monster/monster.rb#L566-L591
train
PRX/audio_monster
lib/audio_monster/monster.rb
AudioMonster.Monster.run_command
def run_command(command, options={}) timeout = options[:timeout] || 7200 # default to adding a nice 13 if nothing specified nice = if options.key?(:nice) (options[:nice] == 'n') ? '' : "nice -n #{options[:nice]} " else 'nice -n 19 ' end echo_return = (options.key?(:echo_return) && !options[:echo_return]) ? '' : '; echo $?' cmd = "#{nice}#{command}#{echo_return}" logger.info "run_command: #{cmd}" begin result = Timeout::timeout(timeout) { Open3::popen3(cmd) do |i,o,e| out_str = "" err_str = "" i.close # important! o.sync = true e.sync = true o.each{|line| out_str << line line.chomp! logger.debug "stdout: #{line}" } e.each { |line| err_str << line line.chomp! logger.debug "stderr: #{line}" } return out_str, err_str end } rescue Timeout::Error => toe logger.error "run_command:Timeout Error - running command, took longer than #{timeout} seconds to execute: '#{cmd}'" raise toe end end
ruby
def run_command(command, options={}) timeout = options[:timeout] || 7200 # default to adding a nice 13 if nothing specified nice = if options.key?(:nice) (options[:nice] == 'n') ? '' : "nice -n #{options[:nice]} " else 'nice -n 19 ' end echo_return = (options.key?(:echo_return) && !options[:echo_return]) ? '' : '; echo $?' cmd = "#{nice}#{command}#{echo_return}" logger.info "run_command: #{cmd}" begin result = Timeout::timeout(timeout) { Open3::popen3(cmd) do |i,o,e| out_str = "" err_str = "" i.close # important! o.sync = true e.sync = true o.each{|line| out_str << line line.chomp! logger.debug "stdout: #{line}" } e.each { |line| err_str << line line.chomp! logger.debug "stderr: #{line}" } return out_str, err_str end } rescue Timeout::Error => toe logger.error "run_command:Timeout Error - running command, took longer than #{timeout} seconds to execute: '#{cmd}'" raise toe end end
[ "def", "run_command", "(", "command", ",", "options", "=", "{", "}", ")", "timeout", "=", "options", "[", ":timeout", "]", "||", "7200", "nice", "=", "if", "options", ".", "key?", "(", ":nice", ")", "(", "options", "[", ":nice", "]", "==", "'n'", ")", "?", "''", ":", "\"nice -n #{options[:nice]} \"", "else", "'nice -n 19 '", "end", "echo_return", "=", "(", "options", ".", "key?", "(", ":echo_return", ")", "&&", "!", "options", "[", ":echo_return", "]", ")", "?", "''", ":", "'; echo $?'", "cmd", "=", "\"#{nice}#{command}#{echo_return}\"", "logger", ".", "info", "\"run_command: #{cmd}\"", "begin", "result", "=", "Timeout", "::", "timeout", "(", "timeout", ")", "{", "Open3", "::", "popen3", "(", "cmd", ")", "do", "|", "i", ",", "o", ",", "e", "|", "out_str", "=", "\"\"", "err_str", "=", "\"\"", "i", ".", "close", "o", ".", "sync", "=", "true", "e", ".", "sync", "=", "true", "o", ".", "each", "{", "|", "line", "|", "out_str", "<<", "line", "line", ".", "chomp!", "logger", ".", "debug", "\"stdout: #{line}\"", "}", "e", ".", "each", "{", "|", "line", "|", "err_str", "<<", "line", "line", ".", "chomp!", "logger", ".", "debug", "\"stderr: #{line}\"", "}", "return", "out_str", ",", "err_str", "end", "}", "rescue", "Timeout", "::", "Error", "=>", "toe", "logger", ".", "error", "\"run_command:Timeout Error - running command, took longer than #{timeout} seconds to execute: '#{cmd}'\"", "raise", "toe", "end", "end" ]
Pass the command to run, and a timeout
[ "Pass", "the", "command", "to", "run", "and", "a", "timeout" ]
51654ec0937258902c0c7af1f7d230c5cd2c932b
https://github.com/PRX/audio_monster/blob/51654ec0937258902c0c7af1f7d230c5cd2c932b/lib/audio_monster/monster.rb#L903-L943
train
GetEmerson/emerson-rb
lib/emerson/responder.rb
Emerson.Responder.key_for_primary
def key_for_primary @_key_for_primary ||= if options[:as] options[:as] else controller_name = controller.controller_name (resource.respond_to?(:each) ? controller_name : controller_name.singularize).intern end end
ruby
def key_for_primary @_key_for_primary ||= if options[:as] options[:as] else controller_name = controller.controller_name (resource.respond_to?(:each) ? controller_name : controller_name.singularize).intern end end
[ "def", "key_for_primary", "@_key_for_primary", "||=", "if", "options", "[", ":as", "]", "options", "[", ":as", "]", "else", "controller_name", "=", "controller", ".", "controller_name", "(", "resource", ".", "respond_to?", "(", ":each", ")", "?", "controller_name", ":", "controller_name", ".", "singularize", ")", ".", "intern", "end", "end" ]
The primary resource is keyed per the request.
[ "The", "primary", "resource", "is", "keyed", "per", "the", "request", "." ]
184facb853e69fdf79c977fb7573f350844603b5
https://github.com/GetEmerson/emerson-rb/blob/184facb853e69fdf79c977fb7573f350844603b5/lib/emerson/responder.rb#L150-L157
train
juandebravo/quora-client
lib/quora/client.rb
Quora.Client.get
def get(field, filter = true) if field.nil? or !field.instance_of?(String) raise ArgumentError, "Field value must be a string" end resp = http.get("#{BASEPATH}?fields=#{field}", headers) data = resp.body[RESP_PREFIX.length..-1] data = JSON.parse(data) if filter && data.has_key?(field) data[field] else data end end
ruby
def get(field, filter = true) if field.nil? or !field.instance_of?(String) raise ArgumentError, "Field value must be a string" end resp = http.get("#{BASEPATH}?fields=#{field}", headers) data = resp.body[RESP_PREFIX.length..-1] data = JSON.parse(data) if filter && data.has_key?(field) data[field] else data end end
[ "def", "get", "(", "field", ",", "filter", "=", "true", ")", "if", "field", ".", "nil?", "or", "!", "field", ".", "instance_of?", "(", "String", ")", "raise", "ArgumentError", ",", "\"Field value must be a string\"", "end", "resp", "=", "http", ".", "get", "(", "\"#{BASEPATH}?fields=#{field}\"", ",", "headers", ")", "data", "=", "resp", ".", "body", "[", "RESP_PREFIX", ".", "length", "..", "-", "1", "]", "data", "=", "JSON", ".", "parse", "(", "data", ")", "if", "filter", "&&", "data", ".", "has_key?", "(", "field", ")", "data", "[", "field", "]", "else", "data", "end", "end" ]
Base method to send a request to Quora API. @param [required, string] supported field (or multiple fields CSV) to retrieve @param [optional, bool] filter if field is a key in result hash, only this value is returned
[ "Base", "method", "to", "send", "a", "request", "to", "Quora", "API", "." ]
eb09bbb70aef5c5c77887dc0b689ccb422fba49f
https://github.com/juandebravo/quora-client/blob/eb09bbb70aef5c5c77887dc0b689ccb422fba49f/lib/quora/client.rb#L83-L95
train
juandebravo/quora-client
lib/quora/client.rb
Quora.Client.method_missing
def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^get_[\w]+/ self.class.send :define_method, method_id do field = method_id.to_s[4..-1] get(field) end self.send(method_id) else super end end
ruby
def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^get_[\w]+/ self.class.send :define_method, method_id do field = method_id.to_s[4..-1] get(field) end self.send(method_id) else super end end
[ "def", "method_missing", "(", "method_id", ",", "*", "arguments", ",", "&", "block", ")", "if", "method_id", ".", "to_s", "=~", "/", "\\w", "/", "self", ".", "class", ".", "send", ":define_method", ",", "method_id", "do", "field", "=", "method_id", ".", "to_s", "[", "4", "..", "-", "1", "]", "get", "(", "field", ")", "end", "self", ".", "send", "(", "method_id", ")", "else", "super", "end", "end" ]
Override method_missing so any method that starts with "get_" will be defined. i.e. client.get_profile will generate => def get_profile get("profile") end
[ "Override", "method_missing", "so", "any", "method", "that", "starts", "with", "get_", "will", "be", "defined", "." ]
eb09bbb70aef5c5c77887dc0b689ccb422fba49f
https://github.com/juandebravo/quora-client/blob/eb09bbb70aef5c5c77887dc0b689ccb422fba49f/lib/quora/client.rb#L131-L141
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/controllers.rb
UnionStationHooks.RequestReporter.log_controller_action_block
def log_controller_action_block(options = {}) if null? do_nothing_on_null(:log_controller_action_block) yield else build_full_controller_action_string(options) has_error = true begin_time = UnionStationHooks.now begin result = yield has_error = false result ensure log_controller_action( options.merge( :begin_time => begin_time, :end_time => UnionStationHooks.now, :has_error => has_error ) ) end end end
ruby
def log_controller_action_block(options = {}) if null? do_nothing_on_null(:log_controller_action_block) yield else build_full_controller_action_string(options) has_error = true begin_time = UnionStationHooks.now begin result = yield has_error = false result ensure log_controller_action( options.merge( :begin_time => begin_time, :end_time => UnionStationHooks.now, :has_error => has_error ) ) end end end
[ "def", "log_controller_action_block", "(", "options", "=", "{", "}", ")", "if", "null?", "do_nothing_on_null", "(", ":log_controller_action_block", ")", "yield", "else", "build_full_controller_action_string", "(", "options", ")", "has_error", "=", "true", "begin_time", "=", "UnionStationHooks", ".", "now", "begin", "result", "=", "yield", "has_error", "=", "false", "result", "ensure", "log_controller_action", "(", "options", ".", "merge", "(", ":begin_time", "=>", "begin_time", ",", ":end_time", "=>", "UnionStationHooks", ".", "now", ",", ":has_error", "=>", "has_error", ")", ")", "end", "end", "end" ]
Logging controller-related information Logs that you are calling a web framework controller action. Of course, you should only call this if your web framework has the concept of controller actions. For example Rails does, but Sinatra and Grape don't. This form takes an options hash as well as a block. You can pass additional information about the web framework controller action, which will be logged. The block is expected to perform the actual request handling. When the block returns, timing information about the block is automatically logged. See also {#log_controller_action} for a form that doesn't expect a block. The `union_station_hooks_rails` gem automatically calls this for you if your application is a Rails app. @yield The given block is expected to perform request handling. @param [Hash] options Information about the controller action. All options are optional. @option options [String] :controller_name The controller's name, e.g. `PostsController`. @option options [String] :action_name The controller action's name, e.g. `create`. @option options [String] :method The HTTP method that the web framework thinks this request should have, e.g. `GET` and `PUT`. The main use case for this option is to support Rails's HTTP verb emulation. Rails uses a parameter named [`_method`](http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark) to emulate HTTP verbs besides GET and POST. Other web frameworks may have a similar mechanism. @return The return value of the block. @example Rails example # This example shows what to put inside a Rails controller action # method. Note that all of this is automatically done for you if you # use the union_station_hooks_rails gem. options = { :controller_name => self.class.name, :action_name => action_name, :method => request.request_method } reporter.log_controller_action_block(options) do do_some_request_processing_here end
[ "Logging", "controller", "-", "related", "information", "Logs", "that", "you", "are", "calling", "a", "web", "framework", "controller", "action", ".", "Of", "course", "you", "should", "only", "call", "this", "if", "your", "web", "framework", "has", "the", "concept", "of", "controller", "actions", ".", "For", "example", "Rails", "does", "but", "Sinatra", "and", "Grape", "don", "t", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/controllers.rb#L75-L97
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/controllers.rb
UnionStationHooks.RequestReporter.log_controller_action
def log_controller_action(options) return do_nothing_on_null(:log_controller_action) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) if options[:controller_name] build_full_controller_action_string(options) @transaction.message("Controller action: #{@controller_action}") end if options[:method] @transaction.message("Application request method: #{options[:method]}") end @transaction.log_activity('framework request processing', options[:begin_time], options[:end_time], nil, options[:has_error]) end
ruby
def log_controller_action(options) return do_nothing_on_null(:log_controller_action) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) if options[:controller_name] build_full_controller_action_string(options) @transaction.message("Controller action: #{@controller_action}") end if options[:method] @transaction.message("Application request method: #{options[:method]}") end @transaction.log_activity('framework request processing', options[:begin_time], options[:end_time], nil, options[:has_error]) end
[ "def", "log_controller_action", "(", "options", ")", "return", "do_nothing_on_null", "(", ":log_controller_action", ")", "if", "null?", "Utils", ".", "require_key", "(", "options", ",", ":begin_time", ")", "Utils", ".", "require_key", "(", "options", ",", ":end_time", ")", "if", "options", "[", ":controller_name", "]", "build_full_controller_action_string", "(", "options", ")", "@transaction", ".", "message", "(", "\"Controller action: #{@controller_action}\"", ")", "end", "if", "options", "[", ":method", "]", "@transaction", ".", "message", "(", "\"Application request method: #{options[:method]}\"", ")", "end", "@transaction", ".", "log_activity", "(", "'framework request processing'", ",", "options", "[", ":begin_time", "]", ",", "options", "[", ":end_time", "]", ",", "nil", ",", "options", "[", ":has_error", "]", ")", "end" ]
Logs that you are calling a web framework controller action. Of course, you should only call this if your web framework has the concept of controller actions. For example Rails does, but Sinatra and Grape don't. You can pass additional information about the web framework controller action, which will be logged. Unlike {#log_controller_action_block}, this form does not expect a block. However, you are expected to pass timing information to the options hash. The `union_station_hooks_rails` gem automatically calls {#log_controller_action_block} for you if your application is a Rails app. @param [Hash] options Information about the controller action. @option options [String] :controller_name (optional) The controller's name, e.g. `PostsController`. @option options [String] :action_name (optional if :controller_name isn't set) The controller action's name, e.g. `create`. @option options [String] :method (optional) The HTTP method that the web framework thinks this request should have, e.g. `GET` and `PUT`. The main use case for this option is to support Rails's HTTP verb emulation. Rails uses a parameter named [`_method`](http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark) to emulate HTTP verbs besides GET and POST. Other web frameworks may have a similar mechanism. @option options [TimePoint or Time] :begin_time The time at which the controller action begun. See {UnionStationHooks.now} to learn more. @option options [TimePoint or Time] :end_time The time at which the controller action ended. See {UnionStationHooks.now} to learn more. @option options [Boolean] :has_error (optional) Whether an uncaught exception occurred during the request. Default: false. @example # This example shows what to put inside a Rails controller action # method. Note that all of this is automatically done for you if you # use the union_station_hooks_rails gem. options = { :controller_name => self.class.name, :action_name => action_name, :method => request.request_method, :begin_time => UnionStationHooks.now } begin do_some_request_processing_here rescue Exception options[:has_error] = true raise ensure options[:end_time] = UnionStationHooks.now reporter.log_controller_action(options) end
[ "Logs", "that", "you", "are", "calling", "a", "web", "framework", "controller", "action", ".", "Of", "course", "you", "should", "only", "call", "this", "if", "your", "web", "framework", "has", "the", "concept", "of", "controller", "actions", ".", "For", "example", "Rails", "does", "but", "Sinatra", "and", "Grape", "don", "t", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/controllers.rb#L153-L167
train
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.remove_vertex
def remove_vertex(vertex) # The vertex must exist raise "not a vertex" unless vertex.is_a?(Vertex) if !vertex raise "Vertex does not exist" # The vertex must not be connected to anything elsif !vertex.connections.empty? raise "Vertex has edges. Break them first." # If it exists and isn't connected, delete it else @vertices.delete(vertex) end end
ruby
def remove_vertex(vertex) # The vertex must exist raise "not a vertex" unless vertex.is_a?(Vertex) if !vertex raise "Vertex does not exist" # The vertex must not be connected to anything elsif !vertex.connections.empty? raise "Vertex has edges. Break them first." # If it exists and isn't connected, delete it else @vertices.delete(vertex) end end
[ "def", "remove_vertex", "(", "vertex", ")", "raise", "\"not a vertex\"", "unless", "vertex", ".", "is_a?", "(", "Vertex", ")", "if", "!", "vertex", "raise", "\"Vertex does not exist\"", "elsif", "!", "vertex", ".", "connections", ".", "empty?", "raise", "\"Vertex has edges. Break them first.\"", "else", "@vertices", ".", "delete", "(", "vertex", ")", "end", "end" ]
Remove a vertex
[ "Remove", "a", "vertex" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L31-L43
train
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.make_connection
def make_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "already connected" if is_connected?(v1, v2) # Make new edge edge = Edge.new(v1, v2) # Connect the two using the vertex method "connect" v1.connect(v2, edge) v2.connect(v1, edge) # Add to edge catalog @edges << edge edge end
ruby
def make_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "already connected" if is_connected?(v1, v2) # Make new edge edge = Edge.new(v1, v2) # Connect the two using the vertex method "connect" v1.connect(v2, edge) v2.connect(v1, edge) # Add to edge catalog @edges << edge edge end
[ "def", "make_connection", "(", "v1", ",", "v2", ")", "raise", "\"not a vertex\"", "unless", "v1", ".", "is_a?", "(", "Vertex", ")", "&&", "v2", ".", "is_a?", "(", "Vertex", ")", "raise", "\"already connected\"", "if", "is_connected?", "(", "v1", ",", "v2", ")", "edge", "=", "Edge", ".", "new", "(", "v1", ",", "v2", ")", "v1", ".", "connect", "(", "v2", ",", "edge", ")", "v2", ".", "connect", "(", "v1", ",", "edge", ")", "@edges", "<<", "edge", "edge", "end" ]
Make an edge between two vertices
[ "Make", "an", "edge", "between", "two", "vertices" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L46-L58
train
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.find_connection
def find_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "Vertices not connected" if !is_connected?(v1, v2) connection = v1.edges.select {|edge| edge.connection.include?(v2)} raise "Error finding connection" if connection.length > 1 connection.first end
ruby
def find_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "Vertices not connected" if !is_connected?(v1, v2) connection = v1.edges.select {|edge| edge.connection.include?(v2)} raise "Error finding connection" if connection.length > 1 connection.first end
[ "def", "find_connection", "(", "v1", ",", "v2", ")", "raise", "\"not a vertex\"", "unless", "v1", ".", "is_a?", "(", "Vertex", ")", "&&", "v2", ".", "is_a?", "(", "Vertex", ")", "raise", "\"Vertices not connected\"", "if", "!", "is_connected?", "(", "v1", ",", "v2", ")", "connection", "=", "v1", ".", "edges", ".", "select", "{", "|", "edge", "|", "edge", ".", "connection", ".", "include?", "(", "v2", ")", "}", "raise", "\"Error finding connection\"", "if", "connection", ".", "length", ">", "1", "connection", ".", "first", "end" ]
Find the edge connecting two vertices
[ "Find", "the", "edge", "connecting", "two", "vertices" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L61-L67
train
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.is_connected?
def is_connected?(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) v1.connections.include?(v2) end
ruby
def is_connected?(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) v1.connections.include?(v2) end
[ "def", "is_connected?", "(", "v1", ",", "v2", ")", "raise", "\"not a vertex\"", "unless", "v1", ".", "is_a?", "(", "Vertex", ")", "&&", "v2", ".", "is_a?", "(", "Vertex", ")", "v1", ".", "connections", ".", "include?", "(", "v2", ")", "end" ]
Returns whether two vertices are connected
[ "Returns", "whether", "two", "vertices", "are", "connected" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L70-L73
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/class_methods.rb
ActsAsSolr.ClassMethods.find_by_solr
def find_by_solr(query, options={}) data = parse_query(query, options) return parse_results(data, options) end
ruby
def find_by_solr(query, options={}) data = parse_query(query, options) return parse_results(data, options) end
[ "def", "find_by_solr", "(", "query", ",", "options", "=", "{", "}", ")", "data", "=", "parse_query", "(", "query", ",", "options", ")", "return", "parse_results", "(", "data", ",", "options", ")", "end" ]
Finds instances of a model. Terms are ANDed by default, can be overwritten by using OR between terms Here's a sample (untested) code for your controller: def search results = Book.find_by_solr params[:query] end For specific fields searching use :filter_queries options ====options: offset:: - The first document to be retrieved (offset) page:: - The page to be retrieved limit:: - The number of rows per page per_page:: - Alias for limit filter_queries:: - Use solr filter queries to sort by fields Book.find_by_solr 'ruby', :filter_queries => ['price:5'] sort:: - Orders (sort by) the result set using a given criteria: Book.find_by_solr 'ruby', :sort => 'description asc' field_types:: This option is deprecated and will be obsolete by version 1.0. There's no need to specify the :field_types anymore when doing a search in a model that specifies a field type for a field. The field types are automatically traced back when they're included. class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => :range_float}] end facets:: This option argument accepts the following arguments: fields:: The fields to be included in the faceted search (Solr's facet.field) query:: The queries to be included in the faceted search (Solr's facet.query) zeros:: Display facets with count of zero. (true|false) sort:: Sorts the faceted resuls by highest to lowest count. (true|false) browse:: This is where the 'drill-down' of the facets work. Accepts an array of fields in the format "facet_field:term" mincount:: Replacement for zeros (it has been deprecated in Solr). Specifies the minimum count necessary for a facet field to be returned. (Solr's facet.mincount) Overrides :zeros if it is specified. Default is 0. dates:: Run date faceted queries using the following arguments: fields:: The fields to be included in the faceted date search (Solr's facet.date). It may be either a String/Symbol or Hash. If it's a hash the options are the same as date_facets minus the fields option (i.e., :start:, :end, :gap, :other, :between). These options if provided will override the base options. (Solr's f.<field_name>.date.<key>=<value>). start:: The lower bound for the first date range for all Date Faceting. Required if :fields is present end:: The upper bound for the last date range for all Date Faceting. Required if :fields is prsent gap:: The size of each date range expressed as an interval to be added to the lower bound using the DateMathParser syntax. Required if :fields is prsent hardend:: A Boolean parameter instructing Solr what do do in the event that facet.date.gap does not divide evenly between facet.date.start and facet.date.end. other:: This param indicates that in addition to the counts for each date range constraint between facet.date.start and facet.date.end, other counds should be calculated. May specify more then one in an Array. The possible options are: before:: - all records with lower bound less than start after:: - all records with upper bound greater than end between:: - all records with field values between start and end none:: - compute no other bounds (useful in per field assignment) all:: - shortcut for before, after, and between filter:: Similar to :query option provided by :facets, in that accepts an array of of date queries to limit results. Can not be used as a part of a :field hash. This is the only option that can be used if :fields is not present. Example: Electronic.find_by_solr "memory", :facets => {:zeros => false, :sort => true, :query => ["price:[* TO 200]", "price:[200 TO 500]", "price:[500 TO *]"], :fields => [:category, :manufacturer], :browse => ["category:Memory","manufacturer:Someone"]} Examples of date faceting: basic: Electronic.find_by_solr "memory", :facets => {:dates => {:fields => [:updated_at, :created_at], :start => 'NOW-10YEARS/DAY', :end => 'NOW/DAY', :gap => '+2YEARS', :other => :before}} advanced: Electronic.find_by_solr "memory", :facets => {:dates => {:fields => [:updated_at, {:created_at => {:start => 'NOW-20YEARS/DAY', :end => 'NOW-10YEARS/DAY', :other => [:before, :after]} }], :start => 'NOW-10YEARS/DAY', :end => 'NOW/DAY', :other => :before, :filter => ["created_at:[NOW-10YEARS/DAY TO NOW/DAY]", "updated_at:[NOW-1YEAR/DAY TO NOW/DAY]"]}} filter only: Electronic.find_by_solr "memory", :facets => {:dates => {:filter => "updated_at:[NOW-1YEAR/DAY TO NOW/DAY]"}} scores:: If set to true this will return the score as a 'solr_score' attribute for each one of the instances found. Does not currently work with find_id_by_solr books = Book.find_by_solr 'ruby OR splinter', :scores => true books.records.first.solr_score => 1.21321397 books.records.last.solr_score => 0.12321548 lazy:: If set to true the search will return objects that will touch the database when you ask for one of their attributes for the first time. Useful when you're using fragment caching based solely on types and ids. relevance:: Sets fields relevance Book.find_by_solr "zidane", :relevance => {:title => 5, :author => 2}
[ "Finds", "instances", "of", "a", "model", ".", "Terms", "are", "ANDed", "by", "default", "can", "be", "overwritten", "by", "using", "OR", "between", "terms" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/class_methods.rb#L121-L124
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/class_methods.rb
ActsAsSolr.ClassMethods.rebuild_solr_index
def rebuild_solr_index(batch_size=300, options = {}, &finder) finder ||= lambda do |ar, sql_options| ar.all sql_options.merge!({:order => self.primary_key, :include => configuration[:solr_includes].keys}) end start_time = Time.now options[:offset] ||= 0 options[:threads] ||= 2 options[:delayed_job] &= defined?(Delayed::Job) if batch_size > 0 items_processed = 0 offset = options[:offset] end_reached = false threads = [] mutex = Mutex.new queue = Queue.new loop do items = finder.call(self, {:limit => batch_size, :offset => offset}) add_batch = items.collect { |content| content.to_solr_doc } offset += items.size end_reached = items.size == 0 break if end_reached if options[:threads] == threads.size threads.first.join threads.shift end queue << [items, add_batch] threads << Thread.new do iteration_start = Time.now iteration_items, iteration_add_batch = queue.pop(true) if options[:delayed_job] delay.solr_add iteration_add_batch else solr_add iteration_add_batch solr_commit end last_id = iteration_items.last.id time_so_far = Time.now - start_time iteration_time = Time.now - iteration_start mutex.synchronize do items_processed += iteration_items.size if options[:delayed_job] logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been sent to Delayed::Job in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" else logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" end end end end solr_commit if options[:delayed_job] threads.each{ |t| t.join } else items = finder.call(self, {}) items.each { |content| content.solr_save } items_processed = items.size end if items_processed > 0 solr_optimize time_elapsed = Time.now - start_time logger.info "Index for #{self.name} has been rebuilt (took #{'%.3f' % time_elapsed}s)" else "Nothing to index for #{self.name}" end end
ruby
def rebuild_solr_index(batch_size=300, options = {}, &finder) finder ||= lambda do |ar, sql_options| ar.all sql_options.merge!({:order => self.primary_key, :include => configuration[:solr_includes].keys}) end start_time = Time.now options[:offset] ||= 0 options[:threads] ||= 2 options[:delayed_job] &= defined?(Delayed::Job) if batch_size > 0 items_processed = 0 offset = options[:offset] end_reached = false threads = [] mutex = Mutex.new queue = Queue.new loop do items = finder.call(self, {:limit => batch_size, :offset => offset}) add_batch = items.collect { |content| content.to_solr_doc } offset += items.size end_reached = items.size == 0 break if end_reached if options[:threads] == threads.size threads.first.join threads.shift end queue << [items, add_batch] threads << Thread.new do iteration_start = Time.now iteration_items, iteration_add_batch = queue.pop(true) if options[:delayed_job] delay.solr_add iteration_add_batch else solr_add iteration_add_batch solr_commit end last_id = iteration_items.last.id time_so_far = Time.now - start_time iteration_time = Time.now - iteration_start mutex.synchronize do items_processed += iteration_items.size if options[:delayed_job] logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been sent to Delayed::Job in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" else logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" end end end end solr_commit if options[:delayed_job] threads.each{ |t| t.join } else items = finder.call(self, {}) items.each { |content| content.solr_save } items_processed = items.size end if items_processed > 0 solr_optimize time_elapsed = Time.now - start_time logger.info "Index for #{self.name} has been rebuilt (took #{'%.3f' % time_elapsed}s)" else "Nothing to index for #{self.name}" end end
[ "def", "rebuild_solr_index", "(", "batch_size", "=", "300", ",", "options", "=", "{", "}", ",", "&", "finder", ")", "finder", "||=", "lambda", "do", "|", "ar", ",", "sql_options", "|", "ar", ".", "all", "sql_options", ".", "merge!", "(", "{", ":order", "=>", "self", ".", "primary_key", ",", ":include", "=>", "configuration", "[", ":solr_includes", "]", ".", "keys", "}", ")", "end", "start_time", "=", "Time", ".", "now", "options", "[", ":offset", "]", "||=", "0", "options", "[", ":threads", "]", "||=", "2", "options", "[", ":delayed_job", "]", "&=", "defined?", "(", "Delayed", "::", "Job", ")", "if", "batch_size", ">", "0", "items_processed", "=", "0", "offset", "=", "options", "[", ":offset", "]", "end_reached", "=", "false", "threads", "=", "[", "]", "mutex", "=", "Mutex", ".", "new", "queue", "=", "Queue", ".", "new", "loop", "do", "items", "=", "finder", ".", "call", "(", "self", ",", "{", ":limit", "=>", "batch_size", ",", ":offset", "=>", "offset", "}", ")", "add_batch", "=", "items", ".", "collect", "{", "|", "content", "|", "content", ".", "to_solr_doc", "}", "offset", "+=", "items", ".", "size", "end_reached", "=", "items", ".", "size", "==", "0", "break", "if", "end_reached", "if", "options", "[", ":threads", "]", "==", "threads", ".", "size", "threads", ".", "first", ".", "join", "threads", ".", "shift", "end", "queue", "<<", "[", "items", ",", "add_batch", "]", "threads", "<<", "Thread", ".", "new", "do", "iteration_start", "=", "Time", ".", "now", "iteration_items", ",", "iteration_add_batch", "=", "queue", ".", "pop", "(", "true", ")", "if", "options", "[", ":delayed_job", "]", "delay", ".", "solr_add", "iteration_add_batch", "else", "solr_add", "iteration_add_batch", "solr_commit", "end", "last_id", "=", "iteration_items", ".", "last", ".", "id", "time_so_far", "=", "Time", ".", "now", "-", "start_time", "iteration_time", "=", "Time", ".", "now", "-", "iteration_start", "mutex", ".", "synchronize", "do", "items_processed", "+=", "iteration_items", ".", "size", "if", "options", "[", ":delayed_job", "]", "logger", ".", "info", "\"#{Process.pid}: #{items_processed} items for #{self.name} have been sent to Delayed::Job in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}\"", "else", "logger", ".", "info", "\"#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}\"", "end", "end", "end", "end", "solr_commit", "if", "options", "[", ":delayed_job", "]", "threads", ".", "each", "{", "|", "t", "|", "t", ".", "join", "}", "else", "items", "=", "finder", ".", "call", "(", "self", ",", "{", "}", ")", "items", ".", "each", "{", "|", "content", "|", "content", ".", "solr_save", "}", "items_processed", "=", "items", ".", "size", "end", "if", "items_processed", ">", "0", "solr_optimize", "time_elapsed", "=", "Time", ".", "now", "-", "start_time", "logger", ".", "info", "\"Index for #{self.name} has been rebuilt (took #{'%.3f' % time_elapsed}s)\"", "else", "\"Nothing to index for #{self.name}\"", "end", "end" ]
It's used to rebuild the Solr index for a specific model. Book.rebuild_solr_index If batch_size is greater than 0, adds will be done in batches. NOTE: If using sqlserver, be sure to use a finder with an explicit order. Non-edge versions of rails do not handle pagination correctly for sqlserver without an order clause. If a finder block is given, it will be called to retrieve the items to index. This can be very useful for things such as updating based on conditions or using eager loading for indexed associations.
[ "It", "s", "used", "to", "rebuild", "the", "Solr", "index", "for", "a", "specific", "model", ".", "Book", ".", "rebuild_solr_index" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/class_methods.rb#L205-L274
train
grosser/s3_meta_sync
lib/s3_meta_sync/syncer.rb
S3MetaSync.Syncer.delete_old_temp_folders
def delete_old_temp_folders path = File.join(Dir.tmpdir, STAGING_AREA_PREFIX + '*') day = 24 * 60 * 60 dirs = Dir.glob(path) dirs.select! { |dir| Time.now.utc - File.ctime(dir).utc > day } # only stale ones removed = dirs.each { |dir| FileUtils.rm_rf(dir) } log "Removed #{removed} old temp folder(s)" if removed.count > 0 end
ruby
def delete_old_temp_folders path = File.join(Dir.tmpdir, STAGING_AREA_PREFIX + '*') day = 24 * 60 * 60 dirs = Dir.glob(path) dirs.select! { |dir| Time.now.utc - File.ctime(dir).utc > day } # only stale ones removed = dirs.each { |dir| FileUtils.rm_rf(dir) } log "Removed #{removed} old temp folder(s)" if removed.count > 0 end
[ "def", "delete_old_temp_folders", "path", "=", "File", ".", "join", "(", "Dir", ".", "tmpdir", ",", "STAGING_AREA_PREFIX", "+", "'*'", ")", "day", "=", "24", "*", "60", "*", "60", "dirs", "=", "Dir", ".", "glob", "(", "path", ")", "dirs", ".", "select!", "{", "|", "dir", "|", "Time", ".", "now", ".", "utc", "-", "File", ".", "ctime", "(", "dir", ")", ".", "utc", ">", "day", "}", "removed", "=", "dirs", ".", "each", "{", "|", "dir", "|", "FileUtils", ".", "rm_rf", "(", "dir", ")", "}", "log", "\"Removed #{removed} old temp folder(s)\"", "if", "removed", ".", "count", ">", "0", "end" ]
Sometimes SIGTERM causes Dir.mktmpdir to not properly delete the temp folder Remove 1 day old folders
[ "Sometimes", "SIGTERM", "causes", "Dir", ".", "mktmpdir", "to", "not", "properly", "delete", "the", "temp", "folder", "Remove", "1", "day", "old", "folders" ]
52178496c15aa9b1d868064cbf72e452193d757e
https://github.com/grosser/s3_meta_sync/blob/52178496c15aa9b1d868064cbf72e452193d757e/lib/s3_meta_sync/syncer.rb#L97-L106
train
coupler/linkage
lib/linkage/field_set.rb
Linkage.FieldSet.fetch_key
def fetch_key(key) string_key = key.to_s keys.detect { |k| k.to_s.casecmp(string_key) == 0 } end
ruby
def fetch_key(key) string_key = key.to_s keys.detect { |k| k.to_s.casecmp(string_key) == 0 } end
[ "def", "fetch_key", "(", "key", ")", "string_key", "=", "key", ".", "to_s", "keys", ".", "detect", "{", "|", "k", "|", "k", ".", "to_s", ".", "casecmp", "(", "string_key", ")", "==", "0", "}", "end" ]
Returns a key that matches the parameter in a case-insensitive manner. @param key [String, Symbol] @return [Symbol]
[ "Returns", "a", "key", "that", "matches", "the", "parameter", "in", "a", "case", "-", "insensitive", "manner", "." ]
2f208ae0709a141a6a8e5ba3bc6914677e986cb0
https://github.com/coupler/linkage/blob/2f208ae0709a141a6a8e5ba3bc6914677e986cb0/lib/linkage/field_set.rb#L38-L41
train
appoxy/simple_record
lib/simple_record/translations.rb
SimpleRecord.Translations.ruby_to_sdb
def ruby_to_sdb(name, value) return nil if value.nil? name = name.to_s # puts "Converting #{name} to sdb value=#{value}" # puts "atts_local=" + defined_attributes_local.inspect att_meta = get_att_meta(name) if value.is_a? Array ret = value.collect { |x| ruby_to_string_val(att_meta, x) } else ret = ruby_to_string_val(att_meta, value) end unless value.blank? if att_meta.options if att_meta.options[:encrypted] # puts "ENCRYPTING #{name} value #{value}" ret = Translations.encrypt(ret, att_meta.options[:encrypted]) # puts 'encrypted value=' + ret.to_s end if att_meta.options[:hashed] # puts "hashing #{name}" ret = Translations.pass_hash(ret) # puts "hashed value=" + ret.inspect end end end return ret end
ruby
def ruby_to_sdb(name, value) return nil if value.nil? name = name.to_s # puts "Converting #{name} to sdb value=#{value}" # puts "atts_local=" + defined_attributes_local.inspect att_meta = get_att_meta(name) if value.is_a? Array ret = value.collect { |x| ruby_to_string_val(att_meta, x) } else ret = ruby_to_string_val(att_meta, value) end unless value.blank? if att_meta.options if att_meta.options[:encrypted] # puts "ENCRYPTING #{name} value #{value}" ret = Translations.encrypt(ret, att_meta.options[:encrypted]) # puts 'encrypted value=' + ret.to_s end if att_meta.options[:hashed] # puts "hashing #{name}" ret = Translations.pass_hash(ret) # puts "hashed value=" + ret.inspect end end end return ret end
[ "def", "ruby_to_sdb", "(", "name", ",", "value", ")", "return", "nil", "if", "value", ".", "nil?", "name", "=", "name", ".", "to_s", "att_meta", "=", "get_att_meta", "(", "name", ")", "if", "value", ".", "is_a?", "Array", "ret", "=", "value", ".", "collect", "{", "|", "x", "|", "ruby_to_string_val", "(", "att_meta", ",", "x", ")", "}", "else", "ret", "=", "ruby_to_string_val", "(", "att_meta", ",", "value", ")", "end", "unless", "value", ".", "blank?", "if", "att_meta", ".", "options", "if", "att_meta", ".", "options", "[", ":encrypted", "]", "ret", "=", "Translations", ".", "encrypt", "(", "ret", ",", "att_meta", ".", "options", "[", ":encrypted", "]", ")", "end", "if", "att_meta", ".", "options", "[", ":hashed", "]", "ret", "=", "Translations", ".", "pass_hash", "(", "ret", ")", "end", "end", "end", "return", "ret", "end" ]
Time to second precision
[ "Time", "to", "second", "precision" ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/translations.rb#L22-L53
train
appoxy/simple_record
lib/simple_record/translations.rb
SimpleRecord.Translations.sdb_to_ruby
def sdb_to_ruby(name, value) # puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s return nil if value.nil? att_meta = get_att_meta(name) if att_meta.options if att_meta.options[:encrypted] value = Translations.decrypt(value, att_meta.options[:encrypted]) end if att_meta.options[:hashed] return PasswordHashed.new(value) end end if !has_id_on_end(name) && att_meta.type == :belongs_to class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length] # Camelize classnames with underscores (ie my_model.rb --> MyModel) class_name = class_name.camelize # puts "attr=" + @attributes[arg_id].inspect # puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil? ret = nil arg_id = name.to_s + '_id' arg_id_val = send("#{arg_id}") if arg_id_val if !cache_store.nil? # arg_id_val = @attributes[arg_id][0] cache_key = self.class.cache_key(class_name, arg_id_val) # puts 'cache_key=' + cache_key ret = cache_store.read(cache_key) # puts 'belongs_to incache=' + ret.inspect end if ret.nil? to_eval = "#{class_name}.find('#{arg_id_val}')" # puts 'to eval=' + to_eval begin ret = eval(to_eval) # (defined? #{arg}_id) rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex if ex.message.include? "Couldn't find" ret = RemoteNil.new else raise ex end end end end value = ret else if value.is_a? Array value = value.collect { |x| string_val_to_ruby(att_meta, x) } else value = string_val_to_ruby(att_meta, value) end end value end
ruby
def sdb_to_ruby(name, value) # puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s return nil if value.nil? att_meta = get_att_meta(name) if att_meta.options if att_meta.options[:encrypted] value = Translations.decrypt(value, att_meta.options[:encrypted]) end if att_meta.options[:hashed] return PasswordHashed.new(value) end end if !has_id_on_end(name) && att_meta.type == :belongs_to class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length] # Camelize classnames with underscores (ie my_model.rb --> MyModel) class_name = class_name.camelize # puts "attr=" + @attributes[arg_id].inspect # puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil? ret = nil arg_id = name.to_s + '_id' arg_id_val = send("#{arg_id}") if arg_id_val if !cache_store.nil? # arg_id_val = @attributes[arg_id][0] cache_key = self.class.cache_key(class_name, arg_id_val) # puts 'cache_key=' + cache_key ret = cache_store.read(cache_key) # puts 'belongs_to incache=' + ret.inspect end if ret.nil? to_eval = "#{class_name}.find('#{arg_id_val}')" # puts 'to eval=' + to_eval begin ret = eval(to_eval) # (defined? #{arg}_id) rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex if ex.message.include? "Couldn't find" ret = RemoteNil.new else raise ex end end end end value = ret else if value.is_a? Array value = value.collect { |x| string_val_to_ruby(att_meta, x) } else value = string_val_to_ruby(att_meta, value) end end value end
[ "def", "sdb_to_ruby", "(", "name", ",", "value", ")", "return", "nil", "if", "value", ".", "nil?", "att_meta", "=", "get_att_meta", "(", "name", ")", "if", "att_meta", ".", "options", "if", "att_meta", ".", "options", "[", ":encrypted", "]", "value", "=", "Translations", ".", "decrypt", "(", "value", ",", "att_meta", ".", "options", "[", ":encrypted", "]", ")", "end", "if", "att_meta", ".", "options", "[", ":hashed", "]", "return", "PasswordHashed", ".", "new", "(", "value", ")", "end", "end", "if", "!", "has_id_on_end", "(", "name", ")", "&&", "att_meta", ".", "type", "==", ":belongs_to", "class_name", "=", "att_meta", ".", "options", "[", ":class_name", "]", "||", "name", ".", "to_s", "[", "0", "...", "1", "]", ".", "capitalize", "+", "name", ".", "to_s", "[", "1", "...", "name", ".", "to_s", ".", "length", "]", "class_name", "=", "class_name", ".", "camelize", "ret", "=", "nil", "arg_id", "=", "name", ".", "to_s", "+", "'_id'", "arg_id_val", "=", "send", "(", "\"#{arg_id}\"", ")", "if", "arg_id_val", "if", "!", "cache_store", ".", "nil?", "cache_key", "=", "self", ".", "class", ".", "cache_key", "(", "class_name", ",", "arg_id_val", ")", "ret", "=", "cache_store", ".", "read", "(", "cache_key", ")", "end", "if", "ret", ".", "nil?", "to_eval", "=", "\"#{class_name}.find('#{arg_id_val}')\"", "begin", "ret", "=", "eval", "(", "to_eval", ")", "rescue", "SimpleRecord", "::", "ActiveSdb", "::", "ActiveSdbError", "=>", "ex", "if", "ex", ".", "message", ".", "include?", "\"Couldn't find\"", "ret", "=", "RemoteNil", ".", "new", "else", "raise", "ex", "end", "end", "end", "end", "value", "=", "ret", "else", "if", "value", ".", "is_a?", "Array", "value", "=", "value", ".", "collect", "{", "|", "x", "|", "string_val_to_ruby", "(", "att_meta", ",", "x", ")", "}", "else", "value", "=", "string_val_to_ruby", "(", "att_meta", ",", "value", ")", "end", "end", "value", "end" ]
Convert value from SimpleDB String version to real ruby value.
[ "Convert", "value", "from", "SimpleDB", "String", "version", "to", "real", "ruby", "value", "." ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/translations.rb#L57-L113
train
jimmyz/familysearch-rb
lib/familysearch/url_template.rb
FamilySearch.URLTemplate.head
def head(template_values) raise FamilySearch::Error::MethodNotAllowed unless allow.include?('head') template_values = validate_values(template_values) t = Addressable::Template.new(@template) url = t.expand(template_values).to_s @client.head url end
ruby
def head(template_values) raise FamilySearch::Error::MethodNotAllowed unless allow.include?('head') template_values = validate_values(template_values) t = Addressable::Template.new(@template) url = t.expand(template_values).to_s @client.head url end
[ "def", "head", "(", "template_values", ")", "raise", "FamilySearch", "::", "Error", "::", "MethodNotAllowed", "unless", "allow", ".", "include?", "(", "'head'", ")", "template_values", "=", "validate_values", "(", "template_values", ")", "t", "=", "Addressable", "::", "Template", ".", "new", "(", "@template", ")", "url", "=", "t", ".", "expand", "(", "template_values", ")", ".", "to_s", "@client", ".", "head", "url", "end" ]
Calls HTTP HEAD on the URL template. It takes the +template_values+ hash and merges the values into the template. A template will contain a URL like this: https://sandbox.familysearch.org/platform/tree/persons-with-relationships{?access_token,person} or https://sandbox.familysearch.org/platform/tree/persons/{pid}/matches{?access_token} The {?person} type attributes in the first example will be passed as querystring parameters. These will automatically be URL Encoded by the underlying Faraday library that handles the HTTP request. The {pid} type attibutes will simply be substituted into the URL. *Note*: The +access_token+ parameter doesn't need to be passed here. This should be handled by the FamilySearch::Client's Authorization header. *Args* : - +template_values+: A Hash object containing the values for the items in the URL template. For example, if the URL is: https://sandbox.familysearch.org/platform/tree/persons-with-relationships{?access_token,person} then you would pass a hash like this: :person => 'KWQS-BBQ' or 'person' => 'KWQS-BBQ' *Returns* : - +Faraday::Response+ object. This object contains methods +body+, +headers+, and +status+. +body+ should contain a Hash of the parsed result of the request. *Raises* : - +FamilySearch::Error::MethodNotAllowed+: if you call +head+ for a template that doesn't allow HEAD method.
[ "Calls", "HTTP", "HEAD", "on", "the", "URL", "template", ".", "It", "takes", "the", "+", "template_values", "+", "hash", "and", "merges", "the", "values", "into", "the", "template", "." ]
be6ae2ea6f4ad4734a3355fa5f8fdf8d33f0c7a1
https://github.com/jimmyz/familysearch-rb/blob/be6ae2ea6f4ad4734a3355fa5f8fdf8d33f0c7a1/lib/familysearch/url_template.rb#L122-L128
train
LAS-IT/ps_utilities
lib/ps_utilities/pre_built_get.rb
PsUtilities.PreBuiltGet.get_one_student
def get_one_student(params) # api_path = "/ws/v1/district/student/{dcid}?expansions=school_enrollment,contact&q=student_username==xxxxxx237" ps_dcid = params[:dcid] || params[:dc_id] || params[:id] api_path = "/ws/v1/student/#{ps_dcid.to_i}" options = { query: { "extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields", "expansions" => "demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch" } } return {"errorMessage"=>{"message"=>"A valid dcid must be entered."}} if "#{ps_dcid.to_i}".eql? "0" answer = api(:get, api_path, options) return { student: (answer["student"] || []) } if answer.code.to_s.eql? "200" # return { student: (answer.parsed_response["student"] || []) } if answer.code.to_s.eql? "200" return {"errorMessage"=>"#{answer.response}"} end
ruby
def get_one_student(params) # api_path = "/ws/v1/district/student/{dcid}?expansions=school_enrollment,contact&q=student_username==xxxxxx237" ps_dcid = params[:dcid] || params[:dc_id] || params[:id] api_path = "/ws/v1/student/#{ps_dcid.to_i}" options = { query: { "extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields", "expansions" => "demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch" } } return {"errorMessage"=>{"message"=>"A valid dcid must be entered."}} if "#{ps_dcid.to_i}".eql? "0" answer = api(:get, api_path, options) return { student: (answer["student"] || []) } if answer.code.to_s.eql? "200" # return { student: (answer.parsed_response["student"] || []) } if answer.code.to_s.eql? "200" return {"errorMessage"=>"#{answer.response}"} end
[ "def", "get_one_student", "(", "params", ")", "ps_dcid", "=", "params", "[", ":dcid", "]", "||", "params", "[", ":dc_id", "]", "||", "params", "[", ":id", "]", "api_path", "=", "\"/ws/v1/student/#{ps_dcid.to_i}\"", "options", "=", "{", "query", ":", "{", "\"extensions\"", "=>", "\"s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields\"", ",", "\"expansions\"", "=>", "\"demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch\"", "}", "}", "return", "{", "\"errorMessage\"", "=>", "{", "\"message\"", "=>", "\"A valid dcid must be entered.\"", "}", "}", "if", "\"#{ps_dcid.to_i}\"", ".", "eql?", "\"0\"", "answer", "=", "api", "(", ":get", ",", "api_path", ",", "options", ")", "return", "{", "student", ":", "(", "answer", "[", "\"student\"", "]", "||", "[", "]", ")", "}", "if", "answer", ".", "code", ".", "to_s", ".", "eql?", "\"200\"", "return", "{", "\"errorMessage\"", "=>", "\"#{answer.response}\"", "}", "end" ]
retrieves all individual student's details - you must use the DCID !!! @param params [Hash] - use either: {dcid: "12345"} or {id: "12345"} @return [Hash] - in the format of: { :student=> { "@expansions"=> "demographics, addresses, alerts, phones, school_enrollment, ethnicity_race, contact, contact_info, initial_enrollment, schedule_setup, fees, lunch", "@extensions"=> "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields", "_extension_data"=> { "_table_extension"=> [ { "recordFound"=>false, "_field"=> [ {"name"=>"preferredname", "type"=>"String", "value"=>"Guy"}, {"name"=>"student_email", "type"=>"String", "value"=>"[email protected]"} ], "name"=>"u_students_extension" }, { "recordFound"=>false, "_field"=> [ {"name"=>"transcriptaddrzip", "type"=>"String", "value"=>1858}, {"name"=>"transcriptaddrcountry", "type"=>"String", "value"=>"CH"}, {"name"=>"transcriptaddrcity", "type"=>"String", "value"=>"Bex"}, {"name"=>"transcriptaddrstate", "type"=>"String", "value"=>"VD"}, {"name"=>"transcriptaddrline1", "type"=>"String", "value"=>"LAS"}, {"name"=>"transcriptaddrline2", "type"=>"String", "value"=>"CP 108"} ], "name"=>"u_studentsuserfields" } ] }, "id"=>7337, "local_id"=>555807, "student_username"=>"guy807", "name"=>{"first_name"=>"Mountain", "last_name"=>"BIV"}, "demographics"=>{"gender"=>"M", "birth_date"=>"2002-08-26", "projected_graduation_year"=>2021}, "addresses"=>"", "alerts"=>"", "phones"=>"", "school_enrollment"=> { "enroll_status"=>"A", "enroll_status_description"=>"Active", "enroll_status_code"=>0, "grade_level"=>9, "entry_date"=>"2018-06-22", "exit_date"=>"2019-08-06", "school_number"=>2, "school_id"=>2, "full_time_equivalency"=>{"fteid"=>970, "name"=>"FTE Admissions"} }, "ethnicity_race"=>{"federal_ethnicity"=>"NO"}, "contact"=>{"guardian_email"=>"[email protected]"}, "contact_info"=>{"email"=>"[email protected]"}, "initial_enrollment"=>{"district_entry_grade_level"=>0, "school_entry_grade_level"=>0}, "schedule_setup"=>{"next_school"=>33, "sched_next_year_grade"=>10}, "fees"=>"", "lunch"=>{"balance_1"=>"0.00", "balance_2"=>"0.00", "balance_3"=>"0.00", "balance_4"=>"0.00", "lunch_id"=>0} } } @note the data within "u_students_extension" - is unique for each school
[ "retrieves", "all", "individual", "student", "s", "details", "-", "you", "must", "use", "the", "DCID", "!!!" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_get.rb#L108-L123
train
LAS-IT/ps_utilities
lib/ps_utilities/pre_built_get.rb
PsUtilities.PreBuiltGet.build_query
def build_query(params) query = [] query << "school_enrollment.enroll_status_code==#{params[:status_code]}" if params.has_key?(:status_code) query << "school_enrollment.enroll_status==#{params[:enroll_status]}" if params.has_key?(:enroll_status) query << "student_username==#{params[:username]}" if params.has_key?(:username) query << "name.last_name==#{params[:last_name]}" if params.has_key?(:last_name) query << "name.first_name==#{params[:first_name]}" if params.has_key?(:first_name) query << "local_id==#{params[:local_id]}" if params.has_key?(:local_id) query << "local_id==#{params[:student_id]}" if params.has_key?(:student_id) query << "id==#{params[:dcid]}" if params.has_key?(:dcid) query << "id==#{params[:id]}" if params.has_key?(:id) answer = query.join(";") answer end
ruby
def build_query(params) query = [] query << "school_enrollment.enroll_status_code==#{params[:status_code]}" if params.has_key?(:status_code) query << "school_enrollment.enroll_status==#{params[:enroll_status]}" if params.has_key?(:enroll_status) query << "student_username==#{params[:username]}" if params.has_key?(:username) query << "name.last_name==#{params[:last_name]}" if params.has_key?(:last_name) query << "name.first_name==#{params[:first_name]}" if params.has_key?(:first_name) query << "local_id==#{params[:local_id]}" if params.has_key?(:local_id) query << "local_id==#{params[:student_id]}" if params.has_key?(:student_id) query << "id==#{params[:dcid]}" if params.has_key?(:dcid) query << "id==#{params[:id]}" if params.has_key?(:id) answer = query.join(";") answer end
[ "def", "build_query", "(", "params", ")", "query", "=", "[", "]", "query", "<<", "\"school_enrollment.enroll_status_code==#{params[:status_code]}\"", "if", "params", ".", "has_key?", "(", ":status_code", ")", "query", "<<", "\"school_enrollment.enroll_status==#{params[:enroll_status]}\"", "if", "params", ".", "has_key?", "(", ":enroll_status", ")", "query", "<<", "\"student_username==#{params[:username]}\"", "if", "params", ".", "has_key?", "(", ":username", ")", "query", "<<", "\"name.last_name==#{params[:last_name]}\"", "if", "params", ".", "has_key?", "(", ":last_name", ")", "query", "<<", "\"name.first_name==#{params[:first_name]}\"", "if", "params", ".", "has_key?", "(", ":first_name", ")", "query", "<<", "\"local_id==#{params[:local_id]}\"", "if", "params", ".", "has_key?", "(", ":local_id", ")", "query", "<<", "\"local_id==#{params[:student_id]}\"", "if", "params", ".", "has_key?", "(", ":student_id", ")", "query", "<<", "\"id==#{params[:dcid]}\"", "if", "params", ".", "has_key?", "(", ":dcid", ")", "query", "<<", "\"id==#{params[:id]}\"", "if", "params", ".", "has_key?", "(", ":id", ")", "answer", "=", "query", ".", "join", "(", "\";\"", ")", "answer", "end" ]
build the api query - you can use splats to match any character @param params [Hash] - valid keys include: :status_code (or :enroll_status), :username, :last_name, :first_name, :student_id (or :local_id), :id (or :dcid) @return [String] - "id==345;name.last_name==BA*"
[ "build", "the", "api", "query", "-", "you", "can", "use", "splats", "to", "match", "any", "character" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_get.rb#L131-L144
train
JonnieCache/tinyci
lib/tinyci/compactor.rb
TinyCI.Compactor.directories_to_compact
def directories_to_compact builds = Dir.entries builds_dir builds.select! {|e| File.directory? builds_dir(e) } builds.reject! {|e| %w{. ..}.include? e } builds.sort! builds = builds[0..-(@num_builds_to_leave+1)] builds.reject! {|e| @builds_to_leave.include?(e) || @builds_to_leave.include?(builds_dir(e, 'export'))} builds end
ruby
def directories_to_compact builds = Dir.entries builds_dir builds.select! {|e| File.directory? builds_dir(e) } builds.reject! {|e| %w{. ..}.include? e } builds.sort! builds = builds[0..-(@num_builds_to_leave+1)] builds.reject! {|e| @builds_to_leave.include?(e) || @builds_to_leave.include?(builds_dir(e, 'export'))} builds end
[ "def", "directories_to_compact", "builds", "=", "Dir", ".", "entries", "builds_dir", "builds", ".", "select!", "{", "|", "e", "|", "File", ".", "directory?", "builds_dir", "(", "e", ")", "}", "builds", ".", "reject!", "{", "|", "e", "|", "%w{", ".", "..", "}", ".", "include?", "e", "}", "builds", ".", "sort!", "builds", "=", "builds", "[", "0", "..", "-", "(", "@num_builds_to_leave", "+", "1", ")", "]", "builds", ".", "reject!", "{", "|", "e", "|", "@builds_to_leave", ".", "include?", "(", "e", ")", "||", "@builds_to_leave", ".", "include?", "(", "builds_dir", "(", "e", ",", "'export'", ")", ")", "}", "builds", "end" ]
Build the list of directories to compact according to the options
[ "Build", "the", "list", "of", "directories", "to", "compact", "according", "to", "the", "options" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/compactor.rb#L47-L57
train
JonnieCache/tinyci
lib/tinyci/compactor.rb
TinyCI.Compactor.compress_directory
def compress_directory(dir) File.open archive_path(dir), 'wb' do |oarchive_path| Zlib::GzipWriter.wrap oarchive_path do |gz| Gem::Package::TarWriter.new gz do |tar| Find.find "#{builds_dir}/"+dir do |f| relative_path = f.sub "#{builds_dir}/", "" mode = File.stat(f).mode size = File.stat(f).size if File.directory? f tar.mkdir relative_path, mode else tar.add_file_simple relative_path, mode, size do |tio| File.open f, 'rb' do |rio| while buffer = rio.read(BLOCKSIZE_TO_READ) tio.write buffer end end end end end end end end end
ruby
def compress_directory(dir) File.open archive_path(dir), 'wb' do |oarchive_path| Zlib::GzipWriter.wrap oarchive_path do |gz| Gem::Package::TarWriter.new gz do |tar| Find.find "#{builds_dir}/"+dir do |f| relative_path = f.sub "#{builds_dir}/", "" mode = File.stat(f).mode size = File.stat(f).size if File.directory? f tar.mkdir relative_path, mode else tar.add_file_simple relative_path, mode, size do |tio| File.open f, 'rb' do |rio| while buffer = rio.read(BLOCKSIZE_TO_READ) tio.write buffer end end end end end end end end end
[ "def", "compress_directory", "(", "dir", ")", "File", ".", "open", "archive_path", "(", "dir", ")", ",", "'wb'", "do", "|", "oarchive_path", "|", "Zlib", "::", "GzipWriter", ".", "wrap", "oarchive_path", "do", "|", "gz", "|", "Gem", "::", "Package", "::", "TarWriter", ".", "new", "gz", "do", "|", "tar", "|", "Find", ".", "find", "\"#{builds_dir}/\"", "+", "dir", "do", "|", "f", "|", "relative_path", "=", "f", ".", "sub", "\"#{builds_dir}/\"", ",", "\"\"", "mode", "=", "File", ".", "stat", "(", "f", ")", ".", "mode", "size", "=", "File", ".", "stat", "(", "f", ")", ".", "size", "if", "File", ".", "directory?", "f", "tar", ".", "mkdir", "relative_path", ",", "mode", "else", "tar", ".", "add_file_simple", "relative_path", ",", "mode", ",", "size", "do", "|", "tio", "|", "File", ".", "open", "f", ",", "'rb'", "do", "|", "rio", "|", "while", "buffer", "=", "rio", ".", "read", "(", "BLOCKSIZE_TO_READ", ")", "tio", ".", "write", "buffer", "end", "end", "end", "end", "end", "end", "end", "end", "end" ]
Create a .tar.gz file from a directory Done in pure ruby to ensure portability
[ "Create", "a", ".", "tar", ".", "gz", "file", "from", "a", "directory", "Done", "in", "pure", "ruby", "to", "ensure", "portability" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/compactor.rb#L71-L97
train
JonnieCache/tinyci
lib/tinyci/subprocesses.rb
TinyCI.Subprocesses.execute
def execute(*command, label: nil) output, status = Open3.capture2(*command.flatten) log_debug caller[0] log_debug "CMD: #{command.join(' ')}" log_debug "OUT: #{output}" unless status.success? log_error output raise SubprocessError.new(label, command.join(' '), status) end output.chomp end
ruby
def execute(*command, label: nil) output, status = Open3.capture2(*command.flatten) log_debug caller[0] log_debug "CMD: #{command.join(' ')}" log_debug "OUT: #{output}" unless status.success? log_error output raise SubprocessError.new(label, command.join(' '), status) end output.chomp end
[ "def", "execute", "(", "*", "command", ",", "label", ":", "nil", ")", "output", ",", "status", "=", "Open3", ".", "capture2", "(", "*", "command", ".", "flatten", ")", "log_debug", "caller", "[", "0", "]", "log_debug", "\"CMD: #{command.join(' ')}\"", "log_debug", "\"OUT: #{output}\"", "unless", "status", ".", "success?", "log_error", "output", "raise", "SubprocessError", ".", "new", "(", "label", ",", "command", ".", "join", "(", "' '", ")", ",", "status", ")", "end", "output", ".", "chomp", "end" ]
Synchronously execute a command as a subprocess and return the output. @param [Array<String>] command The command line @param [String] label A label for debug and logging purposes @return [String] The output of the command @raise [SubprocessError] if the subprocess returns status > 0
[ "Synchronously", "execute", "a", "command", "as", "a", "subprocess", "and", "return", "the", "output", "." ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/subprocesses.rb#L15-L28
train
JonnieCache/tinyci
lib/tinyci/subprocesses.rb
TinyCI.Subprocesses.execute_pipe
def execute_pipe(*commands, label: nil) stdout, waiters = Open3.pipeline_r(*commands) output = stdout.read waiters.each_with_index do |waiter, i| status = waiter.value unless status.success? log_error output raise SubprocessError.new(label, commands[i].join(' '), status) end end output.chomp end
ruby
def execute_pipe(*commands, label: nil) stdout, waiters = Open3.pipeline_r(*commands) output = stdout.read waiters.each_with_index do |waiter, i| status = waiter.value unless status.success? log_error output raise SubprocessError.new(label, commands[i].join(' '), status) end end output.chomp end
[ "def", "execute_pipe", "(", "*", "commands", ",", "label", ":", "nil", ")", "stdout", ",", "waiters", "=", "Open3", ".", "pipeline_r", "(", "*", "commands", ")", "output", "=", "stdout", ".", "read", "waiters", ".", "each_with_index", "do", "|", "waiter", ",", "i", "|", "status", "=", "waiter", ".", "value", "unless", "status", ".", "success?", "log_error", "output", "raise", "SubprocessError", ".", "new", "(", "label", ",", "commands", "[", "i", "]", ".", "join", "(", "' '", ")", ",", "status", ")", "end", "end", "output", ".", "chomp", "end" ]
Synchronously execute a chain multiple commands piped into each other as a subprocess and return the output. @param [Array<Array<String>>] commands The command lines @param [String] label A label for debug and logging purposes @return [String] The output of the command @raise [SubprocessError] if the subprocess returns status > 0
[ "Synchronously", "execute", "a", "chain", "multiple", "commands", "piped", "into", "each", "other", "as", "a", "subprocess", "and", "return", "the", "output", "." ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/subprocesses.rb#L38-L51
train
JonnieCache/tinyci
lib/tinyci/subprocesses.rb
TinyCI.Subprocesses.execute_stream
def execute_stream(*command, label: nil, pwd: nil) opts = {} opts[:chdir] = pwd unless pwd.nil? Open3.popen2e(command.join(' '), opts) do |stdin, stdout_and_stderr, wait_thr| stdin.close until stdout_and_stderr.closed? || stdout_and_stderr.eof? line = stdout_and_stderr.gets log_info line.chomp $stdout.flush end unless wait_thr.value.success? raise SubprocessError.new(label, command.join(' '), wait_thr.value) end stdout_and_stderr.close end true end
ruby
def execute_stream(*command, label: nil, pwd: nil) opts = {} opts[:chdir] = pwd unless pwd.nil? Open3.popen2e(command.join(' '), opts) do |stdin, stdout_and_stderr, wait_thr| stdin.close until stdout_and_stderr.closed? || stdout_and_stderr.eof? line = stdout_and_stderr.gets log_info line.chomp $stdout.flush end unless wait_thr.value.success? raise SubprocessError.new(label, command.join(' '), wait_thr.value) end stdout_and_stderr.close end true end
[ "def", "execute_stream", "(", "*", "command", ",", "label", ":", "nil", ",", "pwd", ":", "nil", ")", "opts", "=", "{", "}", "opts", "[", ":chdir", "]", "=", "pwd", "unless", "pwd", ".", "nil?", "Open3", ".", "popen2e", "(", "command", ".", "join", "(", "' '", ")", ",", "opts", ")", "do", "|", "stdin", ",", "stdout_and_stderr", ",", "wait_thr", "|", "stdin", ".", "close", "until", "stdout_and_stderr", ".", "closed?", "||", "stdout_and_stderr", ".", "eof?", "line", "=", "stdout_and_stderr", ".", "gets", "log_info", "line", ".", "chomp", "$stdout", ".", "flush", "end", "unless", "wait_thr", ".", "value", ".", "success?", "raise", "SubprocessError", ".", "new", "(", "label", ",", "command", ".", "join", "(", "' '", ")", ",", "wait_thr", ".", "value", ")", "end", "stdout_and_stderr", ".", "close", "end", "true", "end" ]
Synchronously execute a command as a subprocess and and stream the output to `STDOUT` @param [Array<String>] command The command line @param [String] label A label for debug and logging purposes @param [String] pwd Optionally specify a different working directory in which to execute the command @return [TrueClass] `true` if the command executed successfully @raise [SubprocessError] if the subprocess returns status > 0
[ "Synchronously", "execute", "a", "command", "as", "a", "subprocess", "and", "and", "stream", "the", "output", "to", "STDOUT" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/subprocesses.rb#L62-L82
train
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.property
def property(contractid, groupid, propertyid) begin property_hash = @client.get_json_body( "/papi/v0/properties/#{propertyid}", { 'contractId' => contractid, 'groupId' => groupid, }, ) rescue puts "# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.message}" end Property.new property_hash['properties']['items'].first end
ruby
def property(contractid, groupid, propertyid) begin property_hash = @client.get_json_body( "/papi/v0/properties/#{propertyid}", { 'contractId' => contractid, 'groupId' => groupid, }, ) rescue puts "# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.message}" end Property.new property_hash['properties']['items'].first end
[ "def", "property", "(", "contractid", ",", "groupid", ",", "propertyid", ")", "begin", "property_hash", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/#{propertyid}\"", ",", "{", "'contractId'", "=>", "contractid", ",", "'groupId'", "=>", "groupid", ",", "}", ",", ")", "rescue", "puts", "\"# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.message}\"", "end", "Property", ".", "new", "property_hash", "[", "'properties'", "]", "[", "'items'", "]", ".", "first", "end" ]
fetch a single property
[ "fetch", "a", "single", "property" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L40-L50
train
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.properties
def properties properties = [] contract_group_pairs.each do |cg| begin properties_hash = @client.get_json_body( "/papi/v0/properties/", { 'contractId' => cg[:contract], 'groupId' => cg[:group], } ) if properties_hash && properties_hash['properties']['items'] properties_hash['properties']['items'].each do |prp| properties << Property.new(prp) end end rescue Exception => e # probably due to Akamai PM permissions, don't raise for caller to handle puts "# unable to retrieve properties for (group=#{cg[:group]},contract=#{cg[:contract]}): #{e.message}" end end properties end
ruby
def properties properties = [] contract_group_pairs.each do |cg| begin properties_hash = @client.get_json_body( "/papi/v0/properties/", { 'contractId' => cg[:contract], 'groupId' => cg[:group], } ) if properties_hash && properties_hash['properties']['items'] properties_hash['properties']['items'].each do |prp| properties << Property.new(prp) end end rescue Exception => e # probably due to Akamai PM permissions, don't raise for caller to handle puts "# unable to retrieve properties for (group=#{cg[:group]},contract=#{cg[:contract]}): #{e.message}" end end properties end
[ "def", "properties", "properties", "=", "[", "]", "contract_group_pairs", ".", "each", "do", "|", "cg", "|", "begin", "properties_hash", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/\"", ",", "{", "'contractId'", "=>", "cg", "[", ":contract", "]", ",", "'groupId'", "=>", "cg", "[", ":group", "]", ",", "}", ")", "if", "properties_hash", "&&", "properties_hash", "[", "'properties'", "]", "[", "'items'", "]", "properties_hash", "[", "'properties'", "]", "[", "'items'", "]", ".", "each", "do", "|", "prp", "|", "properties", "<<", "Property", ".", "new", "(", "prp", ")", "end", "end", "rescue", "Exception", "=>", "e", "puts", "\"# unable to retrieve properties for (group=#{cg[:group]},contract=#{cg[:contract]}): #{e.message}\"", "end", "end", "properties", "end" ]
takes a long time to complete!
[ "takes", "a", "long", "time", "to", "complete!" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L53-L72
train
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.hostnames
def hostnames(property, skip_update_dns_status = false, version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion begin hostnames_hash = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/hostnames/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) rescue Exception => e raise "unable to retrieve hostnames for #{property.name}: #{e.message}" end if hostnames_hash && hostnames_hash['hostnames'] && hostnames_hash['hostnames']['items'] hostnames = hostnames_hash['hostnames']['items'].map do |ehn| h = Hostname.new ehn h.update_status unless skip_update_dns_status h end else # no hostnames returned hostnames = nil end hostnames end
ruby
def hostnames(property, skip_update_dns_status = false, version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion begin hostnames_hash = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/hostnames/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) rescue Exception => e raise "unable to retrieve hostnames for #{property.name}: #{e.message}" end if hostnames_hash && hostnames_hash['hostnames'] && hostnames_hash['hostnames']['items'] hostnames = hostnames_hash['hostnames']['items'].map do |ehn| h = Hostname.new ehn h.update_status unless skip_update_dns_status h end else # no hostnames returned hostnames = nil end hostnames end
[ "def", "hostnames", "(", "property", ",", "skip_update_dns_status", "=", "false", ",", "version", "=", "nil", ")", "raise", "'property must be a Borderlands::Property object'", "unless", "property", ".", "is_a?", "Property", "version", "||=", "property", ".", "productionversion", "begin", "hostnames_hash", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/#{property.id}/versions/#{version}/hostnames/\"", ",", "{", "'contractId'", "=>", "property", ".", "contractid", ",", "'groupId'", "=>", "property", ".", "groupid", "}", ",", ")", "rescue", "Exception", "=>", "e", "raise", "\"unable to retrieve hostnames for #{property.name}: #{e.message}\"", "end", "if", "hostnames_hash", "&&", "hostnames_hash", "[", "'hostnames'", "]", "&&", "hostnames_hash", "[", "'hostnames'", "]", "[", "'items'", "]", "hostnames", "=", "hostnames_hash", "[", "'hostnames'", "]", "[", "'items'", "]", ".", "map", "do", "|", "ehn", "|", "h", "=", "Hostname", ".", "new", "ehn", "h", ".", "update_status", "unless", "skip_update_dns_status", "h", "end", "else", "hostnames", "=", "nil", "end", "hostnames", "end" ]
version defaults to the current production version, which is pretty much always going to be the most meaningful thing to look at
[ "version", "defaults", "to", "the", "current", "production", "version", "which", "is", "pretty", "much", "always", "going", "to", "be", "the", "most", "meaningful", "thing", "to", "look", "at" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L76-L98
train
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.ruletree
def ruletree(property,version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion tree = nil begin rt = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/rules/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) tree = Rule.new rt['rules'] rescue Exception => e raise "unable to retrieve rule tree for #{property.name}: #{e.message}" end tree end
ruby
def ruletree(property,version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion tree = nil begin rt = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/rules/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) tree = Rule.new rt['rules'] rescue Exception => e raise "unable to retrieve rule tree for #{property.name}: #{e.message}" end tree end
[ "def", "ruletree", "(", "property", ",", "version", "=", "nil", ")", "raise", "'property must be a Borderlands::Property object'", "unless", "property", ".", "is_a?", "Property", "version", "||=", "property", ".", "productionversion", "tree", "=", "nil", "begin", "rt", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/#{property.id}/versions/#{version}/rules/\"", ",", "{", "'contractId'", "=>", "property", ".", "contractid", ",", "'groupId'", "=>", "property", ".", "groupid", "}", ",", ")", "tree", "=", "Rule", ".", "new", "rt", "[", "'rules'", "]", "rescue", "Exception", "=>", "e", "raise", "\"unable to retrieve rule tree for #{property.name}: #{e.message}\"", "end", "tree", "end" ]
version defaults to current production version here too
[ "version", "defaults", "to", "current", "production", "version", "here", "too" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L101-L115
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.find_passenger_config
def find_passenger_config passenger_config = ENV['PASSENGER_CONFIG'] if passenger_config.nil? || passenger_config.empty? passenger_config = find_passenger_config_vendor || find_passenger_config_in_path end if passenger_config.nil? || passenger_config.empty? abort 'ERROR: The unit tests are to be run against a specific ' \ 'Passenger version. However, the \'passenger-config\' command is ' \ 'not found. Please install Passenger, or (if you are sure ' \ 'Passenger is installed) set the PASSENGER_CONFIG environment ' \ 'variable to the \'passenger-config\' command.' end passenger_config end
ruby
def find_passenger_config passenger_config = ENV['PASSENGER_CONFIG'] if passenger_config.nil? || passenger_config.empty? passenger_config = find_passenger_config_vendor || find_passenger_config_in_path end if passenger_config.nil? || passenger_config.empty? abort 'ERROR: The unit tests are to be run against a specific ' \ 'Passenger version. However, the \'passenger-config\' command is ' \ 'not found. Please install Passenger, or (if you are sure ' \ 'Passenger is installed) set the PASSENGER_CONFIG environment ' \ 'variable to the \'passenger-config\' command.' end passenger_config end
[ "def", "find_passenger_config", "passenger_config", "=", "ENV", "[", "'PASSENGER_CONFIG'", "]", "if", "passenger_config", ".", "nil?", "||", "passenger_config", ".", "empty?", "passenger_config", "=", "find_passenger_config_vendor", "||", "find_passenger_config_in_path", "end", "if", "passenger_config", ".", "nil?", "||", "passenger_config", ".", "empty?", "abort", "'ERROR: The unit tests are to be run against a specific '", "'Passenger version. However, the \\'passenger-config\\' command is '", "'not found. Please install Passenger, or (if you are sure '", "'Passenger is installed) set the PASSENGER_CONFIG environment '", "'variable to the \\'passenger-config\\' command.'", "end", "passenger_config", "end" ]
Lookup the `passenger-config` command, either by respecting the `PASSENGER_CONFIG` environment variable, or by looking it up in `PATH`. If the command cannot be found, the current process aborts with an error message.
[ "Lookup", "the", "passenger", "-", "config", "command", "either", "by", "respecting", "the", "PASSENGER_CONFIG", "environment", "variable", "or", "by", "looking", "it", "up", "in", "PATH", ".", "If", "the", "command", "cannot", "be", "found", "the", "current", "process", "aborts", "with", "an", "error", "message", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L56-L70
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.undo_bundler
def undo_bundler clean_env = nil Bundler.with_clean_env do clean_env = ENV.to_hash end ENV.replace(clean_env) end
ruby
def undo_bundler clean_env = nil Bundler.with_clean_env do clean_env = ENV.to_hash end ENV.replace(clean_env) end
[ "def", "undo_bundler", "clean_env", "=", "nil", "Bundler", ".", "with_clean_env", "do", "clean_env", "=", "ENV", ".", "to_hash", "end", "ENV", ".", "replace", "(", "clean_env", ")", "end" ]
Unit tests must undo the Bundler environment so that the gem's own Gemfile doesn't affect subprocesses that may have their own Gemfile.
[ "Unit", "tests", "must", "undo", "the", "Bundler", "environment", "so", "that", "the", "gem", "s", "own", "Gemfile", "doesn", "t", "affect", "subprocesses", "that", "may", "have", "their", "own", "Gemfile", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L134-L140
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.write_file
def write_file(path, content) dir = File.dirname(path) if !File.exist?(dir) FileUtils.mkdir_p(dir) end File.open(path, 'wb') do |f| f.write(content) end end
ruby
def write_file(path, content) dir = File.dirname(path) if !File.exist?(dir) FileUtils.mkdir_p(dir) end File.open(path, 'wb') do |f| f.write(content) end end
[ "def", "write_file", "(", "path", ",", "content", ")", "dir", "=", "File", ".", "dirname", "(", "path", ")", "if", "!", "File", ".", "exist?", "(", "dir", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "end", "File", ".", "open", "(", "path", ",", "'wb'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "content", ")", "end", "end" ]
Writes the given content to the file at the given path. If or or more parent directories don't exist, then they are created.
[ "Writes", "the", "given", "content", "to", "the", "file", "at", "the", "given", "path", ".", "If", "or", "or", "more", "parent", "directories", "don", "t", "exist", "then", "they", "are", "created", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L149-L157
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.debug_shell
def debug_shell puts '------ Opening debug shell -----' @orig_dir = Dir.pwd begin if respond_to?(:prepare_debug_shell) prepare_debug_shell end system('bash') ensure Dir.chdir(@orig_dir) end puts '------ Exiting debug shell -----' end
ruby
def debug_shell puts '------ Opening debug shell -----' @orig_dir = Dir.pwd begin if respond_to?(:prepare_debug_shell) prepare_debug_shell end system('bash') ensure Dir.chdir(@orig_dir) end puts '------ Exiting debug shell -----' end
[ "def", "debug_shell", "puts", "'------ Opening debug shell -----'", "@orig_dir", "=", "Dir", ".", "pwd", "begin", "if", "respond_to?", "(", ":prepare_debug_shell", ")", "prepare_debug_shell", "end", "system", "(", "'bash'", ")", "ensure", "Dir", ".", "chdir", "(", "@orig_dir", ")", "end", "puts", "'------ Exiting debug shell -----'", "end" ]
Opens a debug shell. By default, the debug shell is opened in the current working directory. If the current module has the `prepare_debug_shell` method, that method is called before opening the debug shell. The method could, for example, change the working directory. This method does *not* raise an exception if the debug shell exits with an error.
[ "Opens", "a", "debug", "shell", ".", "By", "default", "the", "debug", "shell", "is", "opened", "in", "the", "current", "working", "directory", ".", "If", "the", "current", "module", "has", "the", "prepare_debug_shell", "method", "that", "method", "is", "called", "before", "opening", "the", "debug", "shell", ".", "The", "method", "could", "for", "example", "change", "the", "working", "directory", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L187-L199
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.eventually
def eventually(deadline_duration = 3, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield return else sleep(check_interval) end end raise 'Time limit exceeded' end
ruby
def eventually(deadline_duration = 3, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield return else sleep(check_interval) end end raise 'Time limit exceeded' end
[ "def", "eventually", "(", "deadline_duration", "=", "3", ",", "check_interval", "=", "0.05", ")", "deadline", "=", "Time", ".", "now", "+", "deadline_duration", "while", "Time", ".", "now", "<", "deadline", "if", "yield", "return", "else", "sleep", "(", "check_interval", ")", "end", "end", "raise", "'Time limit exceeded'", "end" ]
Asserts that something should eventually happen. This is done by checking that the given block eventually returns true. The block is called once every `check_interval` msec. If the block does not return true within `deadline_duration` secs, then an exception is raised.
[ "Asserts", "that", "something", "should", "eventually", "happen", ".", "This", "is", "done", "by", "checking", "that", "the", "given", "block", "eventually", "returns", "true", ".", "The", "block", "is", "called", "once", "every", "check_interval", "msec", ".", "If", "the", "block", "does", "not", "return", "true", "within", "deadline_duration", "secs", "then", "an", "exception", "is", "raised", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L252-L262
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.should_never_happen
def should_never_happen(deadline_duration = 0.5, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield raise "That which shouldn't happen happened anyway" else sleep(check_interval) end end end
ruby
def should_never_happen(deadline_duration = 0.5, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield raise "That which shouldn't happen happened anyway" else sleep(check_interval) end end end
[ "def", "should_never_happen", "(", "deadline_duration", "=", "0.5", ",", "check_interval", "=", "0.05", ")", "deadline", "=", "Time", ".", "now", "+", "deadline_duration", "while", "Time", ".", "now", "<", "deadline", "if", "yield", "raise", "\"That which shouldn't happen happened anyway\"", "else", "sleep", "(", "check_interval", ")", "end", "end", "end" ]
Asserts that something should never happen. This is done by checking that the given block never returns true. The block is called once every `check_interval` msec, until `deadline_duration` seconds have passed. If the block ever returns true, then an exception is raised.
[ "Asserts", "that", "something", "should", "never", "happen", ".", "This", "is", "done", "by", "checking", "that", "the", "given", "block", "never", "returns", "true", ".", "The", "block", "is", "called", "once", "every", "check_interval", "msec", "until", "deadline_duration", "seconds", "have", "passed", ".", "If", "the", "block", "ever", "returns", "true", "then", "an", "exception", "is", "raised", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L268-L277
train