id
int32
0
24.9k
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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
24,600
holtrop/rscons
lib/rscons/environment.rb
Rscons.Environment.wait_for_threaded_commands
def wait_for_threaded_commands(options = {}) options[:which] ||= @threaded_commands threads = options[:which].map(&:thread) if finished_thread = find_finished_thread(threads, options[:nonblock]) threaded_command = @threaded_commands.find do |tc| tc.thread == finished_thread end @threaded_commands.delete(threaded_command) threaded_command end end
ruby
def wait_for_threaded_commands(options = {}) options[:which] ||= @threaded_commands threads = options[:which].map(&:thread) if finished_thread = find_finished_thread(threads, options[:nonblock]) threaded_command = @threaded_commands.find do |tc| tc.thread == finished_thread end @threaded_commands.delete(threaded_command) threaded_command end end
[ "def", "wait_for_threaded_commands", "(", "options", "=", "{", "}", ")", "options", "[", ":which", "]", "||=", "@threaded_commands", "threads", "=", "options", "[", ":which", "]", ".", "map", "(", ":thread", ")", "if", "finished_thread", "=", "find_finished_thread", "(", "threads", ",", "options", "[", ":nonblock", "]", ")", "threaded_command", "=", "@threaded_commands", ".", "find", "do", "|", "tc", "|", "tc", ".", "thread", "==", "finished_thread", "end", "@threaded_commands", ".", "delete", "(", "threaded_command", ")", "threaded_command", "end", "end" ]
Wait for threaded commands to complete. @param options [Hash] Options. @option options [Set<ThreadedCommand>, Array<ThreadedCommand>] :which Which {ThreadedCommand} objects to wait for. If not specified, this method will wait for any. @option options [Boolean] :nonblock Set to true to not block. @return [ThreadedCommand, nil] The {ThreadedCommand} object that is finished.
[ "Wait", "for", "threaded", "commands", "to", "complete", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L967-L977
24,601
holtrop/rscons
lib/rscons/environment.rb
Rscons.Environment.find_finished_thread
def find_finished_thread(threads, nonblock) if nonblock threads.find do |thread| !thread.alive? end else if threads.empty? raise "No threads to wait for" end ThreadsWait.new(*threads).next_wait end end
ruby
def find_finished_thread(threads, nonblock) if nonblock threads.find do |thread| !thread.alive? end else if threads.empty? raise "No threads to wait for" end ThreadsWait.new(*threads).next_wait end end
[ "def", "find_finished_thread", "(", "threads", ",", "nonblock", ")", "if", "nonblock", "threads", ".", "find", "do", "|", "thread", "|", "!", "thread", ".", "alive?", "end", "else", "if", "threads", ".", "empty?", "raise", "\"No threads to wait for\"", "end", "ThreadsWait", ".", "new", "(", "threads", ")", ".", "next_wait", "end", "end" ]
Check if any of the requested threads are finished. @param threads [Array<Thread>] The threads to check. @param nonblock [Boolean] Whether to be non-blocking. If true, nil will be returned if no thread is finished. If false, the method will wait until one of the threads is finished. @return [Thread, nil] The finished thread, if any.
[ "Check", "if", "any", "of", "the", "requested", "threads", "are", "finished", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L990-L1001
24,602
holtrop/rscons
lib/rscons/environment.rb
Rscons.Environment.find_builder_for
def find_builder_for(target, source, features) @builders.values.find do |builder| features_met?(builder, features) and builder.produces?(target, source, self) end end
ruby
def find_builder_for(target, source, features) @builders.values.find do |builder| features_met?(builder, features) and builder.produces?(target, source, self) end end
[ "def", "find_builder_for", "(", "target", ",", "source", ",", "features", ")", "@builders", ".", "values", ".", "find", "do", "|", "builder", "|", "features_met?", "(", "builder", ",", "features", ")", "and", "builder", ".", "produces?", "(", "target", ",", "source", ",", "self", ")", "end", "end" ]
Find a builder that meets the requested features and produces a target of the requested name. @param target [String] Target file name. @param source [String] Source file name. @param features [Array<String>] See {#register_builds}. @return [Builder, nil] The builder found, if any.
[ "Find", "a", "builder", "that", "meets", "the", "requested", "features", "and", "produces", "a", "target", "of", "the", "requested", "name", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L1040-L1044
24,603
holtrop/rscons
lib/rscons/environment.rb
Rscons.Environment.features_met?
def features_met?(builder, features) builder_features = builder.features features.all? do |feature| want_feature = true if feature =~ /^-(.*)$/ want_feature = false feature = $1 end builder_has_feature = builder_features.include?(feature) want_feature ? builder_has_feature : !builder_has_feature end end
ruby
def features_met?(builder, features) builder_features = builder.features features.all? do |feature| want_feature = true if feature =~ /^-(.*)$/ want_feature = false feature = $1 end builder_has_feature = builder_features.include?(feature) want_feature ? builder_has_feature : !builder_has_feature end end
[ "def", "features_met?", "(", "builder", ",", "features", ")", "builder_features", "=", "builder", ".", "features", "features", ".", "all?", "do", "|", "feature", "|", "want_feature", "=", "true", "if", "feature", "=~", "/", "/", "want_feature", "=", "false", "feature", "=", "$1", "end", "builder_has_feature", "=", "builder_features", ".", "include?", "(", "feature", ")", "want_feature", "?", "builder_has_feature", ":", "!", "builder_has_feature", "end", "end" ]
Determine if a builder meets the requested features. @param builder [Builder] The builder. @param features [Array<String>] See {#register_builds}. @return [Boolean] Whether the builder meets the requested features.
[ "Determine", "if", "a", "builder", "meets", "the", "requested", "features", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/environment.rb#L1055-L1066
24,604
puppetlabs/beaker-answers
lib/beaker-answers/answers.rb
BeakerAnswers.Answers.answer_for
def answer_for(options, q, default = nil) case @format when :bash answer = DEFAULT_ANSWERS[q] answers = options[:answers] when :hiera answer = DEFAULT_HIERA_ANSWERS[q] answers = flatten_keys_to_joined_string(options[:answers]) if options[:answers] else raise NotImplementedError, "Don't know how to determine answers for #{@format}" end # check to see if there is a value for this in the provided options if answers && answers[q] answer = answers[q] end # use the default if we don't have anything if not answer answer = default end answer end
ruby
def answer_for(options, q, default = nil) case @format when :bash answer = DEFAULT_ANSWERS[q] answers = options[:answers] when :hiera answer = DEFAULT_HIERA_ANSWERS[q] answers = flatten_keys_to_joined_string(options[:answers]) if options[:answers] else raise NotImplementedError, "Don't know how to determine answers for #{@format}" end # check to see if there is a value for this in the provided options if answers && answers[q] answer = answers[q] end # use the default if we don't have anything if not answer answer = default end answer end
[ "def", "answer_for", "(", "options", ",", "q", ",", "default", "=", "nil", ")", "case", "@format", "when", ":bash", "answer", "=", "DEFAULT_ANSWERS", "[", "q", "]", "answers", "=", "options", "[", ":answers", "]", "when", ":hiera", "answer", "=", "DEFAULT_HIERA_ANSWERS", "[", "q", "]", "answers", "=", "flatten_keys_to_joined_string", "(", "options", "[", ":answers", "]", ")", "if", "options", "[", ":answers", "]", "else", "raise", "NotImplementedError", ",", "\"Don't know how to determine answers for #{@format}\"", "end", "# check to see if there is a value for this in the provided options", "if", "answers", "&&", "answers", "[", "q", "]", "answer", "=", "answers", "[", "q", "]", "end", "# use the default if we don't have anything", "if", "not", "answer", "answer", "=", "default", "end", "answer", "end" ]
The answer value for a provided question. Use the user answer when available, otherwise return the default. @param [Hash] options options for answer file @option options [Symbol] :answers Contains a hash of user provided question name and answer value pairs. @param [String] default Should there be no user value for the provided question name return this default @return [String] The answer value
[ "The", "answer", "value", "for", "a", "provided", "question", ".", "Use", "the", "user", "answer", "when", "available", "otherwise", "return", "the", "default", "." ]
3193bf986fd1842f2c7d8940a88df36db4200f3f
https://github.com/puppetlabs/beaker-answers/blob/3193bf986fd1842f2c7d8940a88df36db4200f3f/lib/beaker-answers/answers.rb#L124-L145
24,605
chef-workflow/chef-workflow
lib/chef-workflow/support/knife.rb
ChefWorkflow.KnifeSupport.build_knife_config
def build_knife_config FileUtils.mkdir_p(chef_config_path) File.binwrite(knife_config_path, ERB.new(knife_config_template).result(binding)) end
ruby
def build_knife_config FileUtils.mkdir_p(chef_config_path) File.binwrite(knife_config_path, ERB.new(knife_config_template).result(binding)) end
[ "def", "build_knife_config", "FileUtils", ".", "mkdir_p", "(", "chef_config_path", ")", "File", ".", "binwrite", "(", "knife_config_path", ",", "ERB", ".", "new", "(", "knife_config_template", ")", ".", "result", "(", "binding", ")", ")", "end" ]
Writes out a knife.rb based on the settings in this configuration. Uses the `knife_config_path` and `chef_config_path` to determine where to write it.
[ "Writes", "out", "a", "knife", ".", "rb", "based", "on", "the", "settings", "in", "this", "configuration", ".", "Uses", "the", "knife_config_path", "and", "chef_config_path", "to", "determine", "where", "to", "write", "it", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/knife.rb#L89-L92
24,606
itrp/itrp-client
lib/itrp/client/attachments.rb
Itrp.Attachments.upload_attachment
def upload_attachment(storage, attachment, raise_exceptions) begin # attachment is already a file or we need to open the file from disk unless attachment.respond_to?(:path) && attachment.respond_to?(:read) raise "file does not exist: #{attachment}" unless File.exists?(attachment) attachment = File.open(attachment, 'rb') end # there are two different upload methods: AWS S3 and ITRP local storage key_template = "#{storage[:upload_path]}#{FILENAME_TEMPLATE}" key = key_template.gsub(FILENAME_TEMPLATE, File.basename(attachment.path)) upload_method = storage[:provider] == AWS_PROVIDER ? :aws_upload : :itrp_upload send(upload_method, storage, key_template, key, attachment) # return the values for the note_attachments param {key: key, filesize: File.size(attachment.path)} rescue ::Exception => e report_error("Attachment upload failed: #{e.message}", raise_exceptions) nil end end
ruby
def upload_attachment(storage, attachment, raise_exceptions) begin # attachment is already a file or we need to open the file from disk unless attachment.respond_to?(:path) && attachment.respond_to?(:read) raise "file does not exist: #{attachment}" unless File.exists?(attachment) attachment = File.open(attachment, 'rb') end # there are two different upload methods: AWS S3 and ITRP local storage key_template = "#{storage[:upload_path]}#{FILENAME_TEMPLATE}" key = key_template.gsub(FILENAME_TEMPLATE, File.basename(attachment.path)) upload_method = storage[:provider] == AWS_PROVIDER ? :aws_upload : :itrp_upload send(upload_method, storage, key_template, key, attachment) # return the values for the note_attachments param {key: key, filesize: File.size(attachment.path)} rescue ::Exception => e report_error("Attachment upload failed: #{e.message}", raise_exceptions) nil end end
[ "def", "upload_attachment", "(", "storage", ",", "attachment", ",", "raise_exceptions", ")", "begin", "# attachment is already a file or we need to open the file from disk", "unless", "attachment", ".", "respond_to?", "(", ":path", ")", "&&", "attachment", ".", "respond_to?", "(", ":read", ")", "raise", "\"file does not exist: #{attachment}\"", "unless", "File", ".", "exists?", "(", "attachment", ")", "attachment", "=", "File", ".", "open", "(", "attachment", ",", "'rb'", ")", "end", "# there are two different upload methods: AWS S3 and ITRP local storage", "key_template", "=", "\"#{storage[:upload_path]}#{FILENAME_TEMPLATE}\"", "key", "=", "key_template", ".", "gsub", "(", "FILENAME_TEMPLATE", ",", "File", ".", "basename", "(", "attachment", ".", "path", ")", ")", "upload_method", "=", "storage", "[", ":provider", "]", "==", "AWS_PROVIDER", "?", ":aws_upload", ":", ":itrp_upload", "send", "(", "upload_method", ",", "storage", ",", "key_template", ",", "key", ",", "attachment", ")", "# return the values for the note_attachments param", "{", "key", ":", "key", ",", "filesize", ":", "File", ".", "size", "(", "attachment", ".", "path", ")", "}", "rescue", "::", "Exception", "=>", "e", "report_error", "(", "\"Attachment upload failed: #{e.message}\"", ",", "raise_exceptions", ")", "nil", "end", "end" ]
upload a single attachment and return the data for the note_attachments returns nil and provides an error in case the attachment upload failed
[ "upload", "a", "single", "attachment", "and", "return", "the", "data", "for", "the", "note_attachments", "returns", "nil", "and", "provides", "an", "error", "in", "case", "the", "attachment", "upload", "failed" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client/attachments.rb#L48-L68
24,607
itrp/itrp-client
lib/itrp/client/attachments.rb
Itrp.Attachments.itrp_upload
def itrp_upload(itrp, key_template, key, attachment) uri = itrp[:upload_uri] =~ /\/v1/ ? itrp[:upload_uri] : itrp[:upload_uri].gsub('/attachments', '/v1/attachments') response = send_file(uri, {file: attachment, key: key_template}, @client.send(:expand_header)) raise "ITRP upload to #{itrp[:upload_uri]} for #{key} failed: #{response.message}" unless response.valid? end
ruby
def itrp_upload(itrp, key_template, key, attachment) uri = itrp[:upload_uri] =~ /\/v1/ ? itrp[:upload_uri] : itrp[:upload_uri].gsub('/attachments', '/v1/attachments') response = send_file(uri, {file: attachment, key: key_template}, @client.send(:expand_header)) raise "ITRP upload to #{itrp[:upload_uri]} for #{key} failed: #{response.message}" unless response.valid? end
[ "def", "itrp_upload", "(", "itrp", ",", "key_template", ",", "key", ",", "attachment", ")", "uri", "=", "itrp", "[", ":upload_uri", "]", "=~", "/", "\\/", "/", "?", "itrp", "[", ":upload_uri", "]", ":", "itrp", "[", ":upload_uri", "]", ".", "gsub", "(", "'/attachments'", ",", "'/v1/attachments'", ")", "response", "=", "send_file", "(", "uri", ",", "{", "file", ":", "attachment", ",", "key", ":", "key_template", "}", ",", "@client", ".", "send", "(", ":expand_header", ")", ")", "raise", "\"ITRP upload to #{itrp[:upload_uri]} for #{key} failed: #{response.message}\"", "unless", "response", ".", "valid?", "end" ]
upload the file directly to ITRP
[ "upload", "the", "file", "directly", "to", "ITRP" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client/attachments.rb#L93-L97
24,608
devp/sanitize_attributes
lib/sanitize_attributes/macros.rb
SanitizeAttributes.Macros.sanitize_attributes
def sanitize_attributes(*args, &block) if (args.last && args.last.is_a?(Hash)) options = args.pop end options ||= {} unless @sanitize_hook_already_defined include InstanceMethods extend ClassMethods if options[:before_validation] before_validation :sanitize! else before_save :sanitize! end cattr_accessor :sanitizable_attribute_hash cattr_accessor :sanitization_block_array self.sanitizable_attribute_hash ||= {} self.sanitization_block_array ||= [] @sanitize_hook_already_defined = true end if block self.sanitization_block_array << block block = self.sanitization_block_array.index(block) else block = nil end args.each do |attr| self.sanitizable_attribute_hash[attr] = block end true end
ruby
def sanitize_attributes(*args, &block) if (args.last && args.last.is_a?(Hash)) options = args.pop end options ||= {} unless @sanitize_hook_already_defined include InstanceMethods extend ClassMethods if options[:before_validation] before_validation :sanitize! else before_save :sanitize! end cattr_accessor :sanitizable_attribute_hash cattr_accessor :sanitization_block_array self.sanitizable_attribute_hash ||= {} self.sanitization_block_array ||= [] @sanitize_hook_already_defined = true end if block self.sanitization_block_array << block block = self.sanitization_block_array.index(block) else block = nil end args.each do |attr| self.sanitizable_attribute_hash[attr] = block end true end
[ "def", "sanitize_attributes", "(", "*", "args", ",", "&", "block", ")", "if", "(", "args", ".", "last", "&&", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", ")", "options", "=", "args", ".", "pop", "end", "options", "||=", "{", "}", "unless", "@sanitize_hook_already_defined", "include", "InstanceMethods", "extend", "ClassMethods", "if", "options", "[", ":before_validation", "]", "before_validation", ":sanitize!", "else", "before_save", ":sanitize!", "end", "cattr_accessor", ":sanitizable_attribute_hash", "cattr_accessor", ":sanitization_block_array", "self", ".", "sanitizable_attribute_hash", "||=", "{", "}", "self", ".", "sanitization_block_array", "||=", "[", "]", "@sanitize_hook_already_defined", "=", "true", "end", "if", "block", "self", ".", "sanitization_block_array", "<<", "block", "block", "=", "self", ".", "sanitization_block_array", ".", "index", "(", "block", ")", "else", "block", "=", "nil", "end", "args", ".", "each", "do", "|", "attr", "|", "self", ".", "sanitizable_attribute_hash", "[", "attr", "]", "=", "block", "end", "true", "end" ]
sanitize_attributes is used to define sanitizable attributes within a model definition.
[ "sanitize_attributes", "is", "used", "to", "define", "sanitizable", "attributes", "within", "a", "model", "definition", "." ]
75f482b58d0b82a84b70658dd752d4c5b6ea9f02
https://github.com/devp/sanitize_attributes/blob/75f482b58d0b82a84b70658dd752d4c5b6ea9f02/lib/sanitize_attributes/macros.rb#L4-L39
24,609
vito/atomy
lib/atomy/locals.rb
Atomy.EvalLocalState.search_local
def search_local(name) if variable = variables[name] return variable.nested_reference end if variable = search_scopes(name) variables[name] = variable return variable.nested_reference end end
ruby
def search_local(name) if variable = variables[name] return variable.nested_reference end if variable = search_scopes(name) variables[name] = variable return variable.nested_reference end end
[ "def", "search_local", "(", "name", ")", "if", "variable", "=", "variables", "[", "name", "]", "return", "variable", ".", "nested_reference", "end", "if", "variable", "=", "search_scopes", "(", "name", ")", "variables", "[", "name", "]", "=", "variable", "return", "variable", ".", "nested_reference", "end", "end" ]
Returns a cached reference to a variable or searches all surrounding scopes for a variable. If no variable is found, it returns nil and a nested scope will create the variable in itself.
[ "Returns", "a", "cached", "reference", "to", "a", "variable", "or", "searches", "all", "surrounding", "scopes", "for", "a", "variable", ".", "If", "no", "variable", "is", "found", "it", "returns", "nil", "and", "a", "nested", "scope", "will", "create", "the", "variable", "in", "itself", "." ]
12a4a233722979e5e96567943df86e92a81d9343
https://github.com/vito/atomy/blob/12a4a233722979e5e96567943df86e92a81d9343/lib/atomy/locals.rb#L33-L42
24,610
yas4891/stripe_invoice
app/helpers/stripe_invoice/invoices_helper.rb
StripeInvoice.InvoicesHelper.format_currency
def format_currency(amount, currency) currency = currency.upcase() # assuming that all currencies are split into 100 parts is probably wrong # on an i18n scale but it works for USD, EUR and LBP # TODO fix this maybe? amount = amount / 100.0 options = { # use comma for euro separator: currency == 'EUR' ? ',' : '.', delimiter: currency == 'EUR' ? '.' : ',', format: currency == 'EUR' ? '%n %u' : '%u%n', } case currency when 'EUR' options[:unit] = '€' when 'LBP' options[:unit] = '£' when 'USD' options[:unit] = '$' else options[:unit] = currency end return number_to_currency(amount, options) end
ruby
def format_currency(amount, currency) currency = currency.upcase() # assuming that all currencies are split into 100 parts is probably wrong # on an i18n scale but it works for USD, EUR and LBP # TODO fix this maybe? amount = amount / 100.0 options = { # use comma for euro separator: currency == 'EUR' ? ',' : '.', delimiter: currency == 'EUR' ? '.' : ',', format: currency == 'EUR' ? '%n %u' : '%u%n', } case currency when 'EUR' options[:unit] = '€' when 'LBP' options[:unit] = '£' when 'USD' options[:unit] = '$' else options[:unit] = currency end return number_to_currency(amount, options) end
[ "def", "format_currency", "(", "amount", ",", "currency", ")", "currency", "=", "currency", ".", "upcase", "(", ")", "# assuming that all currencies are split into 100 parts is probably wrong", "# on an i18n scale but it works for USD, EUR and LBP", "# TODO fix this maybe?", "amount", "=", "amount", "/", "100.0", "options", "=", "{", "# use comma for euro ", "separator", ":", "currency", "==", "'EUR'", "?", "','", ":", "'.'", ",", "delimiter", ":", "currency", "==", "'EUR'", "?", "'.'", ":", "','", ",", "format", ":", "currency", "==", "'EUR'", "?", "'%n %u'", ":", "'%u%n'", ",", "}", "case", "currency", "when", "'EUR'", "options", "[", ":unit", "]", "=", "'€' ", "when", "'LBP'", "options", "[", ":unit", "]", "=", "'£'", "when", "'USD'", "options", "[", ":unit", "]", "=", "'$'", "else", "options", "[", ":unit", "]", "=", "currency", "end", "return", "number_to_currency", "(", "amount", ",", "options", ")", "end" ]
nicely formats the amount and currency
[ "nicely", "formats", "the", "amount", "and", "currency" ]
7b97dc0fb908e1648712fce69adb2fa689467c7a
https://github.com/yas4891/stripe_invoice/blob/7b97dc0fb908e1648712fce69adb2fa689467c7a/app/helpers/stripe_invoice/invoices_helper.rb#L5-L29
24,611
movitto/reterm
lib/reterm/color_pair.rb
RETerm.ColorPair.format
def format(win) win.win.attron(nc) yield win.win.attroff(nc) end
ruby
def format(win) win.win.attron(nc) yield win.win.attroff(nc) end
[ "def", "format", "(", "win", ")", "win", ".", "win", ".", "attron", "(", "nc", ")", "yield", "win", ".", "win", ".", "attroff", "(", "nc", ")", "end" ]
Encapsulates window operation in color pair attribute
[ "Encapsulates", "window", "operation", "in", "color", "pair", "attribute" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/color_pair.rb#L177-L181
24,612
chef-workflow/chef-workflow
lib/chef-workflow/support/scheduler.rb
ChefWorkflow.Scheduler.schedule_provision
def schedule_provision(group_name, provisioner, dependencies=[]) return nil if vm_groups[group_name] provisioner = [provisioner] unless provisioner.kind_of?(Array) provisioner.each { |x| x.name = group_name } vm_groups[group_name] = provisioner unless dependencies.all? { |x| vm_groups.has_key?(x) } raise "One of your dependencies for #{group_name} has not been pre-declared. Cannot continue" end vm_dependencies[group_name] = dependencies.to_set @waiters_mutex.synchronize do @waiters.add(group_name) end end
ruby
def schedule_provision(group_name, provisioner, dependencies=[]) return nil if vm_groups[group_name] provisioner = [provisioner] unless provisioner.kind_of?(Array) provisioner.each { |x| x.name = group_name } vm_groups[group_name] = provisioner unless dependencies.all? { |x| vm_groups.has_key?(x) } raise "One of your dependencies for #{group_name} has not been pre-declared. Cannot continue" end vm_dependencies[group_name] = dependencies.to_set @waiters_mutex.synchronize do @waiters.add(group_name) end end
[ "def", "schedule_provision", "(", "group_name", ",", "provisioner", ",", "dependencies", "=", "[", "]", ")", "return", "nil", "if", "vm_groups", "[", "group_name", "]", "provisioner", "=", "[", "provisioner", "]", "unless", "provisioner", ".", "kind_of?", "(", "Array", ")", "provisioner", ".", "each", "{", "|", "x", "|", "x", ".", "name", "=", "group_name", "}", "vm_groups", "[", "group_name", "]", "=", "provisioner", "unless", "dependencies", ".", "all?", "{", "|", "x", "|", "vm_groups", ".", "has_key?", "(", "x", ")", "}", "raise", "\"One of your dependencies for #{group_name} has not been pre-declared. Cannot continue\"", "end", "vm_dependencies", "[", "group_name", "]", "=", "dependencies", ".", "to_set", "@waiters_mutex", ".", "synchronize", "do", "@waiters", ".", "add", "(", "group_name", ")", "end", "end" ]
Schedule a group of VMs for provision. This takes a group name, which is a string, an array of provisioner objects, and a list of string dependencies. If anything in the dependencies list hasn't been pre-declared, it refuses to continue. This method will return nil if the server group is already provisioned.
[ "Schedule", "a", "group", "of", "VMs", "for", "provision", ".", "This", "takes", "a", "group", "name", "which", "is", "a", "string", "an", "array", "of", "provisioner", "objects", "and", "a", "list", "of", "string", "dependencies", ".", "If", "anything", "in", "the", "dependencies", "list", "hasn", "t", "been", "pre", "-", "declared", "it", "refuses", "to", "continue", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/scheduler.rb#L89-L103
24,613
chef-workflow/chef-workflow
lib/chef-workflow/support/scheduler.rb
ChefWorkflow.Scheduler.wait_for
def wait_for(*dependencies) return nil if @serial return nil if dependencies.empty? dep_set = dependencies.to_set until dep_set & solved == dep_set sleep 1 @solver_thread.join unless @solver_thread.alive? end end
ruby
def wait_for(*dependencies) return nil if @serial return nil if dependencies.empty? dep_set = dependencies.to_set until dep_set & solved == dep_set sleep 1 @solver_thread.join unless @solver_thread.alive? end end
[ "def", "wait_for", "(", "*", "dependencies", ")", "return", "nil", "if", "@serial", "return", "nil", "if", "dependencies", ".", "empty?", "dep_set", "=", "dependencies", ".", "to_set", "until", "dep_set", "&", "solved", "==", "dep_set", "sleep", "1", "@solver_thread", ".", "join", "unless", "@solver_thread", ".", "alive?", "end", "end" ]
Sleep until this list of dependencies are resolved. In parallel mode, will raise if an exeception occurred while waiting for these resources. In serial mode, wait_for just returns nil.
[ "Sleep", "until", "this", "list", "of", "dependencies", "are", "resolved", ".", "In", "parallel", "mode", "will", "raise", "if", "an", "exeception", "occurred", "while", "waiting", "for", "these", "resources", ".", "In", "serial", "mode", "wait_for", "just", "returns", "nil", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/scheduler.rb#L110-L119
24,614
chef-workflow/chef-workflow
lib/chef-workflow/support/scheduler.rb
ChefWorkflow.Scheduler.with_timeout
def with_timeout(do_loop=true) Timeout.timeout(10) do dead_working = @working.values.reject(&:alive?) if dead_working.size > 0 dead_working.map(&:join) end yield end rescue TimeoutError retry if do_loop end
ruby
def with_timeout(do_loop=true) Timeout.timeout(10) do dead_working = @working.values.reject(&:alive?) if dead_working.size > 0 dead_working.map(&:join) end yield end rescue TimeoutError retry if do_loop end
[ "def", "with_timeout", "(", "do_loop", "=", "true", ")", "Timeout", ".", "timeout", "(", "10", ")", "do", "dead_working", "=", "@working", ".", "values", ".", "reject", "(", ":alive?", ")", "if", "dead_working", ".", "size", ">", "0", "dead_working", ".", "map", "(", ":join", ")", "end", "yield", "end", "rescue", "TimeoutError", "retry", "if", "do_loop", "end" ]
Helper method for scheduling. Wraps items in a timeout and immediately checks all running workers for exceptions, which are immediately bubbled up if there are any. If do_loop is true, it will retry the timeout.
[ "Helper", "method", "for", "scheduling", ".", "Wraps", "items", "in", "a", "timeout", "and", "immediately", "checks", "all", "running", "workers", "for", "exceptions", "which", "are", "immediately", "bubbled", "up", "if", "there", "are", "any", ".", "If", "do_loop", "is", "true", "it", "will", "retry", "the", "timeout", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/scheduler.rb#L126-L137
24,615
chef-workflow/chef-workflow
lib/chef-workflow/support/scheduler.rb
ChefWorkflow.Scheduler.service_resolved_waiters
def service_resolved_waiters @waiters_mutex.synchronize do @waiters.replace(@waiters.to_set - (@working.keys.to_set + solved)) end waiter_iteration = lambda do @waiters.each do |group_name| if (solved.to_set & vm_dependencies[group_name]).to_a == vm_dependencies[group_name] if_debug do $stderr.puts "Provisioning #{group_name}" end provisioner = vm_groups[group_name] provision_block = lambda do # FIXME maybe a way to specify initial args? args = nil provisioner.each do |this_prov| vm_groups[group_name] = provisioner # force a write to the db unless args = this_prov.startup(args) $stderr.puts "Could not provision #{group_name} with provisioner #{this_prov.class.name}" raise "Could not provision #{group_name} with provisioner #{this_prov.class.name}" end end @queue << group_name end vm_working.add(group_name) if @serial # HACK: just give the working check something that will always work. # Probably should just mock it. @working[group_name] = Thread.new { sleep } provision_block.call else @working[group_name] = Thread.new(&provision_block) end end end end if @serial waiter_iteration.call else @waiters_mutex.synchronize(&waiter_iteration) end end
ruby
def service_resolved_waiters @waiters_mutex.synchronize do @waiters.replace(@waiters.to_set - (@working.keys.to_set + solved)) end waiter_iteration = lambda do @waiters.each do |group_name| if (solved.to_set & vm_dependencies[group_name]).to_a == vm_dependencies[group_name] if_debug do $stderr.puts "Provisioning #{group_name}" end provisioner = vm_groups[group_name] provision_block = lambda do # FIXME maybe a way to specify initial args? args = nil provisioner.each do |this_prov| vm_groups[group_name] = provisioner # force a write to the db unless args = this_prov.startup(args) $stderr.puts "Could not provision #{group_name} with provisioner #{this_prov.class.name}" raise "Could not provision #{group_name} with provisioner #{this_prov.class.name}" end end @queue << group_name end vm_working.add(group_name) if @serial # HACK: just give the working check something that will always work. # Probably should just mock it. @working[group_name] = Thread.new { sleep } provision_block.call else @working[group_name] = Thread.new(&provision_block) end end end end if @serial waiter_iteration.call else @waiters_mutex.synchronize(&waiter_iteration) end end
[ "def", "service_resolved_waiters", "@waiters_mutex", ".", "synchronize", "do", "@waiters", ".", "replace", "(", "@waiters", ".", "to_set", "-", "(", "@working", ".", "keys", ".", "to_set", "+", "solved", ")", ")", "end", "waiter_iteration", "=", "lambda", "do", "@waiters", ".", "each", "do", "|", "group_name", "|", "if", "(", "solved", ".", "to_set", "&", "vm_dependencies", "[", "group_name", "]", ")", ".", "to_a", "==", "vm_dependencies", "[", "group_name", "]", "if_debug", "do", "$stderr", ".", "puts", "\"Provisioning #{group_name}\"", "end", "provisioner", "=", "vm_groups", "[", "group_name", "]", "provision_block", "=", "lambda", "do", "# FIXME maybe a way to specify initial args?", "args", "=", "nil", "provisioner", ".", "each", "do", "|", "this_prov", "|", "vm_groups", "[", "group_name", "]", "=", "provisioner", "# force a write to the db", "unless", "args", "=", "this_prov", ".", "startup", "(", "args", ")", "$stderr", ".", "puts", "\"Could not provision #{group_name} with provisioner #{this_prov.class.name}\"", "raise", "\"Could not provision #{group_name} with provisioner #{this_prov.class.name}\"", "end", "end", "@queue", "<<", "group_name", "end", "vm_working", ".", "add", "(", "group_name", ")", "if", "@serial", "# HACK: just give the working check something that will always work.", "# Probably should just mock it.", "@working", "[", "group_name", "]", "=", "Thread", ".", "new", "{", "sleep", "}", "provision_block", ".", "call", "else", "@working", "[", "group_name", "]", "=", "Thread", ".", "new", "(", "provision_block", ")", "end", "end", "end", "end", "if", "@serial", "waiter_iteration", ".", "call", "else", "@waiters_mutex", ".", "synchronize", "(", "waiter_iteration", ")", "end", "end" ]
This method determines what 'waiters', or provisioners that cannot provision yet because of unresolved dependencies, can be executed.
[ "This", "method", "determines", "what", "waiters", "or", "provisioners", "that", "cannot", "provision", "yet", "because", "of", "unresolved", "dependencies", "can", "be", "executed", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/scheduler.rb#L245-L291
24,616
movitto/reterm
lib/reterm/layout.rb
RETerm.Layout.layout_containing
def layout_containing(component) return self if children.include?(component) found = nil children.each { |c| next if found if c.kind_of?(Layout) found = c unless c.layout_containing(component).nil? end } found end
ruby
def layout_containing(component) return self if children.include?(component) found = nil children.each { |c| next if found if c.kind_of?(Layout) found = c unless c.layout_containing(component).nil? end } found end
[ "def", "layout_containing", "(", "component", ")", "return", "self", "if", "children", ".", "include?", "(", "component", ")", "found", "=", "nil", "children", ".", "each", "{", "|", "c", "|", "next", "if", "found", "if", "c", ".", "kind_of?", "(", "Layout", ")", "found", "=", "c", "unless", "c", ".", "layout_containing", "(", "component", ")", ".", "nil?", "end", "}", "found", "end" ]
Return layout containing component If coordinates are contained in a child in current layout
[ "Return", "layout", "containing", "component", "If", "coordinates", "are", "contained", "in", "a", "child", "in", "current", "layout" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/layout.rb#L73-L86
24,617
movitto/reterm
lib/reterm/layout.rb
RETerm.Layout.contains?
def contains?(child) children.any? { |c| (c.kind_of?(Layout) && c.contains?(child)) || c == child } end
ruby
def contains?(child) children.any? { |c| (c.kind_of?(Layout) && c.contains?(child)) || c == child } end
[ "def", "contains?", "(", "child", ")", "children", ".", "any?", "{", "|", "c", "|", "(", "c", ".", "kind_of?", "(", "Layout", ")", "&&", "c", ".", "contains?", "(", "child", ")", ")", "||", "c", "==", "child", "}", "end" ]
Return boolean indicating if layout contains specified child
[ "Return", "boolean", "indicating", "if", "layout", "contains", "specified", "child" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/layout.rb#L89-L93
24,618
movitto/reterm
lib/reterm/layout.rb
RETerm.Layout.add_child
def add_child(h={}) c = nil if h.key?(:component) c = h[:component] h = {:rows => c.requested_rows + c.extra_padding, :cols => c.requested_cols + c.extra_padding}.merge(h) end raise ArgumentError, "must specify x/y" unless h.key?(:x) && h.key?(:y) raise ArgumentError, "must specify rows/cols" unless h.key?(:rows) && h.key?(:cols) h[:rows], h[:cols] = *Window.adjust_proportional(window, h[:rows], h[:cols]) h[:x], h[:y] = *Window.align(window, h[:x], h[:y], h[:rows], h[:cols]) h[:rows], h[:cols] = *Window.fill_parent(parent? ? parent.window : Terminal, h[:x], h[:y], h[:rows], h[:cols]) if h[:fill] if exceeds_bounds_with?(h) if expandable? # ... && can_expand_to?(h) expand(h) else raise ArgumentError, "child exceeds bounds" end end child = window.create_child(h) # TODO need to reverse expansion if operation fails at any # point on, or verify expandable before create_child but # do not expand until after if child.win.nil? raise ArgumentError, "could not create child window" end if exceeds_bounds? window.del_child(child) unless child.win.nil? raise ArgumentError, "child exceeds bounds" end child.component = c unless c.nil? update_reterm child end
ruby
def add_child(h={}) c = nil if h.key?(:component) c = h[:component] h = {:rows => c.requested_rows + c.extra_padding, :cols => c.requested_cols + c.extra_padding}.merge(h) end raise ArgumentError, "must specify x/y" unless h.key?(:x) && h.key?(:y) raise ArgumentError, "must specify rows/cols" unless h.key?(:rows) && h.key?(:cols) h[:rows], h[:cols] = *Window.adjust_proportional(window, h[:rows], h[:cols]) h[:x], h[:y] = *Window.align(window, h[:x], h[:y], h[:rows], h[:cols]) h[:rows], h[:cols] = *Window.fill_parent(parent? ? parent.window : Terminal, h[:x], h[:y], h[:rows], h[:cols]) if h[:fill] if exceeds_bounds_with?(h) if expandable? # ... && can_expand_to?(h) expand(h) else raise ArgumentError, "child exceeds bounds" end end child = window.create_child(h) # TODO need to reverse expansion if operation fails at any # point on, or verify expandable before create_child but # do not expand until after if child.win.nil? raise ArgumentError, "could not create child window" end if exceeds_bounds? window.del_child(child) unless child.win.nil? raise ArgumentError, "child exceeds bounds" end child.component = c unless c.nil? update_reterm child end
[ "def", "add_child", "(", "h", "=", "{", "}", ")", "c", "=", "nil", "if", "h", ".", "key?", "(", ":component", ")", "c", "=", "h", "[", ":component", "]", "h", "=", "{", ":rows", "=>", "c", ".", "requested_rows", "+", "c", ".", "extra_padding", ",", ":cols", "=>", "c", ".", "requested_cols", "+", "c", ".", "extra_padding", "}", ".", "merge", "(", "h", ")", "end", "raise", "ArgumentError", ",", "\"must specify x/y\"", "unless", "h", ".", "key?", "(", ":x", ")", "&&", "h", ".", "key?", "(", ":y", ")", "raise", "ArgumentError", ",", "\"must specify rows/cols\"", "unless", "h", ".", "key?", "(", ":rows", ")", "&&", "h", ".", "key?", "(", ":cols", ")", "h", "[", ":rows", "]", ",", "h", "[", ":cols", "]", "=", "Window", ".", "adjust_proportional", "(", "window", ",", "h", "[", ":rows", "]", ",", "h", "[", ":cols", "]", ")", "h", "[", ":x", "]", ",", "h", "[", ":y", "]", "=", "Window", ".", "align", "(", "window", ",", "h", "[", ":x", "]", ",", "h", "[", ":y", "]", ",", "h", "[", ":rows", "]", ",", "h", "[", ":cols", "]", ")", "h", "[", ":rows", "]", ",", "h", "[", ":cols", "]", "=", "Window", ".", "fill_parent", "(", "parent?", "?", "parent", ".", "window", ":", "Terminal", ",", "h", "[", ":x", "]", ",", "h", "[", ":y", "]", ",", "h", "[", ":rows", "]", ",", "h", "[", ":cols", "]", ")", "if", "h", "[", ":fill", "]", "if", "exceeds_bounds_with?", "(", "h", ")", "if", "expandable?", "# ... && can_expand_to?(h)", "expand", "(", "h", ")", "else", "raise", "ArgumentError", ",", "\"child exceeds bounds\"", "end", "end", "child", "=", "window", ".", "create_child", "(", "h", ")", "# TODO need to reverse expansion if operation fails at any", "# point on, or verify expandable before create_child but", "# do not expand until after", "if", "child", ".", "win", ".", "nil?", "raise", "ArgumentError", ",", "\"could not create child window\"", "end", "if", "exceeds_bounds?", "window", ".", "del_child", "(", "child", ")", "unless", "child", ".", "win", ".", "nil?", "raise", "ArgumentError", ",", "\"child exceeds bounds\"", "end", "child", ".", "component", "=", "c", "unless", "c", ".", "nil?", "update_reterm", "child", "end" ]
Create new child window and add it to layout
[ "Create", "new", "child", "window", "and", "add", "it", "to", "layout" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/layout.rb#L107-L158
24,619
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.select
def select(&predicate) filter("select") do |yielder| each do |element| yielder.call(element) if yield(element) end end end
ruby
def select(&predicate) filter("select") do |yielder| each do |element| yielder.call(element) if yield(element) end end end
[ "def", "select", "(", "&", "predicate", ")", "filter", "(", "\"select\"", ")", "do", "|", "yielder", "|", "each", "do", "|", "element", "|", "yielder", ".", "call", "(", "element", ")", "if", "yield", "(", "element", ")", "end", "end", "end" ]
Select elements using a predicate block. @return [Enumerable] the elements that pass the predicate @see ::Enumerable#select
[ "Select", "elements", "using", "a", "predicate", "block", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L28-L34
24,620
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.uniq
def uniq filter("uniq") do |yielder| seen = Set.new each do |element| key = if block_given? yield element else element end yielder.call(element) if seen.add?(key) end end end
ruby
def uniq filter("uniq") do |yielder| seen = Set.new each do |element| key = if block_given? yield element else element end yielder.call(element) if seen.add?(key) end end end
[ "def", "uniq", "filter", "(", "\"uniq\"", ")", "do", "|", "yielder", "|", "seen", "=", "Set", ".", "new", "each", "do", "|", "element", "|", "key", "=", "if", "block_given?", "yield", "element", "else", "element", "end", "yielder", ".", "call", "(", "element", ")", "if", "seen", ".", "add?", "(", "key", ")", "end", "end", "end" ]
Remove duplicate values. @return [Enumerable] elements which have not been previously encountered @overload uniq @overload uniq(&block) @see ::Enumerable#uniq
[ "Remove", "duplicate", "values", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L63-L75
24,621
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.take
def take(n) filter("take") do |yielder, all_done| if n > 0 each_with_index do |element, index| yielder.call(element) throw all_done if index + 1 == n end end end end
ruby
def take(n) filter("take") do |yielder, all_done| if n > 0 each_with_index do |element, index| yielder.call(element) throw all_done if index + 1 == n end end end end
[ "def", "take", "(", "n", ")", "filter", "(", "\"take\"", ")", "do", "|", "yielder", ",", "all_done", "|", "if", "n", ">", "0", "each_with_index", "do", "|", "element", ",", "index", "|", "yielder", ".", "call", "(", "element", ")", "throw", "all_done", "if", "index", "+", "1", "==", "n", "end", "end", "end", "end" ]
Select the first n elements. @param n [Integer] the number of elements to take @return [Enumerable] the first N elements @see ::Enumerable#take
[ "Select", "the", "first", "n", "elements", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L84-L93
24,622
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.take_while
def take_while(&predicate) filter("take_while") do |yielder, all_done| each do |element| throw all_done unless yield(element) yielder.call(element) end end end
ruby
def take_while(&predicate) filter("take_while") do |yielder, all_done| each do |element| throw all_done unless yield(element) yielder.call(element) end end end
[ "def", "take_while", "(", "&", "predicate", ")", "filter", "(", "\"take_while\"", ")", "do", "|", "yielder", ",", "all_done", "|", "each", "do", "|", "element", "|", "throw", "all_done", "unless", "yield", "(", "element", ")", "yielder", ".", "call", "(", "element", ")", "end", "end", "end" ]
Select elements while a predicate returns true. @return [Enumerable] all elements before the first that fails the predicate @see ::Enumerable#take_while
[ "Select", "elements", "while", "a", "predicate", "returns", "true", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L101-L108
24,623
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.drop
def drop(n) filter("drop") do |yielder| each_with_index do |element, index| next if index < n yielder.call(element) end end end
ruby
def drop(n) filter("drop") do |yielder| each_with_index do |element, index| next if index < n yielder.call(element) end end end
[ "def", "drop", "(", "n", ")", "filter", "(", "\"drop\"", ")", "do", "|", "yielder", "|", "each_with_index", "do", "|", "element", ",", "index", "|", "next", "if", "index", "<", "n", "yielder", ".", "call", "(", "element", ")", "end", "end", "end" ]
Ignore the first n elements. @param n [Integer] the number of elements to drop @return [Enumerable] elements after the first N @see ::Enumerable#drop
[ "Ignore", "the", "first", "n", "elements", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L117-L124
24,624
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.drop_while
def drop_while(&predicate) filter("drop_while") do |yielder| take = false each do |element| take ||= !yield(element) yielder.call(element) if take end end end
ruby
def drop_while(&predicate) filter("drop_while") do |yielder| take = false each do |element| take ||= !yield(element) yielder.call(element) if take end end end
[ "def", "drop_while", "(", "&", "predicate", ")", "filter", "(", "\"drop_while\"", ")", "do", "|", "yielder", "|", "take", "=", "false", "each", "do", "|", "element", "|", "take", "||=", "!", "yield", "(", "element", ")", "yielder", ".", "call", "(", "element", ")", "if", "take", "end", "end", "end" ]
Reject elements while a predicate returns true. @return [Enumerable] all elements including and after the first that fails the predicate @see ::Enumerable#drop_while
[ "Reject", "elements", "while", "a", "predicate", "returns", "true", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L132-L140
24,625
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.grep
def grep(pattern) filter("grep") do |yielder| each do |element| if pattern === element result = if block_given? yield element else element end yielder.call(result) end end end end
ruby
def grep(pattern) filter("grep") do |yielder| each do |element| if pattern === element result = if block_given? yield element else element end yielder.call(result) end end end end
[ "def", "grep", "(", "pattern", ")", "filter", "(", "\"grep\"", ")", "do", "|", "yielder", "|", "each", "do", "|", "element", "|", "if", "pattern", "===", "element", "result", "=", "if", "block_given?", "yield", "element", "else", "element", "end", "yielder", ".", "call", "(", "result", ")", "end", "end", "end", "end" ]
Select elements matching a pattern. @return [Enumerable] elements for which the pattern matches @see ::Enumerable#grep
[ "Select", "elements", "matching", "a", "pattern", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L148-L161
24,626
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.flatten
def flatten(level = 1) filter("flatten") do |yielder| each do |element| if level > 0 && element.respond_to?(:each) element.flatten(level - 1).each(&yielder) else yielder.call(element) end end end end
ruby
def flatten(level = 1) filter("flatten") do |yielder| each do |element| if level > 0 && element.respond_to?(:each) element.flatten(level - 1).each(&yielder) else yielder.call(element) end end end end
[ "def", "flatten", "(", "level", "=", "1", ")", "filter", "(", "\"flatten\"", ")", "do", "|", "yielder", "|", "each", "do", "|", "element", "|", "if", "level", ">", "0", "&&", "element", ".", "respond_to?", "(", ":each", ")", "element", ".", "flatten", "(", "level", "-", "1", ")", ".", "each", "(", "yielder", ")", "else", "yielder", ".", "call", "(", "element", ")", "end", "end", "end", "end" ]
Flatten the collection, such that Enumerable elements are included inline. @return [Enumerable] elements of elements of the collection @see ::Array#flatten
[ "Flatten", "the", "collection", "such", "that", "Enumerable", "elements", "are", "included", "inline", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L169-L179
24,627
mdub/lazily
lib/lazily/filtering.rb
Lazily.Enumerable.compact
def compact filter("compact") do |yielder| each do |element| yielder.call(element) unless element.nil? end end end
ruby
def compact filter("compact") do |yielder| each do |element| yielder.call(element) unless element.nil? end end end
[ "def", "compact", "filter", "(", "\"compact\"", ")", "do", "|", "yielder", "|", "each", "do", "|", "element", "|", "yielder", ".", "call", "(", "element", ")", "unless", "element", ".", "nil?", "end", "end", "end" ]
Ignore nil values. @return [Enumerable] the elements that are not nil @see ::Array#compact
[ "Ignore", "nil", "values", "." ]
8665e3532ea2d2ea3a41e6ec6a47088308979754
https://github.com/mdub/lazily/blob/8665e3532ea2d2ea3a41e6ec6a47088308979754/lib/lazily/filtering.rb#L193-L199
24,628
movitto/reterm
lib/reterm/mixins/nav_input.rb
RETerm.NavInput.handle_input
def handle_input(from_parent=false) @focus ||= 0 # focus on first component ch = handle_focused unless nav_select # Repeat until quit until quit_nav?(ch) # Navigate to the specified component (nav_select) if self.nav_select # it is a descendent of this one if self.contains?(self.nav_select) nav_to_selected # specified component is not a descendent, else nav_to_parent return nil end elsif ENTER_CONTROLS.include?(ch) focused.activate! elsif MOVEMENT_CONTROLS.include?(ch) handle_movement(ch, from_parent) elsif mev = process_mouse(ch) handle_mouse(mev) else dispatch(:entry, ch) end return ch unless sanitize_focus!(from_parent) ch = handle_focused unless nav_select || shutdown? || deactivate? end ch end
ruby
def handle_input(from_parent=false) @focus ||= 0 # focus on first component ch = handle_focused unless nav_select # Repeat until quit until quit_nav?(ch) # Navigate to the specified component (nav_select) if self.nav_select # it is a descendent of this one if self.contains?(self.nav_select) nav_to_selected # specified component is not a descendent, else nav_to_parent return nil end elsif ENTER_CONTROLS.include?(ch) focused.activate! elsif MOVEMENT_CONTROLS.include?(ch) handle_movement(ch, from_parent) elsif mev = process_mouse(ch) handle_mouse(mev) else dispatch(:entry, ch) end return ch unless sanitize_focus!(from_parent) ch = handle_focused unless nav_select || shutdown? || deactivate? end ch end
[ "def", "handle_input", "(", "from_parent", "=", "false", ")", "@focus", "||=", "0", "# focus on first component", "ch", "=", "handle_focused", "unless", "nav_select", "# Repeat until quit", "until", "quit_nav?", "(", "ch", ")", "# Navigate to the specified component (nav_select)", "if", "self", ".", "nav_select", "# it is a descendent of this one", "if", "self", ".", "contains?", "(", "self", ".", "nav_select", ")", "nav_to_selected", "# specified component is not a descendent,", "else", "nav_to_parent", "return", "nil", "end", "elsif", "ENTER_CONTROLS", ".", "include?", "(", "ch", ")", "focused", ".", "activate!", "elsif", "MOVEMENT_CONTROLS", ".", "include?", "(", "ch", ")", "handle_movement", "(", "ch", ",", "from_parent", ")", "elsif", "mev", "=", "process_mouse", "(", "ch", ")", "handle_mouse", "(", "mev", ")", "else", "dispatch", "(", ":entry", ",", "ch", ")", "end", "return", "ch", "unless", "sanitize_focus!", "(", "from_parent", ")", "ch", "=", "handle_focused", "unless", "nav_select", "||", "shutdown?", "||", "deactivate?", "end", "ch", "end" ]
Helper to be internally invoked by navigation component on activation
[ "Helper", "to", "be", "internally", "invoked", "by", "navigation", "component", "on", "activation" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/nav_input.rb#L37-L79
24,629
movitto/reterm
lib/reterm/mixins/nav_input.rb
RETerm.NavInput.handle_focused
def handle_focused ch = nil focused.dispatch :focused update_focus if focused.activate_focus? focused.activate! elsif focused.kind_of?(Layout) ch = focused.handle_input(true) elsif !deactivate? && !nav_select ch = sync_getch end if self.ch_select ch = self.ch_select self.ch_select = nil end ch end
ruby
def handle_focused ch = nil focused.dispatch :focused update_focus if focused.activate_focus? focused.activate! elsif focused.kind_of?(Layout) ch = focused.handle_input(true) elsif !deactivate? && !nav_select ch = sync_getch end if self.ch_select ch = self.ch_select self.ch_select = nil end ch end
[ "def", "handle_focused", "ch", "=", "nil", "focused", ".", "dispatch", ":focused", "update_focus", "if", "focused", ".", "activate_focus?", "focused", ".", "activate!", "elsif", "focused", ".", "kind_of?", "(", "Layout", ")", "ch", "=", "focused", ".", "handle_input", "(", "true", ")", "elsif", "!", "deactivate?", "&&", "!", "nav_select", "ch", "=", "sync_getch", "end", "if", "self", ".", "ch_select", "ch", "=", "self", ".", "ch_select", "self", ".", "ch_select", "=", "nil", "end", "ch", "end" ]
Internal helper, logic invoked when a component gains focus
[ "Internal", "helper", "logic", "invoked", "when", "a", "component", "gains", "focus" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/nav_input.rb#L118-L140
24,630
movitto/reterm
lib/reterm/mixins/nav_input.rb
RETerm.NavInput.nav_to_selected
def nav_to_selected # clear nav_select ns = self.nav_select self.nav_select = nil # specified component is a direct child if self.children.include?(ns) remove_focus @focus = focusable.index(ns) #handle_focused #update_focus #focused.activate! # not a direct child, navigate down to layout # containing it else child = self.layout_containing(ns) child.nav_select = ns ch = child.handle_input(true) end end
ruby
def nav_to_selected # clear nav_select ns = self.nav_select self.nav_select = nil # specified component is a direct child if self.children.include?(ns) remove_focus @focus = focusable.index(ns) #handle_focused #update_focus #focused.activate! # not a direct child, navigate down to layout # containing it else child = self.layout_containing(ns) child.nav_select = ns ch = child.handle_input(true) end end
[ "def", "nav_to_selected", "# clear nav_select", "ns", "=", "self", ".", "nav_select", "self", ".", "nav_select", "=", "nil", "# specified component is a direct child", "if", "self", ".", "children", ".", "include?", "(", "ns", ")", "remove_focus", "@focus", "=", "focusable", ".", "index", "(", "ns", ")", "#handle_focused", "#update_focus", "#focused.activate!", "# not a direct child, navigate down to layout", "# containing it", "else", "child", "=", "self", ".", "layout_containing", "(", "ns", ")", "child", ".", "nav_select", "=", "ns", "ch", "=", "child", ".", "handle_input", "(", "true", ")", "end", "end" ]
Internal helper, navigate to selected component under current
[ "Internal", "helper", "navigate", "to", "selected", "component", "under", "current" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/nav_input.rb#L149-L169
24,631
bluegod/rint
lib/interface/helpers.rb
Interface.Helpers.must_implement
def must_implement(*args) parsed_args(args).each do |method, arity| raise_interface_error(method, arity) unless valid_method?(method, arity) end end
ruby
def must_implement(*args) parsed_args(args).each do |method, arity| raise_interface_error(method, arity) unless valid_method?(method, arity) end end
[ "def", "must_implement", "(", "*", "args", ")", "parsed_args", "(", "args", ")", ".", "each", "do", "|", "method", ",", "arity", "|", "raise_interface_error", "(", "method", ",", "arity", ")", "unless", "valid_method?", "(", "method", ",", "arity", ")", "end", "end" ]
Errors raised here identify the class_name that is not implementing or is implemented with the wrong arity required by the Interface.
[ "Errors", "raised", "here", "identify", "the", "class_name", "that", "is", "not", "implementing", "or", "is", "implemented", "with", "the", "wrong", "arity", "required", "by", "the", "Interface", "." ]
bbe04035fed22df6a14cfaef869b2b9fa8e97dc4
https://github.com/bluegod/rint/blob/bbe04035fed22df6a14cfaef869b2b9fa8e97dc4/lib/interface/helpers.rb#L7-L11
24,632
bluegod/rint
lib/interface/helpers.rb
Interface.Helpers.parsed_args
def parsed_args(args) args.inject({}) do |memo, method| memo.merge(method.is_a?(Hash) ? method : { method => nil }) end end
ruby
def parsed_args(args) args.inject({}) do |memo, method| memo.merge(method.is_a?(Hash) ? method : { method => nil }) end end
[ "def", "parsed_args", "(", "args", ")", "args", ".", "inject", "(", "{", "}", ")", "do", "|", "memo", ",", "method", "|", "memo", ".", "merge", "(", "method", ".", "is_a?", "(", "Hash", ")", "?", "method", ":", "{", "method", "=>", "nil", "}", ")", "end", "end" ]
Transform symbol arguments to a hash of nil arity
[ "Transform", "symbol", "arguments", "to", "a", "hash", "of", "nil", "arity" ]
bbe04035fed22df6a14cfaef869b2b9fa8e97dc4
https://github.com/bluegod/rint/blob/bbe04035fed22df6a14cfaef869b2b9fa8e97dc4/lib/interface/helpers.rb#L16-L20
24,633
actfong/apilayer
lib/apilayer/connection_helper.rb
Apilayer.ConnectionHelper.get_request
def get_request(slug, params={}) # calls connection method on the extended module connection.get do |req| req.url "api/#{slug}" params.each_pair do |k,v| req.params[k] = v end end end
ruby
def get_request(slug, params={}) # calls connection method on the extended module connection.get do |req| req.url "api/#{slug}" params.each_pair do |k,v| req.params[k] = v end end end
[ "def", "get_request", "(", "slug", ",", "params", "=", "{", "}", ")", "# calls connection method on the extended module", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"api/#{slug}\"", "params", ".", "each_pair", "do", "|", "k", ",", "v", "|", "req", ".", "params", "[", "k", "]", "=", "v", "end", "end", "end" ]
Makes a get-request to apilayer's service
[ "Makes", "a", "get", "-", "request", "to", "apilayer", "s", "service" ]
976b2a6552247d0d345f312b804b72d17b618670
https://github.com/actfong/apilayer/blob/976b2a6552247d0d345f312b804b72d17b618670/lib/apilayer/connection_helper.rb#L50-L58
24,634
infosimples/infosimples-data
lib/infosimples/data/client.rb
Infosimples::Data.Client.download_sites_urls
def download_sites_urls(response) return [] if !response.is_a?(Hash) || (sites_urls = response.dig('receipt', 'sites_urls')).nil? sites_urls.map do |url| Infosimples::Data::HTTP.request(url: url, http_timeout: 30) end end
ruby
def download_sites_urls(response) return [] if !response.is_a?(Hash) || (sites_urls = response.dig('receipt', 'sites_urls')).nil? sites_urls.map do |url| Infosimples::Data::HTTP.request(url: url, http_timeout: 30) end end
[ "def", "download_sites_urls", "(", "response", ")", "return", "[", "]", "if", "!", "response", ".", "is_a?", "(", "Hash", ")", "||", "(", "sites_urls", "=", "response", ".", "dig", "(", "'receipt'", ",", "'sites_urls'", ")", ")", ".", "nil?", "sites_urls", ".", "map", "do", "|", "url", "|", "Infosimples", "::", "Data", "::", "HTTP", ".", "request", "(", "url", ":", "url", ",", "http_timeout", ":", "30", ")", "end", "end" ]
Download sites_urls from response. @param [Hash] response Response returned by #automate. @return [Array] HTML bodies from sites_urls.
[ "Download", "sites_urls", "from", "response", "." ]
3712c76a12eb24d27340ee3aa5c98fb7b13f36e0
https://github.com/infosimples/infosimples-data/blob/3712c76a12eb24d27340ee3aa5c98fb7b13f36e0/lib/infosimples/data/client.rb#L62-L68
24,635
infosimples/infosimples-data
lib/infosimples/data/client.rb
Infosimples::Data.Client.request
def request(service, method = :get, payload = {}) res = Infosimples::Data::HTTP.request( url: BASE_URL.gsub(':service', service), http_timeout: timeout, method: method, payload: payload.merge( token: token, timeout: timeout, max_age: max_age, header: 1 ) ) JSON.parse(res) end
ruby
def request(service, method = :get, payload = {}) res = Infosimples::Data::HTTP.request( url: BASE_URL.gsub(':service', service), http_timeout: timeout, method: method, payload: payload.merge( token: token, timeout: timeout, max_age: max_age, header: 1 ) ) JSON.parse(res) end
[ "def", "request", "(", "service", ",", "method", "=", ":get", ",", "payload", "=", "{", "}", ")", "res", "=", "Infosimples", "::", "Data", "::", "HTTP", ".", "request", "(", "url", ":", "BASE_URL", ".", "gsub", "(", "':service'", ",", "service", ")", ",", "http_timeout", ":", "timeout", ",", "method", ":", "method", ",", "payload", ":", "payload", ".", "merge", "(", "token", ":", "token", ",", "timeout", ":", "timeout", ",", "max_age", ":", "max_age", ",", "header", ":", "1", ")", ")", "JSON", ".", "parse", "(", "res", ")", "end" ]
Perform an HTTP request to the Infosimples Data API. @param [String] service API method name. @param [Symbol] method HTTP method (:get, :post, :multipart). @param [Hash] payload Data to be sent through the HTTP request. @return [Hash] Parsed JSON from the API response.
[ "Perform", "an", "HTTP", "request", "to", "the", "Infosimples", "Data", "API", "." ]
3712c76a12eb24d27340ee3aa5c98fb7b13f36e0
https://github.com/infosimples/infosimples-data/blob/3712c76a12eb24d27340ee3aa5c98fb7b13f36e0/lib/infosimples/data/client.rb#L90-L103
24,636
yas4891/stripe_invoice
app/models/stripe_invoice/charge.rb
StripeInvoice.Charge.source_country
def source_country # source can only be accessed via Customer cus = Stripe::Customer.retrieve self.indifferent_json[:customer] # TODO this is wrong, because there might be multiple sources and I # just randomly select the first one - also some source types might NOT even # have a country information cus.sources.data[0].country end
ruby
def source_country # source can only be accessed via Customer cus = Stripe::Customer.retrieve self.indifferent_json[:customer] # TODO this is wrong, because there might be multiple sources and I # just randomly select the first one - also some source types might NOT even # have a country information cus.sources.data[0].country end
[ "def", "source_country", "# source can only be accessed via Customer", "cus", "=", "Stripe", "::", "Customer", ".", "retrieve", "self", ".", "indifferent_json", "[", ":customer", "]", "# TODO this is wrong, because there might be multiple sources and I ", "# just randomly select the first one - also some source types might NOT even", "# have a country information", "cus", ".", "sources", ".", "data", "[", "0", "]", ".", "country", "end" ]
the country the source is registered in
[ "the", "country", "the", "source", "is", "registered", "in" ]
7b97dc0fb908e1648712fce69adb2fa689467c7a
https://github.com/yas4891/stripe_invoice/blob/7b97dc0fb908e1648712fce69adb2fa689467c7a/app/models/stripe_invoice/charge.rb#L75-L82
24,637
shanebdavis/Babel-Bridge
lib/babel_bridge/shell.rb
BabelBridge.Shell.start
def start(options={},&block) @stdout = options[:stdout] || $stdout @stderr = options[:stdout] || @stdout @stdin = options[:stdin] || $stdin while line = @stdin == $stdin ? Readline.readline("> ", true) : @stdin.gets line.strip! next if line.length==0 parse_tree_node = parser.parse line if parse_tree_node evaluate parse_tree_node, &block else errputs parser.parser_failure_info :verbose => true end end end
ruby
def start(options={},&block) @stdout = options[:stdout] || $stdout @stderr = options[:stdout] || @stdout @stdin = options[:stdin] || $stdin while line = @stdin == $stdin ? Readline.readline("> ", true) : @stdin.gets line.strip! next if line.length==0 parse_tree_node = parser.parse line if parse_tree_node evaluate parse_tree_node, &block else errputs parser.parser_failure_info :verbose => true end end end
[ "def", "start", "(", "options", "=", "{", "}", ",", "&", "block", ")", "@stdout", "=", "options", "[", ":stdout", "]", "||", "$stdout", "@stderr", "=", "options", "[", ":stdout", "]", "||", "@stdout", "@stdin", "=", "options", "[", ":stdin", "]", "||", "$stdin", "while", "line", "=", "@stdin", "==", "$stdin", "?", "Readline", ".", "readline", "(", "\"> \"", ",", "true", ")", ":", "@stdin", ".", "gets", "line", ".", "strip!", "next", "if", "line", ".", "length", "==", "0", "parse_tree_node", "=", "parser", ".", "parse", "line", "if", "parse_tree_node", "evaluate", "parse_tree_node", ",", "block", "else", "errputs", "parser", ".", "parser_failure_info", ":verbose", "=>", "true", "end", "end", "end" ]
Each line of input is parsed. If parser fails, output explaination of why. If parser succeeds, evaluate parse_tree_node, &block
[ "Each", "line", "of", "input", "is", "parsed", ".", "If", "parser", "fails", "output", "explaination", "of", "why", ".", "If", "parser", "succeeds", "evaluate", "parse_tree_node", "&block" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/shell.rb#L46-L60
24,638
platanus/negroku
lib/negroku/modes/env.rb
Negroku::Modes.Env.set_vars_to_stage
def set_vars_to_stage(stage, variables) # convert to array using VAR=value vars_array = variables.map{|k,v| "#{k}=#{v}" } Capistrano::Application.invoke(stage) Capistrano::Application.invoke("rbenv:vars:set", *vars_array) end
ruby
def set_vars_to_stage(stage, variables) # convert to array using VAR=value vars_array = variables.map{|k,v| "#{k}=#{v}" } Capistrano::Application.invoke(stage) Capistrano::Application.invoke("rbenv:vars:set", *vars_array) end
[ "def", "set_vars_to_stage", "(", "stage", ",", "variables", ")", "# convert to array using VAR=value", "vars_array", "=", "variables", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v}\"", "}", "Capistrano", "::", "Application", ".", "invoke", "(", "stage", ")", "Capistrano", "::", "Application", ".", "invoke", "(", "\"rbenv:vars:set\"", ",", "vars_array", ")", "end" ]
Sets the variables to the selected stage using cap rbenv set
[ "Sets", "the", "variables", "to", "the", "selected", "stage", "using", "cap", "rbenv", "set" ]
7124973132de65026b30b66477678387a07dfa4d
https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/env.rb#L17-L22
24,639
platanus/negroku
lib/negroku/modes/env.rb
Negroku::Modes.Env.get_variables
def get_variables return unless File.exists?(ENV_FILE) File.open(ENV_FILE).each do |line| var_name = line.split("=").first yield var_name unless line =~ /^\#/ end end
ruby
def get_variables return unless File.exists?(ENV_FILE) File.open(ENV_FILE).each do |line| var_name = line.split("=").first yield var_name unless line =~ /^\#/ end end
[ "def", "get_variables", "return", "unless", "File", ".", "exists?", "(", "ENV_FILE", ")", "File", ".", "open", "(", "ENV_FILE", ")", ".", "each", "do", "|", "line", "|", "var_name", "=", "line", ".", "split", "(", "\"=\"", ")", ".", "first", "yield", "var_name", "unless", "line", "=~", "/", "\\#", "/", "end", "end" ]
build a list of variables from ENV_FILE and yeilds it
[ "build", "a", "list", "of", "variables", "from", "ENV_FILE", "and", "yeilds", "it" ]
7124973132de65026b30b66477678387a07dfa4d
https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/env.rb#L25-L32
24,640
platanus/negroku
lib/negroku/modes/env.rb
Negroku::Modes.Env.select_variables
def select_variables selection = {} puts I18n.t(:ask_variables_message, scope: :negroku) get_variables do |var_name| selection[var_name] = Ask.input(var_name) end selection.reject {|key, value| value.empty? } end
ruby
def select_variables selection = {} puts I18n.t(:ask_variables_message, scope: :negroku) get_variables do |var_name| selection[var_name] = Ask.input(var_name) end selection.reject {|key, value| value.empty? } end
[ "def", "select_variables", "selection", "=", "{", "}", "puts", "I18n", ".", "t", "(", ":ask_variables_message", ",", "scope", ":", ":negroku", ")", "get_variables", "do", "|", "var_name", "|", "selection", "[", "var_name", "]", "=", "Ask", ".", "input", "(", "var_name", ")", "end", "selection", ".", "reject", "{", "|", "key", ",", "value", "|", "value", ".", "empty?", "}", "end" ]
Returns a hash of selected variables and values
[ "Returns", "a", "hash", "of", "selected", "variables", "and", "values" ]
7124973132de65026b30b66477678387a07dfa4d
https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/env.rb#L35-L42
24,641
holtrop/rscons
lib/rscons/varset.rb
Rscons.VarSet.[]
def [](key) if @my_vars.include?(key) @my_vars[key] else @coa_vars.each do |coa_vars| if coa_vars.include?(key) @my_vars[key] = deep_dup(coa_vars[key]) return @my_vars[key] end end nil end end
ruby
def [](key) if @my_vars.include?(key) @my_vars[key] else @coa_vars.each do |coa_vars| if coa_vars.include?(key) @my_vars[key] = deep_dup(coa_vars[key]) return @my_vars[key] end end nil end end
[ "def", "[]", "(", "key", ")", "if", "@my_vars", ".", "include?", "(", "key", ")", "@my_vars", "[", "key", "]", "else", "@coa_vars", ".", "each", "do", "|", "coa_vars", "|", "if", "coa_vars", ".", "include?", "(", "key", ")", "@my_vars", "[", "key", "]", "=", "deep_dup", "(", "coa_vars", "[", "key", "]", ")", "return", "@my_vars", "[", "key", "]", "end", "end", "nil", "end", "end" ]
Create a VarSet. @param vars [Hash] Optional initial variables. Access the value of variable. @param key [String, Symbol] The variable name. @return [Object] The variable's value.
[ "Create", "a", "VarSet", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/varset.rb#L19-L31
24,642
holtrop/rscons
lib/rscons/varset.rb
Rscons.VarSet.include?
def include?(key) if @my_vars.include?(key) true else @coa_vars.find do |coa_vars| coa_vars.include?(key) end end end
ruby
def include?(key) if @my_vars.include?(key) true else @coa_vars.find do |coa_vars| coa_vars.include?(key) end end end
[ "def", "include?", "(", "key", ")", "if", "@my_vars", ".", "include?", "(", "key", ")", "true", "else", "@coa_vars", ".", "find", "do", "|", "coa_vars", "|", "coa_vars", ".", "include?", "(", "key", ")", "end", "end", "end" ]
Check if the VarSet contains a variable. @param key [String, Symbol] The variable name. @return [Boolean] Whether the VarSet contains the variable.
[ "Check", "if", "the", "VarSet", "contains", "a", "variable", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/varset.rb#L47-L55
24,643
holtrop/rscons
lib/rscons/varset.rb
Rscons.VarSet.append
def append(values) coa! if values.is_a?(VarSet) values.send(:coa!) @coa_vars = values.instance_variable_get(:@coa_vars) + @coa_vars else @my_vars = deep_dup(values) end self end
ruby
def append(values) coa! if values.is_a?(VarSet) values.send(:coa!) @coa_vars = values.instance_variable_get(:@coa_vars) + @coa_vars else @my_vars = deep_dup(values) end self end
[ "def", "append", "(", "values", ")", "coa!", "if", "values", ".", "is_a?", "(", "VarSet", ")", "values", ".", "send", "(", ":coa!", ")", "@coa_vars", "=", "values", ".", "instance_variable_get", "(", ":@coa_vars", ")", "+", "@coa_vars", "else", "@my_vars", "=", "deep_dup", "(", "values", ")", "end", "self", "end" ]
Add or overwrite a set of variables. @param values [VarSet, Hash] New set of variables. @return [VarSet] Returns self.
[ "Add", "or", "overwrite", "a", "set", "of", "variables", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/varset.rb#L62-L71
24,644
holtrop/rscons
lib/rscons/varset.rb
Rscons.VarSet.merge
def merge(other = {}) coa! varset = self.class.new varset.instance_variable_set(:@coa_vars, @coa_vars.dup) varset.append(other) end
ruby
def merge(other = {}) coa! varset = self.class.new varset.instance_variable_set(:@coa_vars, @coa_vars.dup) varset.append(other) end
[ "def", "merge", "(", "other", "=", "{", "}", ")", "coa!", "varset", "=", "self", ".", "class", ".", "new", "varset", ".", "instance_variable_set", "(", ":@coa_vars", ",", "@coa_vars", ".", "dup", ")", "varset", ".", "append", "(", "other", ")", "end" ]
Create a new VarSet object based on the first merged with other. @param other [VarSet, Hash] Other variables to add or overwrite. @return [VarSet] The newly created VarSet.
[ "Create", "a", "new", "VarSet", "object", "based", "on", "the", "first", "merged", "with", "other", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/varset.rb#L78-L83
24,645
holtrop/rscons
lib/rscons/varset.rb
Rscons.VarSet.to_h
def to_h result = deep_dup(@my_vars) @coa_vars.reduce(result) do |result, coa_vars| coa_vars.each_pair do |key, value| unless result.include?(key) result[key] = deep_dup(value) end end result end end
ruby
def to_h result = deep_dup(@my_vars) @coa_vars.reduce(result) do |result, coa_vars| coa_vars.each_pair do |key, value| unless result.include?(key) result[key] = deep_dup(value) end end result end end
[ "def", "to_h", "result", "=", "deep_dup", "(", "@my_vars", ")", "@coa_vars", ".", "reduce", "(", "result", ")", "do", "|", "result", ",", "coa_vars", "|", "coa_vars", ".", "each_pair", "do", "|", "key", ",", "value", "|", "unless", "result", ".", "include?", "(", "key", ")", "result", "[", "key", "]", "=", "deep_dup", "(", "value", ")", "end", "end", "result", "end", "end" ]
Return a Hash containing all variables in the VarSet. @since 1.8.0 This method is not terribly efficient. It is intended to be used only by debugging code to dump out a VarSet's variables. @return [Hash] All variables in the VarSet.
[ "Return", "a", "Hash", "containing", "all", "variables", "in", "the", "VarSet", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/varset.rb#L144-L154
24,646
holtrop/rscons
lib/rscons/varset.rb
Rscons.VarSet.deep_dup
def deep_dup(obj) obj_class = obj.class if obj_class == Hash obj.reduce({}) do |result, (k, v)| result[k] = deep_dup(v) result end elsif obj_class == Array obj.map { |v| deep_dup(v) } elsif obj_class == String obj.dup else obj end end
ruby
def deep_dup(obj) obj_class = obj.class if obj_class == Hash obj.reduce({}) do |result, (k, v)| result[k] = deep_dup(v) result end elsif obj_class == Array obj.map { |v| deep_dup(v) } elsif obj_class == String obj.dup else obj end end
[ "def", "deep_dup", "(", "obj", ")", "obj_class", "=", "obj", ".", "class", "if", "obj_class", "==", "Hash", "obj", ".", "reduce", "(", "{", "}", ")", "do", "|", "result", ",", "(", "k", ",", "v", ")", "|", "result", "[", "k", "]", "=", "deep_dup", "(", "v", ")", "result", "end", "elsif", "obj_class", "==", "Array", "obj", ".", "map", "{", "|", "v", "|", "deep_dup", "(", "v", ")", "}", "elsif", "obj_class", "==", "String", "obj", ".", "dup", "else", "obj", "end", "end" ]
Create a deep copy of an object. Only objects which are of type String, Array, or Hash are deep copied. Any other object just has its referenced copied. @param obj [Object] Object to deep copy. @return [Object] Deep copied value.
[ "Create", "a", "deep", "copy", "of", "an", "object", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/varset.rb#L196-L210
24,647
itrp/itrp-client
lib/itrp/client.rb
Itrp.Client.import
def import(csv, type, block_until_completed = false) csv = File.open(csv, 'rb') unless csv.respond_to?(:path) && csv.respond_to?(:read) data, headers = Itrp::Multipart::Post.prepare_query(type: type, file: csv) request = Net::HTTP::Post.new(expand_path('/import'), expand_header(headers)) request.body = data response = _send(request) @logger.info { "Import file '#{csv.path}' successfully uploaded with token '#{response[:token]}'." } if response.valid? if block_until_completed raise ::Itrp::UploadFailed.new("Failed to queue #{type} import. #{response.message}") unless response.valid? token = response[:token] while true response = get("/import/#{token}") unless response.valid? sleep(5) response = get("/import/#{token}") # single retry to recover from a network error raise ::Itrp::Exception.new("Unable to monitor progress for #{type} import. #{response.message}") unless response.valid? end # wait 30 seconds while the response is OK and import is still busy break unless ['queued', 'processing'].include?(response[:state]) @logger.debug { "Import of '#{csv.path}' is #{response[:state]}. Checking again in 30 seconds." } sleep(30) end end response end
ruby
def import(csv, type, block_until_completed = false) csv = File.open(csv, 'rb') unless csv.respond_to?(:path) && csv.respond_to?(:read) data, headers = Itrp::Multipart::Post.prepare_query(type: type, file: csv) request = Net::HTTP::Post.new(expand_path('/import'), expand_header(headers)) request.body = data response = _send(request) @logger.info { "Import file '#{csv.path}' successfully uploaded with token '#{response[:token]}'." } if response.valid? if block_until_completed raise ::Itrp::UploadFailed.new("Failed to queue #{type} import. #{response.message}") unless response.valid? token = response[:token] while true response = get("/import/#{token}") unless response.valid? sleep(5) response = get("/import/#{token}") # single retry to recover from a network error raise ::Itrp::Exception.new("Unable to monitor progress for #{type} import. #{response.message}") unless response.valid? end # wait 30 seconds while the response is OK and import is still busy break unless ['queued', 'processing'].include?(response[:state]) @logger.debug { "Import of '#{csv.path}' is #{response[:state]}. Checking again in 30 seconds." } sleep(30) end end response end
[ "def", "import", "(", "csv", ",", "type", ",", "block_until_completed", "=", "false", ")", "csv", "=", "File", ".", "open", "(", "csv", ",", "'rb'", ")", "unless", "csv", ".", "respond_to?", "(", ":path", ")", "&&", "csv", ".", "respond_to?", "(", ":read", ")", "data", ",", "headers", "=", "Itrp", "::", "Multipart", "::", "Post", ".", "prepare_query", "(", "type", ":", "type", ",", "file", ":", "csv", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "expand_path", "(", "'/import'", ")", ",", "expand_header", "(", "headers", ")", ")", "request", ".", "body", "=", "data", "response", "=", "_send", "(", "request", ")", "@logger", ".", "info", "{", "\"Import file '#{csv.path}' successfully uploaded with token '#{response[:token]}'.\"", "}", "if", "response", ".", "valid?", "if", "block_until_completed", "raise", "::", "Itrp", "::", "UploadFailed", ".", "new", "(", "\"Failed to queue #{type} import. #{response.message}\"", ")", "unless", "response", ".", "valid?", "token", "=", "response", "[", ":token", "]", "while", "true", "response", "=", "get", "(", "\"/import/#{token}\"", ")", "unless", "response", ".", "valid?", "sleep", "(", "5", ")", "response", "=", "get", "(", "\"/import/#{token}\"", ")", "# single retry to recover from a network error", "raise", "::", "Itrp", "::", "Exception", ".", "new", "(", "\"Unable to monitor progress for #{type} import. #{response.message}\"", ")", "unless", "response", ".", "valid?", "end", "# wait 30 seconds while the response is OK and import is still busy", "break", "unless", "[", "'queued'", ",", "'processing'", "]", ".", "include?", "(", "response", "[", ":state", "]", ")", "@logger", ".", "debug", "{", "\"Import of '#{csv.path}' is #{response[:state]}. Checking again in 30 seconds.\"", "}", "sleep", "(", "30", ")", "end", "end", "response", "end" ]
upload a CSV file to import @param csv: The CSV File or the location of the CSV file @param type: The type, e.g. person, organization, people_contact_details @raise Itrp::UploadFailed in case the file could was not accepted by ITRP and +block_until_completed+ is +true+ @raise Itrp::Exception in case the import progress could not be monitored
[ "upload", "a", "CSV", "file", "to", "import" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client.rb#L122-L148
24,648
itrp/itrp-client
lib/itrp/client.rb
Itrp.Client.export
def export(types, from = nil, block_until_completed = false, locale = nil) data = {type: [types].flatten.join(',')} data[:from] = from unless from.blank? data[:locale] = locale unless locale.blank? response = post('/export', data) if response.valid? if response.raw.code.to_s == '204' @logger.info { "No changed records for '#{data[:type]}' since #{data[:from]}." } return response end @logger.info { "Export for '#{data[:type]}' successfully queued with token '#{response[:token]}'." } end if block_until_completed raise ::Itrp::UploadFailed.new("Failed to queue '#{data[:type]}' export. #{response.message}") unless response.valid? token = response[:token] while true response = get("/export/#{token}") unless response.valid? sleep(5) response = get("/export/#{token}") # single retry to recover from a network error raise ::Itrp::Exception.new("Unable to monitor progress for '#{data[:type]}' export. #{response.message}") unless response.valid? end # wait 30 seconds while the response is OK and export is still busy break unless ['queued', 'processing'].include?(response[:state]) @logger.debug { "Export of '#{data[:type]}' is #{response[:state]}. Checking again in 30 seconds." } sleep(30) end end response end
ruby
def export(types, from = nil, block_until_completed = false, locale = nil) data = {type: [types].flatten.join(',')} data[:from] = from unless from.blank? data[:locale] = locale unless locale.blank? response = post('/export', data) if response.valid? if response.raw.code.to_s == '204' @logger.info { "No changed records for '#{data[:type]}' since #{data[:from]}." } return response end @logger.info { "Export for '#{data[:type]}' successfully queued with token '#{response[:token]}'." } end if block_until_completed raise ::Itrp::UploadFailed.new("Failed to queue '#{data[:type]}' export. #{response.message}") unless response.valid? token = response[:token] while true response = get("/export/#{token}") unless response.valid? sleep(5) response = get("/export/#{token}") # single retry to recover from a network error raise ::Itrp::Exception.new("Unable to monitor progress for '#{data[:type]}' export. #{response.message}") unless response.valid? end # wait 30 seconds while the response is OK and export is still busy break unless ['queued', 'processing'].include?(response[:state]) @logger.debug { "Export of '#{data[:type]}' is #{response[:state]}. Checking again in 30 seconds." } sleep(30) end end response end
[ "def", "export", "(", "types", ",", "from", "=", "nil", ",", "block_until_completed", "=", "false", ",", "locale", "=", "nil", ")", "data", "=", "{", "type", ":", "[", "types", "]", ".", "flatten", ".", "join", "(", "','", ")", "}", "data", "[", ":from", "]", "=", "from", "unless", "from", ".", "blank?", "data", "[", ":locale", "]", "=", "locale", "unless", "locale", ".", "blank?", "response", "=", "post", "(", "'/export'", ",", "data", ")", "if", "response", ".", "valid?", "if", "response", ".", "raw", ".", "code", ".", "to_s", "==", "'204'", "@logger", ".", "info", "{", "\"No changed records for '#{data[:type]}' since #{data[:from]}.\"", "}", "return", "response", "end", "@logger", ".", "info", "{", "\"Export for '#{data[:type]}' successfully queued with token '#{response[:token]}'.\"", "}", "end", "if", "block_until_completed", "raise", "::", "Itrp", "::", "UploadFailed", ".", "new", "(", "\"Failed to queue '#{data[:type]}' export. #{response.message}\"", ")", "unless", "response", ".", "valid?", "token", "=", "response", "[", ":token", "]", "while", "true", "response", "=", "get", "(", "\"/export/#{token}\"", ")", "unless", "response", ".", "valid?", "sleep", "(", "5", ")", "response", "=", "get", "(", "\"/export/#{token}\"", ")", "# single retry to recover from a network error", "raise", "::", "Itrp", "::", "Exception", ".", "new", "(", "\"Unable to monitor progress for '#{data[:type]}' export. #{response.message}\"", ")", "unless", "response", ".", "valid?", "end", "# wait 30 seconds while the response is OK and export is still busy", "break", "unless", "[", "'queued'", ",", "'processing'", "]", ".", "include?", "(", "response", "[", ":state", "]", ")", "@logger", ".", "debug", "{", "\"Export of '#{data[:type]}' is #{response[:state]}. Checking again in 30 seconds.\"", "}", "sleep", "(", "30", ")", "end", "end", "response", "end" ]
Export CSV files @param types: The types to export, e.g. person, organization, people_contact_details @param from: Retrieve all files since a given data and time @param block_until_completed: Set to true to monitor the export progress @param locale: Required for translations export @raise Itrp::Exception in case the export progress could not be monitored
[ "Export", "CSV", "files" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client.rb#L156-L187
24,649
itrp/itrp-client
lib/itrp/client.rb
Itrp.Client.expand_header
def expand_header(header = {}) header = DEFAULT_HEADER.merge(header) header['X-ITRP-Account'] = option(:account) if option(:account) header['AUTHORIZATION'] = 'Basic ' + ["#{option(:api_token)}:x"].pack('m*').gsub(/\s/, '') if option(:source) header['X-ITRP-Source'] = option(:source) header['HTTP_USER_AGENT'] = option(:source) end header end
ruby
def expand_header(header = {}) header = DEFAULT_HEADER.merge(header) header['X-ITRP-Account'] = option(:account) if option(:account) header['AUTHORIZATION'] = 'Basic ' + ["#{option(:api_token)}:x"].pack('m*').gsub(/\s/, '') if option(:source) header['X-ITRP-Source'] = option(:source) header['HTTP_USER_AGENT'] = option(:source) end header end
[ "def", "expand_header", "(", "header", "=", "{", "}", ")", "header", "=", "DEFAULT_HEADER", ".", "merge", "(", "header", ")", "header", "[", "'X-ITRP-Account'", "]", "=", "option", "(", ":account", ")", "if", "option", "(", ":account", ")", "header", "[", "'AUTHORIZATION'", "]", "=", "'Basic '", "+", "[", "\"#{option(:api_token)}:x\"", "]", ".", "pack", "(", "'m*'", ")", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", "if", "option", "(", ":source", ")", "header", "[", "'X-ITRP-Source'", "]", "=", "option", "(", ":source", ")", "header", "[", "'HTTP_USER_AGENT'", "]", "=", "option", "(", ":source", ")", "end", "header", "end" ]
Expand the given header with the default header
[ "Expand", "the", "given", "header", "with", "the", "default", "header" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client.rb#L211-L220
24,650
itrp/itrp-client
lib/itrp/client.rb
Itrp.Client.typecast
def typecast(value, escape = true) case value.class.name.to_sym when :NilClass then '' when :String then escape ? uri_escape(value) : value when :TrueClass then 'true' when :FalseClass then 'false' when :DateTime then datetime = value.new_offset(0).iso8601; escape ? uri_escape(datetime) : datetime when :Date then value.strftime("%Y-%m-%d") when :Time then value.strftime("%H:%M") # do not convert arrays in put/post requests as squashing arrays is only used in filtering when :Array then escape ? value.map{ |v| typecast(v, escape) }.join(',') : value # TODO: temporary for special constructions to update contact details, see Request #1444166 when :Hash then escape ? value.to_s : value else escape ? value.to_json : value.to_s end end
ruby
def typecast(value, escape = true) case value.class.name.to_sym when :NilClass then '' when :String then escape ? uri_escape(value) : value when :TrueClass then 'true' when :FalseClass then 'false' when :DateTime then datetime = value.new_offset(0).iso8601; escape ? uri_escape(datetime) : datetime when :Date then value.strftime("%Y-%m-%d") when :Time then value.strftime("%H:%M") # do not convert arrays in put/post requests as squashing arrays is only used in filtering when :Array then escape ? value.map{ |v| typecast(v, escape) }.join(',') : value # TODO: temporary for special constructions to update contact details, see Request #1444166 when :Hash then escape ? value.to_s : value else escape ? value.to_json : value.to_s end end
[ "def", "typecast", "(", "value", ",", "escape", "=", "true", ")", "case", "value", ".", "class", ".", "name", ".", "to_sym", "when", ":NilClass", "then", "''", "when", ":String", "then", "escape", "?", "uri_escape", "(", "value", ")", ":", "value", "when", ":TrueClass", "then", "'true'", "when", ":FalseClass", "then", "'false'", "when", ":DateTime", "then", "datetime", "=", "value", ".", "new_offset", "(", "0", ")", ".", "iso8601", ";", "escape", "?", "uri_escape", "(", "datetime", ")", ":", "datetime", "when", ":Date", "then", "value", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "when", ":Time", "then", "value", ".", "strftime", "(", "\"%H:%M\"", ")", "# do not convert arrays in put/post requests as squashing arrays is only used in filtering", "when", ":Array", "then", "escape", "?", "value", ".", "map", "{", "|", "v", "|", "typecast", "(", "v", ",", "escape", ")", "}", ".", "join", "(", "','", ")", ":", "value", "# TODO: temporary for special constructions to update contact details, see Request #1444166", "when", ":Hash", "then", "escape", "?", "value", ".", "to_s", ":", "value", "else", "escape", "?", "value", ".", "to_json", ":", "value", ".", "to_s", "end", "end" ]
Parameter value typecasting
[ "Parameter", "value", "typecasting" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client.rb#L247-L262
24,651
movitto/reterm
lib/reterm/mixins/cdk_component.rb
RETerm.CDKComponent.component
def component enable_cdk! @component ||= begin c = _component c.setBackgroundColor("</#{@colors.id}>") if colored? c.timeout(SYNC_TIMEOUT) if sync_enabled? # XXX c.title_attrib = @title_attrib if @title_attrib c end end
ruby
def component enable_cdk! @component ||= begin c = _component c.setBackgroundColor("</#{@colors.id}>") if colored? c.timeout(SYNC_TIMEOUT) if sync_enabled? # XXX c.title_attrib = @title_attrib if @title_attrib c end end
[ "def", "component", "enable_cdk!", "@component", "||=", "begin", "c", "=", "_component", "c", ".", "setBackgroundColor", "(", "\"</#{@colors.id}>\"", ")", "if", "colored?", "c", ".", "timeout", "(", "SYNC_TIMEOUT", ")", "if", "sync_enabled?", "# XXX", "c", ".", "title_attrib", "=", "@title_attrib", "if", "@title_attrib", "c", "end", "end" ]
Return completely initialized CDK component
[ "Return", "completely", "initialized", "CDK", "component" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/cdk_component.rb#L33-L42
24,652
movitto/reterm
lib/reterm/mixins/cdk_component.rb
RETerm.CDKComponent.activate!
def activate!(*input) dispatch :activated component.resetExitType r = nil while [:EARLY_EXIT, :NEVER_ACTIVATED, :TIMEOUT].include?(component.exit_type) && !shutdown? r = component.activate(input) run_sync! if sync_enabled? end dispatch :deactivated r end
ruby
def activate!(*input) dispatch :activated component.resetExitType r = nil while [:EARLY_EXIT, :NEVER_ACTIVATED, :TIMEOUT].include?(component.exit_type) && !shutdown? r = component.activate(input) run_sync! if sync_enabled? end dispatch :deactivated r end
[ "def", "activate!", "(", "*", "input", ")", "dispatch", ":activated", "component", ".", "resetExitType", "r", "=", "nil", "while", "[", ":EARLY_EXIT", ",", ":NEVER_ACTIVATED", ",", ":TIMEOUT", "]", ".", "include?", "(", "component", ".", "exit_type", ")", "&&", "!", "shutdown?", "r", "=", "component", ".", "activate", "(", "input", ")", "run_sync!", "if", "sync_enabled?", "end", "dispatch", ":deactivated", "r", "end" ]
Invoke CDK activation routine
[ "Invoke", "CDK", "activation", "routine" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/cdk_component.rb#L81-L95
24,653
movitto/reterm
lib/reterm/mixins/cdk_component.rb
RETerm.CDKComponent.bind_key
def bind_key(key, kcb=nil, &bl) kcb = bl if kcb.nil? && !bl.nil? cb = lambda do |cdktype, widget, component, key| kcb.call component, key end component.bind(:ENTRY, key, cb, self) end
ruby
def bind_key(key, kcb=nil, &bl) kcb = bl if kcb.nil? && !bl.nil? cb = lambda do |cdktype, widget, component, key| kcb.call component, key end component.bind(:ENTRY, key, cb, self) end
[ "def", "bind_key", "(", "key", ",", "kcb", "=", "nil", ",", "&", "bl", ")", "kcb", "=", "bl", "if", "kcb", ".", "nil?", "&&", "!", "bl", ".", "nil?", "cb", "=", "lambda", "do", "|", "cdktype", ",", "widget", ",", "component", ",", "key", "|", "kcb", ".", "call", "component", ",", "key", "end", "component", ".", "bind", "(", ":ENTRY", ",", "key", ",", "cb", ",", "self", ")", "end" ]
Override bind_key to use cdk bindings mechanism
[ "Override", "bind_key", "to", "use", "cdk", "bindings", "mechanism" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/cdk_component.rb#L108-L116
24,654
platanus/negroku
lib/negroku/modes/app.rb
Negroku::Modes.App.ask_name
def ask_name question = I18n.t :application_name, scope: :negroku Ask.input question, default: File.basename(Dir.getwd) end
ruby
def ask_name question = I18n.t :application_name, scope: :negroku Ask.input question, default: File.basename(Dir.getwd) end
[ "def", "ask_name", "question", "=", "I18n", ".", "t", ":application_name", ",", "scope", ":", ":negroku", "Ask", ".", "input", "question", ",", "default", ":", "File", ".", "basename", "(", "Dir", ".", "getwd", ")", "end" ]
Ask the application name
[ "Ask", "the", "application", "name" ]
7124973132de65026b30b66477678387a07dfa4d
https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/app.rb#L74-L77
24,655
platanus/negroku
lib/negroku/modes/app.rb
Negroku::Modes.App.select_repo
def select_repo remote_urls = %x(git remote -v 2> /dev/null | awk '{print $2}' | uniq).split("\n") remote_urls << (I18n.t :other, scope: :negroku) question = I18n.t :choose_repo_url, scope: :negroku selected_idx = Ask.list question, remote_urls if selected_idx == remote_urls.length - 1 question = I18n.t :type_repo_url, scope: :negroku Ask.input question else remote_urls[selected_idx] end end
ruby
def select_repo remote_urls = %x(git remote -v 2> /dev/null | awk '{print $2}' | uniq).split("\n") remote_urls << (I18n.t :other, scope: :negroku) question = I18n.t :choose_repo_url, scope: :negroku selected_idx = Ask.list question, remote_urls if selected_idx == remote_urls.length - 1 question = I18n.t :type_repo_url, scope: :negroku Ask.input question else remote_urls[selected_idx] end end
[ "def", "select_repo", "remote_urls", "=", "%x(", ")", ".", "split", "(", "\"\\n\"", ")", "remote_urls", "<<", "(", "I18n", ".", "t", ":other", ",", "scope", ":", ":negroku", ")", "question", "=", "I18n", ".", "t", ":choose_repo_url", ",", "scope", ":", ":negroku", "selected_idx", "=", "Ask", ".", "list", "question", ",", "remote_urls", "if", "selected_idx", "==", "remote_urls", ".", "length", "-", "1", "question", "=", "I18n", ".", "t", ":type_repo_url", ",", "scope", ":", ":negroku", "Ask", ".", "input", "question", "else", "remote_urls", "[", "selected_idx", "]", "end", "end" ]
Get git remotes from current git and ask to select one
[ "Get", "git", "remotes", "from", "current", "git", "and", "ask", "to", "select", "one" ]
7124973132de65026b30b66477678387a07dfa4d
https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/app.rb#L93-L104
24,656
shanebdavis/Babel-Bridge
lib/babel_bridge/rule_variant.rb
BabelBridge.RuleVariant.pattern_elements
def pattern_elements @pattern_elements||=pattern.collect { |match| [PatternElement.new(match, :rule_variant => self, :pattern_element => true), delimiter_pattern] }.flatten[0..-2] end
ruby
def pattern_elements @pattern_elements||=pattern.collect { |match| [PatternElement.new(match, :rule_variant => self, :pattern_element => true), delimiter_pattern] }.flatten[0..-2] end
[ "def", "pattern_elements", "@pattern_elements", "||=", "pattern", ".", "collect", "{", "|", "match", "|", "[", "PatternElement", ".", "new", "(", "match", ",", ":rule_variant", "=>", "self", ",", ":pattern_element", "=>", "true", ")", ",", "delimiter_pattern", "]", "}", ".", "flatten", "[", "0", "..", "-", "2", "]", "end" ]
convert the pattern into a set of lamba functions
[ "convert", "the", "pattern", "into", "a", "set", "of", "lamba", "functions" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/rule_variant.rb#L36-L38
24,657
shanebdavis/Babel-Bridge
lib/babel_bridge/rule_variant.rb
BabelBridge.RuleVariant.parse
def parse(parent_node) #return parse_nongreedy_optional(src,offset,parent_node) # nongreedy optionals break standard PEG node = variant_node_class.new(parent_node, delimiter_pattern) node.match parser.delimiter_pattern if root_rule? pattern_elements.each do |pe| return unless node.match(pe) end node.pop_match if node.last_match && node.last_match.delimiter node.match parser.delimiter_pattern if root_rule? node && node.post_match_processing end
ruby
def parse(parent_node) #return parse_nongreedy_optional(src,offset,parent_node) # nongreedy optionals break standard PEG node = variant_node_class.new(parent_node, delimiter_pattern) node.match parser.delimiter_pattern if root_rule? pattern_elements.each do |pe| return unless node.match(pe) end node.pop_match if node.last_match && node.last_match.delimiter node.match parser.delimiter_pattern if root_rule? node && node.post_match_processing end
[ "def", "parse", "(", "parent_node", ")", "#return parse_nongreedy_optional(src,offset,parent_node) # nongreedy optionals break standard PEG", "node", "=", "variant_node_class", ".", "new", "(", "parent_node", ",", "delimiter_pattern", ")", "node", ".", "match", "parser", ".", "delimiter_pattern", "if", "root_rule?", "pattern_elements", ".", "each", "do", "|", "pe", "|", "return", "unless", "node", ".", "match", "(", "pe", ")", "end", "node", ".", "pop_match", "if", "node", ".", "last_match", "&&", "node", ".", "last_match", ".", "delimiter", "node", ".", "match", "parser", ".", "delimiter_pattern", "if", "root_rule?", "node", "&&", "node", ".", "post_match_processing", "end" ]
returns a Node object if it matches, nil otherwise
[ "returns", "a", "Node", "object", "if", "it", "matches", "nil", "otherwise" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/rule_variant.rb#L41-L55
24,658
holtrop/rscons
lib/rscons/cache.rb
Rscons.Cache.write
def write @cache["version"] = VERSION File.open(CACHE_FILE, "w") do |fh| fh.puts(JSON.dump(@cache)) end end
ruby
def write @cache["version"] = VERSION File.open(CACHE_FILE, "w") do |fh| fh.puts(JSON.dump(@cache)) end end
[ "def", "write", "@cache", "[", "\"version\"", "]", "=", "VERSION", "File", ".", "open", "(", "CACHE_FILE", ",", "\"w\"", ")", "do", "|", "fh", "|", "fh", ".", "puts", "(", "JSON", ".", "dump", "(", "@cache", ")", ")", "end", "end" ]
Write the cache to disk. @return [void]
[ "Write", "the", "cache", "to", "disk", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/cache.rb#L91-L96
24,659
holtrop/rscons
lib/rscons/cache.rb
Rscons.Cache.mkdir_p
def mkdir_p(path) parts = path.split(/[\\\/]/) parts.each_index do |i| next if parts[i] == "" subpath = File.join(*parts[0, i + 1]) unless File.exists?(subpath) FileUtils.mkdir_p(subpath) @cache["directories"][subpath] = true end end end
ruby
def mkdir_p(path) parts = path.split(/[\\\/]/) parts.each_index do |i| next if parts[i] == "" subpath = File.join(*parts[0, i + 1]) unless File.exists?(subpath) FileUtils.mkdir_p(subpath) @cache["directories"][subpath] = true end end end
[ "def", "mkdir_p", "(", "path", ")", "parts", "=", "path", ".", "split", "(", "/", "\\\\", "\\/", "/", ")", "parts", ".", "each_index", "do", "|", "i", "|", "next", "if", "parts", "[", "i", "]", "==", "\"\"", "subpath", "=", "File", ".", "join", "(", "parts", "[", "0", ",", "i", "+", "1", "]", ")", "unless", "File", ".", "exists?", "(", "subpath", ")", "FileUtils", ".", "mkdir_p", "(", "subpath", ")", "@cache", "[", "\"directories\"", "]", "[", "subpath", "]", "=", "true", "end", "end", "end" ]
Make any needed directories and record the ones that are created for removal upon a "clean" operation. @param path [String] Directory to create. @return [void]
[ "Make", "any", "needed", "directories", "and", "record", "the", "ones", "that", "are", "created", "for", "removal", "upon", "a", "clean", "operation", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/cache.rb#L265-L275
24,660
holtrop/rscons
lib/rscons/cache.rb
Rscons.Cache.calculate_checksum
def calculate_checksum(file) @lookup_checksums[file] = Digest::MD5.hexdigest(File.read(file, mode: "rb")) rescue "" end
ruby
def calculate_checksum(file) @lookup_checksums[file] = Digest::MD5.hexdigest(File.read(file, mode: "rb")) rescue "" end
[ "def", "calculate_checksum", "(", "file", ")", "@lookup_checksums", "[", "file", "]", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "File", ".", "read", "(", "file", ",", "mode", ":", "\"rb\"", ")", ")", "rescue", "\"\"", "end" ]
Calculate and return a file's checksum. @param file [String] The file name. @return [String] The file's checksum.
[ "Calculate", "and", "return", "a", "file", "s", "checksum", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/cache.rb#L330-L332
24,661
reset/chozo
lib/chozo/mixin/from_file.rb
Chozo::Mixin.FromFile.from_file
def from_file(filename) filename = filename.to_s if File.exists?(filename) && File.readable?(filename) self.instance_eval(IO.read(filename), filename, 1) self else raise IOError, "Could not open or read: '#{filename}'" end end
ruby
def from_file(filename) filename = filename.to_s if File.exists?(filename) && File.readable?(filename) self.instance_eval(IO.read(filename), filename, 1) self else raise IOError, "Could not open or read: '#{filename}'" end end
[ "def", "from_file", "(", "filename", ")", "filename", "=", "filename", ".", "to_s", "if", "File", ".", "exists?", "(", "filename", ")", "&&", "File", ".", "readable?", "(", "filename", ")", "self", ".", "instance_eval", "(", "IO", ".", "read", "(", "filename", ")", ",", "filename", ",", "1", ")", "self", "else", "raise", "IOError", ",", "\"Could not open or read: '#{filename}'\"", "end", "end" ]
Loads the contents of a file within the context of the current object @param [#to_s] filename path to the file to load @raise [IOError] if the file does not exist or cannot be read
[ "Loads", "the", "contents", "of", "a", "file", "within", "the", "context", "of", "the", "current", "object" ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/from_file.rb#L26-L35
24,662
reset/chozo
lib/chozo/mixin/from_file.rb
Chozo::Mixin.FromFile.class_from_file
def class_from_file(filename) filename = filename.to_s if File.exists?(filename) && File.readable?(filename) self.class_eval(IO.read(filename), filename, 1) self else raise IOError, "Could not open or read: '#{filename}'" end end
ruby
def class_from_file(filename) filename = filename.to_s if File.exists?(filename) && File.readable?(filename) self.class_eval(IO.read(filename), filename, 1) self else raise IOError, "Could not open or read: '#{filename}'" end end
[ "def", "class_from_file", "(", "filename", ")", "filename", "=", "filename", ".", "to_s", "if", "File", ".", "exists?", "(", "filename", ")", "&&", "File", ".", "readable?", "(", "filename", ")", "self", ".", "class_eval", "(", "IO", ".", "read", "(", "filename", ")", ",", "filename", ",", "1", ")", "self", "else", "raise", "IOError", ",", "\"Could not open or read: '#{filename}'\"", "end", "end" ]
Loads the contents of a file within the context of the current object's class @param [#to_s] filename path to the file to load @raise [IOError] if the file does not exist or cannot be read
[ "Loads", "the", "contents", "of", "a", "file", "within", "the", "context", "of", "the", "current", "object", "s", "class" ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/from_file.rb#L43-L52
24,663
shanebdavis/Babel-Bridge
lib/babel_bridge/pattern_element.rb
BabelBridge.PatternElement.parse
def parse(parent_node) # run element parser begin parent_node.parser.matching_negative if negative match = parser.call(parent_node) ensure parent_node.parser.unmatching_negative if negative end # Negative patterns (PEG: !element) match = match ? nil : EmptyNode.new(parent_node) if negative # Optional patterns (PEG: element?) match = EmptyNode.new(parent_node) if !match && optional # Could-match patterns (PEG: &element) match.match_length = 0 if match && could_match if !match && (terminal || negative) # log failures on Terminal patterns for debug output if overall parse fails parent_node.parser.log_parsing_failure parent_node.next, :pattern => self.to_s, :node => parent_node end match.delimiter = delimiter if match # return match match end
ruby
def parse(parent_node) # run element parser begin parent_node.parser.matching_negative if negative match = parser.call(parent_node) ensure parent_node.parser.unmatching_negative if negative end # Negative patterns (PEG: !element) match = match ? nil : EmptyNode.new(parent_node) if negative # Optional patterns (PEG: element?) match = EmptyNode.new(parent_node) if !match && optional # Could-match patterns (PEG: &element) match.match_length = 0 if match && could_match if !match && (terminal || negative) # log failures on Terminal patterns for debug output if overall parse fails parent_node.parser.log_parsing_failure parent_node.next, :pattern => self.to_s, :node => parent_node end match.delimiter = delimiter if match # return match match end
[ "def", "parse", "(", "parent_node", ")", "# run element parser", "begin", "parent_node", ".", "parser", ".", "matching_negative", "if", "negative", "match", "=", "parser", ".", "call", "(", "parent_node", ")", "ensure", "parent_node", ".", "parser", ".", "unmatching_negative", "if", "negative", "end", "# Negative patterns (PEG: !element)", "match", "=", "match", "?", "nil", ":", "EmptyNode", ".", "new", "(", "parent_node", ")", "if", "negative", "# Optional patterns (PEG: element?)", "match", "=", "EmptyNode", ".", "new", "(", "parent_node", ")", "if", "!", "match", "&&", "optional", "# Could-match patterns (PEG: &element)", "match", ".", "match_length", "=", "0", "if", "match", "&&", "could_match", "if", "!", "match", "&&", "(", "terminal", "||", "negative", ")", "# log failures on Terminal patterns for debug output if overall parse fails", "parent_node", ".", "parser", ".", "log_parsing_failure", "parent_node", ".", "next", ",", ":pattern", "=>", "self", ".", "to_s", ",", ":node", "=>", "parent_node", "end", "match", ".", "delimiter", "=", "delimiter", "if", "match", "# return match", "match", "end" ]
attempt to match the pattern defined in self.parser in parent_node.src starting at offset parent_node.next
[ "attempt", "to", "match", "the", "pattern", "defined", "in", "self", ".", "parser", "in", "parent_node", ".", "src", "starting", "at", "offset", "parent_node", ".", "next" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/pattern_element.rb#L54-L82
24,664
shanebdavis/Babel-Bridge
lib/babel_bridge/pattern_element.rb
BabelBridge.PatternElement.init_rule
def init_rule(rule_name) rule_name.to_s[/^([^?!]*)([?!])?$/] rule_name = $1.to_sym option = $2 match_rule = rules[rule_name] raise "no rule for #{rule_name}" unless match_rule self.parser = lambda {|parent_node| match_rule.parse(parent_node)} self.name ||= rule_name case option when "?" then self.optional = true when "!" then self.negative = true end end
ruby
def init_rule(rule_name) rule_name.to_s[/^([^?!]*)([?!])?$/] rule_name = $1.to_sym option = $2 match_rule = rules[rule_name] raise "no rule for #{rule_name}" unless match_rule self.parser = lambda {|parent_node| match_rule.parse(parent_node)} self.name ||= rule_name case option when "?" then self.optional = true when "!" then self.negative = true end end
[ "def", "init_rule", "(", "rule_name", ")", "rule_name", ".", "to_s", "[", "/", "/", "]", "rule_name", "=", "$1", ".", "to_sym", "option", "=", "$2", "match_rule", "=", "rules", "[", "rule_name", "]", "raise", "\"no rule for #{rule_name}\"", "unless", "match_rule", "self", ".", "parser", "=", "lambda", "{", "|", "parent_node", "|", "match_rule", ".", "parse", "(", "parent_node", ")", "}", "self", ".", "name", "||=", "rule_name", "case", "option", "when", "\"?\"", "then", "self", ".", "optional", "=", "true", "when", "\"!\"", "then", "self", ".", "negative", "=", "true", "end", "end" ]
initialize PatternElement as a parser that matches a named sub-rule
[ "initialize", "PatternElement", "as", "a", "parser", "that", "matches", "a", "named", "sub", "-", "rule" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/pattern_element.rb#L120-L133
24,665
shanebdavis/Babel-Bridge
lib/babel_bridge/pattern_element.rb
BabelBridge.PatternElement.init_hash
def init_hash(hash) if hash[:parser] self.parser=hash[:parser] elsif hash[:many] init_many hash elsif hash[:match] init hash[:match] elsif hash[:any] init_any hash[:any] else raise "extended-options patterns (specified by a hash) must have either :parser=> or a :match=> set" end self.name = hash[:as] || self.name self.optional ||= hash[:optional] || hash[:optionally] self.could_match ||= hash[:could] self.negative ||= hash[:dont] end
ruby
def init_hash(hash) if hash[:parser] self.parser=hash[:parser] elsif hash[:many] init_many hash elsif hash[:match] init hash[:match] elsif hash[:any] init_any hash[:any] else raise "extended-options patterns (specified by a hash) must have either :parser=> or a :match=> set" end self.name = hash[:as] || self.name self.optional ||= hash[:optional] || hash[:optionally] self.could_match ||= hash[:could] self.negative ||= hash[:dont] end
[ "def", "init_hash", "(", "hash", ")", "if", "hash", "[", ":parser", "]", "self", ".", "parser", "=", "hash", "[", ":parser", "]", "elsif", "hash", "[", ":many", "]", "init_many", "hash", "elsif", "hash", "[", ":match", "]", "init", "hash", "[", ":match", "]", "elsif", "hash", "[", ":any", "]", "init_any", "hash", "[", ":any", "]", "else", "raise", "\"extended-options patterns (specified by a hash) must have either :parser=> or a :match=> set\"", "end", "self", ".", "name", "=", "hash", "[", ":as", "]", "||", "self", ".", "name", "self", ".", "optional", "||=", "hash", "[", ":optional", "]", "||", "hash", "[", ":optionally", "]", "self", ".", "could_match", "||=", "hash", "[", ":could", "]", "self", ".", "negative", "||=", "hash", "[", ":dont", "]", "end" ]
initialize the PatternElement from hashed parameters
[ "initialize", "the", "PatternElement", "from", "hashed", "parameters" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/pattern_element.rb#L159-L176
24,666
PRX/google_speech
lib/google_speech/chunk_factory.rb
GoogleSpeech.ChunkFactory.each
def each pos = 0 while(pos < @original_duration) do chunk = nil begin chunk = Chunk.new(@original_file, @original_duration, pos, (@chunk_duration + @overlap), @rate) yield chunk pos = pos + [chunk.duration, @chunk_duration].min ensure chunk.close_file if chunk end end end
ruby
def each pos = 0 while(pos < @original_duration) do chunk = nil begin chunk = Chunk.new(@original_file, @original_duration, pos, (@chunk_duration + @overlap), @rate) yield chunk pos = pos + [chunk.duration, @chunk_duration].min ensure chunk.close_file if chunk end end end
[ "def", "each", "pos", "=", "0", "while", "(", "pos", "<", "@original_duration", ")", "do", "chunk", "=", "nil", "begin", "chunk", "=", "Chunk", ".", "new", "(", "@original_file", ",", "@original_duration", ",", "pos", ",", "(", "@chunk_duration", "+", "@overlap", ")", ",", "@rate", ")", "yield", "chunk", "pos", "=", "pos", "+", "[", "chunk", ".", "duration", ",", "@chunk_duration", "]", ".", "min", "ensure", "chunk", ".", "close_file", "if", "chunk", "end", "end", "end" ]
return temp file for each chunk
[ "return", "temp", "file", "for", "each", "chunk" ]
a073bfcffc318013c740edd6e6e1de91a60a31bd
https://github.com/PRX/google_speech/blob/a073bfcffc318013c740edd6e6e1de91a60a31bd/lib/google_speech/chunk_factory.rb#L18-L30
24,667
chef-workflow/chef-workflow
lib/chef-workflow/support/ssh.rb
ChefWorkflow.SSHHelper.ssh_role_command
def ssh_role_command(role, command) t = [] ChefWorkflow::IPSupport.get_role_ips(role).each do |ip| t.push( Thread.new do ssh_command(ip, command) end ) end t.each(&:join) end
ruby
def ssh_role_command(role, command) t = [] ChefWorkflow::IPSupport.get_role_ips(role).each do |ip| t.push( Thread.new do ssh_command(ip, command) end ) end t.each(&:join) end
[ "def", "ssh_role_command", "(", "role", ",", "command", ")", "t", "=", "[", "]", "ChefWorkflow", "::", "IPSupport", ".", "get_role_ips", "(", "role", ")", ".", "each", "do", "|", "ip", "|", "t", ".", "push", "(", "Thread", ".", "new", "do", "ssh_command", "(", "ip", ",", "command", ")", "end", ")", "end", "t", ".", "each", "(", ":join", ")", "end" ]
run a command against a group of servers. These commands are run in parallel, but the command itself does not complete until all the threads have finished running.
[ "run", "a", "command", "against", "a", "group", "of", "servers", ".", "These", "commands", "are", "run", "in", "parallel", "but", "the", "command", "itself", "does", "not", "complete", "until", "all", "the", "threads", "have", "finished", "running", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/ssh.rb#L19-L29
24,668
chef-workflow/chef-workflow
lib/chef-workflow/support/ssh.rb
ChefWorkflow.SSHHelper.ssh_command
def ssh_command(ip, command) configure_ssh_command(ip, command) do |ch, success| return 1 unless success if_debug(2) do ch.on_data do |ch, data| $stderr.puts data end end ch.on_request("exit-status") do |ch, data| return data.read_long end end end
ruby
def ssh_command(ip, command) configure_ssh_command(ip, command) do |ch, success| return 1 unless success if_debug(2) do ch.on_data do |ch, data| $stderr.puts data end end ch.on_request("exit-status") do |ch, data| return data.read_long end end end
[ "def", "ssh_command", "(", "ip", ",", "command", ")", "configure_ssh_command", "(", "ip", ",", "command", ")", "do", "|", "ch", ",", "success", "|", "return", "1", "unless", "success", "if_debug", "(", "2", ")", "do", "ch", ".", "on_data", "do", "|", "ch", ",", "data", "|", "$stderr", ".", "puts", "data", "end", "end", "ch", ".", "on_request", "(", "\"exit-status\"", ")", "do", "|", "ch", ",", "data", "|", "return", "data", ".", "read_long", "end", "end", "end" ]
Run a command against a single IP. Returns the exit status.
[ "Run", "a", "command", "against", "a", "single", "IP", ".", "Returns", "the", "exit", "status", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/ssh.rb#L70-L84
24,669
chef-workflow/chef-workflow
lib/chef-workflow/support/ssh.rb
ChefWorkflow.SSHHelper.ssh_capture
def ssh_capture(ip, command) retval = "" configure_ssh_command(ip, command) do |ch, success| return "" unless success ch.on_data do |ch, data| retval << data end ch.on_request("exit-status") do |ch, data| return retval end end return retval end
ruby
def ssh_capture(ip, command) retval = "" configure_ssh_command(ip, command) do |ch, success| return "" unless success ch.on_data do |ch, data| retval << data end ch.on_request("exit-status") do |ch, data| return retval end end return retval end
[ "def", "ssh_capture", "(", "ip", ",", "command", ")", "retval", "=", "\"\"", "configure_ssh_command", "(", "ip", ",", "command", ")", "do", "|", "ch", ",", "success", "|", "return", "\"\"", "unless", "success", "ch", ".", "on_data", "do", "|", "ch", ",", "data", "|", "retval", "<<", "data", "end", "ch", ".", "on_request", "(", "\"exit-status\"", ")", "do", "|", "ch", ",", "data", "|", "return", "retval", "end", "end", "return", "retval", "end" ]
run a command, and instead of capturing the exit status, return the data captured during the command run.
[ "run", "a", "command", "and", "instead", "of", "capturing", "the", "exit", "status", "return", "the", "data", "captured", "during", "the", "command", "run", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/ssh.rb#L90-L105
24,670
chef-workflow/chef-workflow
lib/chef-workflow/support/ec2.rb
ChefWorkflow.EC2Support.create_security_group
def create_security_group aws_ec2 = ec2_obj name = nil loop do name = 'chef-workflow-' + (0..rand(10).to_i).map { rand(0..9).to_s }.join("") if_debug(3) do $stderr.puts "Seeing if security group name #{name} is taken" end break unless aws_ec2.security_groups.filter('group-name', [name]).first sleep 0.3 end group = aws_ec2.security_groups.create(name) security_group_open_ports.each do |port| group.authorize_ingress(:tcp, port) group.authorize_ingress(:udp, port) end group.authorize_ingress(:tcp, (0..65535), group) group.authorize_ingress(:udp, (0..65535), group) # XXX I think the name should be enough, but maybe this'll cause a problem. File.binwrite(security_group_setting_path, Marshal.dump([name])) return [name] end
ruby
def create_security_group aws_ec2 = ec2_obj name = nil loop do name = 'chef-workflow-' + (0..rand(10).to_i).map { rand(0..9).to_s }.join("") if_debug(3) do $stderr.puts "Seeing if security group name #{name} is taken" end break unless aws_ec2.security_groups.filter('group-name', [name]).first sleep 0.3 end group = aws_ec2.security_groups.create(name) security_group_open_ports.each do |port| group.authorize_ingress(:tcp, port) group.authorize_ingress(:udp, port) end group.authorize_ingress(:tcp, (0..65535), group) group.authorize_ingress(:udp, (0..65535), group) # XXX I think the name should be enough, but maybe this'll cause a problem. File.binwrite(security_group_setting_path, Marshal.dump([name])) return [name] end
[ "def", "create_security_group", "aws_ec2", "=", "ec2_obj", "name", "=", "nil", "loop", "do", "name", "=", "'chef-workflow-'", "+", "(", "0", "..", "rand", "(", "10", ")", ".", "to_i", ")", ".", "map", "{", "rand", "(", "0", "..", "9", ")", ".", "to_s", "}", ".", "join", "(", "\"\"", ")", "if_debug", "(", "3", ")", "do", "$stderr", ".", "puts", "\"Seeing if security group name #{name} is taken\"", "end", "break", "unless", "aws_ec2", ".", "security_groups", ".", "filter", "(", "'group-name'", ",", "[", "name", "]", ")", ".", "first", "sleep", "0.3", "end", "group", "=", "aws_ec2", ".", "security_groups", ".", "create", "(", "name", ")", "security_group_open_ports", ".", "each", "do", "|", "port", "|", "group", ".", "authorize_ingress", "(", ":tcp", ",", "port", ")", "group", ".", "authorize_ingress", "(", ":udp", ",", "port", ")", "end", "group", ".", "authorize_ingress", "(", ":tcp", ",", "(", "0", "..", "65535", ")", ",", "group", ")", "group", ".", "authorize_ingress", "(", ":udp", ",", "(", "0", "..", "65535", ")", ",", "group", ")", "# XXX I think the name should be enough, but maybe this'll cause a problem.", "File", ".", "binwrite", "(", "security_group_setting_path", ",", "Marshal", ".", "dump", "(", "[", "name", "]", ")", ")", "return", "[", "name", "]", "end" ]
Creates a security group and saves it to the security_group_setting_path.
[ "Creates", "a", "security", "group", "and", "saves", "it", "to", "the", "security_group_setting_path", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/ec2.rb#L57-L86
24,671
chef-workflow/chef-workflow
lib/chef-workflow/support/ec2.rb
ChefWorkflow.EC2Support.assert_security_groups
def assert_security_groups aws_ec2 = ec2_obj if security_groups == :auto loaded_groups = load_security_group # this will make it hit the second block everytime from now on (and # bootstrap it recursively) if loaded_groups self.security_groups loaded_groups assert_security_groups else self.security_groups create_security_group end else self.security_groups = [security_groups] unless security_groups.kind_of?(Array) self.security_groups.each do |group| # # just retry this until it works -- some stupid flexible proxy in aws-sdk will bark about a missing method otherwise. # begin aws_ec2.security_groups[group] rescue sleep 1 retry end raise "EC2 security group #{group} does not exist and it should." unless aws_ec2.security_groups[group] end end end
ruby
def assert_security_groups aws_ec2 = ec2_obj if security_groups == :auto loaded_groups = load_security_group # this will make it hit the second block everytime from now on (and # bootstrap it recursively) if loaded_groups self.security_groups loaded_groups assert_security_groups else self.security_groups create_security_group end else self.security_groups = [security_groups] unless security_groups.kind_of?(Array) self.security_groups.each do |group| # # just retry this until it works -- some stupid flexible proxy in aws-sdk will bark about a missing method otherwise. # begin aws_ec2.security_groups[group] rescue sleep 1 retry end raise "EC2 security group #{group} does not exist and it should." unless aws_ec2.security_groups[group] end end end
[ "def", "assert_security_groups", "aws_ec2", "=", "ec2_obj", "if", "security_groups", "==", ":auto", "loaded_groups", "=", "load_security_group", "# this will make it hit the second block everytime from now on (and", "# bootstrap it recursively)", "if", "loaded_groups", "self", ".", "security_groups", "loaded_groups", "assert_security_groups", "else", "self", ".", "security_groups", "create_security_group", "end", "else", "self", ".", "security_groups", "=", "[", "security_groups", "]", "unless", "security_groups", ".", "kind_of?", "(", "Array", ")", "self", ".", "security_groups", ".", "each", "do", "|", "group", "|", "#", "# just retry this until it works -- some stupid flexible proxy in aws-sdk will bark about a missing method otherwise.", "#", "begin", "aws_ec2", ".", "security_groups", "[", "group", "]", "rescue", "sleep", "1", "retry", "end", "raise", "\"EC2 security group #{group} does not exist and it should.\"", "unless", "aws_ec2", ".", "security_groups", "[", "group", "]", "end", "end", "end" ]
Ensures security groups exist. If @security_groups is :auto, creates one and sets it up with the security_group_open_ports on TCP and UDP. If @security_groups is an array of group names or a single group name, asserts they exist. If they do not exist, it raises.
[ "Ensures", "security", "groups", "exist", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/ec2.rb#L104-L136
24,672
itrp/itrp-client
lib/itrp/client/response.rb
Itrp.Response.json
def json return @json if defined?(@json) # no content, no JSON if @response.code.to_s == '204' data = {} elsif @response.body.blank? # no body, no json data = {message: @response.message.blank? ? 'empty body' : @response.message.strip} end begin data ||= JSON.parse(@response.body) rescue ::Exception => e data = { message: "Invalid JSON - #{e.message} for:\n#{@response.body}" } end # indifferent access to hashes data = data.is_a?(Array) ? data.map(&:with_indifferent_access) : data.with_indifferent_access # empty OK response is not seen as an error data = {} if data.is_a?(Hash) && data.size == 1 && data[:message] == 'OK' # prepend HTTP response code to message data[:message] = "#{response.code}: #{data[:message]}" unless @response.is_a?(Net::HTTPSuccess) @json = data end
ruby
def json return @json if defined?(@json) # no content, no JSON if @response.code.to_s == '204' data = {} elsif @response.body.blank? # no body, no json data = {message: @response.message.blank? ? 'empty body' : @response.message.strip} end begin data ||= JSON.parse(@response.body) rescue ::Exception => e data = { message: "Invalid JSON - #{e.message} for:\n#{@response.body}" } end # indifferent access to hashes data = data.is_a?(Array) ? data.map(&:with_indifferent_access) : data.with_indifferent_access # empty OK response is not seen as an error data = {} if data.is_a?(Hash) && data.size == 1 && data[:message] == 'OK' # prepend HTTP response code to message data[:message] = "#{response.code}: #{data[:message]}" unless @response.is_a?(Net::HTTPSuccess) @json = data end
[ "def", "json", "return", "@json", "if", "defined?", "(", "@json", ")", "# no content, no JSON", "if", "@response", ".", "code", ".", "to_s", "==", "'204'", "data", "=", "{", "}", "elsif", "@response", ".", "body", ".", "blank?", "# no body, no json", "data", "=", "{", "message", ":", "@response", ".", "message", ".", "blank?", "?", "'empty body'", ":", "@response", ".", "message", ".", "strip", "}", "end", "begin", "data", "||=", "JSON", ".", "parse", "(", "@response", ".", "body", ")", "rescue", "::", "Exception", "=>", "e", "data", "=", "{", "message", ":", "\"Invalid JSON - #{e.message} for:\\n#{@response.body}\"", "}", "end", "# indifferent access to hashes", "data", "=", "data", ".", "is_a?", "(", "Array", ")", "?", "data", ".", "map", "(", ":with_indifferent_access", ")", ":", "data", ".", "with_indifferent_access", "# empty OK response is not seen as an error", "data", "=", "{", "}", "if", "data", ".", "is_a?", "(", "Hash", ")", "&&", "data", ".", "size", "==", "1", "&&", "data", "[", ":message", "]", "==", "'OK'", "# prepend HTTP response code to message", "data", "[", ":message", "]", "=", "\"#{response.code}: #{data[:message]}\"", "unless", "@response", ".", "is_a?", "(", "Net", "::", "HTTPSuccess", ")", "@json", "=", "data", "end" ]
The JSON value, if single resource is queried this is a Hash, if multiple resources where queried it is an Array If the response is not +valid?+ it is a Hash with 'message' and optionally 'errors'
[ "The", "JSON", "value", "if", "single", "resource", "is", "queried", "this", "is", "a", "Hash", "if", "multiple", "resources", "where", "queried", "it", "is", "an", "Array", "If", "the", "response", "is", "not", "+", "valid?", "+", "it", "is", "a", "Hash", "with", "message", "and", "optionally", "errors" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client/response.rb#L23-L44
24,673
itrp/itrp-client
lib/itrp/client/response.rb
Itrp.Response.[]
def[](*keys) values = json.is_a?(Array) ? json : [json] keys.each { |key| values = values.map{ |value| value.is_a?(Hash) ? value[key] : nil} } json.is_a?(Array) ? values : values.first end
ruby
def[](*keys) values = json.is_a?(Array) ? json : [json] keys.each { |key| values = values.map{ |value| value.is_a?(Hash) ? value[key] : nil} } json.is_a?(Array) ? values : values.first end
[ "def", "[]", "(", "*", "keys", ")", "values", "=", "json", ".", "is_a?", "(", "Array", ")", "?", "json", ":", "[", "json", "]", "keys", ".", "each", "{", "|", "key", "|", "values", "=", "values", ".", "map", "{", "|", "value", "|", "value", ".", "is_a?", "(", "Hash", ")", "?", "value", "[", "key", "]", ":", "nil", "}", "}", "json", ".", "is_a?", "(", "Array", ")", "?", "values", ":", "values", ".", "first", "end" ]
retrieve a value from the resource if the JSON value is an Array a array with the value for each resource will be given @param keys: a single key or a key-path separated by comma
[ "retrieve", "a", "value", "from", "the", "resource", "if", "the", "JSON", "value", "is", "an", "Array", "a", "array", "with", "the", "value", "for", "each", "resource", "will", "be", "given" ]
80294aa93d7a64c1966d06d4f12ed24b606e3078
https://github.com/itrp/itrp-client/blob/80294aa93d7a64c1966d06d4f12ed24b606e3078/lib/itrp/client/response.rb#L65-L69
24,674
hayesdavis/mockingbird
lib/mockingbird/script.rb
Mockingbird.Script.on_connection
def on_connection(selector=nil,&block) if selector.nil? || selector == '*' instance_eval(&block) else @current_connection = ConnectionScript.new instance_eval(&block) @connections << [selector,@current_connection] @current_connection = nil end end
ruby
def on_connection(selector=nil,&block) if selector.nil? || selector == '*' instance_eval(&block) else @current_connection = ConnectionScript.new instance_eval(&block) @connections << [selector,@current_connection] @current_connection = nil end end
[ "def", "on_connection", "(", "selector", "=", "nil", ",", "&", "block", ")", "if", "selector", ".", "nil?", "||", "selector", "==", "'*'", "instance_eval", "(", "block", ")", "else", "@current_connection", "=", "ConnectionScript", ".", "new", "instance_eval", "(", "block", ")", "@connections", "<<", "[", "selector", ",", "@current_connection", "]", "@current_connection", "=", "nil", "end", "end" ]
Configuration API Specifies behavior to run for specific connections based on the id number assigned to that connection. Connection ids are 1-based. The selector can be any of the following: Number - Run the code on that connection id Range - Run the code for a connection id in that range Proc - Call the proc with the id and run if it matches '*' - Run this code for any connection that doesn't match others
[ "Configuration", "API", "Specifies", "behavior", "to", "run", "for", "specific", "connections", "based", "on", "the", "id", "number", "assigned", "to", "that", "connection", ".", "Connection", "ids", "are", "1", "-", "based", "." ]
128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b
https://github.com/hayesdavis/mockingbird/blob/128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b/lib/mockingbird/script.rb#L31-L40
24,675
hayesdavis/mockingbird
lib/mockingbird/script.rb
Mockingbird.Script.add_command
def add_command(command=nil,&block) command = Commands::Command.new(&block) if block_given? current_connection.add_command(command) end
ruby
def add_command(command=nil,&block) command = Commands::Command.new(&block) if block_given? current_connection.add_command(command) end
[ "def", "add_command", "(", "command", "=", "nil", ",", "&", "block", ")", "command", "=", "Commands", "::", "Command", ".", "new", "(", "block", ")", "if", "block_given?", "current_connection", ".", "add_command", "(", "command", ")", "end" ]
Not really part of the public API but users could use this to implement their own fancy command
[ "Not", "really", "part", "of", "the", "public", "API", "but", "users", "could", "use", "this", "to", "implement", "their", "own", "fancy", "command" ]
128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b
https://github.com/hayesdavis/mockingbird/blob/128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b/lib/mockingbird/script.rb#L89-L92
24,676
kevgo/active_cucumber
lib/active_cucumber/active_record_builder.rb
ActiveCucumber.ActiveRecordBuilder.create_record
def create_record attributes creator = @creator_class.new attributes, @context FactoryGirl.create @clazz.name.underscore.to_sym, creator.factorygirl_attributes end
ruby
def create_record attributes creator = @creator_class.new attributes, @context FactoryGirl.create @clazz.name.underscore.to_sym, creator.factorygirl_attributes end
[ "def", "create_record", "attributes", "creator", "=", "@creator_class", ".", "new", "attributes", ",", "@context", "FactoryGirl", ".", "create", "@clazz", ".", "name", ".", "underscore", ".", "to_sym", ",", "creator", ".", "factorygirl_attributes", "end" ]
Creates a new record with the given attributes in the database
[ "Creates", "a", "new", "record", "with", "the", "given", "attributes", "in", "the", "database" ]
9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf
https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/active_record_builder.rb#L27-L30
24,677
holtrop/rscons
lib/rscons/job_set.rb
Rscons.JobSet.get_next_job_to_run
def get_next_job_to_run(targets_still_building) targets_not_built_yet = targets_still_building + @jobs.keys side_effects = targets_not_built_yet.map do |target| @side_effects[target] || [] end.flatten targets_not_built_yet += side_effects @jobs.keys.each do |target| skip = false (@jobs[target][0][:sources] + (@build_dependencies[target] || []).to_a).each do |src| if targets_not_built_yet.include?(src) skip = true break end end next if skip job = @jobs[target][0] if @jobs[target].size > 1 @jobs[target].slice!(0) else @jobs.delete(target) end return job end # If there is a job to run, and nothing is still building, but we did # not find a job to run above, then there might be a circular dependency # introduced by the user. if (@jobs.size > 0) and targets_still_building.empty? raise "Could not find a runnable job. Possible circular dependency for #{@jobs.keys.first}" end end
ruby
def get_next_job_to_run(targets_still_building) targets_not_built_yet = targets_still_building + @jobs.keys side_effects = targets_not_built_yet.map do |target| @side_effects[target] || [] end.flatten targets_not_built_yet += side_effects @jobs.keys.each do |target| skip = false (@jobs[target][0][:sources] + (@build_dependencies[target] || []).to_a).each do |src| if targets_not_built_yet.include?(src) skip = true break end end next if skip job = @jobs[target][0] if @jobs[target].size > 1 @jobs[target].slice!(0) else @jobs.delete(target) end return job end # If there is a job to run, and nothing is still building, but we did # not find a job to run above, then there might be a circular dependency # introduced by the user. if (@jobs.size > 0) and targets_still_building.empty? raise "Could not find a runnable job. Possible circular dependency for #{@jobs.keys.first}" end end
[ "def", "get_next_job_to_run", "(", "targets_still_building", ")", "targets_not_built_yet", "=", "targets_still_building", "+", "@jobs", ".", "keys", "side_effects", "=", "targets_not_built_yet", ".", "map", "do", "|", "target", "|", "@side_effects", "[", "target", "]", "||", "[", "]", "end", ".", "flatten", "targets_not_built_yet", "+=", "side_effects", "@jobs", ".", "keys", ".", "each", "do", "|", "target", "|", "skip", "=", "false", "(", "@jobs", "[", "target", "]", "[", "0", "]", "[", ":sources", "]", "+", "(", "@build_dependencies", "[", "target", "]", "||", "[", "]", ")", ".", "to_a", ")", ".", "each", "do", "|", "src", "|", "if", "targets_not_built_yet", ".", "include?", "(", "src", ")", "skip", "=", "true", "break", "end", "end", "next", "if", "skip", "job", "=", "@jobs", "[", "target", "]", "[", "0", "]", "if", "@jobs", "[", "target", "]", ".", "size", ">", "1", "@jobs", "[", "target", "]", ".", "slice!", "(", "0", ")", "else", "@jobs", ".", "delete", "(", "target", ")", "end", "return", "job", "end", "# If there is a job to run, and nothing is still building, but we did", "# not find a job to run above, then there might be a circular dependency", "# introduced by the user.", "if", "(", "@jobs", ".", "size", ">", "0", ")", "and", "targets_still_building", ".", "empty?", "raise", "\"Could not find a runnable job. Possible circular dependency for #{@jobs.keys.first}\"", "end", "end" ]
Get the next job that is ready to run from the JobSet. This method will remove the job from the JobSet. @param targets_still_building [Array<String>] Targets that are not finished building. This is used to avoid returning a job as available to run if it depends on one of the targets that are still building as a source. @return [nil, Hash] The next job to run.
[ "Get", "the", "next", "job", "that", "is", "ready", "to", "run", "from", "the", "JobSet", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/job_set.rb#L54-L85
24,678
platanus/negroku
lib/negroku/modes/stage.rb
Negroku::Modes.Stage.ask_stage
def ask_stage question = I18n.t :ask_stage_name, scope: :negroku stage_name = Ask.input question raise "Stage name required" if stage_name.empty? stage_name end
ruby
def ask_stage question = I18n.t :ask_stage_name, scope: :negroku stage_name = Ask.input question raise "Stage name required" if stage_name.empty? stage_name end
[ "def", "ask_stage", "question", "=", "I18n", ".", "t", ":ask_stage_name", ",", "scope", ":", ":negroku", "stage_name", "=", "Ask", ".", "input", "question", "raise", "\"Stage name required\"", "if", "stage_name", ".", "empty?", "stage_name", "end" ]
Ask the stage name
[ "Ask", "the", "stage", "name" ]
7124973132de65026b30b66477678387a07dfa4d
https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/stage.rb#L60-L65
24,679
chef-workflow/chef-workflow
lib/chef-workflow/support/debug.rb
ChefWorkflow.DebugSupport.if_debug
def if_debug(minimum=1, else_block=nil) $CHEF_WORKFLOW_DEBUG ||= ENV.has_key?("CHEF_WORKFLOW_DEBUG") ? ENV["CHEF_WORKFLOW_DEBUG"].to_i : CHEF_WORKFLOW_DEBUG_DEFAULT if $CHEF_WORKFLOW_DEBUG >= minimum yield if block_given? elsif else_block else_block.call end end
ruby
def if_debug(minimum=1, else_block=nil) $CHEF_WORKFLOW_DEBUG ||= ENV.has_key?("CHEF_WORKFLOW_DEBUG") ? ENV["CHEF_WORKFLOW_DEBUG"].to_i : CHEF_WORKFLOW_DEBUG_DEFAULT if $CHEF_WORKFLOW_DEBUG >= minimum yield if block_given? elsif else_block else_block.call end end
[ "def", "if_debug", "(", "minimum", "=", "1", ",", "else_block", "=", "nil", ")", "$CHEF_WORKFLOW_DEBUG", "||=", "ENV", ".", "has_key?", "(", "\"CHEF_WORKFLOW_DEBUG\"", ")", "?", "ENV", "[", "\"CHEF_WORKFLOW_DEBUG\"", "]", ".", "to_i", ":", "CHEF_WORKFLOW_DEBUG_DEFAULT", "if", "$CHEF_WORKFLOW_DEBUG", ">=", "minimum", "yield", "if", "block_given?", "elsif", "else_block", "else_block", ".", "call", "end", "end" ]
Conditionally executes based on the level of debugging requested. `CHEF_WORKFLOW_DEBUG` in the environment is converted to an integer. This integer is compared to the first argument. If it is higher than the first argument, the block supplied will execute. Optionally, if there is a `else_block`, this block will be executed if the condition is *not* met. This allows a slightly more elegant (if less ugly) variant of dealing with the situation where if debugging is on, do one thing, and if not, do something else. Examples: if_debug(1) do $stderr.puts "Here's a debug message" end This will print "here's a debug message" to standard error if debugging is set to 1 or greater. do_thing = lambda { run_thing } if_debug(2, &do_thing) do $stderr.puts "Doing this thing" do_thing.call end If debugging is set to 2 or higher, "Doing this thing" will be printed to standard error and then `run_thing` will be executed. If lower than 2 or off, will just execute `run_thing`.
[ "Conditionally", "executes", "based", "on", "the", "level", "of", "debugging", "requested", "." ]
956c8f6cd694dacc25dfa405d70b05b12b7c1691
https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/debug.rb#L40-L51
24,680
liquidm/zmachine
lib/zmachine/tcp_msg_channel.rb
ZMachine.TcpMsgChannel.read_inbound_data
def read_inbound_data ZMachine.logger.debug("zmachine:tcp_msg_channel:#{__method__}", channel: self) if ZMachine.debug raise IOException.new("EOF") if @socket.read(@buffer) == -1 pos = @buffer.position @buffer.flip # validate magic if @buffer.remaining >= 4 bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4) @buffer.position(@buffer.position+4) if String.from_java_bytes(bytes) != MAGIC # read broken message - client should reconnect ZMachine.logger.error("read broken message", worker: self) close! return end else @buffer.position(pos).limit(@buffer.capacity) return end # extract number of msg parts if @buffer.remaining >= 4 bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4) @buffer.position(@buffer.position+4) array_length = String.from_java_bytes(bytes).unpack('V')[0] else @buffer.position(pos).limit(@buffer.capacity) return end # extract data data = Array.new(array_length) array_length.times do |i| if @buffer.remaining >= 4 bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4) @buffer.position(@buffer.position+4) data_length = String.from_java_bytes(bytes).unpack('V')[0] else @buffer.position(pos).limit(@buffer.capacity) return end if @buffer.remaining >= data_length data[i] = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+data_length) @buffer.position(@buffer.position+data_length) else @buffer.position(pos).limit(@buffer.capacity) return end end @buffer.compact data end
ruby
def read_inbound_data ZMachine.logger.debug("zmachine:tcp_msg_channel:#{__method__}", channel: self) if ZMachine.debug raise IOException.new("EOF") if @socket.read(@buffer) == -1 pos = @buffer.position @buffer.flip # validate magic if @buffer.remaining >= 4 bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4) @buffer.position(@buffer.position+4) if String.from_java_bytes(bytes) != MAGIC # read broken message - client should reconnect ZMachine.logger.error("read broken message", worker: self) close! return end else @buffer.position(pos).limit(@buffer.capacity) return end # extract number of msg parts if @buffer.remaining >= 4 bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4) @buffer.position(@buffer.position+4) array_length = String.from_java_bytes(bytes).unpack('V')[0] else @buffer.position(pos).limit(@buffer.capacity) return end # extract data data = Array.new(array_length) array_length.times do |i| if @buffer.remaining >= 4 bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4) @buffer.position(@buffer.position+4) data_length = String.from_java_bytes(bytes).unpack('V')[0] else @buffer.position(pos).limit(@buffer.capacity) return end if @buffer.remaining >= data_length data[i] = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+data_length) @buffer.position(@buffer.position+data_length) else @buffer.position(pos).limit(@buffer.capacity) return end end @buffer.compact data end
[ "def", "read_inbound_data", "ZMachine", ".", "logger", ".", "debug", "(", "\"zmachine:tcp_msg_channel:#{__method__}\"", ",", "channel", ":", "self", ")", "if", "ZMachine", ".", "debug", "raise", "IOException", ".", "new", "(", "\"EOF\"", ")", "if", "@socket", ".", "read", "(", "@buffer", ")", "==", "-", "1", "pos", "=", "@buffer", ".", "position", "@buffer", ".", "flip", "# validate magic", "if", "@buffer", ".", "remaining", ">=", "4", "bytes", "=", "java", ".", "util", ".", "Arrays", ".", "copyOfRange", "(", "@buffer", ".", "array", ",", "@buffer", ".", "position", ",", "@buffer", ".", "position", "+", "4", ")", "@buffer", ".", "position", "(", "@buffer", ".", "position", "+", "4", ")", "if", "String", ".", "from_java_bytes", "(", "bytes", ")", "!=", "MAGIC", "# read broken message - client should reconnect", "ZMachine", ".", "logger", ".", "error", "(", "\"read broken message\"", ",", "worker", ":", "self", ")", "close!", "return", "end", "else", "@buffer", ".", "position", "(", "pos", ")", ".", "limit", "(", "@buffer", ".", "capacity", ")", "return", "end", "# extract number of msg parts", "if", "@buffer", ".", "remaining", ">=", "4", "bytes", "=", "java", ".", "util", ".", "Arrays", ".", "copyOfRange", "(", "@buffer", ".", "array", ",", "@buffer", ".", "position", ",", "@buffer", ".", "position", "+", "4", ")", "@buffer", ".", "position", "(", "@buffer", ".", "position", "+", "4", ")", "array_length", "=", "String", ".", "from_java_bytes", "(", "bytes", ")", ".", "unpack", "(", "'V'", ")", "[", "0", "]", "else", "@buffer", ".", "position", "(", "pos", ")", ".", "limit", "(", "@buffer", ".", "capacity", ")", "return", "end", "# extract data", "data", "=", "Array", ".", "new", "(", "array_length", ")", "array_length", ".", "times", "do", "|", "i", "|", "if", "@buffer", ".", "remaining", ">=", "4", "bytes", "=", "java", ".", "util", ".", "Arrays", ".", "copyOfRange", "(", "@buffer", ".", "array", ",", "@buffer", ".", "position", ",", "@buffer", ".", "position", "+", "4", ")", "@buffer", ".", "position", "(", "@buffer", ".", "position", "+", "4", ")", "data_length", "=", "String", ".", "from_java_bytes", "(", "bytes", ")", ".", "unpack", "(", "'V'", ")", "[", "0", "]", "else", "@buffer", ".", "position", "(", "pos", ")", ".", "limit", "(", "@buffer", ".", "capacity", ")", "return", "end", "if", "@buffer", ".", "remaining", ">=", "data_length", "data", "[", "i", "]", "=", "java", ".", "util", ".", "Arrays", ".", "copyOfRange", "(", "@buffer", ".", "array", ",", "@buffer", ".", "position", ",", "@buffer", ".", "position", "+", "data_length", ")", "@buffer", ".", "position", "(", "@buffer", ".", "position", "+", "data_length", ")", "else", "@buffer", ".", "position", "(", "pos", ")", ".", "limit", "(", "@buffer", ".", "capacity", ")", "return", "end", "end", "@buffer", ".", "compact", "data", "end" ]
return nil if no addional data is available
[ "return", "nil", "if", "no", "addional", "data", "is", "available" ]
ded5c4e83a2378f97568e2902fb7799c2723f5f4
https://github.com/liquidm/zmachine/blob/ded5c4e83a2378f97568e2902fb7799c2723f5f4/lib/zmachine/tcp_msg_channel.rb#L34-L90
24,681
fredemmott/rxhp
lib/rxhp/attribute_validator.rb
Rxhp.AttributeValidator.validate_attributes!
def validate_attributes! # Check for required attributes self.class.required_attributes.each do |matcher| matched = self.attributes.any? do |key, value| key = key.to_s Rxhp::AttributeValidator.match? matcher, key, value end if !matched raise MissingRequiredAttributeError.new(self, matcher) end end # Check other attributes are acceptable return true if self.attributes.empty? self.attributes.each do |key, value| key = key.to_s matched = self.class.acceptable_attributes.any? do |matcher| Rxhp::AttributeValidator.match? matcher, key, value end if !matched raise UnacceptableAttributeError.new(self, key, value) end end true end
ruby
def validate_attributes! # Check for required attributes self.class.required_attributes.each do |matcher| matched = self.attributes.any? do |key, value| key = key.to_s Rxhp::AttributeValidator.match? matcher, key, value end if !matched raise MissingRequiredAttributeError.new(self, matcher) end end # Check other attributes are acceptable return true if self.attributes.empty? self.attributes.each do |key, value| key = key.to_s matched = self.class.acceptable_attributes.any? do |matcher| Rxhp::AttributeValidator.match? matcher, key, value end if !matched raise UnacceptableAttributeError.new(self, key, value) end end true end
[ "def", "validate_attributes!", "# Check for required attributes", "self", ".", "class", ".", "required_attributes", ".", "each", "do", "|", "matcher", "|", "matched", "=", "self", ".", "attributes", ".", "any?", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "to_s", "Rxhp", "::", "AttributeValidator", ".", "match?", "matcher", ",", "key", ",", "value", "end", "if", "!", "matched", "raise", "MissingRequiredAttributeError", ".", "new", "(", "self", ",", "matcher", ")", "end", "end", "# Check other attributes are acceptable", "return", "true", "if", "self", ".", "attributes", ".", "empty?", "self", ".", "attributes", ".", "each", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "to_s", "matched", "=", "self", ".", "class", ".", "acceptable_attributes", ".", "any?", "do", "|", "matcher", "|", "Rxhp", "::", "AttributeValidator", ".", "match?", "matcher", ",", "key", ",", "value", "end", "if", "!", "matched", "raise", "UnacceptableAttributeError", ".", "new", "(", "self", ",", "key", ",", "value", ")", "end", "end", "true", "end" ]
Check if attributes are valid, and raise an exception if they're not. @raise {MissingRequiredAttributeError} if an attribute that is required was not provided. @raise {UnacceptableAttributeError} if a non-whitelisted attribute was provided. @return [true] if the attribute are all valid, and all required attributes are provided.
[ "Check", "if", "attributes", "are", "valid", "and", "raise", "an", "exception", "if", "they", "re", "not", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/attribute_validator.rb#L64-L89
24,682
fredemmott/rxhp
lib/rxhp/html_element.rb
Rxhp.HtmlElement.render
def render options = {} validate! options = fill_options(options) open = render_open_tag(options) inner = render_children(options) close = render_close_tag(options) if options[:pretty] indent = ' ' * (options[:indent] * options[:depth]) out = indent.dup out << open << "\n" out << inner if inner out << indent << close << "\n" if close && !close.empty? out else out = open out << inner if inner out << close if close out end end
ruby
def render options = {} validate! options = fill_options(options) open = render_open_tag(options) inner = render_children(options) close = render_close_tag(options) if options[:pretty] indent = ' ' * (options[:indent] * options[:depth]) out = indent.dup out << open << "\n" out << inner if inner out << indent << close << "\n" if close && !close.empty? out else out = open out << inner if inner out << close if close out end end
[ "def", "render", "options", "=", "{", "}", "validate!", "options", "=", "fill_options", "(", "options", ")", "open", "=", "render_open_tag", "(", "options", ")", "inner", "=", "render_children", "(", "options", ")", "close", "=", "render_close_tag", "(", "options", ")", "if", "options", "[", ":pretty", "]", "indent", "=", "' '", "*", "(", "options", "[", ":indent", "]", "*", "options", "[", ":depth", "]", ")", "out", "=", "indent", ".", "dup", "out", "<<", "open", "<<", "\"\\n\"", "out", "<<", "inner", "if", "inner", "out", "<<", "indent", "<<", "close", "<<", "\"\\n\"", "if", "close", "&&", "!", "close", ".", "empty?", "out", "else", "out", "=", "open", "out", "<<", "inner", "if", "inner", "out", "<<", "close", "if", "close", "out", "end", "end" ]
Render the element. Pays attention to the formatter type, doctype, pretty print options, etc. See {Element#render} for options.
[ "Render", "the", "element", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/html_element.rb#L54-L75
24,683
fredemmott/rxhp
lib/rxhp/html_element.rb
Rxhp.HtmlElement.render_string
def render_string string, options escaped = html_escape(string) if options[:pretty] indent = ' ' * (options[:indent] * options[:depth]) indent + escaped + "\n" else escaped end end
ruby
def render_string string, options escaped = html_escape(string) if options[:pretty] indent = ' ' * (options[:indent] * options[:depth]) indent + escaped + "\n" else escaped end end
[ "def", "render_string", "string", ",", "options", "escaped", "=", "html_escape", "(", "string", ")", "if", "options", "[", ":pretty", "]", "indent", "=", "' '", "*", "(", "options", "[", ":indent", "]", "*", "options", "[", ":depth", "]", ")", "indent", "+", "escaped", "+", "\"\\n\"", "else", "escaped", "end", "end" ]
html-escape a string, paying attention to indentation too.
[ "html", "-", "escape", "a", "string", "paying", "attention", "to", "indentation", "too", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/html_element.rb#L89-L97
24,684
fredemmott/rxhp
lib/rxhp/html_element.rb
Rxhp.HtmlElement.render_open_tag
def render_open_tag options out = '<' + tag_name unless attributes.empty? attributes.each do |name,value| name = name.to_s.gsub('_', '-') if name.is_a? Symbol value = value.to_s.gsub('_', '-') if value.is_a? Symbol case value when false next when true if options[:format] == Rxhp::XHTML_FORMAT out += ' ' + name + '="' + name + '"' else out += ' ' + name end else out += ' ' + name.to_s + '="' + html_escape(value.to_s) + '"' end end end if options[:format] == Rxhp::XHTML_FORMAT && !children? out + ' />' else out + '>' end end
ruby
def render_open_tag options out = '<' + tag_name unless attributes.empty? attributes.each do |name,value| name = name.to_s.gsub('_', '-') if name.is_a? Symbol value = value.to_s.gsub('_', '-') if value.is_a? Symbol case value when false next when true if options[:format] == Rxhp::XHTML_FORMAT out += ' ' + name + '="' + name + '"' else out += ' ' + name end else out += ' ' + name.to_s + '="' + html_escape(value.to_s) + '"' end end end if options[:format] == Rxhp::XHTML_FORMAT && !children? out + ' />' else out + '>' end end
[ "def", "render_open_tag", "options", "out", "=", "'<'", "+", "tag_name", "unless", "attributes", ".", "empty?", "attributes", ".", "each", "do", "|", "name", ",", "value", "|", "name", "=", "name", ".", "to_s", ".", "gsub", "(", "'_'", ",", "'-'", ")", "if", "name", ".", "is_a?", "Symbol", "value", "=", "value", ".", "to_s", ".", "gsub", "(", "'_'", ",", "'-'", ")", "if", "value", ".", "is_a?", "Symbol", "case", "value", "when", "false", "next", "when", "true", "if", "options", "[", ":format", "]", "==", "Rxhp", "::", "XHTML_FORMAT", "out", "+=", "' '", "+", "name", "+", "'=\"'", "+", "name", "+", "'\"'", "else", "out", "+=", "' '", "+", "name", "end", "else", "out", "+=", "' '", "+", "name", ".", "to_s", "+", "'=\"'", "+", "html_escape", "(", "value", ".", "to_s", ")", "+", "'\"'", "end", "end", "end", "if", "options", "[", ":format", "]", "==", "Rxhp", "::", "XHTML_FORMAT", "&&", "!", "children?", "out", "+", "' />'", "else", "out", "+", "'>'", "end", "end" ]
Render the opening tag. Considers: - attributes - XHTML or HTML? - are there any children? #render_close_tag assumes that this will not leave a tag open in XHTML unless there are children.
[ "Render", "the", "opening", "tag", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/html_element.rb#L108-L135
24,685
fredemmott/rxhp
lib/rxhp/element.rb
Rxhp.Element.render_children
def render_children options = {} return if children.empty? flattened_children.map{ |child| render_child(child, options) }.join end
ruby
def render_children options = {} return if children.empty? flattened_children.map{ |child| render_child(child, options) }.join end
[ "def", "render_children", "options", "=", "{", "}", "return", "if", "children", ".", "empty?", "flattened_children", ".", "map", "{", "|", "child", "|", "render_child", "(", "child", ",", "options", ")", "}", ".", "join", "end" ]
Iterate over all the children, calling render.
[ "Iterate", "over", "all", "the", "children", "calling", "render", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/element.rb#L79-L83
24,686
fredemmott/rxhp
lib/rxhp/element.rb
Rxhp.Element.fill_options
def fill_options options { :pretty => true, :format => Rxhp::HTML_FORMAT, :skip_doctype => false, :doctype => Rxhp::HTML_5, :depth => 0, :indent => 2, }.merge(options) end
ruby
def fill_options options { :pretty => true, :format => Rxhp::HTML_FORMAT, :skip_doctype => false, :doctype => Rxhp::HTML_5, :depth => 0, :indent => 2, }.merge(options) end
[ "def", "fill_options", "options", "{", ":pretty", "=>", "true", ",", ":format", "=>", "Rxhp", "::", "HTML_FORMAT", ",", ":skip_doctype", "=>", "false", ",", ":doctype", "=>", "Rxhp", "::", "HTML_5", ",", ":depth", "=>", "0", ",", ":indent", "=>", "2", ",", "}", ".", "merge", "(", "options", ")", "end" ]
Fill default render options. These are as defined for {#render}, with the addition of a +:depth+ value of 0. Other values aren't guaranteed to stay fixed, check source for current values.
[ "Fill", "default", "render", "options", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/element.rb#L90-L99
24,687
fredemmott/rxhp
lib/rxhp/element.rb
Rxhp.Element.flattened_children
def flattened_children no_frags = [] children.each do |node| if node.is_a? Rxhp::Fragment no_frags += node.children else no_frags.push node end end previous = nil no_consecutive_strings = [] no_frags.each do |node| if node.is_a?(String) && previous.is_a?(String) previous << node else no_consecutive_strings.push node previous = node end end no_consecutive_strings end
ruby
def flattened_children no_frags = [] children.each do |node| if node.is_a? Rxhp::Fragment no_frags += node.children else no_frags.push node end end previous = nil no_consecutive_strings = [] no_frags.each do |node| if node.is_a?(String) && previous.is_a?(String) previous << node else no_consecutive_strings.push node previous = node end end no_consecutive_strings end
[ "def", "flattened_children", "no_frags", "=", "[", "]", "children", ".", "each", "do", "|", "node", "|", "if", "node", ".", "is_a?", "Rxhp", "::", "Fragment", "no_frags", "+=", "node", ".", "children", "else", "no_frags", ".", "push", "node", "end", "end", "previous", "=", "nil", "no_consecutive_strings", "=", "[", "]", "no_frags", ".", "each", "do", "|", "node", "|", "if", "node", ".", "is_a?", "(", "String", ")", "&&", "previous", ".", "is_a?", "(", "String", ")", "previous", "<<", "node", "else", "no_consecutive_strings", ".", "push", "node", "previous", "=", "node", "end", "end", "no_consecutive_strings", "end" ]
Normalize the children. For example, turn +['foo', 'bar']+ into +['foobar']+. This is needed to stop things like pretty printing adding extra whitespace between the two strings.
[ "Normalize", "the", "children", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/element.rb#L122-L144
24,688
fredemmott/rxhp
lib/rxhp/composable_element.rb
Rxhp.ComposableElement.render
def render options = {} validate! self.compose do # Allow 'yield' to embed all children self.children.each do |child| fragment child end end.render(options) end
ruby
def render options = {} validate! self.compose do # Allow 'yield' to embed all children self.children.each do |child| fragment child end end.render(options) end
[ "def", "render", "options", "=", "{", "}", "validate!", "self", ".", "compose", "do", "# Allow 'yield' to embed all children", "self", ".", "children", ".", "each", "do", "|", "child", "|", "fragment", "child", "end", "end", ".", "render", "(", "options", ")", "end" ]
You don't want to implement this function in your subclasses - just reimplement compose instead. This calls compose, provides the 'yield' magic, and callls render on the output.
[ "You", "don", "t", "want", "to", "implement", "this", "function", "in", "your", "subclasses", "-", "just", "reimplement", "compose", "instead", "." ]
45b39680c64e3a47741c4ba2ab6a92c1a4c1b975
https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/composable_element.rb#L17-L25
24,689
liquidm/zmachine
lib/zmachine/connection.rb
ZMachine.Connection.bind
def bind(address, port_or_type, &block) ZMachine.logger.debug("zmachine:connection:#{__method__}", connection: self) if ZMachine.debug klass = channel_class(address) @channel = klass.new @channel.bind(sanitize_adress(address, klass), port_or_type) @block = block @block.call(self) if @block && @channel.is_a?(ZMQChannel) self end
ruby
def bind(address, port_or_type, &block) ZMachine.logger.debug("zmachine:connection:#{__method__}", connection: self) if ZMachine.debug klass = channel_class(address) @channel = klass.new @channel.bind(sanitize_adress(address, klass), port_or_type) @block = block @block.call(self) if @block && @channel.is_a?(ZMQChannel) self end
[ "def", "bind", "(", "address", ",", "port_or_type", ",", "&", "block", ")", "ZMachine", ".", "logger", ".", "debug", "(", "\"zmachine:connection:#{__method__}\"", ",", "connection", ":", "self", ")", "if", "ZMachine", ".", "debug", "klass", "=", "channel_class", "(", "address", ")", "@channel", "=", "klass", ".", "new", "@channel", ".", "bind", "(", "sanitize_adress", "(", "address", ",", "klass", ")", ",", "port_or_type", ")", "@block", "=", "block", "@block", ".", "call", "(", "self", ")", "if", "@block", "&&", "@channel", ".", "is_a?", "(", "ZMQChannel", ")", "self", "end" ]
channel type dispatch
[ "channel", "type", "dispatch" ]
ded5c4e83a2378f97568e2902fb7799c2723f5f4
https://github.com/liquidm/zmachine/blob/ded5c4e83a2378f97568e2902fb7799c2723f5f4/lib/zmachine/connection.rb#L26-L34
24,690
datasift/datasift-ruby
lib/account.rb
DataSift.Account.usage
def usage(start_time, end_time, period = '') params = { start: start_time, end: end_time } params.merge!(period: period) unless period.empty? DataSift.request(:GET, 'account/usage', @config, params) end
ruby
def usage(start_time, end_time, period = '') params = { start: start_time, end: end_time } params.merge!(period: period) unless period.empty? DataSift.request(:GET, 'account/usage', @config, params) end
[ "def", "usage", "(", "start_time", ",", "end_time", ",", "period", "=", "''", ")", "params", "=", "{", "start", ":", "start_time", ",", "end", ":", "end_time", "}", "params", ".", "merge!", "(", "period", ":", "period", ")", "unless", "period", ".", "empty?", "DataSift", ".", "request", "(", ":GET", ",", "'account/usage'", ",", "@config", ",", "params", ")", "end" ]
Check your account usage for a given period and timeframe @param period [String] (Optional) Period is one of either hourly, daily or monthly @param start_time [Integer] (Optional) Unix timestamp of the start of the period you are querying @param end_time [Integer] (Optional) Unix timestamp of the end of the period you are querying @return [Object] API reponse object
[ "Check", "your", "account", "usage", "for", "a", "given", "period", "and", "timeframe" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account.rb#L13-L18
24,691
zhimin/rwebspec
lib/rwebspec-webdriver/web_browser.rb
RWebSpec.WebBrowser.locate_input_element
def locate_input_element(how, what, types, value=nil) @browser.locate_input_element(how, what, types, value) end
ruby
def locate_input_element(how, what, types, value=nil) @browser.locate_input_element(how, what, types, value) end
[ "def", "locate_input_element", "(", "how", ",", "what", ",", "types", ",", "value", "=", "nil", ")", "@browser", ".", "locate_input_element", "(", "how", ",", "what", ",", "types", ",", "value", ")", "end" ]
Returns the specified ole object for input elements on a web page. This method is used internally by Watir and should not be used externally. It cannot be marked as private because of the way mixins and inheritance work in watir * how - symbol - the way we look for the object. Supported values are - :name - :id - :index - :value etc * what - string that we are looking for, ex. the name, or id tag attribute or index of the object we are looking for. * types - what object types we will look at. * value - used for objects that have one name, but many values. ex. radio lists and checkboxes
[ "Returns", "the", "specified", "ole", "object", "for", "input", "elements", "on", "a", "web", "page", "." ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L217-L219
24,692
zhimin/rwebspec
lib/rwebspec-webdriver/web_browser.rb
RWebSpec.WebBrowser.click_button_with_caption
def click_button_with_caption(caption, opts={}) all_buttons = button_elements matching_buttons = all_buttons.select{|x| x.attribute('value') == caption} if matching_buttons.size > 0 if opts && opts[:index] the_index = opts[:index].to_i() - 1 puts "Call matching buttons: #{matching_buttons.inspect} => #{the_index}" first_match = matching_buttons[the_index] first_match.click else the_button = matching_buttons[0] the_button.click end else raise "No button with value: #{caption} found" end end
ruby
def click_button_with_caption(caption, opts={}) all_buttons = button_elements matching_buttons = all_buttons.select{|x| x.attribute('value') == caption} if matching_buttons.size > 0 if opts && opts[:index] the_index = opts[:index].to_i() - 1 puts "Call matching buttons: #{matching_buttons.inspect} => #{the_index}" first_match = matching_buttons[the_index] first_match.click else the_button = matching_buttons[0] the_button.click end else raise "No button with value: #{caption} found" end end
[ "def", "click_button_with_caption", "(", "caption", ",", "opts", "=", "{", "}", ")", "all_buttons", "=", "button_elements", "matching_buttons", "=", "all_buttons", ".", "select", "{", "|", "x", "|", "x", ".", "attribute", "(", "'value'", ")", "==", "caption", "}", "if", "matching_buttons", ".", "size", ">", "0", "if", "opts", "&&", "opts", "[", ":index", "]", "the_index", "=", "opts", "[", ":index", "]", ".", "to_i", "(", ")", "-", "1", "puts", "\"Call matching buttons: #{matching_buttons.inspect} => #{the_index}\"", "first_match", "=", "matching_buttons", "[", "the_index", "]", "first_match", ".", "click", "else", "the_button", "=", "matching_buttons", "[", "0", "]", "the_button", ".", "click", "end", "else", "raise", "\"No button with value: #{caption} found\"", "end", "end" ]
Click a button with caption TODO: Caption is same as value Usage: click_button_with_caption("Confirm payment")
[ "Click", "a", "button", "with", "caption" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L525-L543
24,693
zhimin/rwebspec
lib/rwebspec-webdriver/web_browser.rb
RWebSpec.WebBrowser.submit
def submit(buttonName = nil) if (buttonName.nil?) then buttons.each { |button| next if button.type != 'submit' button.click return } else click_button_with_name(buttonName) end end
ruby
def submit(buttonName = nil) if (buttonName.nil?) then buttons.each { |button| next if button.type != 'submit' button.click return } else click_button_with_name(buttonName) end end
[ "def", "submit", "(", "buttonName", "=", "nil", ")", "if", "(", "buttonName", ".", "nil?", ")", "then", "buttons", ".", "each", "{", "|", "button", "|", "next", "if", "button", ".", "type", "!=", "'submit'", "button", ".", "click", "return", "}", "else", "click_button_with_name", "(", "buttonName", ")", "end", "end" ]
submit first submit button
[ "submit", "first", "submit", "button" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L590-L600
24,694
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/watch.rb
MediaWiki.Watch.watch_request
def watch_request(titles, unwatch = false) titles = titles.is_a?(Array) ? titles : [titles] params = { action: 'watch', titles: titles.shift(get_limited(titles.length, 50, 500)).join('|'), token: get_token('watch') } success_key = 'watched' if unwatch params[:unwatch] = 1 success_key = 'unwatched' end post(params)['watch'].inject({}) do |result, entry| title = entry['title'] if entry.key?(success_key) result[title] = entry.key?('missing') ? nil : true else result[title] = false end result end end
ruby
def watch_request(titles, unwatch = false) titles = titles.is_a?(Array) ? titles : [titles] params = { action: 'watch', titles: titles.shift(get_limited(titles.length, 50, 500)).join('|'), token: get_token('watch') } success_key = 'watched' if unwatch params[:unwatch] = 1 success_key = 'unwatched' end post(params)['watch'].inject({}) do |result, entry| title = entry['title'] if entry.key?(success_key) result[title] = entry.key?('missing') ? nil : true else result[title] = false end result end end
[ "def", "watch_request", "(", "titles", ",", "unwatch", "=", "false", ")", "titles", "=", "titles", ".", "is_a?", "(", "Array", ")", "?", "titles", ":", "[", "titles", "]", "params", "=", "{", "action", ":", "'watch'", ",", "titles", ":", "titles", ".", "shift", "(", "get_limited", "(", "titles", ".", "length", ",", "50", ",", "500", ")", ")", ".", "join", "(", "'|'", ")", ",", "token", ":", "get_token", "(", "'watch'", ")", "}", "success_key", "=", "'watched'", "if", "unwatch", "params", "[", ":unwatch", "]", "=", "1", "success_key", "=", "'unwatched'", "end", "post", "(", "params", ")", "[", "'watch'", "]", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "entry", "|", "title", "=", "entry", "[", "'title'", "]", "if", "entry", ".", "key?", "(", "success_key", ")", "result", "[", "title", "]", "=", "entry", ".", "key?", "(", "'missing'", ")", "?", "nil", ":", "true", "else", "result", "[", "title", "]", "=", "false", "end", "result", "end", "end" ]
Submits a watch action request. @param (see #watch) @param unwatch [Boolean] Whether the request should unwatch the pages or not. @return (see #watch)
[ "Submits", "a", "watch", "action", "request", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/watch.rb#L26-L49
24,695
zhimin/rwebspec
lib/rwebspec-common/core.rb
RWebSpec.Core.failsafe
def failsafe(& block) begin yield rescue RWebSpec::Assertion => e1 rescue ArgumentError => ae rescue RSpec::Expectations::ExpectationNotMetError => ree rescue =>e end end
ruby
def failsafe(& block) begin yield rescue RWebSpec::Assertion => e1 rescue ArgumentError => ae rescue RSpec::Expectations::ExpectationNotMetError => ree rescue =>e end end
[ "def", "failsafe", "(", "&", "block", ")", "begin", "yield", "rescue", "RWebSpec", "::", "Assertion", "=>", "e1", "rescue", "ArgumentError", "=>", "ae", "rescue", "RSpec", "::", "Expectations", "::", "ExpectationNotMetError", "=>", "ree", "rescue", "=>", "e", "end", "end" ]
try operation, ignore if errors occur Example: failsafe { click_link("Logout") } # try logout, but it still OK if not being able to (already logout))
[ "try", "operation", "ignore", "if", "errors", "occur" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L254-L262
24,696
zhimin/rwebspec
lib/rwebspec-common/core.rb
RWebSpec.Core.random_string_in
def random_string_in(arr) return nil if arr.empty? index = random_number(0, arr.length-1) arr[index] end
ruby
def random_string_in(arr) return nil if arr.empty? index = random_number(0, arr.length-1) arr[index] end
[ "def", "random_string_in", "(", "arr", ")", "return", "nil", "if", "arr", ".", "empty?", "index", "=", "random_number", "(", "0", ",", "arr", ".", "length", "-", "1", ")", "arr", "[", "index", "]", "end" ]
Return a random string in a rangeof pre-defined strings
[ "Return", "a", "random", "string", "in", "a", "rangeof", "pre", "-", "defined", "strings" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L355-L359
24,697
zhimin/rwebspec
lib/rwebspec-common/core.rb
RWebSpec.Core.interpret_value
def interpret_value(value) case value when Array then value.rand when Range then value_in_range(value) else value end end
ruby
def interpret_value(value) case value when Array then value.rand when Range then value_in_range(value) else value end end
[ "def", "interpret_value", "(", "value", ")", "case", "value", "when", "Array", "then", "value", ".", "rand", "when", "Range", "then", "value_in_range", "(", "value", ")", "else", "value", "end", "end" ]
If an array or range is passed, a random value will be selected to match. All other values are simply returned.
[ "If", "an", "array", "or", "range", "is", "passed", "a", "random", "value", "will", "be", "selected", "to", "match", ".", "All", "other", "values", "are", "simply", "returned", "." ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L403-L409
24,698
zhimin/rwebspec
lib/rwebspec-common/core.rb
RWebSpec.Core.process_each_row_in_csv_file
def process_each_row_in_csv_file(csv_file, &block) require 'faster_csv' connect_to_testwise("CSV_START", csv_file) if $testwise_support has_error = false idx = 0 FasterCSV.foreach(csv_file, :headers => :first_row, :encoding => 'u') do |row| connect_to_testwise("CSV_ON_ROW", idx.to_s) if $testwise_support begin yield row connect_to_testwise("CSV_ROW_PASS", idx.to_s) if $testwise_support rescue => e connect_to_testwise("CSV_ROW_FAIL", idx.to_s) if $testwise_support has_error = true ensure idx += 1 end end connect_to_testwise("CSV_END", "") if $testwise_support raise "Test failed on data" if has_error end
ruby
def process_each_row_in_csv_file(csv_file, &block) require 'faster_csv' connect_to_testwise("CSV_START", csv_file) if $testwise_support has_error = false idx = 0 FasterCSV.foreach(csv_file, :headers => :first_row, :encoding => 'u') do |row| connect_to_testwise("CSV_ON_ROW", idx.to_s) if $testwise_support begin yield row connect_to_testwise("CSV_ROW_PASS", idx.to_s) if $testwise_support rescue => e connect_to_testwise("CSV_ROW_FAIL", idx.to_s) if $testwise_support has_error = true ensure idx += 1 end end connect_to_testwise("CSV_END", "") if $testwise_support raise "Test failed on data" if has_error end
[ "def", "process_each_row_in_csv_file", "(", "csv_file", ",", "&", "block", ")", "require", "'faster_csv'", "connect_to_testwise", "(", "\"CSV_START\"", ",", "csv_file", ")", "if", "$testwise_support", "has_error", "=", "false", "idx", "=", "0", "FasterCSV", ".", "foreach", "(", "csv_file", ",", ":headers", "=>", ":first_row", ",", ":encoding", "=>", "'u'", ")", "do", "|", "row", "|", "connect_to_testwise", "(", "\"CSV_ON_ROW\"", ",", "idx", ".", "to_s", ")", "if", "$testwise_support", "begin", "yield", "row", "connect_to_testwise", "(", "\"CSV_ROW_PASS\"", ",", "idx", ".", "to_s", ")", "if", "$testwise_support", "rescue", "=>", "e", "connect_to_testwise", "(", "\"CSV_ROW_FAIL\"", ",", "idx", ".", "to_s", ")", "if", "$testwise_support", "has_error", "=", "true", "ensure", "idx", "+=", "1", "end", "end", "connect_to_testwise", "(", "\"CSV_END\"", ",", "\"\"", ")", "if", "$testwise_support", "raise", "\"Test failed on data\"", "if", "has_error", "end" ]
Data Driven Tests Processing each row in a CSV file, must have heading rows Usage: process_each_row_in_csv_file(@csv_file) { |row| goto_page("/") enter_text("username", row[1]) enter_text("password", row[2]) click_button("Sign in") page_text.should contain(row[3]) failsafe{ click_link("Sign off") } }
[ "Data", "Driven", "Tests" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L488-L508
24,699
xing/crep
lib/crep/crash_controller.rb
Crep.CrashController.top_crashes
def top_crashes(version, build) @version = version @build = build @crashes = @crash_source.crashes(@top, version, build, @show_only_unresolved) @total_crashes = @crash_source.crash_count(version: @version, build: @build) report end
ruby
def top_crashes(version, build) @version = version @build = build @crashes = @crash_source.crashes(@top, version, build, @show_only_unresolved) @total_crashes = @crash_source.crash_count(version: @version, build: @build) report end
[ "def", "top_crashes", "(", "version", ",", "build", ")", "@version", "=", "version", "@build", "=", "build", "@crashes", "=", "@crash_source", ".", "crashes", "(", "@top", ",", "version", ",", "build", ",", "@show_only_unresolved", ")", "@total_crashes", "=", "@crash_source", ".", "crash_count", "(", "version", ":", "@version", ",", "build", ":", "@build", ")", "report", "end" ]
returns list of top crashes for the given build
[ "returns", "list", "of", "top", "crashes", "for", "the", "given", "build" ]
bee045b59cf3bfd40e2a7f1d3dd3d749bd3d4614
https://github.com/xing/crep/blob/bee045b59cf3bfd40e2a7f1d3dd3d749bd3d4614/lib/crep/crash_controller.rb#L32-L38