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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
6,000
riddopic/garcun
lib/garcon/task/executor.rb
Garcon.RubyExecutor.post
def post(*args, &task) raise ArgumentError.new('no block given') unless block_given? mutex.synchronize do # If the executor is shut down, reject this task return handle_fallback(*args, &task) unless running? execute(*args, &task) true end end
ruby
def post(*args, &task) raise ArgumentError.new('no block given') unless block_given? mutex.synchronize do # If the executor is shut down, reject this task return handle_fallback(*args, &task) unless running? execute(*args, &task) true end end
[ "def", "post", "(", "*", "args", ",", "&", "task", ")", "raise", "ArgumentError", ".", "new", "(", "'no block given'", ")", "unless", "block_given?", "mutex", ".", "synchronize", "do", "# If the executor is shut down, reject this task", "return", "handle_fallback", "(", "args", ",", "task", ")", "unless", "running?", "execute", "(", "args", ",", "task", ")", "true", "end", "end" ]
Submit a task to the executor for asynchronous processing. @param [Array] args Zero or more arguments to be passed to the task @yield the asynchronous task to perform @raise [ArgumentError] if no task is given @return [Boolean] True if the task is queued, false if the executor is not running.
[ "Submit", "a", "task", "to", "the", "executor", "for", "asynchronous", "processing", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor.rb#L155-L163
6,001
riddopic/garcun
lib/garcon/task/executor.rb
Garcon.RubyExecutor.kill
def kill mutex.synchronize do break if shutdown? stop_event.set kill_execution stopped_event.set end true end
ruby
def kill mutex.synchronize do break if shutdown? stop_event.set kill_execution stopped_event.set end true end
[ "def", "kill", "mutex", ".", "synchronize", "do", "break", "if", "shutdown?", "stop_event", ".", "set", "kill_execution", "stopped_event", ".", "set", "end", "true", "end" ]
Begin an immediate shutdown. In-progress tasks will be allowed to complete but enqueued tasks will be dismissed and no new tasks will be accepted. Has no additional effect if the thread pool is not running.
[ "Begin", "an", "immediate", "shutdown", ".", "In", "-", "progress", "tasks", "will", "be", "allowed", "to", "complete", "but", "enqueued", "tasks", "will", "be", "dismissed", "and", "no", "new", "tasks", "will", "be", "accepted", ".", "Has", "no", "additional", "effect", "if", "the", "thread", "pool", "is", "not", "running", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor.rb#L218-L226
6,002
GlobalNamesArchitecture/taxamatch_rb
lib/taxamatch_rb/base.rb
Taxamatch.Base.taxamatch
def taxamatch(str1, str2, return_boolean = true) preparsed_1 = @parser.parse(str1) preparsed_2 = @parser.parse(str2) match = taxamatch_preparsed(preparsed_1, preparsed_2) rescue nil return_boolean ? (!!match && match['match']) : match end
ruby
def taxamatch(str1, str2, return_boolean = true) preparsed_1 = @parser.parse(str1) preparsed_2 = @parser.parse(str2) match = taxamatch_preparsed(preparsed_1, preparsed_2) rescue nil return_boolean ? (!!match && match['match']) : match end
[ "def", "taxamatch", "(", "str1", ",", "str2", ",", "return_boolean", "=", "true", ")", "preparsed_1", "=", "@parser", ".", "parse", "(", "str1", ")", "preparsed_2", "=", "@parser", ".", "parse", "(", "str2", ")", "match", "=", "taxamatch_preparsed", "(", "preparsed_1", ",", "preparsed_2", ")", "rescue", "nil", "return_boolean", "?", "(", "!", "!", "match", "&&", "match", "[", "'match'", "]", ")", ":", "match", "end" ]
takes two scientific names and returns true if names match and false if they don't
[ "takes", "two", "scientific", "names", "and", "returns", "true", "if", "names", "match", "and", "false", "if", "they", "don", "t" ]
1feabf9a1ae78777d21005f4567d0c221c6ef2e1
https://github.com/GlobalNamesArchitecture/taxamatch_rb/blob/1feabf9a1ae78777d21005f4567d0c221c6ef2e1/lib/taxamatch_rb/base.rb#L10-L15
6,003
GlobalNamesArchitecture/taxamatch_rb
lib/taxamatch_rb/base.rb
Taxamatch.Base.taxamatch_preparsed
def taxamatch_preparsed(preparsed_1, preparsed_2) result = nil if preparsed_1[:uninomial] && preparsed_2[:uninomial] result = match_uninomial(preparsed_1, preparsed_2) end if preparsed_1[:genus] && preparsed_2[:genus] result = match_multinomial(preparsed_1, preparsed_2) end if result && result['match'] result['match'] = match_authors(preparsed_1, preparsed_2) == -1 ? false : true end return result end
ruby
def taxamatch_preparsed(preparsed_1, preparsed_2) result = nil if preparsed_1[:uninomial] && preparsed_2[:uninomial] result = match_uninomial(preparsed_1, preparsed_2) end if preparsed_1[:genus] && preparsed_2[:genus] result = match_multinomial(preparsed_1, preparsed_2) end if result && result['match'] result['match'] = match_authors(preparsed_1, preparsed_2) == -1 ? false : true end return result end
[ "def", "taxamatch_preparsed", "(", "preparsed_1", ",", "preparsed_2", ")", "result", "=", "nil", "if", "preparsed_1", "[", ":uninomial", "]", "&&", "preparsed_2", "[", ":uninomial", "]", "result", "=", "match_uninomial", "(", "preparsed_1", ",", "preparsed_2", ")", "end", "if", "preparsed_1", "[", ":genus", "]", "&&", "preparsed_2", "[", ":genus", "]", "result", "=", "match_multinomial", "(", "preparsed_1", ",", "preparsed_2", ")", "end", "if", "result", "&&", "result", "[", "'match'", "]", "result", "[", "'match'", "]", "=", "match_authors", "(", "preparsed_1", ",", "preparsed_2", ")", "==", "-", "1", "?", "false", ":", "true", "end", "return", "result", "end" ]
takes two hashes of parsed scientific names, analyses them and returns back this function is useful when species strings are preparsed.
[ "takes", "two", "hashes", "of", "parsed", "scientific", "names", "analyses", "them", "and", "returns", "back", "this", "function", "is", "useful", "when", "species", "strings", "are", "preparsed", "." ]
1feabf9a1ae78777d21005f4567d0c221c6ef2e1
https://github.com/GlobalNamesArchitecture/taxamatch_rb/blob/1feabf9a1ae78777d21005f4567d0c221c6ef2e1/lib/taxamatch_rb/base.rb#L19-L32
6,004
mrackwitz/CLIntegracon
lib/CLIntegracon/configuration.rb
CLIntegracon.Configuration.hook_into
def hook_into test_framework adapter = self.class.adapters[test_framework] raise ArgumentError.new "No adapter for test framework #{test_framework}" if adapter.nil? require adapter end
ruby
def hook_into test_framework adapter = self.class.adapters[test_framework] raise ArgumentError.new "No adapter for test framework #{test_framework}" if adapter.nil? require adapter end
[ "def", "hook_into", "test_framework", "adapter", "=", "self", ".", "class", ".", "adapters", "[", "test_framework", "]", "raise", "ArgumentError", ".", "new", "\"No adapter for test framework #{test_framework}\"", "if", "adapter", ".", "nil?", "require", "adapter", "end" ]
Hook this gem in a test framework by a supported adapter @param [Symbol] test_framework the test framework
[ "Hook", "this", "gem", "in", "a", "test", "framework", "by", "a", "supported", "adapter" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/configuration.rb#L66-L70
6,005
Fluxx/gazette
lib/gazette/client.rb
Gazette.Client.parse_response_for
def parse_response_for(response) case response when Net::HTTPOK, Net::HTTPCreated then return Response::Success.new(response) when Net::HTTPForbidden then raise Response::InvalidCredentials when Net::HTTPInternalServerError then raise Response::ServerError else raise Response::UnknownError end end
ruby
def parse_response_for(response) case response when Net::HTTPOK, Net::HTTPCreated then return Response::Success.new(response) when Net::HTTPForbidden then raise Response::InvalidCredentials when Net::HTTPInternalServerError then raise Response::ServerError else raise Response::UnknownError end end
[ "def", "parse_response_for", "(", "response", ")", "case", "response", "when", "Net", "::", "HTTPOK", ",", "Net", "::", "HTTPCreated", "then", "return", "Response", "::", "Success", ".", "new", "(", "response", ")", "when", "Net", "::", "HTTPForbidden", "then", "raise", "Response", "::", "InvalidCredentials", "when", "Net", "::", "HTTPInternalServerError", "then", "raise", "Response", "::", "ServerError", "else", "raise", "Response", "::", "UnknownError", "end", "end" ]
Handles the response from Instapaper. @todo Put the raising logic in the Api class/module, then leave the response return to this method
[ "Handles", "the", "response", "from", "Instapaper", "." ]
02fa3aa46d2b39cfa4184d374842a91f7f8d9e17
https://github.com/Fluxx/gazette/blob/02fa3aa46d2b39cfa4184d374842a91f7f8d9e17/lib/gazette/client.rb#L72-L79
6,006
Fluxx/gazette
lib/gazette/client.rb
Gazette.Client.request
def request(method, params = {}) http = Net::HTTP.new(Api::ADDRESS, (@https ? 443 : 80)) http.use_ssl = @https http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(Api::ENDPOINT+method.to_s) request.basic_auth @username, @password request.set_form_data(params) http.start { http.request(request) } end
ruby
def request(method, params = {}) http = Net::HTTP.new(Api::ADDRESS, (@https ? 443 : 80)) http.use_ssl = @https http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(Api::ENDPOINT+method.to_s) request.basic_auth @username, @password request.set_form_data(params) http.start { http.request(request) } end
[ "def", "request", "(", "method", ",", "params", "=", "{", "}", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "Api", "::", "ADDRESS", ",", "(", "@https", "?", "443", ":", "80", ")", ")", "http", ".", "use_ssl", "=", "@https", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "Api", "::", "ENDPOINT", "+", "method", ".", "to_s", ")", "request", ".", "basic_auth", "@username", ",", "@password", "request", ".", "set_form_data", "(", "params", ")", "http", ".", "start", "{", "http", ".", "request", "(", "request", ")", "}", "end" ]
Actually heads out to the internet and performs the request @todo Perhaps put me in the Api class/module?
[ "Actually", "heads", "out", "to", "the", "internet", "and", "performs", "the", "request" ]
02fa3aa46d2b39cfa4184d374842a91f7f8d9e17
https://github.com/Fluxx/gazette/blob/02fa3aa46d2b39cfa4184d374842a91f7f8d9e17/lib/gazette/client.rb#L83-L91
6,007
sanichi/icu_ratings
lib/icu_ratings/tournament.rb
ICU.RatedTournament.rate!
def rate!(opt={}) # The original algorithm (version 0). max_iterations = [30, 1] phase_2_bonuses = true update_bonuses = false threshold = 0.5 # New versions of the algorithm. version = opt[:version].to_i if version >= 1 # See http://ratings.icu.ie/articles/18 (Part 1) max_iterations[1] = 30 end if version >= 2 # See http://ratings.icu.ie/articles/18 (Part 2) phase_2_bonuses = false update_bonuses = true threshold = 0.1 end if version >= 3 # See http://ratings.icu.ie/articles/18 (Part 3) max_iterations = [50, 50] end # Phase 1. players.each { |p| p.reset } @iterations1 = performance_ratings(max_iterations[0], threshold) players.each { |p| p.rate! } # Phase 2. if !no_bonuses && calculate_bonuses > 0 players.each { |p| p.rate!(update_bonuses) } @iterations2 = performance_ratings(max_iterations[1], threshold) calculate_bonuses if phase_2_bonuses else @iterations2 = 0 end end
ruby
def rate!(opt={}) # The original algorithm (version 0). max_iterations = [30, 1] phase_2_bonuses = true update_bonuses = false threshold = 0.5 # New versions of the algorithm. version = opt[:version].to_i if version >= 1 # See http://ratings.icu.ie/articles/18 (Part 1) max_iterations[1] = 30 end if version >= 2 # See http://ratings.icu.ie/articles/18 (Part 2) phase_2_bonuses = false update_bonuses = true threshold = 0.1 end if version >= 3 # See http://ratings.icu.ie/articles/18 (Part 3) max_iterations = [50, 50] end # Phase 1. players.each { |p| p.reset } @iterations1 = performance_ratings(max_iterations[0], threshold) players.each { |p| p.rate! } # Phase 2. if !no_bonuses && calculate_bonuses > 0 players.each { |p| p.rate!(update_bonuses) } @iterations2 = performance_ratings(max_iterations[1], threshold) calculate_bonuses if phase_2_bonuses else @iterations2 = 0 end end
[ "def", "rate!", "(", "opt", "=", "{", "}", ")", "# The original algorithm (version 0).", "max_iterations", "=", "[", "30", ",", "1", "]", "phase_2_bonuses", "=", "true", "update_bonuses", "=", "false", "threshold", "=", "0.5", "# New versions of the algorithm.", "version", "=", "opt", "[", ":version", "]", ".", "to_i", "if", "version", ">=", "1", "# See http://ratings.icu.ie/articles/18 (Part 1)", "max_iterations", "[", "1", "]", "=", "30", "end", "if", "version", ">=", "2", "# See http://ratings.icu.ie/articles/18 (Part 2)", "phase_2_bonuses", "=", "false", "update_bonuses", "=", "true", "threshold", "=", "0.1", "end", "if", "version", ">=", "3", "# See http://ratings.icu.ie/articles/18 (Part 3)", "max_iterations", "=", "[", "50", ",", "50", "]", "end", "# Phase 1.", "players", ".", "each", "{", "|", "p", "|", "p", ".", "reset", "}", "@iterations1", "=", "performance_ratings", "(", "max_iterations", "[", "0", "]", ",", "threshold", ")", "players", ".", "each", "{", "|", "p", "|", "p", ".", "rate!", "}", "# Phase 2.", "if", "!", "no_bonuses", "&&", "calculate_bonuses", ">", "0", "players", ".", "each", "{", "|", "p", "|", "p", ".", "rate!", "(", "update_bonuses", ")", "}", "@iterations2", "=", "performance_ratings", "(", "max_iterations", "[", "1", "]", ",", "threshold", ")", "calculate_bonuses", "if", "phase_2_bonuses", "else", "@iterations2", "=", "0", "end", "end" ]
Rate the tournament. Called after all players and results have been added.
[ "Rate", "the", "tournament", ".", "Called", "after", "all", "players", "and", "results", "have", "been", "added", "." ]
edcb1bb903f123101fbc25d16192c4524a7112da
https://github.com/sanichi/icu_ratings/blob/edcb1bb903f123101fbc25d16192c4524a7112da/lib/icu_ratings/tournament.rb#L108-L145
6,008
sanichi/icu_ratings
lib/icu_ratings/tournament.rb
ICU.RatedTournament.calculate_bonuses
def calculate_bonuses @player.values.select{ |p| p.respond_to?(:bonus) }.inject(0) { |t,p| t + (p.calculate_bonus ? 1 : 0) } end
ruby
def calculate_bonuses @player.values.select{ |p| p.respond_to?(:bonus) }.inject(0) { |t,p| t + (p.calculate_bonus ? 1 : 0) } end
[ "def", "calculate_bonuses", "@player", ".", "values", ".", "select", "{", "|", "p", "|", "p", ".", "respond_to?", "(", ":bonus", ")", "}", ".", "inject", "(", "0", ")", "{", "|", "t", ",", "p", "|", "t", "+", "(", "p", ".", "calculate_bonus", "?", "1", ":", "0", ")", "}", "end" ]
Calculate bonuses for all players and return the number who got one.
[ "Calculate", "bonuses", "for", "all", "players", "and", "return", "the", "number", "who", "got", "one", "." ]
edcb1bb903f123101fbc25d16192c4524a7112da
https://github.com/sanichi/icu_ratings/blob/edcb1bb903f123101fbc25d16192c4524a7112da/lib/icu_ratings/tournament.rb#L188-L190
6,009
jinx/migrate
lib/jinx/migration/migratable.rb
Jinx.Migratable.migrate_references
def migrate_references(row, migrated, target, proc_hash=nil) # migrate the owner migratable__migrate_owner(row, migrated, target, proc_hash) # migrate the remaining attributes migratable__set_nonowner_references(migratable_independent_attributes, row, migrated, proc_hash) migratable__set_nonowner_references(self.class.unidirectional_dependent_attributes, row, migrated, proc_hash) end
ruby
def migrate_references(row, migrated, target, proc_hash=nil) # migrate the owner migratable__migrate_owner(row, migrated, target, proc_hash) # migrate the remaining attributes migratable__set_nonowner_references(migratable_independent_attributes, row, migrated, proc_hash) migratable__set_nonowner_references(self.class.unidirectional_dependent_attributes, row, migrated, proc_hash) end
[ "def", "migrate_references", "(", "row", ",", "migrated", ",", "target", ",", "proc_hash", "=", "nil", ")", "# migrate the owner", "migratable__migrate_owner", "(", "row", ",", "migrated", ",", "target", ",", "proc_hash", ")", "# migrate the remaining attributes", "migratable__set_nonowner_references", "(", "migratable_independent_attributes", ",", "row", ",", "migrated", ",", "proc_hash", ")", "migratable__set_nonowner_references", "(", "self", ".", "class", ".", "unidirectional_dependent_attributes", ",", "row", ",", "migrated", ",", "proc_hash", ")", "end" ]
Migrates this domain object's migratable references. This method is called by the Migrator and should not be overridden by subclasses. Subclasses tailor individual reference attribute migration by defining a +migrate_+_attribute_ method for the _attribute_ to modify. The migratable reference attributes consist of the non-collection saved independent attributes and the unidirectional dependent attributes which don't already have a value. For each such migratable attribute, if there is a single instance of the attribute type in the given migrated domain objects, then the attribute is set to that migrated instance. If the attribute is associated with a method in proc_hash, then that method is called on the migrated instance and input row. The attribute is set to the method return value. proc_hash includes an entry for each +migrate_+_attribute_ method defined by this Resource's class. @param [{Symbol => Object}] row the input row field => value hash @param [<Resource>] migrated the migrated instances, including this Resource @param [Class] target the migration target class @param [{Symbol => Proc}, nil] proc_hash a hash that associates this domain object's attributes to a migration shim block
[ "Migrates", "this", "domain", "object", "s", "migratable", "references", ".", "This", "method", "is", "called", "by", "the", "Migrator", "and", "should", "not", "be", "overridden", "by", "subclasses", ".", "Subclasses", "tailor", "individual", "reference", "attribute", "migration", "by", "defining", "a", "+", "migrate_", "+", "_attribute_", "method", "for", "the", "_attribute_", "to", "modify", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migratable.rb#L114-L120
6,010
mikisvaz/progress-monitor
lib/progress-bar.rb
Progress.Progress::Bar.tick
def tick(step = nil) if step.nil? @current += 1 else @current = step end percent = @current.to_f/ @max.to_f if percent - @last_report > 1.to_f/@num_reports.to_f report @last_report=percent end nil end
ruby
def tick(step = nil) if step.nil? @current += 1 else @current = step end percent = @current.to_f/ @max.to_f if percent - @last_report > 1.to_f/@num_reports.to_f report @last_report=percent end nil end
[ "def", "tick", "(", "step", "=", "nil", ")", "if", "step", ".", "nil?", "@current", "+=", "1", "else", "@current", "=", "step", "end", "percent", "=", "@current", ".", "to_f", "/", "@max", ".", "to_f", "if", "percent", "-", "@last_report", ">", "1", ".", "to_f", "/", "@num_reports", ".", "to_f", "report", "@last_report", "=", "percent", "end", "nil", "end" ]
Creates a new instance. Max is the total number of iterations of the loop. The depth represents how many other loops are above this one, this information is used to find the place to print the progress report. Used to register a new completed loop iteration.
[ "Creates", "a", "new", "instance", ".", "Max", "is", "the", "total", "number", "of", "iterations", "of", "the", "loop", ".", "The", "depth", "represents", "how", "many", "other", "loops", "are", "above", "this", "one", "this", "information", "is", "used", "to", "find", "the", "place", "to", "print", "the", "progress", "report", "." ]
b15cfec9e98160c54586fbf96f25b4915985d4e9
https://github.com/mikisvaz/progress-monitor/blob/b15cfec9e98160c54586fbf96f25b4915985d4e9/lib/progress-bar.rb#L22-L37
6,011
mikisvaz/progress-monitor
lib/progress-bar.rb
Progress.Progress::Bar.report
def report percent = @current.to_f/ @max.to_f percent = 0.001 if percent < 0.001 if @desc != "" indicator = @desc + ": " else indicator = "Progress " end indicator += "[" 10.times{|i| if i < percent * 10 then indicator += "." else indicator += " " end } indicator += "] done #{(percent * 100).to_i}% " eta = (Time.now - @time)/percent * (1-percent) eta = eta.to_i eta = [eta/3600, eta/60 % 60, eta % 60].map{|t| "%02i" % t }.join(':') used = (Time.now - @time).to_i used = [used/3600, used/60 % 60, used % 60].map{|t| "%02i" % t }.join(':') indicator += " (Time left #{eta} seconds) (Started #{used} seconds ago)" STDERR.print("\033[#{@depth + 1}F\033[2K" + indicator + "\n\033[#{@depth + 2}E") end
ruby
def report percent = @current.to_f/ @max.to_f percent = 0.001 if percent < 0.001 if @desc != "" indicator = @desc + ": " else indicator = "Progress " end indicator += "[" 10.times{|i| if i < percent * 10 then indicator += "." else indicator += " " end } indicator += "] done #{(percent * 100).to_i}% " eta = (Time.now - @time)/percent * (1-percent) eta = eta.to_i eta = [eta/3600, eta/60 % 60, eta % 60].map{|t| "%02i" % t }.join(':') used = (Time.now - @time).to_i used = [used/3600, used/60 % 60, used % 60].map{|t| "%02i" % t }.join(':') indicator += " (Time left #{eta} seconds) (Started #{used} seconds ago)" STDERR.print("\033[#{@depth + 1}F\033[2K" + indicator + "\n\033[#{@depth + 2}E") end
[ "def", "report", "percent", "=", "@current", ".", "to_f", "/", "@max", ".", "to_f", "percent", "=", "0.001", "if", "percent", "<", "0.001", "if", "@desc", "!=", "\"\"", "indicator", "=", "@desc", "+", "\": \"", "else", "indicator", "=", "\"Progress \"", "end", "indicator", "+=", "\"[\"", "10", ".", "times", "{", "|", "i", "|", "if", "i", "<", "percent", "*", "10", "then", "indicator", "+=", "\".\"", "else", "indicator", "+=", "\" \"", "end", "}", "indicator", "+=", "\"] done #{(percent * 100).to_i}% \"", "eta", "=", "(", "Time", ".", "now", "-", "@time", ")", "/", "percent", "*", "(", "1", "-", "percent", ")", "eta", "=", "eta", ".", "to_i", "eta", "=", "[", "eta", "/", "3600", ",", "eta", "/", "60", "%", "60", ",", "eta", "%", "60", "]", ".", "map", "{", "|", "t", "|", "\"%02i\"", "%", "t", "}", ".", "join", "(", "':'", ")", "used", "=", "(", "Time", ".", "now", "-", "@time", ")", ".", "to_i", "used", "=", "[", "used", "/", "3600", ",", "used", "/", "60", "%", "60", ",", "used", "%", "60", "]", ".", "map", "{", "|", "t", "|", "\"%02i\"", "%", "t", "}", ".", "join", "(", "':'", ")", "indicator", "+=", "\" (Time left #{eta} seconds) (Started #{used} seconds ago)\"", "STDERR", ".", "print", "(", "\"\\033[#{@depth + 1}F\\033[2K\"", "+", "indicator", "+", "\"\\n\\033[#{@depth + 2}E\"", ")", "end" ]
Prints de progress report. It backs up as many lines as the meters depth. Prints the progress as a line of dots, a percentage, time spent, and time left. And then goes moves the cursor back to its original line. Everything is printed to stderr.
[ "Prints", "de", "progress", "report", ".", "It", "backs", "up", "as", "many", "lines", "as", "the", "meters", "depth", ".", "Prints", "the", "progress", "as", "a", "line", "of", "dots", "a", "percentage", "time", "spent", "and", "time", "left", ".", "And", "then", "goes", "moves", "the", "cursor", "back", "to", "its", "original", "line", ".", "Everything", "is", "printed", "to", "stderr", "." ]
b15cfec9e98160c54586fbf96f25b4915985d4e9
https://github.com/mikisvaz/progress-monitor/blob/b15cfec9e98160c54586fbf96f25b4915985d4e9/lib/progress-bar.rb#L44-L73
6,012
Lupeipei/i18n-processes
lib/i18n/processes/split_key.rb
I18n::Processes.SplitKey.key_parts
def key_parts(key, &block) return enum_for(:key_parts, key) unless block nesting = PARENS counts = PARENS_ZEROS # dup'd later if key contains parenthesis delim = '.' from = to = 0 key.each_char do |char| if char == delim && PARENS_ZEROS == counts block.yield key[from...to] from = to = (to + 1) else nest_i, nest_inc = nesting[char] if nest_i counts = counts.dup if counts.frozen? counts[nest_i] += nest_inc end to += 1 end end block.yield(key[from...to]) if from < to && to <= key.length true end
ruby
def key_parts(key, &block) return enum_for(:key_parts, key) unless block nesting = PARENS counts = PARENS_ZEROS # dup'd later if key contains parenthesis delim = '.' from = to = 0 key.each_char do |char| if char == delim && PARENS_ZEROS == counts block.yield key[from...to] from = to = (to + 1) else nest_i, nest_inc = nesting[char] if nest_i counts = counts.dup if counts.frozen? counts[nest_i] += nest_inc end to += 1 end end block.yield(key[from...to]) if from < to && to <= key.length true end
[ "def", "key_parts", "(", "key", ",", "&", "block", ")", "return", "enum_for", "(", ":key_parts", ",", "key", ")", "unless", "block", "nesting", "=", "PARENS", "counts", "=", "PARENS_ZEROS", "# dup'd later if key contains parenthesis", "delim", "=", "'.'", "from", "=", "to", "=", "0", "key", ".", "each_char", "do", "|", "char", "|", "if", "char", "==", "delim", "&&", "PARENS_ZEROS", "==", "counts", "block", ".", "yield", "key", "[", "from", "...", "to", "]", "from", "=", "to", "=", "(", "to", "+", "1", ")", "else", "nest_i", ",", "nest_inc", "=", "nesting", "[", "char", "]", "if", "nest_i", "counts", "=", "counts", ".", "dup", "if", "counts", ".", "frozen?", "counts", "[", "nest_i", "]", "+=", "nest_inc", "end", "to", "+=", "1", "end", "end", "block", ".", "yield", "(", "key", "[", "from", "...", "to", "]", ")", "if", "from", "<", "to", "&&", "to", "<=", "key", ".", "length", "true", "end" ]
yield each key part dots inside braces or parenthesis are not split on
[ "yield", "each", "key", "part", "dots", "inside", "braces", "or", "parenthesis", "are", "not", "split", "on" ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/split_key.rb#L36-L57
6,013
richard-viney/lightstreamer
lib/lightstreamer/subscription.rb
Lightstreamer.Subscription.process_stream_data
def process_stream_data(line) return true if process_update_message UpdateMessage.parse(line, id, items, fields) return true if process_overflow_message OverflowMessage.parse(line, id, items) return true if process_end_of_snapshot_message EndOfSnapshotMessage.parse(line, id, items) end
ruby
def process_stream_data(line) return true if process_update_message UpdateMessage.parse(line, id, items, fields) return true if process_overflow_message OverflowMessage.parse(line, id, items) return true if process_end_of_snapshot_message EndOfSnapshotMessage.parse(line, id, items) end
[ "def", "process_stream_data", "(", "line", ")", "return", "true", "if", "process_update_message", "UpdateMessage", ".", "parse", "(", "line", ",", "id", ",", "items", ",", "fields", ")", "return", "true", "if", "process_overflow_message", "OverflowMessage", ".", "parse", "(", "line", ",", "id", ",", "items", ")", "return", "true", "if", "process_end_of_snapshot_message", "EndOfSnapshotMessage", ".", "parse", "(", "line", ",", "id", ",", "items", ")", "end" ]
Processes a line of stream data if it is relevant to this subscription. This method is thread-safe and is intended to be called by the session's processing thread. @param [String] line The line of stream data to process. @return [Boolean] Whether the passed line of stream data was processed by this subscription. @private
[ "Processes", "a", "line", "of", "stream", "data", "if", "it", "is", "relevant", "to", "this", "subscription", ".", "This", "method", "is", "thread", "-", "safe", "and", "is", "intended", "to", "be", "called", "by", "the", "session", "s", "processing", "thread", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/subscription.rb#L208-L212
6,014
richard-viney/lightstreamer
lib/lightstreamer/subscription.rb
Lightstreamer.Subscription.control_request_options
def control_request_options(action, options = nil) case action.to_sym when :start start_control_request_options options when :unsilence { LS_session: @session.session_id, LS_op: :start, LS_table: id } when :stop { LS_session: @session.session_id, LS_op: :delete, LS_table: id } end end
ruby
def control_request_options(action, options = nil) case action.to_sym when :start start_control_request_options options when :unsilence { LS_session: @session.session_id, LS_op: :start, LS_table: id } when :stop { LS_session: @session.session_id, LS_op: :delete, LS_table: id } end end
[ "def", "control_request_options", "(", "action", ",", "options", "=", "nil", ")", "case", "action", ".", "to_sym", "when", ":start", "start_control_request_options", "options", "when", ":unsilence", "{", "LS_session", ":", "@session", ".", "session_id", ",", "LS_op", ":", ":start", ",", "LS_table", ":", "id", "}", "when", ":stop", "{", "LS_session", ":", "@session", ".", "session_id", ",", "LS_op", ":", ":delete", ",", "LS_table", ":", "id", "}", "end", "end" ]
Returns the control request arguments to use to perform the specified action on this subscription. @private
[ "Returns", "the", "control", "request", "arguments", "to", "use", "to", "perform", "the", "specified", "action", "on", "this", "subscription", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/subscription.rb#L217-L226
6,015
ziolmar/chaintown
lib/chaintown/steps.rb
Chaintown.Steps.inherited
def inherited(subclass) [:steps, :failed_steps].each do |inheritable_attribute| instance_var = "@#{inheritable_attribute}" subclass.instance_variable_set(instance_var, instance_variable_get(instance_var).dup || []) end end
ruby
def inherited(subclass) [:steps, :failed_steps].each do |inheritable_attribute| instance_var = "@#{inheritable_attribute}" subclass.instance_variable_set(instance_var, instance_variable_get(instance_var).dup || []) end end
[ "def", "inherited", "(", "subclass", ")", "[", ":steps", ",", ":failed_steps", "]", ".", "each", "do", "|", "inheritable_attribute", "|", "instance_var", "=", "\"@#{inheritable_attribute}\"", "subclass", ".", "instance_variable_set", "(", "instance_var", ",", "instance_variable_get", "(", "instance_var", ")", ".", "dup", "||", "[", "]", ")", "end", "end" ]
Callback, assure that we add steps from parent class
[ "Callback", "assure", "that", "we", "add", "steps", "from", "parent", "class" ]
ece36eb5a054f1ec66defb913f4a6d47ea5e4aac
https://github.com/ziolmar/chaintown/blob/ece36eb5a054f1ec66defb913f4a6d47ea5e4aac/lib/chaintown/steps.rb#L50-L55
6,016
webmonarch/movingsign_api
lib/movingsign_api/sign.rb
MovingsignApi.Sign.show_text
def show_text(text, options = {}) cmd = WriteTextCommand.new cmd.display_pause = options[:display_pause] if options[:display_pause] cmd.text = text send_command cmd end
ruby
def show_text(text, options = {}) cmd = WriteTextCommand.new cmd.display_pause = options[:display_pause] if options[:display_pause] cmd.text = text send_command cmd end
[ "def", "show_text", "(", "text", ",", "options", "=", "{", "}", ")", "cmd", "=", "WriteTextCommand", ".", "new", "cmd", ".", "display_pause", "=", "options", "[", ":display_pause", "]", "if", "options", "[", ":display_pause", "]", "cmd", ".", "text", "=", "text", "send_command", "cmd", "end" ]
Displays the given text on the board. This is short-hand for the {WriteTextCommand} @param text [String] the text to display on the sign @param options [Hash] options for {WriteTextCommand} @option options [Integer] :display_pause (2) Time to pause (in seconds) between pages of text. See {WriteTextCommand#display_pause} @return [self]
[ "Displays", "the", "given", "text", "on", "the", "board", "." ]
11c820edcb5f3a367b341257dae4f6249ae6d0a3
https://github.com/webmonarch/movingsign_api/blob/11c820edcb5f3a367b341257dae4f6249ae6d0a3/lib/movingsign_api/sign.rb#L43-L49
6,017
webmonarch/movingsign_api
lib/movingsign_api/sign.rb
MovingsignApi.Sign.send_command
def send_command(command) SerialPort.open(self.device_path, 9600, 8, 1) do |port| # flush anything existing on the port port.flush flush_read_buffer(port) byte_string = command.to_bytes.pack('C*') begin while byte_string && byte_string.length != 0 count = port.write_nonblock(byte_string) byte_string = byte_string[count,-1] port.flush end rescue IO::WaitWritable if IO.select([], [port], [], 5) retry else raise IOError, "Timeout writing command to #{self.device_path}" end end # wait for expected confirmation signals got_eot = false got_soh = false loop do begin c = port.read_nonblock(1) case c when "\x04" if ! got_eot got_eot = true else raise IOError, "Got EOT reply twice from #{self.device_path}" end when "\x01" if got_eot if ! got_soh got_soh = true break else raise IOError, "Got SOH twice from #{self.device_path}" end else raise IOError, "Got SOH before EOT from #{self.device_path}" end end rescue IO::WaitReadable if IO.select([port], [], [], 3) retry else raise IOError, "Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}" end end end end self end
ruby
def send_command(command) SerialPort.open(self.device_path, 9600, 8, 1) do |port| # flush anything existing on the port port.flush flush_read_buffer(port) byte_string = command.to_bytes.pack('C*') begin while byte_string && byte_string.length != 0 count = port.write_nonblock(byte_string) byte_string = byte_string[count,-1] port.flush end rescue IO::WaitWritable if IO.select([], [port], [], 5) retry else raise IOError, "Timeout writing command to #{self.device_path}" end end # wait for expected confirmation signals got_eot = false got_soh = false loop do begin c = port.read_nonblock(1) case c when "\x04" if ! got_eot got_eot = true else raise IOError, "Got EOT reply twice from #{self.device_path}" end when "\x01" if got_eot if ! got_soh got_soh = true break else raise IOError, "Got SOH twice from #{self.device_path}" end else raise IOError, "Got SOH before EOT from #{self.device_path}" end end rescue IO::WaitReadable if IO.select([port], [], [], 3) retry else raise IOError, "Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}" end end end end self end
[ "def", "send_command", "(", "command", ")", "SerialPort", ".", "open", "(", "self", ".", "device_path", ",", "9600", ",", "8", ",", "1", ")", "do", "|", "port", "|", "# flush anything existing on the port", "port", ".", "flush", "flush_read_buffer", "(", "port", ")", "byte_string", "=", "command", ".", "to_bytes", ".", "pack", "(", "'C*'", ")", "begin", "while", "byte_string", "&&", "byte_string", ".", "length", "!=", "0", "count", "=", "port", ".", "write_nonblock", "(", "byte_string", ")", "byte_string", "=", "byte_string", "[", "count", ",", "-", "1", "]", "port", ".", "flush", "end", "rescue", "IO", "::", "WaitWritable", "if", "IO", ".", "select", "(", "[", "]", ",", "[", "port", "]", ",", "[", "]", ",", "5", ")", "retry", "else", "raise", "IOError", ",", "\"Timeout writing command to #{self.device_path}\"", "end", "end", "# wait for expected confirmation signals", "got_eot", "=", "false", "got_soh", "=", "false", "loop", "do", "begin", "c", "=", "port", ".", "read_nonblock", "(", "1", ")", "case", "c", "when", "\"\\x04\"", "if", "!", "got_eot", "got_eot", "=", "true", "else", "raise", "IOError", ",", "\"Got EOT reply twice from #{self.device_path}\"", "end", "when", "\"\\x01\"", "if", "got_eot", "if", "!", "got_soh", "got_soh", "=", "true", "break", "else", "raise", "IOError", ",", "\"Got SOH twice from #{self.device_path}\"", "end", "else", "raise", "IOError", ",", "\"Got SOH before EOT from #{self.device_path}\"", "end", "end", "rescue", "IO", "::", "WaitReadable", "if", "IO", ".", "select", "(", "[", "port", "]", ",", "[", "]", ",", "[", "]", ",", "3", ")", "retry", "else", "raise", "IOError", ",", "\"Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}\"", "end", "end", "end", "end", "self", "end" ]
Sends the specified Movingsign command to this sign's serial port @param [MovingsignApi::Command] command subclass to send @return [self]
[ "Sends", "the", "specified", "Movingsign", "command", "to", "this", "sign", "s", "serial", "port" ]
11c820edcb5f3a367b341257dae4f6249ae6d0a3
https://github.com/webmonarch/movingsign_api/blob/11c820edcb5f3a367b341257dae4f6249ae6d0a3/lib/movingsign_api/sign.rb#L70-L131
6,018
jns/Aims
lib/aims/wurtzite.rb
Aims.Wurtzite.get_bulk
def get_bulk # The lattice constant a = lattice_const c = 1.63299*a # sqrt(8/3)a # The atoms on a HCP as1 = Atom.new(0,0,0,'As') as2 = as1.displace(0.5*a, 0.33333*a, 0.5*c) ga1 = Atom.new(0.0, 0.0, c*0.386, 'Ga') ga2 = ga1.displace(0.5*a,0.33333*a, 0.5*c) # The lattice Vectors v1 = Vector[1.0, 0.0, 0.0]*a v2 = Vector[0.5, 0.5*sqrt(3), 0.0]*a v3 = Vector[0.0, 0.0, 1.0]*c # The unit cell wz = Geometry.new([as1,ga1,as2,ga2], [v1, v2, v3]) # wz.set_miller_indices(millerX, millerY, millerZ) return wz end
ruby
def get_bulk # The lattice constant a = lattice_const c = 1.63299*a # sqrt(8/3)a # The atoms on a HCP as1 = Atom.new(0,0,0,'As') as2 = as1.displace(0.5*a, 0.33333*a, 0.5*c) ga1 = Atom.new(0.0, 0.0, c*0.386, 'Ga') ga2 = ga1.displace(0.5*a,0.33333*a, 0.5*c) # The lattice Vectors v1 = Vector[1.0, 0.0, 0.0]*a v2 = Vector[0.5, 0.5*sqrt(3), 0.0]*a v3 = Vector[0.0, 0.0, 1.0]*c # The unit cell wz = Geometry.new([as1,ga1,as2,ga2], [v1, v2, v3]) # wz.set_miller_indices(millerX, millerY, millerZ) return wz end
[ "def", "get_bulk", "# The lattice constant", "a", "=", "lattice_const", "c", "=", "1.63299", "*", "a", "# sqrt(8/3)a", "# The atoms on a HCP", "as1", "=", "Atom", ".", "new", "(", "0", ",", "0", ",", "0", ",", "'As'", ")", "as2", "=", "as1", ".", "displace", "(", "0.5", "*", "a", ",", "0.33333", "*", "a", ",", "0.5", "*", "c", ")", "ga1", "=", "Atom", ".", "new", "(", "0.0", ",", "0.0", ",", "c", "0.386", ",", "'Ga'", ")", "ga2", "=", "ga1", ".", "displace", "(", "0.5", "*", "a", ",", "0.33333", "*", "a", ",", "0.5", "*", "c", ")", "# The lattice Vectors", "v1", "=", "Vector", "[", "1.0", ",", "0.0", ",", "0.0", "]", "*", "a", "v2", "=", "Vector", "[", "0.5", ",", "0.5", "*", "sqrt", "(", "3", ")", ",", "0.0", "]", "*", "a", "v3", "=", "Vector", "[", "0.0", ",", "0.0", ",", "1.0", "]", "*", "c", "# The unit cell", "wz", "=", "Geometry", ".", "new", "(", "[", "as1", ",", "ga1", ",", "as2", ",", "ga2", "]", ",", "[", "v1", ",", "v2", ",", "v3", "]", ")", "# wz.set_miller_indices(millerX, millerY, millerZ)", "return", "wz", "end" ]
Initialize the wurtzite Geometry cation and anion are the atomic species occupying the two different sub-lattices. lattice_const specifies the lattice constant
[ "Initialize", "the", "wurtzite", "Geometry", "cation", "and", "anion", "are", "the", "atomic", "species", "occupying", "the", "two", "different", "sub", "-", "lattices", ".", "lattice_const", "specifies", "the", "lattice", "constant" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/wurtzite.rb#L21-L43
6,019
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/job_messages_api.rb
TriglavClient.JobMessagesApi.fetch_job_messages
def fetch_job_messages(offset, job_id, opts = {}) data, _status_code, _headers = fetch_job_messages_with_http_info(offset, job_id, opts) return data end
ruby
def fetch_job_messages(offset, job_id, opts = {}) data, _status_code, _headers = fetch_job_messages_with_http_info(offset, job_id, opts) return data end
[ "def", "fetch_job_messages", "(", "offset", ",", "job_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "fetch_job_messages_with_http_info", "(", "offset", ",", "job_id", ",", "opts", ")", "return", "data", "end" ]
Fetch Job messages @param offset Offset (Greater than or equal to) ID for Messages to fetch from @param job_id Job ID @param [Hash] opts the optional parameters @option opts [Integer] :limit Number of limits @return [Array<JobMessageEachResponse>]
[ "Fetch", "Job", "messages" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/job_messages_api.rb#L41-L44
6,020
mrsimonfletcher/roroacms
app/controllers/roroacms/admin_controller.rb
Roroacms.AdminController.authorize_admin_access
def authorize_admin_access Setting.reload_settings if !check_controller_against_user(params[:controller].sub('roroacms/admin/', '')) && params[:controller] != 'roroacms/admin/dashboard' && params[:controller].include?('roroacms') redirect_to admin_path, flash: { error: I18n.t("controllers.admin.misc.authorize_admin_access_error") } end end
ruby
def authorize_admin_access Setting.reload_settings if !check_controller_against_user(params[:controller].sub('roroacms/admin/', '')) && params[:controller] != 'roroacms/admin/dashboard' && params[:controller].include?('roroacms') redirect_to admin_path, flash: { error: I18n.t("controllers.admin.misc.authorize_admin_access_error") } end end
[ "def", "authorize_admin_access", "Setting", ".", "reload_settings", "if", "!", "check_controller_against_user", "(", "params", "[", ":controller", "]", ".", "sub", "(", "'roroacms/admin/'", ",", "''", ")", ")", "&&", "params", "[", ":controller", "]", "!=", "'roroacms/admin/dashboard'", "&&", "params", "[", ":controller", "]", ".", "include?", "(", "'roroacms'", ")", "redirect_to", "admin_path", ",", "flash", ":", "{", "error", ":", "I18n", ".", "t", "(", "\"controllers.admin.misc.authorize_admin_access_error\"", ")", "}", "end", "end" ]
checks to see if the admin logged in has the necesary rights, if not it will redirect them with an error message
[ "checks", "to", "see", "if", "the", "admin", "logged", "in", "has", "the", "necesary", "rights", "if", "not", "it", "will", "redirect", "them", "with", "an", "error", "message" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin_controller.rb#L30-L35
6,021
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.wrap_java_property
def wrap_java_property(property) pd = property.property_descriptor if pd.property_type == Java::JavaLang::String.java_class then wrap_java_string_property(property) elsif pd.property_type == Java::JavaUtil::Date.java_class then wrap_java_date_property(property) end end
ruby
def wrap_java_property(property) pd = property.property_descriptor if pd.property_type == Java::JavaLang::String.java_class then wrap_java_string_property(property) elsif pd.property_type == Java::JavaUtil::Date.java_class then wrap_java_date_property(property) end end
[ "def", "wrap_java_property", "(", "property", ")", "pd", "=", "property", ".", "property_descriptor", "if", "pd", ".", "property_type", "==", "Java", "::", "JavaLang", "::", "String", ".", "java_class", "then", "wrap_java_string_property", "(", "property", ")", "elsif", "pd", ".", "property_type", "==", "Java", "::", "JavaUtil", "::", "Date", ".", "java_class", "then", "wrap_java_date_property", "(", "property", ")", "end", "end" ]
Adds a filter to the given property access methods if it is a String or Date.
[ "Adds", "a", "filter", "to", "the", "given", "property", "access", "methods", "if", "it", "is", "a", "String", "or", "Date", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L107-L114
6,022
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.wrap_java_string_property
def wrap_java_string_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute writer define_method(wa) do |value| stdval = Math.numeric?(value) ? value.to_s : value send(jwa, stdval) end logger.debug { "Filtered #{qp} #{wa} method with non-String -> String converter." } end
ruby
def wrap_java_string_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute writer define_method(wa) do |value| stdval = Math.numeric?(value) ? value.to_s : value send(jwa, stdval) end logger.debug { "Filtered #{qp} #{wa} method with non-String -> String converter." } end
[ "def", "wrap_java_string_property", "(", "property", ")", "ra", ",", "wa", "=", "property", ".", "accessors", "jra", ",", "jwa", "=", "property", ".", "java_accessors", "# filter the attribute writer", "define_method", "(", "wa", ")", "do", "|", "value", "|", "stdval", "=", "Math", ".", "numeric?", "(", "value", ")", "?", "value", ".", "to_s", ":", "value", "send", "(", "jwa", ",", "stdval", ")", "end", "logger", ".", "debug", "{", "\"Filtered #{qp} #{wa} method with non-String -> String converter.\"", "}", "end" ]
Adds a number -> string filter to the given String property Ruby access methods.
[ "Adds", "a", "number", "-", ">", "string", "filter", "to", "the", "given", "String", "property", "Ruby", "access", "methods", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L117-L126
6,023
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.wrap_java_date_property
def wrap_java_date_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute reader define_method(ra) do value = send(jra) Java::JavaUtil::Date === value ? value.to_ruby_date : value end # filter the attribute writer define_method(wa) do |value| value = Java::JavaUtil::Date.from_ruby_date(value) if ::Date === value send(jwa, value) end logger.debug { "Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter." } end
ruby
def wrap_java_date_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute reader define_method(ra) do value = send(jra) Java::JavaUtil::Date === value ? value.to_ruby_date : value end # filter the attribute writer define_method(wa) do |value| value = Java::JavaUtil::Date.from_ruby_date(value) if ::Date === value send(jwa, value) end logger.debug { "Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter." } end
[ "def", "wrap_java_date_property", "(", "property", ")", "ra", ",", "wa", "=", "property", ".", "accessors", "jra", ",", "jwa", "=", "property", ".", "java_accessors", "# filter the attribute reader", "define_method", "(", "ra", ")", "do", "value", "=", "send", "(", "jra", ")", "Java", "::", "JavaUtil", "::", "Date", "===", "value", "?", "value", ".", "to_ruby_date", ":", "value", "end", "# filter the attribute writer", "define_method", "(", "wa", ")", "do", "|", "value", "|", "value", "=", "Java", "::", "JavaUtil", "::", "Date", ".", "from_ruby_date", "(", "value", ")", "if", "::", "Date", "===", "value", "send", "(", "jwa", ",", "value", ")", "end", "logger", ".", "debug", "{", "\"Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter.\"", "}", "end" ]
Adds a Java-Ruby Date filter to the given Date property Ruby access methods. The reader returns a Ruby date. The writer sets a Java date.
[ "Adds", "a", "Java", "-", "Ruby", "Date", "filter", "to", "the", "given", "Date", "property", "Ruby", "access", "methods", ".", "The", "reader", "returns", "a", "Ruby", "date", ".", "The", "writer", "sets", "a", "Java", "date", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L130-L147
6,024
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.alias_property_accessors
def alias_property_accessors(property) # the Java reader and writer accessor method symbols jra, jwa = property.java_accessors # strip the Java reader and writer is/get/set prefix and make a symbol alias_method(property.reader, jra) alias_method(property.writer, jwa) end
ruby
def alias_property_accessors(property) # the Java reader and writer accessor method symbols jra, jwa = property.java_accessors # strip the Java reader and writer is/get/set prefix and make a symbol alias_method(property.reader, jra) alias_method(property.writer, jwa) end
[ "def", "alias_property_accessors", "(", "property", ")", "# the Java reader and writer accessor method symbols", "jra", ",", "jwa", "=", "property", ".", "java_accessors", "# strip the Java reader and writer is/get/set prefix and make a symbol", "alias_method", "(", "property", ".", "reader", ",", "jra", ")", "alias_method", "(", "property", ".", "writer", ",", "jwa", ")", "end" ]
Aliases the given Ruby property reader and writer to its underlying Java property reader and writer, resp. @param [Property] property the property to alias
[ "Aliases", "the", "given", "Ruby", "property", "reader", "and", "writer", "to", "its", "underlying", "Java", "property", "reader", "and", "writer", "resp", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L152-L158
6,025
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.add_java_property
def add_java_property(pd) # make the attribute metadata prop = create_java_property(pd) add_property(prop) # the property name is an alias for the standard attribute pa = prop.attribute # the Java property name as an attribute symbol ja = pd.name.to_sym delegate_to_property(ja, prop) unless prop.reader == ja prop end
ruby
def add_java_property(pd) # make the attribute metadata prop = create_java_property(pd) add_property(prop) # the property name is an alias for the standard attribute pa = prop.attribute # the Java property name as an attribute symbol ja = pd.name.to_sym delegate_to_property(ja, prop) unless prop.reader == ja prop end
[ "def", "add_java_property", "(", "pd", ")", "# make the attribute metadata", "prop", "=", "create_java_property", "(", "pd", ")", "add_property", "(", "prop", ")", "# the property name is an alias for the standard attribute", "pa", "=", "prop", ".", "attribute", "# the Java property name as an attribute symbol", "ja", "=", "pd", ".", "name", ".", "to_sym", "delegate_to_property", "(", "ja", ",", "prop", ")", "unless", "prop", ".", "reader", "==", "ja", "prop", "end" ]
Makes a standard attribute for the given property descriptor. Adds a camelized Java-like alias to the standard attribute. @param (see #define_java_property) @return [Property] the new property
[ "Makes", "a", "standard", "attribute", "for", "the", "given", "property", "descriptor", ".", "Adds", "a", "camelized", "Java", "-", "like", "alias", "to", "the", "standard", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L165-L175
6,026
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.delegate_to_property
def delegate_to_property(aliaz, property) ra, wa = property.accessors if aliaz == ra then raise MetadataError.new("Cannot delegate #{self} #{aliaz} to itself.") end define_method(aliaz) { send(ra) } define_method("#{aliaz}=".to_sym) { |value| send(wa, value) } register_property_alias(aliaz, property.attribute) end
ruby
def delegate_to_property(aliaz, property) ra, wa = property.accessors if aliaz == ra then raise MetadataError.new("Cannot delegate #{self} #{aliaz} to itself.") end define_method(aliaz) { send(ra) } define_method("#{aliaz}=".to_sym) { |value| send(wa, value) } register_property_alias(aliaz, property.attribute) end
[ "def", "delegate_to_property", "(", "aliaz", ",", "property", ")", "ra", ",", "wa", "=", "property", ".", "accessors", "if", "aliaz", "==", "ra", "then", "raise", "MetadataError", ".", "new", "(", "\"Cannot delegate #{self} #{aliaz} to itself.\"", ")", "end", "define_method", "(", "aliaz", ")", "{", "send", "(", "ra", ")", "}", "define_method", "(", "\"#{aliaz}=\"", ".", "to_sym", ")", "{", "|", "value", "|", "send", "(", "wa", ",", "value", ")", "}", "register_property_alias", "(", "aliaz", ",", "property", ".", "attribute", ")", "end" ]
Defines methods _aliaz_ and _aliaz=_ which calls the standard _attribute_ and _attribute=_ accessor methods, resp. Calling rather than aliasing the attribute accessor allows the aliaz accessor to reflect a change to the attribute accessor.
[ "Defines", "methods", "_aliaz_", "and", "_aliaz", "=", "_", "which", "calls", "the", "standard", "_attribute_", "and", "_attribute", "=", "_", "accessor", "methods", "resp", ".", "Calling", "rather", "than", "aliasing", "the", "attribute", "accessor", "allows", "the", "aliaz", "accessor", "to", "reflect", "a", "change", "to", "the", "attribute", "accessor", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L187-L193
6,027
burtcorp/tara
lib/tara/archive.rb
Tara.Archive.create
def create Dir.mktmpdir do |tmp_dir| project_dir = Pathname.new(@config[:app_dir]) package_dir = Pathname.new(tmp_dir) build_dir = Pathname.new(@config[:build_dir]) copy_source(project_dir, package_dir) copy_executables(project_dir, package_dir) create_gem_shims(package_dir) install_dependencies(package_dir, fetcher) Dir.chdir(tmp_dir) do create_archive(build_dir) end File.join(build_dir, @config[:archive_name]) end end
ruby
def create Dir.mktmpdir do |tmp_dir| project_dir = Pathname.new(@config[:app_dir]) package_dir = Pathname.new(tmp_dir) build_dir = Pathname.new(@config[:build_dir]) copy_source(project_dir, package_dir) copy_executables(project_dir, package_dir) create_gem_shims(package_dir) install_dependencies(package_dir, fetcher) Dir.chdir(tmp_dir) do create_archive(build_dir) end File.join(build_dir, @config[:archive_name]) end end
[ "def", "create", "Dir", ".", "mktmpdir", "do", "|", "tmp_dir", "|", "project_dir", "=", "Pathname", ".", "new", "(", "@config", "[", ":app_dir", "]", ")", "package_dir", "=", "Pathname", ".", "new", "(", "tmp_dir", ")", "build_dir", "=", "Pathname", ".", "new", "(", "@config", "[", ":build_dir", "]", ")", "copy_source", "(", "project_dir", ",", "package_dir", ")", "copy_executables", "(", "project_dir", ",", "package_dir", ")", "create_gem_shims", "(", "package_dir", ")", "install_dependencies", "(", "package_dir", ",", "fetcher", ")", "Dir", ".", "chdir", "(", "tmp_dir", ")", "do", "create_archive", "(", "build_dir", ")", "end", "File", ".", "join", "(", "build_dir", ",", "@config", "[", ":archive_name", "]", ")", "end", "end" ]
Create an archive using the instance's configuration. @return [String] Path to the archive
[ "Create", "an", "archive", "using", "the", "instance", "s", "configuration", "." ]
d38a07626da8842bd06a0748d97eacd7902033ee
https://github.com/burtcorp/tara/blob/d38a07626da8842bd06a0748d97eacd7902033ee/lib/tara/archive.rb#L88-L102
6,028
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.identity_parts
def identity_parts(id) @brokers.each do |b| return [b.host, b.port, b.index, priority(b.identity)] if b.identity == id || b.alias == id end [nil, nil, nil, nil] end
ruby
def identity_parts(id) @brokers.each do |b| return [b.host, b.port, b.index, priority(b.identity)] if b.identity == id || b.alias == id end [nil, nil, nil, nil] end
[ "def", "identity_parts", "(", "id", ")", "@brokers", ".", "each", "do", "|", "b", "|", "return", "[", "b", ".", "host", ",", "b", ".", "port", ",", "b", ".", "index", ",", "priority", "(", "b", ".", "identity", ")", "]", "if", "b", ".", "identity", "==", "id", "||", "b", ".", "alias", "==", "id", "end", "[", "nil", ",", "nil", ",", "nil", ",", "nil", "]", "end" ]
Break broker serialized identity down into individual parts if exists === Parameters id(Integer|String):: Broker alias or serialized identity === Return (Array):: Host, port, index, and priority, or all nil if broker not found
[ "Break", "broker", "serialized", "identity", "down", "into", "individual", "parts", "if", "exists" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L281-L286
6,029
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.get
def get(id) @brokers.each { |b| return b.identity if b.identity == id || b.alias == id } nil end
ruby
def get(id) @brokers.each { |b| return b.identity if b.identity == id || b.alias == id } nil end
[ "def", "get", "(", "id", ")", "@brokers", ".", "each", "{", "|", "b", "|", "return", "b", ".", "identity", "if", "b", ".", "identity", "==", "id", "||", "b", ".", "alias", "==", "id", "}", "nil", "end" ]
Get broker serialized identity if client exists === Parameters id(Integer|String):: Broker alias or serialized identity === Return (String|nil):: Broker serialized identity if client found, otherwise nil
[ "Get", "broker", "serialized", "identity", "if", "client", "exists" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L333-L336
6,030
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connected
def connected @brokers.inject([]) { |c, b| if b.connected? then c << b.identity else c end } end
ruby
def connected @brokers.inject([]) { |c, b| if b.connected? then c << b.identity else c end } end
[ "def", "connected", "@brokers", ".", "inject", "(", "[", "]", ")", "{", "|", "c", ",", "b", "|", "if", "b", ".", "connected?", "then", "c", "<<", "b", ".", "identity", "else", "c", "end", "}", "end" ]
Get serialized identity of connected brokers === Return (Array):: Serialized identity of connected brokers
[ "Get", "serialized", "identity", "of", "connected", "brokers" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L353-L355
6,031
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.failed
def failed @brokers.inject([]) { |c, b| b.failed? ? c << b.identity : c } end
ruby
def failed @brokers.inject([]) { |c, b| b.failed? ? c << b.identity : c } end
[ "def", "failed", "@brokers", ".", "inject", "(", "[", "]", ")", "{", "|", "c", ",", "b", "|", "b", ".", "failed?", "?", "c", "<<", "b", ".", "identity", ":", "c", "}", "end" ]
Get serialized identity of failed broker clients, i.e., ones that were never successfully connected, not ones that are just disconnected === Return (Array):: Serialized identity of failed broker clients
[ "Get", "serialized", "identity", "of", "failed", "broker", "clients", "i", ".", "e", ".", "ones", "that", "were", "never", "successfully", "connected", "not", "ones", "that", "are", "just", "disconnected" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L386-L388
6,032
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connect
def connect(host, port, index, priority = nil, force = false, &blk) identity = self.class.identity(host, port) existing = @brokers_hash[identity] if existing && existing.usable? && !force logger.info("Ignored request to reconnect #{identity} because already #{existing.status.to_s}") false else old_identity = identity @brokers.each do |b| if index == b.index # Changing host and/or port of existing broker client old_identity = b.identity break end end unless existing address = {:host => host, :port => port, :index => index} broker = BrokerClient.new(identity, address, @serializer, @exception_stats, @non_delivery_stats, @options, existing) p = priority(old_identity) if priority && priority < p @brokers.insert(priority, broker) elsif priority && priority > p logger.info("Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list") @brokers.insert(p, broker) else @brokers[p].close if @brokers[p] @brokers[p] = broker end @brokers_hash[identity] = broker yield broker.identity if block_given? true end end
ruby
def connect(host, port, index, priority = nil, force = false, &blk) identity = self.class.identity(host, port) existing = @brokers_hash[identity] if existing && existing.usable? && !force logger.info("Ignored request to reconnect #{identity} because already #{existing.status.to_s}") false else old_identity = identity @brokers.each do |b| if index == b.index # Changing host and/or port of existing broker client old_identity = b.identity break end end unless existing address = {:host => host, :port => port, :index => index} broker = BrokerClient.new(identity, address, @serializer, @exception_stats, @non_delivery_stats, @options, existing) p = priority(old_identity) if priority && priority < p @brokers.insert(priority, broker) elsif priority && priority > p logger.info("Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list") @brokers.insert(p, broker) else @brokers[p].close if @brokers[p] @brokers[p] = broker end @brokers_hash[identity] = broker yield broker.identity if block_given? true end end
[ "def", "connect", "(", "host", ",", "port", ",", "index", ",", "priority", "=", "nil", ",", "force", "=", "false", ",", "&", "blk", ")", "identity", "=", "self", ".", "class", ".", "identity", "(", "host", ",", "port", ")", "existing", "=", "@brokers_hash", "[", "identity", "]", "if", "existing", "&&", "existing", ".", "usable?", "&&", "!", "force", "logger", ".", "info", "(", "\"Ignored request to reconnect #{identity} because already #{existing.status.to_s}\"", ")", "false", "else", "old_identity", "=", "identity", "@brokers", ".", "each", "do", "|", "b", "|", "if", "index", "==", "b", ".", "index", "# Changing host and/or port of existing broker client", "old_identity", "=", "b", ".", "identity", "break", "end", "end", "unless", "existing", "address", "=", "{", ":host", "=>", "host", ",", ":port", "=>", "port", ",", ":index", "=>", "index", "}", "broker", "=", "BrokerClient", ".", "new", "(", "identity", ",", "address", ",", "@serializer", ",", "@exception_stats", ",", "@non_delivery_stats", ",", "@options", ",", "existing", ")", "p", "=", "priority", "(", "old_identity", ")", "if", "priority", "&&", "priority", "<", "p", "@brokers", ".", "insert", "(", "priority", ",", "broker", ")", "elsif", "priority", "&&", "priority", ">", "p", "logger", ".", "info", "(", "\"Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list\"", ")", "@brokers", ".", "insert", "(", "p", ",", "broker", ")", "else", "@brokers", "[", "p", "]", ".", "close", "if", "@brokers", "[", "p", "]", "@brokers", "[", "p", "]", "=", "broker", "end", "@brokers_hash", "[", "identity", "]", "=", "broker", "yield", "broker", ".", "identity", "if", "block_given?", "true", "end", "end" ]
Make new connection to broker at specified address unless already connected or currently connecting === Parameters host{String):: IP host name or address for individual broker port(Integer):: TCP port number for individual broker index(Integer):: Unique index for broker within set for use in forming alias priority(Integer|nil):: Priority position of this broker in set for use by this agent with nil or a value that would leave a gap in the list meaning add to end of list force(Boolean):: Reconnect even if already connected === Block Optional block with following parameters to be called after initiating the connection unless already connected to this broker: identity(String):: Broker serialized identity === Return (Boolean):: true if connected, false if no connect attempt made === Raise Exception:: If host and port do not match an existing broker but index does
[ "Make", "new", "connection", "to", "broker", "at", "specified", "address", "unless", "already", "connected", "or", "currently", "connecting" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L423-L455
6,033
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.subscribe
def subscribe(queue, exchange = nil, options = {}, &blk) identities = [] brokers = options.delete(:brokers) each(:usable, brokers) { |b| identities << b.identity if b.subscribe(queue, exchange, options, &blk) } logger.info("Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} " + "on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} " + "from usable #{usable.inspect}") if identities.empty? identities end
ruby
def subscribe(queue, exchange = nil, options = {}, &blk) identities = [] brokers = options.delete(:brokers) each(:usable, brokers) { |b| identities << b.identity if b.subscribe(queue, exchange, options, &blk) } logger.info("Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} " + "on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} " + "from usable #{usable.inspect}") if identities.empty? identities end
[ "def", "subscribe", "(", "queue", ",", "exchange", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "identities", "=", "[", "]", "brokers", "=", "options", ".", "delete", "(", ":brokers", ")", "each", "(", ":usable", ",", "brokers", ")", "{", "|", "b", "|", "identities", "<<", "b", ".", "identity", "if", "b", ".", "subscribe", "(", "queue", ",", "exchange", ",", "options", ",", "blk", ")", "}", "logger", ".", "info", "(", "\"Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} \"", "+", "\"on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} \"", "+", "\"from usable #{usable.inspect}\"", ")", "if", "identities", ".", "empty?", "identities", "end" ]
Subscribe an AMQP queue to an AMQP exchange on all broker clients that are connected or still connecting Allow connecting here because subscribing may happen before all have confirmed connected Do not wait for confirmation from broker client that subscription is complete When a message is received, acknowledge, unserialize, and log it as specified If the message is unserialized and it is not of the right type, it is dropped after logging a warning === Parameters queue(Hash):: AMQP queue being subscribed with keys :name and :options, which are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this queue on the broker to cause its creation; for use when client does not have permission to create or knows the queue already exists and wants to avoid declare overhead exchange(Hash|nil):: AMQP exchange to subscribe to with keys :type, :name, and :options, nil means use empty exchange by directly subscribing to queue; the :options are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this exchange on the broker to cause its creation; for use when client does not have create permission or knows the exchange already exists and wants to avoid declare overhead options(Hash):: Subscribe options: :ack(Boolean):: Whether client takes responsibility for explicitly acknowledging each message received, defaults to implicit acknowledgement in AMQP as part of message receipt :no_unserialize(Boolean):: Do not unserialize message, this is an escape for special situations like enrollment, also implicitly disables receive filtering and logging; this option is implicitly invoked if initialize without a serializer (packet class)(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info, only packet classes specified are accepted, others are not processed but are logged with error :category(String):: Packet category description to be used in error messages :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable receive logging unless debug level :exchange2(Hash):: Additional exchange to which same queue is to be bound :brokers(Array):: Identity of brokers for which to subscribe, defaults to all usable if nil or empty === Block Block with following parameters to be called each time exchange matches a message to the queue: identity(String):: Serialized identity of broker delivering the message message(Packet|String):: Message received, which is unserialized unless :no_unserialize was specified header(AMQP::Protocol::Header):: Message header (optional block parameter) === Return identities(Array):: Identity of brokers where successfully subscribed
[ "Subscribe", "an", "AMQP", "queue", "to", "an", "AMQP", "exchange", "on", "all", "broker", "clients", "that", "are", "connected", "or", "still", "connecting", "Allow", "connecting", "here", "because", "subscribing", "may", "happen", "before", "all", "have", "confirmed", "connected", "Do", "not", "wait", "for", "confirmation", "from", "broker", "client", "that", "subscription", "is", "complete", "When", "a", "message", "is", "received", "acknowledge", "unserialize", "and", "log", "it", "as", "specified", "If", "the", "message", "is", "unserialized", "and", "it", "is", "not", "of", "the", "right", "type", "it", "is", "dropped", "after", "logging", "a", "warning" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L497-L505
6,034
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.unsubscribe
def unsubscribe(queue_names, timeout = nil, &blk) count = each(:usable).inject(0) do |c, b| c + b.queues.inject(0) { |c, q| c + (queue_names.include?(q.name) ? 1 : 0) } end if count == 0 blk.call if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call if blk } each(:usable) { |b| b.unsubscribe(queue_names) { handler.completed_one } } end true end
ruby
def unsubscribe(queue_names, timeout = nil, &blk) count = each(:usable).inject(0) do |c, b| c + b.queues.inject(0) { |c, q| c + (queue_names.include?(q.name) ? 1 : 0) } end if count == 0 blk.call if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call if blk } each(:usable) { |b| b.unsubscribe(queue_names) { handler.completed_one } } end true end
[ "def", "unsubscribe", "(", "queue_names", ",", "timeout", "=", "nil", ",", "&", "blk", ")", "count", "=", "each", "(", ":usable", ")", ".", "inject", "(", "0", ")", "do", "|", "c", ",", "b", "|", "c", "+", "b", ".", "queues", ".", "inject", "(", "0", ")", "{", "|", "c", ",", "q", "|", "c", "+", "(", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "?", "1", ":", "0", ")", "}", "end", "if", "count", "==", "0", "blk", ".", "call", "if", "blk", "else", "handler", "=", "CountedDeferrable", ".", "new", "(", "count", ",", "timeout", ")", "handler", ".", "callback", "{", "blk", ".", "call", "if", "blk", "}", "each", "(", ":usable", ")", "{", "|", "b", "|", "b", ".", "unsubscribe", "(", "queue_names", ")", "{", "handler", ".", "completed_one", "}", "}", "end", "true", "end" ]
Unsubscribe from the specified queues on usable broker clients Silently ignore unknown queues === Parameters queue_names(Array):: Names of queues previously subscribed to timeout(Integer):: Number of seconds to wait for all confirmations, defaults to no timeout === Block Optional block with no parameters to be called after all queues are unsubscribed === Return true:: Always return true
[ "Unsubscribe", "from", "the", "specified", "queues", "on", "usable", "broker", "clients", "Silently", "ignore", "unknown", "queues" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L519-L531
6,035
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.queue_status
def queue_status(queue_names, timeout = nil, &blk) count = 0 status = {} each(:connected) { |b| b.queues.each { |q| count += 1 if queue_names.include?(q.name) } } if count == 0 blk.call(status) if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call(status) if blk } each(:connected) do |b| if b.queue_status(queue_names) do |name, messages, consumers| (status[name] ||= {})[b.identity] = {:messages => messages, :consumers => consumers} handler.completed_one end else b.queues.each { |q| handler.completed_one if queue_names.include?(q.name) } end end end true end
ruby
def queue_status(queue_names, timeout = nil, &blk) count = 0 status = {} each(:connected) { |b| b.queues.each { |q| count += 1 if queue_names.include?(q.name) } } if count == 0 blk.call(status) if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call(status) if blk } each(:connected) do |b| if b.queue_status(queue_names) do |name, messages, consumers| (status[name] ||= {})[b.identity] = {:messages => messages, :consumers => consumers} handler.completed_one end else b.queues.each { |q| handler.completed_one if queue_names.include?(q.name) } end end end true end
[ "def", "queue_status", "(", "queue_names", ",", "timeout", "=", "nil", ",", "&", "blk", ")", "count", "=", "0", "status", "=", "{", "}", "each", "(", ":connected", ")", "{", "|", "b", "|", "b", ".", "queues", ".", "each", "{", "|", "q", "|", "count", "+=", "1", "if", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "}", "}", "if", "count", "==", "0", "blk", ".", "call", "(", "status", ")", "if", "blk", "else", "handler", "=", "CountedDeferrable", ".", "new", "(", "count", ",", "timeout", ")", "handler", ".", "callback", "{", "blk", ".", "call", "(", "status", ")", "if", "blk", "}", "each", "(", ":connected", ")", "do", "|", "b", "|", "if", "b", ".", "queue_status", "(", "queue_names", ")", "do", "|", "name", ",", "messages", ",", "consumers", "|", "(", "status", "[", "name", "]", "||=", "{", "}", ")", "[", "b", ".", "identity", "]", "=", "{", ":messages", "=>", "messages", ",", ":consumers", "=>", "consumers", "}", "handler", ".", "completed_one", "end", "else", "b", ".", "queues", ".", "each", "{", "|", "q", "|", "handler", ".", "completed_one", "if", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "}", "end", "end", "end", "true", "end" ]
Check status of specified queues for connected brokers Silently ignore unknown queues If a queue whose status is being checked does not exist, the associated broker connection will fail and be unusable === Parameters queue_names(Array):: Names of queues previously subscribed to that are to be checked timeout(Integer):: Number of seconds to wait for all status checks, defaults to no timeout === Block Optional block to be called after all queue statuses are obtained with hash parameter containing statuses with queue name as key and value that is a hash with broker identity as key and hash of :messages and :consumers as value; the :messages and :consumers values are nil if there is a failure retrieving them for the given queue === Return true:: Always return true
[ "Check", "status", "of", "specified", "queues", "for", "connected", "brokers", "Silently", "ignore", "unknown", "queues", "If", "a", "queue", "whose", "status", "is", "being", "checked", "does", "not", "exist", "the", "associated", "broker", "connection", "will", "fail", "and", "be", "unusable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L569-L589
6,036
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.publish
def publish(exchange, packet, options = {}) identities = [] no_serialize = options[:no_serialize] || @serializer.nil? message = if no_serialize then packet else @serializer.dump(packet) end brokers = use(options) brokers.each do |b| if b.publish(exchange, packet, message, options.merge(:no_serialize => no_serialize)) identities << b.identity if options[:mandatory] && !no_serialize context = Context.new(packet, options, brokers.map { |b| b.identity }) @published.store(message, context) end break unless options[:fanout] end end if identities.empty? selected = "selected " if options[:brokers] list = aliases(brokers.map { |b| b.identity }).join(", ") raise NoConnectedBrokers, "None of #{selected}brokers [#{list}] are usable for publishing" end identities end
ruby
def publish(exchange, packet, options = {}) identities = [] no_serialize = options[:no_serialize] || @serializer.nil? message = if no_serialize then packet else @serializer.dump(packet) end brokers = use(options) brokers.each do |b| if b.publish(exchange, packet, message, options.merge(:no_serialize => no_serialize)) identities << b.identity if options[:mandatory] && !no_serialize context = Context.new(packet, options, brokers.map { |b| b.identity }) @published.store(message, context) end break unless options[:fanout] end end if identities.empty? selected = "selected " if options[:brokers] list = aliases(brokers.map { |b| b.identity }).join(", ") raise NoConnectedBrokers, "None of #{selected}brokers [#{list}] are usable for publishing" end identities end
[ "def", "publish", "(", "exchange", ",", "packet", ",", "options", "=", "{", "}", ")", "identities", "=", "[", "]", "no_serialize", "=", "options", "[", ":no_serialize", "]", "||", "@serializer", ".", "nil?", "message", "=", "if", "no_serialize", "then", "packet", "else", "@serializer", ".", "dump", "(", "packet", ")", "end", "brokers", "=", "use", "(", "options", ")", "brokers", ".", "each", "do", "|", "b", "|", "if", "b", ".", "publish", "(", "exchange", ",", "packet", ",", "message", ",", "options", ".", "merge", "(", ":no_serialize", "=>", "no_serialize", ")", ")", "identities", "<<", "b", ".", "identity", "if", "options", "[", ":mandatory", "]", "&&", "!", "no_serialize", "context", "=", "Context", ".", "new", "(", "packet", ",", "options", ",", "brokers", ".", "map", "{", "|", "b", "|", "b", ".", "identity", "}", ")", "@published", ".", "store", "(", "message", ",", "context", ")", "end", "break", "unless", "options", "[", ":fanout", "]", "end", "end", "if", "identities", ".", "empty?", "selected", "=", "\"selected \"", "if", "options", "[", ":brokers", "]", "list", "=", "aliases", "(", "brokers", ".", "map", "{", "|", "b", "|", "b", ".", "identity", "}", ")", ".", "join", "(", "\", \"", ")", "raise", "NoConnectedBrokers", ",", "\"None of #{selected}brokers [#{list}] are usable for publishing\"", "end", "identities", "end" ]
Publish message to AMQP exchange of first connected broker === Parameters exchange(Hash):: AMQP exchange to subscribe to with keys :type, :name, and :options, which are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this exchange or queue on the broker to cause its creation; for use when client does not have create permission or knows the object already exists and wants to avoid declare overhead :declare(Boolean):: Whether to delete this exchange or queue from the AMQP cache to force it to be declared on the broker and thus be created if it does not exist packet(Packet):: Message to serialize and publish options(Hash):: Publish options -- standard AMQP ones plus :mandatory(Boolean):: Return message if the exchange does not have any associated queues or if all the associated queues do not have any consumers :immediate(Boolean):: Return message for the same reasons as :mandatory plus if all of the queues associated with the exchange are not immediately ready to consume the message :fanout(Boolean):: true means publish to all connected brokers :brokers(Array):: Identity of brokers selected for use, defaults to all brokers if nil or empty :order(Symbol):: Broker selection order: :random or :priority, defaults to @select if :brokers is nil, otherwise defaults to :priority :no_serialize(Boolean):: Do not serialize packet because it is already serialized, this is an escape for special situations like enrollment, also implicitly disables publish logging; this option is implicitly invoked if initialize without a serializer :log_filter(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable publish logging unless debug level === Return identities(Array):: Identity of brokers where packet was successfully published === Raise NoConnectedBrokers:: If cannot find a connected broker
[ "Publish", "message", "to", "AMQP", "exchange", "of", "first", "connected", "broker" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L624-L645
6,037
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.delete
def delete(name, options = {}) identities = [] u = usable brokers = options.delete(:brokers) ((brokers || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete(name, options) } identities end
ruby
def delete(name, options = {}) identities = [] u = usable brokers = options.delete(:brokers) ((brokers || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete(name, options) } identities end
[ "def", "delete", "(", "name", ",", "options", "=", "{", "}", ")", "identities", "=", "[", "]", "u", "=", "usable", "brokers", "=", "options", ".", "delete", "(", ":brokers", ")", "(", "(", "brokers", "||", "u", ")", "&", "u", ")", ".", "each", "{", "|", "i", "|", "identities", "<<", "i", "if", "(", "b", "=", "@brokers_hash", "[", "i", "]", ")", "&&", "b", ".", "delete", "(", "name", ",", "options", ")", "}", "identities", "end" ]
Delete queue in all usable brokers or all selected brokers that are usable === Parameters name(String):: Queue name options(Hash):: Queue declare options plus :brokers(Array):: Identity of brokers in which queue is to be deleted === Return identities(Array):: Identity of brokers where queue was deleted
[ "Delete", "queue", "in", "all", "usable", "brokers", "or", "all", "selected", "brokers", "that", "are", "usable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L677-L683
6,038
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.delete_amqp_resources
def delete_amqp_resources(name, options = {}) identities = [] u = usable ((options[:brokers] || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete_amqp_resources(:queue, name) } identities end
ruby
def delete_amqp_resources(name, options = {}) identities = [] u = usable ((options[:brokers] || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete_amqp_resources(:queue, name) } identities end
[ "def", "delete_amqp_resources", "(", "name", ",", "options", "=", "{", "}", ")", "identities", "=", "[", "]", "u", "=", "usable", "(", "(", "options", "[", ":brokers", "]", "||", "u", ")", "&", "u", ")", ".", "each", "{", "|", "i", "|", "identities", "<<", "i", "if", "(", "b", "=", "@brokers_hash", "[", "i", "]", ")", "&&", "b", ".", "delete_amqp_resources", "(", ":queue", ",", "name", ")", "}", "identities", "end" ]
Delete queue resources from AMQP in all usable brokers === Parameters name(String):: Queue name options(Hash):: Queue declare options plus :brokers(Array):: Identity of brokers in which queue is to be deleted === Return identities(Array):: Identity of brokers where queue was deleted
[ "Delete", "queue", "resources", "from", "AMQP", "in", "all", "usable", "brokers" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L694-L699
6,039
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.remove
def remove(host, port, &blk) identity = self.class.identity(host, port) if broker = @brokers_hash[identity] logger.info("Removing #{identity}, alias #{broker.alias} from broker list") broker.close(propagate = true, normal = true, log = false) @brokers_hash.delete(identity) @brokers.reject! { |b| b.identity == identity } yield identity if block_given? else logger.info("Ignored request to remove #{identity} from broker list because unknown") identity = nil end identity end
ruby
def remove(host, port, &blk) identity = self.class.identity(host, port) if broker = @brokers_hash[identity] logger.info("Removing #{identity}, alias #{broker.alias} from broker list") broker.close(propagate = true, normal = true, log = false) @brokers_hash.delete(identity) @brokers.reject! { |b| b.identity == identity } yield identity if block_given? else logger.info("Ignored request to remove #{identity} from broker list because unknown") identity = nil end identity end
[ "def", "remove", "(", "host", ",", "port", ",", "&", "blk", ")", "identity", "=", "self", ".", "class", ".", "identity", "(", "host", ",", "port", ")", "if", "broker", "=", "@brokers_hash", "[", "identity", "]", "logger", ".", "info", "(", "\"Removing #{identity}, alias #{broker.alias} from broker list\"", ")", "broker", ".", "close", "(", "propagate", "=", "true", ",", "normal", "=", "true", ",", "log", "=", "false", ")", "@brokers_hash", ".", "delete", "(", "identity", ")", "@brokers", ".", "reject!", "{", "|", "b", "|", "b", ".", "identity", "==", "identity", "}", "yield", "identity", "if", "block_given?", "else", "logger", ".", "info", "(", "\"Ignored request to remove #{identity} from broker list because unknown\"", ")", "identity", "=", "nil", "end", "identity", "end" ]
Remove a broker client from the configuration Invoke connection status callbacks only if connection is not already disabled There is no check whether this is the last usable broker client === Parameters host{String):: IP host name or address for individual broker port(Integer):: TCP port number for individual broker === Block Optional block with following parameters to be called after removing the connection unless broker is not configured identity(String):: Broker serialized identity === Return identity(String|nil):: Serialized identity of broker removed, or nil if unknown
[ "Remove", "a", "broker", "client", "from", "the", "configuration", "Invoke", "connection", "status", "callbacks", "only", "if", "connection", "is", "not", "already", "disabled", "There", "is", "no", "check", "whether", "this", "is", "the", "last", "usable", "broker", "client" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L716-L729
6,040
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.declare_unusable
def declare_unusable(identities) identities.each do |id| broker = @brokers_hash[id] raise Exception, "Cannot mark unknown broker #{id} unusable" unless broker broker.close(propagate = true, normal = false, log = false) end end
ruby
def declare_unusable(identities) identities.each do |id| broker = @brokers_hash[id] raise Exception, "Cannot mark unknown broker #{id} unusable" unless broker broker.close(propagate = true, normal = false, log = false) end end
[ "def", "declare_unusable", "(", "identities", ")", "identities", ".", "each", "do", "|", "id", "|", "broker", "=", "@brokers_hash", "[", "id", "]", "raise", "Exception", ",", "\"Cannot mark unknown broker #{id} unusable\"", "unless", "broker", "broker", ".", "close", "(", "propagate", "=", "true", ",", "normal", "=", "false", ",", "log", "=", "false", ")", "end", "end" ]
Declare a broker client as unusable === Parameters identities(Array):: Identity of brokers === Return true:: Always return true === Raises Exception:: If identified broker is unknown
[ "Declare", "a", "broker", "client", "as", "unusable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L741-L747
6,041
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.close
def close(&blk) if @closed blk.call if blk else @closed = true @connection_status = {} handler = CountedDeferrable.new(@brokers.size) handler.callback { blk.call if blk } @brokers.each do |b| begin b.close(propagate = false) { handler.completed_one } rescue StandardError => e handler.completed_one logger.exception("Failed to close broker #{b.alias}", e, :trace) @exception_stats.track("close", e) end end end true end
ruby
def close(&blk) if @closed blk.call if blk else @closed = true @connection_status = {} handler = CountedDeferrable.new(@brokers.size) handler.callback { blk.call if blk } @brokers.each do |b| begin b.close(propagate = false) { handler.completed_one } rescue StandardError => e handler.completed_one logger.exception("Failed to close broker #{b.alias}", e, :trace) @exception_stats.track("close", e) end end end true end
[ "def", "close", "(", "&", "blk", ")", "if", "@closed", "blk", ".", "call", "if", "blk", "else", "@closed", "=", "true", "@connection_status", "=", "{", "}", "handler", "=", "CountedDeferrable", ".", "new", "(", "@brokers", ".", "size", ")", "handler", ".", "callback", "{", "blk", ".", "call", "if", "blk", "}", "@brokers", ".", "each", "do", "|", "b", "|", "begin", "b", ".", "close", "(", "propagate", "=", "false", ")", "{", "handler", ".", "completed_one", "}", "rescue", "StandardError", "=>", "e", "handler", ".", "completed_one", "logger", ".", "exception", "(", "\"Failed to close broker #{b.alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"close\"", ",", "e", ")", "end", "end", "end", "true", "end" ]
Close all broker client connections === Block Optional block with no parameters to be called after all connections are closed === Return true:: Always return true
[ "Close", "all", "broker", "client", "connections" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L756-L775
6,042
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.close_one
def close_one(identity, propagate = true, &blk) broker = @brokers_hash[identity] raise Exception, "Cannot close unknown broker #{identity}" unless broker broker.close(propagate, &blk) true end
ruby
def close_one(identity, propagate = true, &blk) broker = @brokers_hash[identity] raise Exception, "Cannot close unknown broker #{identity}" unless broker broker.close(propagate, &blk) true end
[ "def", "close_one", "(", "identity", ",", "propagate", "=", "true", ",", "&", "blk", ")", "broker", "=", "@brokers_hash", "[", "identity", "]", "raise", "Exception", ",", "\"Cannot close unknown broker #{identity}\"", "unless", "broker", "broker", ".", "close", "(", "propagate", ",", "blk", ")", "true", "end" ]
Close an individual broker client connection === Parameters identity(String):: Broker serialized identity propagate(Boolean):: Whether to propagate connection status updates === Block Optional block with no parameters to be called after connection closed === Return true:: Always return true === Raise Exception:: If broker unknown
[ "Close", "an", "individual", "broker", "client", "connection" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L791-L796
6,043
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connection_status
def connection_status(options = {}, &callback) id = generate_id @connection_status[id] = {:boundary => options[:boundary], :brokers => options[:brokers], :callback => callback} if timeout = options[:one_off] @connection_status[id][:timer] = EM::Timer.new(timeout) do if @connection_status[id] if @connection_status[id][:callback].arity == 2 @connection_status[id][:callback].call(:timeout, nil) else @connection_status[id][:callback].call(:timeout) end @connection_status.delete(id) end end end id end
ruby
def connection_status(options = {}, &callback) id = generate_id @connection_status[id] = {:boundary => options[:boundary], :brokers => options[:brokers], :callback => callback} if timeout = options[:one_off] @connection_status[id][:timer] = EM::Timer.new(timeout) do if @connection_status[id] if @connection_status[id][:callback].arity == 2 @connection_status[id][:callback].call(:timeout, nil) else @connection_status[id][:callback].call(:timeout) end @connection_status.delete(id) end end end id end
[ "def", "connection_status", "(", "options", "=", "{", "}", ",", "&", "callback", ")", "id", "=", "generate_id", "@connection_status", "[", "id", "]", "=", "{", ":boundary", "=>", "options", "[", ":boundary", "]", ",", ":brokers", "=>", "options", "[", ":brokers", "]", ",", ":callback", "=>", "callback", "}", "if", "timeout", "=", "options", "[", ":one_off", "]", "@connection_status", "[", "id", "]", "[", ":timer", "]", "=", "EM", "::", "Timer", ".", "new", "(", "timeout", ")", "do", "if", "@connection_status", "[", "id", "]", "if", "@connection_status", "[", "id", "]", "[", ":callback", "]", ".", "arity", "==", "2", "@connection_status", "[", "id", "]", "[", ":callback", "]", ".", "call", "(", ":timeout", ",", "nil", ")", "else", "@connection_status", "[", "id", "]", "[", ":callback", "]", ".", "call", "(", ":timeout", ")", "end", "@connection_status", ".", "delete", "(", "id", ")", "end", "end", "end", "id", "end" ]
Register callback to be activated when there is a change in connection status Can be called more than once without affecting previous callbacks === Parameters options(Hash):: Connection status monitoring options :one_off(Integer):: Seconds to wait for status change; only send update once; if timeout, report :timeout as the status :boundary(Symbol):: :any if only report change on any (0/1) boundary, :all if only report change on all (n-1/n) boundary, defaults to :any :brokers(Array):: Only report a status change for these identified brokers === Block Required block activated when connected count crosses a status boundary with following parameters status(Symbol):: Status of connection: :connected, :disconnected, or :failed, with :failed indicating that all selected brokers or all brokers have failed === Return id(String):: Identifier associated with connection status request
[ "Register", "callback", "to", "be", "activated", "when", "there", "is", "a", "change", "in", "connection", "status", "Can", "be", "called", "more", "than", "once", "without", "affecting", "previous", "callbacks" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L816-L832
6,044
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.reset_stats
def reset_stats @return_stats = RightSupport::Stats::Activity.new @non_delivery_stats = RightSupport::Stats::Activity.new @exception_stats = @options[:exception_stats] || RightSupport::Stats::Exceptions.new(self, @options[:exception_callback]) true end
ruby
def reset_stats @return_stats = RightSupport::Stats::Activity.new @non_delivery_stats = RightSupport::Stats::Activity.new @exception_stats = @options[:exception_stats] || RightSupport::Stats::Exceptions.new(self, @options[:exception_callback]) true end
[ "def", "reset_stats", "@return_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "@non_delivery_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "@exception_stats", "=", "@options", "[", ":exception_stats", "]", "||", "RightSupport", "::", "Stats", "::", "Exceptions", ".", "new", "(", "self", ",", "@options", "[", ":exception_callback", "]", ")", "true", "end" ]
Reset broker client statistics Do not reset disconnect and failure stats because they might then be inconsistent with underlying connection status === Return true:: Always return true
[ "Reset", "broker", "client", "statistics", "Do", "not", "reset", "disconnect", "and", "failure", "stats", "because", "they", "might", "then", "be", "inconsistent", "with", "underlying", "connection", "status" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L882-L887
6,045
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connect_all
def connect_all self.class.addresses(@options[:host], @options[:port]).map do |a| identity = self.class.identity(a[:host], a[:port]) BrokerClient.new(identity, a, @serializer, @exception_stats, @non_delivery_stats, @options, nil) end end
ruby
def connect_all self.class.addresses(@options[:host], @options[:port]).map do |a| identity = self.class.identity(a[:host], a[:port]) BrokerClient.new(identity, a, @serializer, @exception_stats, @non_delivery_stats, @options, nil) end end
[ "def", "connect_all", "self", ".", "class", ".", "addresses", "(", "@options", "[", ":host", "]", ",", "@options", "[", ":port", "]", ")", ".", "map", "do", "|", "a", "|", "identity", "=", "self", ".", "class", ".", "identity", "(", "a", "[", ":host", "]", ",", "a", "[", ":port", "]", ")", "BrokerClient", ".", "new", "(", "identity", ",", "a", ",", "@serializer", ",", "@exception_stats", ",", "@non_delivery_stats", ",", "@options", ",", "nil", ")", "end", "end" ]
Connect to all configured brokers === Return (Array):: Broker clients created
[ "Connect", "to", "all", "configured", "brokers" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L895-L900
6,046
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.priority
def priority(identity) priority = 0 @brokers.each do |b| break if b.identity == identity priority += 1 end priority end
ruby
def priority(identity) priority = 0 @brokers.each do |b| break if b.identity == identity priority += 1 end priority end
[ "def", "priority", "(", "identity", ")", "priority", "=", "0", "@brokers", ".", "each", "do", "|", "b", "|", "break", "if", "b", ".", "identity", "==", "identity", "priority", "+=", "1", "end", "priority", "end" ]
Determine priority of broker If broker not found, assign next available priority === Parameters identity(String):: Broker identity === Return (Integer):: Priority position of broker
[ "Determine", "priority", "of", "broker", "If", "broker", "not", "found", "assign", "next", "available", "priority" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L910-L917
6,047
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.each
def each(status, identities = nil) choices = if identities && !identities.empty? identities.inject([]) { |c, i| if b = @brokers_hash[i] then c << b else c end } else @brokers end choices.select do |b| if b.send("#{status}?".to_sym) yield(b) if block_given? true end end end
ruby
def each(status, identities = nil) choices = if identities && !identities.empty? identities.inject([]) { |c, i| if b = @brokers_hash[i] then c << b else c end } else @brokers end choices.select do |b| if b.send("#{status}?".to_sym) yield(b) if block_given? true end end end
[ "def", "each", "(", "status", ",", "identities", "=", "nil", ")", "choices", "=", "if", "identities", "&&", "!", "identities", ".", "empty?", "identities", ".", "inject", "(", "[", "]", ")", "{", "|", "c", ",", "i", "|", "if", "b", "=", "@brokers_hash", "[", "i", "]", "then", "c", "<<", "b", "else", "c", "end", "}", "else", "@brokers", "end", "choices", ".", "select", "do", "|", "b", "|", "if", "b", ".", "send", "(", "\"#{status}?\"", ".", "to_sym", ")", "yield", "(", "b", ")", "if", "block_given?", "true", "end", "end", "end" ]
Iterate over clients that have the specified status === Parameters status(String):: Status for selecting: :usable, :connected, :failed identities(Array):: Identity of brokers to be considered, nil or empty array means all brokers === Block Optional block with following parameters to be called for each broker client selected broker(BrokerClient):: Broker client === Return (Array):: Selected broker clients
[ "Iterate", "over", "clients", "that", "have", "the", "specified", "status" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L942-L954
6,048
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.use
def use(options) choices = [] select = options[:order] if options[:brokers] && !options[:brokers].empty? options[:brokers].each do |identity| if choice = @brokers_hash[identity] choices << choice else logger.exception("Invalid broker identity #{identity.inspect}, check server configuration") end end else choices = @brokers select ||= @select end if select == :random choices.sort_by { rand } else choices end end
ruby
def use(options) choices = [] select = options[:order] if options[:brokers] && !options[:brokers].empty? options[:brokers].each do |identity| if choice = @brokers_hash[identity] choices << choice else logger.exception("Invalid broker identity #{identity.inspect}, check server configuration") end end else choices = @brokers select ||= @select end if select == :random choices.sort_by { rand } else choices end end
[ "def", "use", "(", "options", ")", "choices", "=", "[", "]", "select", "=", "options", "[", ":order", "]", "if", "options", "[", ":brokers", "]", "&&", "!", "options", "[", ":brokers", "]", ".", "empty?", "options", "[", ":brokers", "]", ".", "each", "do", "|", "identity", "|", "if", "choice", "=", "@brokers_hash", "[", "identity", "]", "choices", "<<", "choice", "else", "logger", ".", "exception", "(", "\"Invalid broker identity #{identity.inspect}, check server configuration\"", ")", "end", "end", "else", "choices", "=", "@brokers", "select", "||=", "@select", "end", "if", "select", "==", ":random", "choices", ".", "sort_by", "{", "rand", "}", "else", "choices", "end", "end" ]
Select the broker clients to be used in the desired order === Parameters options(Hash):: Selection options: :brokers(Array):: Identity of brokers selected for use, defaults to all brokers if nil or empty :order(Symbol):: Broker selection order: :random or :priority, defaults to @select if :brokers is nil, otherwise defaults to :priority === Return (Array):: Allowed BrokerClients in the order to be used
[ "Select", "the", "broker", "clients", "to", "be", "used", "in", "the", "desired", "order" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L966-L986
6,049
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.handle_return
def handle_return(identity, to, reason, message) @brokers_hash[identity].update_status(:stopping) if reason == "ACCESS_REFUSED" if context = @published.fetch(message) @return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase})") context.record_failure(identity) name = context.name options = context.options || {} token = context.token one_way = context.one_way persistent = options[:persistent] mandatory = true remaining = (context.brokers - context.failed) & connected logger.info("RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} " + "failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}") if remaining.empty? if (persistent || one_way) && ["ACCESS_REFUSED", "NO_CONSUMERS"].include?(reason) && !(remaining = context.brokers & connected).empty? # Retry because persistent, and this time w/o mandatory so that gets queued even though no consumers mandatory = false else t = token ? " <#{token}>" : "" logger.info("NO ROUTE #{aliases(context.brokers).join(", ")} [#{name}]#{t} to #{to}") @non_delivery.call(reason, context.type, token, context.from, to) if @non_delivery @non_delivery_stats.update("no route") end end unless remaining.empty? t = token ? " <#{token}>" : "" p = persistent ? ", persistent" : "" m = mandatory ? ", mandatory" : "" logger.info("RE-ROUTE #{aliases(remaining).join(", ")} [#{context.name}]#{t} to #{to}#{p}#{m}") exchange = {:type => :queue, :name => to, :options => {:no_declare => true}} publish(exchange, message, options.merge(:no_serialize => true, :brokers => remaining, :persistent => persistent, :mandatory => mandatory)) end else @return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase} - missing context)") logger.info("Dropping message returned from broker #{identity} for reason #{reason} " + "because no message context available for re-routing it to #{to}") end true rescue Exception => e logger.exception("Failed to handle #{reason} return from #{identity} for message being routed to #{to}", e, :trace) @exception_stats.track("return", e) end
ruby
def handle_return(identity, to, reason, message) @brokers_hash[identity].update_status(:stopping) if reason == "ACCESS_REFUSED" if context = @published.fetch(message) @return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase})") context.record_failure(identity) name = context.name options = context.options || {} token = context.token one_way = context.one_way persistent = options[:persistent] mandatory = true remaining = (context.brokers - context.failed) & connected logger.info("RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} " + "failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}") if remaining.empty? if (persistent || one_way) && ["ACCESS_REFUSED", "NO_CONSUMERS"].include?(reason) && !(remaining = context.brokers & connected).empty? # Retry because persistent, and this time w/o mandatory so that gets queued even though no consumers mandatory = false else t = token ? " <#{token}>" : "" logger.info("NO ROUTE #{aliases(context.brokers).join(", ")} [#{name}]#{t} to #{to}") @non_delivery.call(reason, context.type, token, context.from, to) if @non_delivery @non_delivery_stats.update("no route") end end unless remaining.empty? t = token ? " <#{token}>" : "" p = persistent ? ", persistent" : "" m = mandatory ? ", mandatory" : "" logger.info("RE-ROUTE #{aliases(remaining).join(", ")} [#{context.name}]#{t} to #{to}#{p}#{m}") exchange = {:type => :queue, :name => to, :options => {:no_declare => true}} publish(exchange, message, options.merge(:no_serialize => true, :brokers => remaining, :persistent => persistent, :mandatory => mandatory)) end else @return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase} - missing context)") logger.info("Dropping message returned from broker #{identity} for reason #{reason} " + "because no message context available for re-routing it to #{to}") end true rescue Exception => e logger.exception("Failed to handle #{reason} return from #{identity} for message being routed to #{to}", e, :trace) @exception_stats.track("return", e) end
[ "def", "handle_return", "(", "identity", ",", "to", ",", "reason", ",", "message", ")", "@brokers_hash", "[", "identity", "]", ".", "update_status", "(", ":stopping", ")", "if", "reason", "==", "\"ACCESS_REFUSED\"", "if", "context", "=", "@published", ".", "fetch", "(", "message", ")", "@return_stats", ".", "update", "(", "\"#{alias_(identity)} (#{reason.to_s.downcase})\"", ")", "context", ".", "record_failure", "(", "identity", ")", "name", "=", "context", ".", "name", "options", "=", "context", ".", "options", "||", "{", "}", "token", "=", "context", ".", "token", "one_way", "=", "context", ".", "one_way", "persistent", "=", "options", "[", ":persistent", "]", "mandatory", "=", "true", "remaining", "=", "(", "context", ".", "brokers", "-", "context", ".", "failed", ")", "&", "connected", "logger", ".", "info", "(", "\"RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} \"", "+", "\"failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}\"", ")", "if", "remaining", ".", "empty?", "if", "(", "persistent", "||", "one_way", ")", "&&", "[", "\"ACCESS_REFUSED\"", ",", "\"NO_CONSUMERS\"", "]", ".", "include?", "(", "reason", ")", "&&", "!", "(", "remaining", "=", "context", ".", "brokers", "&", "connected", ")", ".", "empty?", "# Retry because persistent, and this time w/o mandatory so that gets queued even though no consumers", "mandatory", "=", "false", "else", "t", "=", "token", "?", "\" <#{token}>\"", ":", "\"\"", "logger", ".", "info", "(", "\"NO ROUTE #{aliases(context.brokers).join(\", \")} [#{name}]#{t} to #{to}\"", ")", "@non_delivery", ".", "call", "(", "reason", ",", "context", ".", "type", ",", "token", ",", "context", ".", "from", ",", "to", ")", "if", "@non_delivery", "@non_delivery_stats", ".", "update", "(", "\"no route\"", ")", "end", "end", "unless", "remaining", ".", "empty?", "t", "=", "token", "?", "\" <#{token}>\"", ":", "\"\"", "p", "=", "persistent", "?", "\", persistent\"", ":", "\"\"", "m", "=", "mandatory", "?", "\", mandatory\"", ":", "\"\"", "logger", ".", "info", "(", "\"RE-ROUTE #{aliases(remaining).join(\", \")} [#{context.name}]#{t} to #{to}#{p}#{m}\"", ")", "exchange", "=", "{", ":type", "=>", ":queue", ",", ":name", "=>", "to", ",", ":options", "=>", "{", ":no_declare", "=>", "true", "}", "}", "publish", "(", "exchange", ",", "message", ",", "options", ".", "merge", "(", ":no_serialize", "=>", "true", ",", ":brokers", "=>", "remaining", ",", ":persistent", "=>", "persistent", ",", ":mandatory", "=>", "mandatory", ")", ")", "end", "else", "@return_stats", ".", "update", "(", "\"#{alias_(identity)} (#{reason.to_s.downcase} - missing context)\"", ")", "logger", ".", "info", "(", "\"Dropping message returned from broker #{identity} for reason #{reason} \"", "+", "\"because no message context available for re-routing it to #{to}\"", ")", "end", "true", "rescue", "Exception", "=>", "e", "logger", ".", "exception", "(", "\"Failed to handle #{reason} return from #{identity} for message being routed to #{to}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"return\"", ",", "e", ")", "end" ]
Handle message returned by broker because it could not deliver it If agent still active, resend using another broker If this is last usable broker and persistent is enabled, allow message to be queued on next send even if the queue has no consumers so there is a chance of message eventually being delivered If persistent or one-way request and all usable brokers have failed, try one more time without mandatory flag to give message opportunity to be queued If there are no more usable broker clients, send non-delivery message to original sender === Parameters identity(String):: Identity of broker that could not deliver message to(String):: Queue to which message was published reason(String):: Reason for return "NO_ROUTE" - queue does not exist "NO_CONSUMERS" - queue exists but it has no consumers, or if :immediate was specified, all consumers are not immediately ready to consume "ACCESS_REFUSED" - queue not usable because broker is in the process of stopping service message(String):: Returned message in serialized packet format === Return true:: Always return true
[ "Handle", "message", "returned", "by", "broker", "because", "it", "could", "not", "deliver", "it", "If", "agent", "still", "active", "resend", "using", "another", "broker", "If", "this", "is", "last", "usable", "broker", "and", "persistent", "is", "enabled", "allow", "message", "to", "be", "queued", "on", "next", "send", "even", "if", "the", "queue", "has", "no", "consumers", "so", "there", "is", "a", "chance", "of", "message", "eventually", "being", "delivered", "If", "persistent", "or", "one", "-", "way", "request", "and", "all", "usable", "brokers", "have", "failed", "try", "one", "more", "time", "without", "mandatory", "flag", "to", "give", "message", "opportunity", "to", "be", "queued", "If", "there", "are", "no", "more", "usable", "broker", "clients", "send", "non", "-", "delivery", "message", "to", "original", "sender" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L1066-L1113
6,050
KatanaCode/evvnt
lib/evvnt/attributes.rb
Evvnt.Attributes.method_missing
def method_missing(method_name, *args) setter = method_name.to_s.ends_with?('=') attr_name = method_name.to_s.gsub(/=$/, "") if setter attributes[attr_name] = args.first else attributes[attr_name] end end
ruby
def method_missing(method_name, *args) setter = method_name.to_s.ends_with?('=') attr_name = method_name.to_s.gsub(/=$/, "") if setter attributes[attr_name] = args.first else attributes[attr_name] end end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ")", "setter", "=", "method_name", ".", "to_s", ".", "ends_with?", "(", "'='", ")", "attr_name", "=", "method_name", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", "if", "setter", "attributes", "[", "attr_name", "]", "=", "args", ".", "first", "else", "attributes", "[", "attr_name", "]", "end", "end" ]
Overrides method missing to catch undefined methods. If +method_name+ is one of the keys on +attributes+, returns the value of that attribute. If +method_name+ is not one of +attributes+, passes up the chain to super. method_name - Symbol of the name of the method we're testing for. args - Array of arguments send with the original mesage. block - Proc of code passed with original message.
[ "Overrides", "method", "missing", "to", "catch", "undefined", "methods", ".", "If", "+", "method_name", "+", "is", "one", "of", "the", "keys", "on", "+", "attributes", "+", "returns", "the", "value", "of", "that", "attribute", ".", "If", "+", "method_name", "+", "is", "not", "one", "of", "+", "attributes", "+", "passes", "up", "the", "chain", "to", "super", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/attributes.rb#L101-L109
6,051
jinx/core
lib/jinx/resource/match_visitor.rb
Jinx.MatchVisitor.visit
def visit(source, target, &block) # clear the match hashes @matches.clear @id_mtchs.clear # seed the matches with the top-level source => target add_match(source, target) # Visit the source reference. super(source) { |src| visit_matched(src, &block) } end
ruby
def visit(source, target, &block) # clear the match hashes @matches.clear @id_mtchs.clear # seed the matches with the top-level source => target add_match(source, target) # Visit the source reference. super(source) { |src| visit_matched(src, &block) } end
[ "def", "visit", "(", "source", ",", "target", ",", "&", "block", ")", "# clear the match hashes", "@matches", ".", "clear", "@id_mtchs", ".", "clear", "# seed the matches with the top-level source => target", "add_match", "(", "source", ",", "target", ")", "# Visit the source reference.", "super", "(", "source", ")", "{", "|", "src", "|", "visit_matched", "(", "src", ",", "block", ")", "}", "end" ]
Creates a new visitor which matches source and target domain object references. The domain attributes to visit are determined by calling the selector block given to this initializer. The selector arguments consist of the match source and target. @param (see ReferenceVisitor#initialize) @option opts [Proc] :mergeable the block which determines which attributes are merged @option opts [Proc] :matchable the block which determines which attributes to match (default is the visit selector) @option opts [:match] :matcher an object which matches sources to targets @option opts [Proc] :copier the block which copies an unmatched source @yield (see ReferenceVisitor#initialize) @yieldparam [Resource] source the matched source object Visits the source and target. If a block is given to this method, then this method returns the evaluation of the block on the visited source reference and its matching copy, if any. The default return value is the target which matches source. @param [Resource] source the match visit source @param [Resource] target the match visit target @yield [target, source] the optional block to call on the matched source and target @yieldparam [Resource] source the visited source domain object @yieldparam [Resource] target the domain object which matches the visited source @yieldparam [Resource] from the visiting domain object @yieldparam [Property] property the visiting property
[ "Creates", "a", "new", "visitor", "which", "matches", "source", "and", "target", "domain", "object", "references", ".", "The", "domain", "attributes", "to", "visit", "are", "determined", "by", "calling", "the", "selector", "block", "given", "to", "this", "initializer", ".", "The", "selector", "arguments", "consist", "of", "the", "match", "source", "and", "target", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/match_visitor.rb#L63-L71
6,052
jinx/core
lib/jinx/resource/match_visitor.rb
Jinx.MatchVisitor.visit_matched
def visit_matched(source) tgt = @matches[source] || return # Match the unvisited matchable references, if any. if @matchable then mas = @matchable.call(source) - attributes_to_visit(source) mas.each { |ma| match_reference(source, tgt, ma) } end block_given? ? yield(source, tgt) : tgt end
ruby
def visit_matched(source) tgt = @matches[source] || return # Match the unvisited matchable references, if any. if @matchable then mas = @matchable.call(source) - attributes_to_visit(source) mas.each { |ma| match_reference(source, tgt, ma) } end block_given? ? yield(source, tgt) : tgt end
[ "def", "visit_matched", "(", "source", ")", "tgt", "=", "@matches", "[", "source", "]", "||", "return", "# Match the unvisited matchable references, if any.", "if", "@matchable", "then", "mas", "=", "@matchable", ".", "call", "(", "source", ")", "-", "attributes_to_visit", "(", "source", ")", "mas", ".", "each", "{", "|", "ma", "|", "match_reference", "(", "source", ",", "tgt", ",", "ma", ")", "}", "end", "block_given?", "?", "yield", "(", "source", ",", "tgt", ")", ":", "tgt", "end" ]
Visits the given source domain object. @param [Resource] source the match visit source @yield [target, source] the optional block to call on the matched source and target @yieldparam [Resource] source the visited source domain object @yieldparam [Resource] target the domain object which matches the visited source @yieldparam [Resource] from the visiting domain object @yieldparam [Property] property the visiting property
[ "Visits", "the", "given", "source", "domain", "object", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/match_visitor.rb#L92-L100
6,053
jinx/core
lib/jinx/resource/match_visitor.rb
Jinx.MatchVisitor.match_reference
def match_reference(source, target, attribute) srcs = source.send(attribute).to_enum tgts = target.send(attribute).to_enum # the match targets mtchd_tgts = Set.new # capture the matched targets and the the unmatched sources unmtchd_srcs = srcs.reject do |src| # the prior match, if any tgt = match_for(src) mtchd_tgts << tgt if tgt end # the unmatched targets unmtchd_tgts = tgts.difference(mtchd_tgts) logger.debug { "#{qp} matching #{unmtchd_tgts.qp}..." } if @verbose and not unmtchd_tgts.empty? # match the residual targets and sources rsd_mtchs = @matcher.match(unmtchd_srcs, unmtchd_tgts, source, attribute) # add residual matches rsd_mtchs.each { |src, tgt| add_match(src, tgt) } logger.debug { "#{qp} matched #{rsd_mtchs.qp}..." } if @verbose and not rsd_mtchs.empty? # The source => target match hash. # If there is a copier, then copy each unmatched source. matches = srcs.to_compact_hash { |src| match_for(src) or copy_unmatched(src) } matches end
ruby
def match_reference(source, target, attribute) srcs = source.send(attribute).to_enum tgts = target.send(attribute).to_enum # the match targets mtchd_tgts = Set.new # capture the matched targets and the the unmatched sources unmtchd_srcs = srcs.reject do |src| # the prior match, if any tgt = match_for(src) mtchd_tgts << tgt if tgt end # the unmatched targets unmtchd_tgts = tgts.difference(mtchd_tgts) logger.debug { "#{qp} matching #{unmtchd_tgts.qp}..." } if @verbose and not unmtchd_tgts.empty? # match the residual targets and sources rsd_mtchs = @matcher.match(unmtchd_srcs, unmtchd_tgts, source, attribute) # add residual matches rsd_mtchs.each { |src, tgt| add_match(src, tgt) } logger.debug { "#{qp} matched #{rsd_mtchs.qp}..." } if @verbose and not rsd_mtchs.empty? # The source => target match hash. # If there is a copier, then copy each unmatched source. matches = srcs.to_compact_hash { |src| match_for(src) or copy_unmatched(src) } matches end
[ "def", "match_reference", "(", "source", ",", "target", ",", "attribute", ")", "srcs", "=", "source", ".", "send", "(", "attribute", ")", ".", "to_enum", "tgts", "=", "target", ".", "send", "(", "attribute", ")", ".", "to_enum", "# the match targets", "mtchd_tgts", "=", "Set", ".", "new", "# capture the matched targets and the the unmatched sources", "unmtchd_srcs", "=", "srcs", ".", "reject", "do", "|", "src", "|", "# the prior match, if any", "tgt", "=", "match_for", "(", "src", ")", "mtchd_tgts", "<<", "tgt", "if", "tgt", "end", "# the unmatched targets", "unmtchd_tgts", "=", "tgts", ".", "difference", "(", "mtchd_tgts", ")", "logger", ".", "debug", "{", "\"#{qp} matching #{unmtchd_tgts.qp}...\"", "}", "if", "@verbose", "and", "not", "unmtchd_tgts", ".", "empty?", "# match the residual targets and sources", "rsd_mtchs", "=", "@matcher", ".", "match", "(", "unmtchd_srcs", ",", "unmtchd_tgts", ",", "source", ",", "attribute", ")", "# add residual matches", "rsd_mtchs", ".", "each", "{", "|", "src", ",", "tgt", "|", "add_match", "(", "src", ",", "tgt", ")", "}", "logger", ".", "debug", "{", "\"#{qp} matched #{rsd_mtchs.qp}...\"", "}", "if", "@verbose", "and", "not", "rsd_mtchs", ".", "empty?", "# The source => target match hash.", "# If there is a copier, then copy each unmatched source.", "matches", "=", "srcs", ".", "to_compact_hash", "{", "|", "src", "|", "match_for", "(", "src", ")", "or", "copy_unmatched", "(", "src", ")", "}", "matches", "end" ]
Matches the given source and target attribute references. The match is performed by this visitor's matcher. @param source (see #visit) @param target (see #visit) @param [Symbol] attribute the parent reference attribute @return [{Resource => Resource}] the referenced source => target matches
[ "Matches", "the", "given", "source", "and", "target", "attribute", "references", ".", "The", "match", "is", "performed", "by", "this", "visitor", "s", "matcher", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/match_visitor.rb#L131-L157
6,054
DigitPaint/html_mockup
lib/html_mockup/extractor.rb
HtmlMockup.Extractor.extract_source_from_file
def extract_source_from_file(file_path, env = {}) source = HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path).render(env.dup) if @options[:url_relativize] source = relativize_urls(source, file_path) end source end
ruby
def extract_source_from_file(file_path, env = {}) source = HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path).render(env.dup) if @options[:url_relativize] source = relativize_urls(source, file_path) end source end
[ "def", "extract_source_from_file", "(", "file_path", ",", "env", "=", "{", "}", ")", "source", "=", "HtmlMockup", "::", "Template", ".", "open", "(", "file_path", ",", ":partials_path", "=>", "self", ".", "project", ".", "partial_path", ",", ":layouts_path", "=>", "self", ".", "project", ".", "layouts_path", ")", ".", "render", "(", "env", ".", "dup", ")", "if", "@options", "[", ":url_relativize", "]", "source", "=", "relativize_urls", "(", "source", ",", "file_path", ")", "end", "source", "end" ]
Runs the extractor on a single file and return processed source.
[ "Runs", "the", "extractor", "on", "a", "single", "file", "and", "return", "processed", "source", "." ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/extractor.rb#L63-L71
6,055
booqable/scoped_serializer
lib/action_controller/serialization.rb
ActionController.Serialization.build_json_serializer
def build_json_serializer(object, options={}) ScopedSerializer.for(object, { :scope => serializer_scope, :super => true }.merge(options.merge(default_serializer_options))) end
ruby
def build_json_serializer(object, options={}) ScopedSerializer.for(object, { :scope => serializer_scope, :super => true }.merge(options.merge(default_serializer_options))) end
[ "def", "build_json_serializer", "(", "object", ",", "options", "=", "{", "}", ")", "ScopedSerializer", ".", "for", "(", "object", ",", "{", ":scope", "=>", "serializer_scope", ",", ":super", "=>", "true", "}", ".", "merge", "(", "options", ".", "merge", "(", "default_serializer_options", ")", ")", ")", "end" ]
JSON serializer to use.
[ "JSON", "serializer", "to", "use", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/action_controller/serialization.rb#L30-L32
6,056
terlar/formatter-number
lib/formatter/number.rb
Formatter.Number.format
def format(number) case number when Float then format_float(number) when Integer then format_integer(number) else fail ArgumentError end end
ruby
def format(number) case number when Float then format_float(number) when Integer then format_integer(number) else fail ArgumentError end end
[ "def", "format", "(", "number", ")", "case", "number", "when", "Float", "then", "format_float", "(", "number", ")", "when", "Integer", "then", "format_integer", "(", "number", ")", "else", "fail", "ArgumentError", "end", "end" ]
Initialize a formatter with the desired options. @param [Hash] options the options to create a formatter with @option options [Integer] :decimals (2) Number of decimal places @option options [Boolean] :fixed (false) Fixed decimal places @option options [String] :separator ('.') Decimal mark @option options [Integer] :grouping (3) Number of digits per group @option options [String] :delimiter (',') Delimiter between groups
[ "Initialize", "a", "formatter", "with", "the", "desired", "options", "." ]
e206c92a6823f12d1019bd9ad5689d914d410ef3
https://github.com/terlar/formatter-number/blob/e206c92a6823f12d1019bd9ad5689d914d410ef3/lib/formatter/number.rb#L26-L32
6,057
binford2k/arnold
gem/lib/arnold/node_manager.rb
Arnold.NodeManager.remove_stale_symlinks
def remove_stale_symlinks(path) Dir.glob("#{path}/*").each { |f| File.unlink(f) if not File.exist?(f) } end
ruby
def remove_stale_symlinks(path) Dir.glob("#{path}/*").each { |f| File.unlink(f) if not File.exist?(f) } end
[ "def", "remove_stale_symlinks", "(", "path", ")", "Dir", ".", "glob", "(", "\"#{path}/*\"", ")", ".", "each", "{", "|", "f", "|", "File", ".", "unlink", "(", "f", ")", "if", "not", "File", ".", "exist?", "(", "f", ")", "}", "end" ]
just loop through a directory and get rid of any stale symlinks
[ "just", "loop", "through", "a", "directory", "and", "get", "rid", "of", "any", "stale", "symlinks" ]
8bf1b3c1ae0e76cc97dff1a07b24c2fa9170b688
https://github.com/binford2k/arnold/blob/8bf1b3c1ae0e76cc97dff1a07b24c2fa9170b688/gem/lib/arnold/node_manager.rb#L114-L116
6,058
bluevialabs/connfu-client
lib/connfu/listener.rb
Connfu.Listener.start
def start(queue = nil) queue.nil? and queue = @queue logger.debug "Listener starts..." @thread = Thread.new { # listen to connFu @connfu_stream.start_listening } while continue do logger.debug "Waiting for a message from connFu stream" message = @connfu_stream.get @counter = @counter + 1 logger.debug "#{self.class} got message => #{message}" # Write in internal Queue queue.put(message) end end
ruby
def start(queue = nil) queue.nil? and queue = @queue logger.debug "Listener starts..." @thread = Thread.new { # listen to connFu @connfu_stream.start_listening } while continue do logger.debug "Waiting for a message from connFu stream" message = @connfu_stream.get @counter = @counter + 1 logger.debug "#{self.class} got message => #{message}" # Write in internal Queue queue.put(message) end end
[ "def", "start", "(", "queue", "=", "nil", ")", "queue", ".", "nil?", "and", "queue", "=", "@queue", "logger", ".", "debug", "\"Listener starts...\"", "@thread", "=", "Thread", ".", "new", "{", "# listen to connFu", "@connfu_stream", ".", "start_listening", "}", "while", "continue", "do", "logger", ".", "debug", "\"Waiting for a message from connFu stream\"", "message", "=", "@connfu_stream", ".", "get", "@counter", "=", "@counter", "+", "1", "logger", ".", "debug", "\"#{self.class} got message => #{message}\"", "# Write in internal Queue", "queue", ".", "put", "(", "message", ")", "end", "end" ]
max amount of messages to receive Listener initializer. ==== Parameters * +queue+ Connfu::Events instance to forward incoming events to be processed by the Dispatcher class * +app_stream+ valid HTTP stream url to connect and listen events * +token+ valid token to get access to a connFu Stream * +stream_endpoint+ endpoint to open a keepalive HTTP connection start listening. Should create a new thread and wait to new events to come ==== Parameters * +queue+ to send incoming events to the Dispatcher class
[ "max", "amount", "of", "messages", "to", "receive" ]
b62a0f5176afa203ba1eecccc7994d6bc61af3a7
https://github.com/bluevialabs/connfu-client/blob/b62a0f5176afa203ba1eecccc7994d6bc61af3a7/lib/connfu/listener.rb#L40-L59
6,059
jinx/core
lib/jinx/resource.rb
Jinx.Resource.owner=
def owner=(obj) if obj.nil? then op, ov = effective_owner_property_value || return else op = self.class.owner_properties.detect { |prop| prop.type === obj } end if op.nil? then raise NoMethodError.new("#{self.class.qp} does not have an owner attribute for #{obj}") end set_property_value(op.attribute, obj) end
ruby
def owner=(obj) if obj.nil? then op, ov = effective_owner_property_value || return else op = self.class.owner_properties.detect { |prop| prop.type === obj } end if op.nil? then raise NoMethodError.new("#{self.class.qp} does not have an owner attribute for #{obj}") end set_property_value(op.attribute, obj) end
[ "def", "owner", "=", "(", "obj", ")", "if", "obj", ".", "nil?", "then", "op", ",", "ov", "=", "effective_owner_property_value", "||", "return", "else", "op", "=", "self", ".", "class", ".", "owner_properties", ".", "detect", "{", "|", "prop", "|", "prop", ".", "type", "===", "obj", "}", "end", "if", "op", ".", "nil?", "then", "raise", "NoMethodError", ".", "new", "(", "\"#{self.class.qp} does not have an owner attribute for #{obj}\"", ")", "end", "set_property_value", "(", "op", ".", "attribute", ",", "obj", ")", "end" ]
Sets this dependent's owner attribute to the given domain object. @param [Resource] obj the owner domain object @raise [NoMethodError] if this Resource's class does not have an owner property which accepts the given domain object
[ "Sets", "this", "dependent", "s", "owner", "attribute", "to", "the", "given", "domain", "object", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L226-L234
6,060
jinx/core
lib/jinx/resource.rb
Jinx.Resource.references
def references(attributes=nil) attributes ||= self.class.domain_attributes attributes.map { |pa| send(pa) }.flatten.compact end
ruby
def references(attributes=nil) attributes ||= self.class.domain_attributes attributes.map { |pa| send(pa) }.flatten.compact end
[ "def", "references", "(", "attributes", "=", "nil", ")", "attributes", "||=", "self", ".", "class", ".", "domain_attributes", "attributes", ".", "map", "{", "|", "pa", "|", "send", "(", "pa", ")", "}", ".", "flatten", ".", "compact", "end" ]
Returns the domain object references for the given attributes. @param [<Symbol>, nil] the domain attributes to include, or nil to include all domain attributes @return [<Resource>] the referenced attribute domain object values
[ "Returns", "the", "domain", "object", "references", "for", "the", "given", "attributes", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L277-L280
6,061
jinx/core
lib/jinx/resource.rb
Jinx.Resource.direct_dependents
def direct_dependents(attribute) deps = send(attribute) case deps when Enumerable then deps when nil then Array::EMPTY_ARRAY else [deps] end end
ruby
def direct_dependents(attribute) deps = send(attribute) case deps when Enumerable then deps when nil then Array::EMPTY_ARRAY else [deps] end end
[ "def", "direct_dependents", "(", "attribute", ")", "deps", "=", "send", "(", "attribute", ")", "case", "deps", "when", "Enumerable", "then", "deps", "when", "nil", "then", "Array", "::", "EMPTY_ARRAY", "else", "[", "deps", "]", "end", "end" ]
Returns the attribute references which directly depend on this owner. The default is the attribute value. Returns an Enumerable. If the value is not already an Enumerable, then this method returns an empty array if value is nil, or a singelton array with value otherwise. If there is more than one owner of a dependent, then subclasses should override this method to select dependents whose dependency path is shorter than an alternative dependency path, e.g. if a Node is owned by both a Graph and a parent Node. In that case, the Graph direct dependents consist of the top-level nodes owned by the Graph but not referenced by another Node. @param [Symbol] attribute the dependent attribute @return [<Resource>] the attribute value, wrapped in an array if necessary
[ "Returns", "the", "attribute", "references", "which", "directly", "depend", "on", "this", "owner", ".", "The", "default", "is", "the", "attribute", "value", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L335-L342
6,062
jinx/core
lib/jinx/resource.rb
Jinx.Resource.match_in
def match_in(others) # trivial case: self is in others return self if others.include?(self) # filter for the same type unless others.all? { |other| self.class === other } then others = others.filter { |other| self.class === other } end # match on primary, secondary or alternate key match_unique_object_with_attributes(others, self.class.primary_key_attributes) or match_unique_object_with_attributes(others, self.class.secondary_key_attributes) or match_unique_object_with_attributes(others, self.class.alternate_key_attributes) end
ruby
def match_in(others) # trivial case: self is in others return self if others.include?(self) # filter for the same type unless others.all? { |other| self.class === other } then others = others.filter { |other| self.class === other } end # match on primary, secondary or alternate key match_unique_object_with_attributes(others, self.class.primary_key_attributes) or match_unique_object_with_attributes(others, self.class.secondary_key_attributes) or match_unique_object_with_attributes(others, self.class.alternate_key_attributes) end
[ "def", "match_in", "(", "others", ")", "# trivial case: self is in others", "return", "self", "if", "others", ".", "include?", "(", "self", ")", "# filter for the same type", "unless", "others", ".", "all?", "{", "|", "other", "|", "self", ".", "class", "===", "other", "}", "then", "others", "=", "others", ".", "filter", "{", "|", "other", "|", "self", ".", "class", "===", "other", "}", "end", "# match on primary, secondary or alternate key", "match_unique_object_with_attributes", "(", "others", ",", "self", ".", "class", ".", "primary_key_attributes", ")", "or", "match_unique_object_with_attributes", "(", "others", ",", "self", ".", "class", ".", "secondary_key_attributes", ")", "or", "match_unique_object_with_attributes", "(", "others", ",", "self", ".", "class", ".", "alternate_key_attributes", ")", "end" ]
Matches this dependent domain object with the others on type and key attributes in the scope of a parent object. Returns the object in others which matches this domain object, or nil if none. The match attributes are, in order: * the primary key * the secondary key * the alternate key This domain object is matched against the others on the above attributes in succession until a unique match is found. The key attribute matches are strict, i.e. each key attribute value must be non-nil and match the other value. @param [<Resource>] the candidate domain object matches @return [Resource, nil] the matching domain object, or nil if no match
[ "Matches", "this", "dependent", "domain", "object", "with", "the", "others", "on", "type", "and", "key", "attributes", "in", "the", "scope", "of", "a", "parent", "object", ".", "Returns", "the", "object", "in", "others", "which", "matches", "this", "domain", "object", "or", "nil", "if", "none", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L393-L404
6,063
jinx/core
lib/jinx/resource.rb
Jinx.Resource.visit_path
def visit_path(*path, &operator) visitor = ReferencePathVisitor.new(self.class, path) visitor.visit(self, &operator) end
ruby
def visit_path(*path, &operator) visitor = ReferencePathVisitor.new(self.class, path) visitor.visit(self, &operator) end
[ "def", "visit_path", "(", "*", "path", ",", "&", "operator", ")", "visitor", "=", "ReferencePathVisitor", ".", "new", "(", "self", ".", "class", ",", "path", ")", "visitor", ".", "visit", "(", "self", ",", "operator", ")", "end" ]
Applies the operator block to this object and each domain object in the reference path. This method visits the transitive closure of each recursive path attribute. @param [<Symbol>] path the attributes to visit @yieldparam [Symbol] attribute the attribute to visit @return the visit result @see ReferencePathVisitor
[ "Applies", "the", "operator", "block", "to", "this", "object", "and", "each", "domain", "object", "in", "the", "reference", "path", ".", "This", "method", "visits", "the", "transitive", "closure", "of", "each", "recursive", "path", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L494-L497
6,064
jinx/core
lib/jinx/resource.rb
Jinx.Resource.printable_content
def printable_content(attributes=nil, &reference_printer) attributes ||= printworthy_attributes vh = value_hash(attributes) vh.transform_value { |value| printable_value(value, &reference_printer) } end
ruby
def printable_content(attributes=nil, &reference_printer) attributes ||= printworthy_attributes vh = value_hash(attributes) vh.transform_value { |value| printable_value(value, &reference_printer) } end
[ "def", "printable_content", "(", "attributes", "=", "nil", ",", "&", "reference_printer", ")", "attributes", "||=", "printworthy_attributes", "vh", "=", "value_hash", "(", "attributes", ")", "vh", ".", "transform_value", "{", "|", "value", "|", "printable_value", "(", "value", ",", "reference_printer", ")", "}", "end" ]
Returns this domain object's attributes content as an attribute => value hash suitable for printing. The default attributes are this object's saved attributes. The optional reference_printer is used to print a referenced domain object. @param [<Symbol>, nil] attributes the attributes to print @yield [ref] the reference print formatter @yieldparam [Resource] ref the referenced domain object to print @return [{Symbol => String}] the attribute => content hash
[ "Returns", "this", "domain", "object", "s", "attributes", "content", "as", "an", "attribute", "=", ">", "value", "hash", "suitable", "for", "printing", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L560-L564
6,065
jinx/core
lib/jinx/resource.rb
Jinx.Resource.validate_mandatory_attributes
def validate_mandatory_attributes invalid = missing_mandatory_attributes unless invalid.empty? then logger.error("Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\n#{dump}") raise ValidationError.new("Required attribute value missing for #{self}: #{invalid.join(', ')}") end validate_owner end
ruby
def validate_mandatory_attributes invalid = missing_mandatory_attributes unless invalid.empty? then logger.error("Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\n#{dump}") raise ValidationError.new("Required attribute value missing for #{self}: #{invalid.join(', ')}") end validate_owner end
[ "def", "validate_mandatory_attributes", "invalid", "=", "missing_mandatory_attributes", "unless", "invalid", ".", "empty?", "then", "logger", ".", "error", "(", "\"Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\\n#{dump}\"", ")", "raise", "ValidationError", ".", "new", "(", "\"Required attribute value missing for #{self}: #{invalid.join(', ')}\"", ")", "end", "validate_owner", "end" ]
Validates that this domain object contains a non-nil value for each mandatory attribute. @raise [ValidationError] if a mandatory attribute value is missing
[ "Validates", "that", "this", "domain", "object", "contains", "a", "non", "-", "nil", "value", "for", "each", "mandatory", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L703-L710
6,066
jinx/core
lib/jinx/resource.rb
Jinx.Resource.validate_owner
def validate_owner # If there is an unambigous owner, then we are done. return unless owner.nil? # If there is more than one owner attribute, then check that there is at most one # unambiguous owner reference. The owner method returns nil if the owner is ambiguous. if self.class.owner_attributes.size > 1 then vh = value_hash(self.class.owner_attributes) if vh.size > 1 then raise ValidationError.new("Dependent #{self} references multiple owners #{vh.pp_s}:\n#{dump}") end end # If there is an owner reference attribute, then there must be an owner. if self.class.bidirectional_java_dependent? then raise ValidationError.new("Dependent #{self} does not reference an owner") end end
ruby
def validate_owner # If there is an unambigous owner, then we are done. return unless owner.nil? # If there is more than one owner attribute, then check that there is at most one # unambiguous owner reference. The owner method returns nil if the owner is ambiguous. if self.class.owner_attributes.size > 1 then vh = value_hash(self.class.owner_attributes) if vh.size > 1 then raise ValidationError.new("Dependent #{self} references multiple owners #{vh.pp_s}:\n#{dump}") end end # If there is an owner reference attribute, then there must be an owner. if self.class.bidirectional_java_dependent? then raise ValidationError.new("Dependent #{self} does not reference an owner") end end
[ "def", "validate_owner", "# If there is an unambigous owner, then we are done.", "return", "unless", "owner", ".", "nil?", "# If there is more than one owner attribute, then check that there is at most one", "# unambiguous owner reference. The owner method returns nil if the owner is ambiguous.", "if", "self", ".", "class", ".", "owner_attributes", ".", "size", ">", "1", "then", "vh", "=", "value_hash", "(", "self", ".", "class", ".", "owner_attributes", ")", "if", "vh", ".", "size", ">", "1", "then", "raise", "ValidationError", ".", "new", "(", "\"Dependent #{self} references multiple owners #{vh.pp_s}:\\n#{dump}\"", ")", "end", "end", "# If there is an owner reference attribute, then there must be an owner.", "if", "self", ".", "class", ".", "bidirectional_java_dependent?", "then", "raise", "ValidationError", ".", "new", "(", "\"Dependent #{self} does not reference an owner\"", ")", "end", "end" ]
Validates that this domain object either doesn't have an owner attribute or has a unique effective owner. @raise [ValidationError] if there is an owner reference attribute that is not set @raise [ValidationError] if there is more than effective owner
[ "Validates", "that", "this", "domain", "object", "either", "doesn", "t", "have", "an", "owner", "attribute", "or", "has", "a", "unique", "effective", "owner", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L717-L732
6,067
jinx/core
lib/jinx/resource.rb
Jinx.Resource.printable_value
def printable_value(value, &reference_printer) Jinx::Collector.on(value) do |item| if Resource === item then block_given? ? yield(item) : printable_value(item) { |ref| ReferencePrinter.new(ref) } else item end end end
ruby
def printable_value(value, &reference_printer) Jinx::Collector.on(value) do |item| if Resource === item then block_given? ? yield(item) : printable_value(item) { |ref| ReferencePrinter.new(ref) } else item end end end
[ "def", "printable_value", "(", "value", ",", "&", "reference_printer", ")", "Jinx", "::", "Collector", ".", "on", "(", "value", ")", "do", "|", "item", "|", "if", "Resource", "===", "item", "then", "block_given?", "?", "yield", "(", "item", ")", ":", "printable_value", "(", "item", ")", "{", "|", "ref", "|", "ReferencePrinter", ".", "new", "(", "ref", ")", "}", "else", "item", "end", "end", "end" ]
Returns a value suitable for printing. If value is a domain object, then the block provided to this method is called. The default block creates a new ReferencePrinter on the value.
[ "Returns", "a", "value", "suitable", "for", "printing", ".", "If", "value", "is", "a", "domain", "object", "then", "the", "block", "provided", "to", "this", "method", "is", "called", ".", "The", "default", "block", "creates", "a", "new", "ReferencePrinter", "on", "the", "value", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L807-L815
6,068
jinx/core
lib/jinx/resource.rb
Jinx.Resource.printworthy_attributes
def printworthy_attributes if self.class.primary_key_attributes.all? { |pa| !!send(pa) } then self.class.primary_key_attributes elsif not self.class.secondary_key_attributes.empty? then self.class.secondary_key_attributes elsif not self.class.nondomain_java_attributes.empty? then self.class.nondomain_java_attributes else self.class.fetched_attributes end end
ruby
def printworthy_attributes if self.class.primary_key_attributes.all? { |pa| !!send(pa) } then self.class.primary_key_attributes elsif not self.class.secondary_key_attributes.empty? then self.class.secondary_key_attributes elsif not self.class.nondomain_java_attributes.empty? then self.class.nondomain_java_attributes else self.class.fetched_attributes end end
[ "def", "printworthy_attributes", "if", "self", ".", "class", ".", "primary_key_attributes", ".", "all?", "{", "|", "pa", "|", "!", "!", "send", "(", "pa", ")", "}", "then", "self", ".", "class", ".", "primary_key_attributes", "elsif", "not", "self", ".", "class", ".", "secondary_key_attributes", ".", "empty?", "then", "self", ".", "class", ".", "secondary_key_attributes", "elsif", "not", "self", ".", "class", ".", "nondomain_java_attributes", ".", "empty?", "then", "self", ".", "class", ".", "nondomain_java_attributes", "else", "self", ".", "class", ".", "fetched_attributes", "end", "end" ]
Returns an attribute => value hash which identifies the object. If this object has a complete primary key, than the primary key attributes are returned. Otherwise, if there are secondary key attributes, then they are returned. Otherwise, if there are nondomain attributes, then they are returned. Otherwise, if there are fetched attributes, then they are returned. @return [<Symbol] the attributes to print
[ "Returns", "an", "attribute", "=", ">", "value", "hash", "which", "identifies", "the", "object", ".", "If", "this", "object", "has", "a", "complete", "primary", "key", "than", "the", "primary", "key", "attributes", "are", "returned", ".", "Otherwise", "if", "there", "are", "secondary", "key", "attributes", "then", "they", "are", "returned", ".", "Otherwise", "if", "there", "are", "nondomain", "attributes", "then", "they", "are", "returned", ".", "Otherwise", "if", "there", "are", "fetched", "attributes", "then", "they", "are", "returned", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L824-L834
6,069
jinx/core
lib/jinx/resource.rb
Jinx.Resource.empty_value
def empty_value(attribute) type = java_type(attribute) || return if type.primitive? then type.name == 'boolean' ? false : 0 else self.class.empty_value(attribute) end end
ruby
def empty_value(attribute) type = java_type(attribute) || return if type.primitive? then type.name == 'boolean' ? false : 0 else self.class.empty_value(attribute) end end
[ "def", "empty_value", "(", "attribute", ")", "type", "=", "java_type", "(", "attribute", ")", "||", "return", "if", "type", ".", "primitive?", "then", "type", ".", "name", "==", "'boolean'", "?", "false", ":", "0", "else", "self", ".", "class", ".", "empty_value", "(", "attribute", ")", "end", "end" ]
Returns 0 if attribute is a Java primitive number, +false+ if attribute is a Java primitive boolean, an empty collectin if the Java attribute is a collection, nil otherwise.
[ "Returns", "0", "if", "attribute", "is", "a", "Java", "primitive", "number", "+", "false", "+", "if", "attribute", "is", "a", "Java", "primitive", "boolean", "an", "empty", "collectin", "if", "the", "Java", "attribute", "is", "a", "collection", "nil", "otherwise", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L872-L879
6,070
jinx/core
lib/jinx/resource.rb
Jinx.Resource.java_type
def java_type(attribute) prop = self.class.property(attribute) prop.property_descriptor.attribute_type if JavaProperty === prop end
ruby
def java_type(attribute) prop = self.class.property(attribute) prop.property_descriptor.attribute_type if JavaProperty === prop end
[ "def", "java_type", "(", "attribute", ")", "prop", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", "prop", ".", "property_descriptor", ".", "attribute_type", "if", "JavaProperty", "===", "prop", "end" ]
Returns the Java type of the given attribute, or nil if attribute is not a Java property attribute.
[ "Returns", "the", "Java", "type", "of", "the", "given", "attribute", "or", "nil", "if", "attribute", "is", "not", "a", "Java", "property", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L882-L885
6,071
jinx/core
lib/jinx/resource.rb
Jinx.Resource.match_unique_object_with_attributes
def match_unique_object_with_attributes(others, attributes) vh = value_hash(attributes) return if vh.empty? or vh.size < attributes.size matches = others.select do |other| self.class == other.class and vh.all? { |pa, v| other.matches_attribute_value?(pa, v) } end matches.first if matches.size == 1 end
ruby
def match_unique_object_with_attributes(others, attributes) vh = value_hash(attributes) return if vh.empty? or vh.size < attributes.size matches = others.select do |other| self.class == other.class and vh.all? { |pa, v| other.matches_attribute_value?(pa, v) } end matches.first if matches.size == 1 end
[ "def", "match_unique_object_with_attributes", "(", "others", ",", "attributes", ")", "vh", "=", "value_hash", "(", "attributes", ")", "return", "if", "vh", ".", "empty?", "or", "vh", ".", "size", "<", "attributes", ".", "size", "matches", "=", "others", ".", "select", "do", "|", "other", "|", "self", ".", "class", "==", "other", ".", "class", "and", "vh", ".", "all?", "{", "|", "pa", ",", "v", "|", "other", ".", "matches_attribute_value?", "(", "pa", ",", "v", ")", "}", "end", "matches", ".", "first", "if", "matches", ".", "size", "==", "1", "end" ]
Returns the object in others which uniquely matches this domain object on the given attributes, or nil if there is no unique match. This method returns nil if any attributes value is nil.
[ "Returns", "the", "object", "in", "others", "which", "uniquely", "matches", "this", "domain", "object", "on", "the", "given", "attributes", "or", "nil", "if", "there", "is", "no", "unique", "match", ".", "This", "method", "returns", "nil", "if", "any", "attributes", "value", "is", "nil", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L930-L938
6,072
jinx/core
lib/jinx/resource.rb
Jinx.Resource.non_id_search_attribute_values
def non_id_search_attribute_values # if there is a secondary key, then search on those attributes. # otherwise, search on all attributes. key_props = self.class.secondary_key_attributes pas = key_props.empty? ? self.class.nondomain_java_attributes : key_props # associate the values attr_values = pas.to_compact_hash { |pa| send(pa) } # if there is no secondary key, then cull empty values key_props.empty? ? attr_values.delete_if { |pa, value| value.nil? } : attr_values end
ruby
def non_id_search_attribute_values # if there is a secondary key, then search on those attributes. # otherwise, search on all attributes. key_props = self.class.secondary_key_attributes pas = key_props.empty? ? self.class.nondomain_java_attributes : key_props # associate the values attr_values = pas.to_compact_hash { |pa| send(pa) } # if there is no secondary key, then cull empty values key_props.empty? ? attr_values.delete_if { |pa, value| value.nil? } : attr_values end
[ "def", "non_id_search_attribute_values", "# if there is a secondary key, then search on those attributes.", "# otherwise, search on all attributes.", "key_props", "=", "self", ".", "class", ".", "secondary_key_attributes", "pas", "=", "key_props", ".", "empty?", "?", "self", ".", "class", ".", "nondomain_java_attributes", ":", "key_props", "# associate the values", "attr_values", "=", "pas", ".", "to_compact_hash", "{", "|", "pa", "|", "send", "(", "pa", ")", "}", "# if there is no secondary key, then cull empty values", "key_props", ".", "empty?", "?", "attr_values", ".", "delete_if", "{", "|", "pa", ",", "value", "|", "value", ".", "nil?", "}", ":", "attr_values", "end" ]
Returns the attribute => value hash to use for matching this domain object. @see #search_attribute_values the method specification
[ "Returns", "the", "attribute", "=", ">", "value", "hash", "to", "use", "for", "matching", "this", "domain", "object", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource.rb#L953-L962
6,073
barkerest/incline
lib/incline/extensions/action_controller_base.rb
Incline::Extensions.ActionControllerBase.render_csv
def render_csv(filename = nil, view_name = nil) filename ||= params[:action] view_name ||= params[:action] filename.downcase! filename += '.csv' unless filename[-4..-1] == '.csv' headers['Content-Type'] = 'text/csv' headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" render view_name, layout: false end
ruby
def render_csv(filename = nil, view_name = nil) filename ||= params[:action] view_name ||= params[:action] filename.downcase! filename += '.csv' unless filename[-4..-1] == '.csv' headers['Content-Type'] = 'text/csv' headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" render view_name, layout: false end
[ "def", "render_csv", "(", "filename", "=", "nil", ",", "view_name", "=", "nil", ")", "filename", "||=", "params", "[", ":action", "]", "view_name", "||=", "params", "[", ":action", "]", "filename", ".", "downcase!", "filename", "+=", "'.csv'", "unless", "filename", "[", "-", "4", "..", "-", "1", "]", "==", "'.csv'", "headers", "[", "'Content-Type'", "]", "=", "'text/csv'", "headers", "[", "'Content-Disposition'", "]", "=", "\"attachment; filename=\\\"#{filename}\\\"\"", "render", "view_name", ",", "layout", ":", "false", "end" ]
Renders the view as a CSV file. Set the +filename+ you would like to provide to the client, or leave it nil to use the action name. Set the +view_name+ you would like to render, or leave it nil to use the action name.
[ "Renders", "the", "view", "as", "a", "CSV", "file", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_controller_base.rb#L213-L224
6,074
barkerest/incline
lib/incline/extensions/action_controller_base.rb
Incline::Extensions.ActionControllerBase.authorize!
def authorize!(*accepted_groups) #:doc: begin # an authenticated user must exist. unless logged_in? store_location if (auth_url = ::Incline::UserManager.begin_external_authentication(request)) ::Incline::Log.debug 'Redirecting for external authentication.' redirect_to auth_url return false end raise_not_logged_in "You need to login to access '#{request.fullpath}'.", 'nobody is logged in' end if system_admin? log_authorize_success 'user is system admin' else # clean up the group list. accepted_groups ||= [] accepted_groups.flatten! accepted_groups.delete false accepted_groups.delete '' if accepted_groups.include?(true) # group_list contains "true" so only a system admin may continue. raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.", 'requires system administrator' elsif accepted_groups.blank? # group_list is empty or contained nothing but empty strings and boolean false. # everyone can continue. log_authorize_success 'only requires authenticated user' else # the group list contains one or more authorized groups. # we want them to all be uppercase strings. accepted_groups = accepted_groups.map{|v| v.to_s.upcase}.sort result = current_user.has_any_group?(*accepted_groups) unless result raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.", "requires one of: #{accepted_groups.inspect}" end log_authorize_success "user has #{result.inspect}" end end rescue ::Incline::NotAuthorized => err flash[:danger] = err.message redirect_to main_app.root_url return false end true end
ruby
def authorize!(*accepted_groups) #:doc: begin # an authenticated user must exist. unless logged_in? store_location if (auth_url = ::Incline::UserManager.begin_external_authentication(request)) ::Incline::Log.debug 'Redirecting for external authentication.' redirect_to auth_url return false end raise_not_logged_in "You need to login to access '#{request.fullpath}'.", 'nobody is logged in' end if system_admin? log_authorize_success 'user is system admin' else # clean up the group list. accepted_groups ||= [] accepted_groups.flatten! accepted_groups.delete false accepted_groups.delete '' if accepted_groups.include?(true) # group_list contains "true" so only a system admin may continue. raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.", 'requires system administrator' elsif accepted_groups.blank? # group_list is empty or contained nothing but empty strings and boolean false. # everyone can continue. log_authorize_success 'only requires authenticated user' else # the group list contains one or more authorized groups. # we want them to all be uppercase strings. accepted_groups = accepted_groups.map{|v| v.to_s.upcase}.sort result = current_user.has_any_group?(*accepted_groups) unless result raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.", "requires one of: #{accepted_groups.inspect}" end log_authorize_success "user has #{result.inspect}" end end rescue ::Incline::NotAuthorized => err flash[:danger] = err.message redirect_to main_app.root_url return false end true end
[ "def", "authorize!", "(", "*", "accepted_groups", ")", "#:doc:", "begin", "# an authenticated user must exist.", "unless", "logged_in?", "store_location", "if", "(", "auth_url", "=", "::", "Incline", "::", "UserManager", ".", "begin_external_authentication", "(", "request", ")", ")", "::", "Incline", "::", "Log", ".", "debug", "'Redirecting for external authentication.'", "redirect_to", "auth_url", "return", "false", "end", "raise_not_logged_in", "\"You need to login to access '#{request.fullpath}'.\"", ",", "'nobody is logged in'", "end", "if", "system_admin?", "log_authorize_success", "'user is system admin'", "else", "# clean up the group list.", "accepted_groups", "||=", "[", "]", "accepted_groups", ".", "flatten!", "accepted_groups", ".", "delete", "false", "accepted_groups", ".", "delete", "''", "if", "accepted_groups", ".", "include?", "(", "true", ")", "# group_list contains \"true\" so only a system admin may continue.", "raise_authorize_failure", "\"Your are not authorized to access '#{request.fullpath}'.\"", ",", "'requires system administrator'", "elsif", "accepted_groups", ".", "blank?", "# group_list is empty or contained nothing but empty strings and boolean false.", "# everyone can continue.", "log_authorize_success", "'only requires authenticated user'", "else", "# the group list contains one or more authorized groups.", "# we want them to all be uppercase strings.", "accepted_groups", "=", "accepted_groups", ".", "map", "{", "|", "v", "|", "v", ".", "to_s", ".", "upcase", "}", ".", "sort", "result", "=", "current_user", ".", "has_any_group?", "(", "accepted_groups", ")", "unless", "result", "raise_authorize_failure", "\"You are not authorized to access '#{request.fullpath}'.\"", ",", "\"requires one of: #{accepted_groups.inspect}\"", "end", "log_authorize_success", "\"user has #{result.inspect}\"", "end", "end", "rescue", "::", "Incline", "::", "NotAuthorized", "=>", "err", "flash", "[", ":danger", "]", "=", "err", ".", "message", "redirect_to", "main_app", ".", "root_url", "return", "false", "end", "true", "end" ]
Authorizes access for the action. * With no arguments, this will validate that a user is currently logged in, but does not check their permission. * With an argument of true, this will validate that the user currently logged in is an administrator. * With one or more strings, this will validate that the user currently logged in has at least one or more of the named permissions. authorize! authorize! true authorize! "Safety Manager", "HR Manager" If no user is logged in, then the user will be redirected to the login page and the method will return false. If a user is logged in, but is not authorized, then the user will be redirected to the home page and the method will return false. If the user is authorized, the method will return true.
[ "Authorizes", "access", "for", "the", "action", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_controller_base.rb#L282-L339
6,075
barkerest/incline
lib/incline/extensions/action_controller_base.rb
Incline::Extensions.ActionControllerBase.valid_user?
def valid_user? #:doc: if require_admin_for_request? authorize! true elsif require_anon_for_request? if logged_in? flash[:warning] = 'The specified action cannot be performed while logged in.' redirect_to incline.user_path(current_user) end elsif allow_anon_for_request? true else action = Incline::ActionSecurity.valid_items[self.class.controller_path, params[:action]] if action && action.groups.count > 0 authorize! action.groups.pluck(:name) else authorize! end end end
ruby
def valid_user? #:doc: if require_admin_for_request? authorize! true elsif require_anon_for_request? if logged_in? flash[:warning] = 'The specified action cannot be performed while logged in.' redirect_to incline.user_path(current_user) end elsif allow_anon_for_request? true else action = Incline::ActionSecurity.valid_items[self.class.controller_path, params[:action]] if action && action.groups.count > 0 authorize! action.groups.pluck(:name) else authorize! end end end
[ "def", "valid_user?", "#:doc:", "if", "require_admin_for_request?", "authorize!", "true", "elsif", "require_anon_for_request?", "if", "logged_in?", "flash", "[", ":warning", "]", "=", "'The specified action cannot be performed while logged in.'", "redirect_to", "incline", ".", "user_path", "(", "current_user", ")", "end", "elsif", "allow_anon_for_request?", "true", "else", "action", "=", "Incline", "::", "ActionSecurity", ".", "valid_items", "[", "self", ".", "class", ".", "controller_path", ",", "params", "[", ":action", "]", "]", "if", "action", "&&", "action", ".", "groups", ".", "count", ">", "0", "authorize!", "action", ".", "groups", ".", "pluck", "(", ":name", ")", "else", "authorize!", "end", "end", "end" ]
Validates that the current user is authorized for the current request. This method is called for every action except the :api action. For the :api action, this method will not be called until the actual requested action is performed. One of four scenarios are possible: 1. If the +require_admin+ method applies to the current action, then a system administrator must be logged in. 1. If a nobody is logged in, then the user will be redirected to the login url. 2. If a system administrator is logged in, then access is granted. 3. Non-system administrators will be redirected to the root url. 2. If the +require_anon+ method applies to the current action, then a user cannot be logged in. 1. If a user is logged in, a warning message is set and the user is redirected to their account. 2. If no user is logged in, then access is granted. 3. If the +allow_anon+ method applies to the current action, then access is granted. 4. The action doesn't require a system administrator, but does require a valid user to be logged in. 1. If nobody is logged in, then the user will be redirected to the login url. 2. If a system administrator is logged in, then access is granted. 3. If the action doesn't have any required permissions, then access is granted to any logged in user. 4. If the action has required permissions and the logged in user shares at least one, then access is granted. 5. Users without at least one required permission are redirected to the root url. Two of the scenarios are configured at design time. If you use +require_admin+ or +allow_anon+, they cannot be changed at runtime. The idea is that anything that allows anonymous access will always allow anonymous access during runtime and anything that requires admin access will always require admin access during runtime. The third scenario is what would be used by most actions. Using the +admin+ controller, which requires admin access, you can customize the permissions required for each available route. Using the +users+ controller, admins can assign permissions to other users.
[ "Validates", "that", "the", "current", "user", "is", "authorized", "for", "the", "current", "request", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_controller_base.rb#L426-L444
6,076
masaomoc/aws-profile_parser
lib/aws/profile_parser.rb
AWS.ProfileParser.get
def get(profile='default') raise 'Config File does not exist' unless File.exists?(@file) @credentials = parse if @credentials.nil? raise 'The profile is not specified in the config file' unless @credentials.has_key?(profile) @credentials[profile] end
ruby
def get(profile='default') raise 'Config File does not exist' unless File.exists?(@file) @credentials = parse if @credentials.nil? raise 'The profile is not specified in the config file' unless @credentials.has_key?(profile) @credentials[profile] end
[ "def", "get", "(", "profile", "=", "'default'", ")", "raise", "'Config File does not exist'", "unless", "File", ".", "exists?", "(", "@file", ")", "@credentials", "=", "parse", "if", "@credentials", ".", "nil?", "raise", "'The profile is not specified in the config file'", "unless", "@credentials", ".", "has_key?", "(", "profile", ")", "@credentials", "[", "profile", "]", "end" ]
returns hash of AWS credential
[ "returns", "hash", "of", "AWS", "credential" ]
b45725b5497864e2f5de2457ae6b7ed0dabe94fa
https://github.com/masaomoc/aws-profile_parser/blob/b45725b5497864e2f5de2457ae6b7ed0dabe94fa/lib/aws/profile_parser.rb#L12-L19
6,077
detroit/detroit-gem
lib/detroit-gem.rb
Detroit.Gem.build
def build trace "gem build #{gemspec}" spec = load_gemspec package = ::Gem::Package.build(spec) mkdir_p(pkgdir) unless File.directory?(pkgdir) mv(package, pkgdir) end
ruby
def build trace "gem build #{gemspec}" spec = load_gemspec package = ::Gem::Package.build(spec) mkdir_p(pkgdir) unless File.directory?(pkgdir) mv(package, pkgdir) end
[ "def", "build", "trace", "\"gem build #{gemspec}\"", "spec", "=", "load_gemspec", "package", "=", "::", "Gem", "::", "Package", ".", "build", "(", "spec", ")", "mkdir_p", "(", "pkgdir", ")", "unless", "File", ".", "directory?", "(", "pkgdir", ")", "mv", "(", "package", ",", "pkgdir", ")", "end" ]
Create a gem package.
[ "Create", "a", "gem", "package", "." ]
3a018942038c430f3fdc73ed5c40783c8f0a7c8b
https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L72-L78
6,078
detroit/detroit-gem
lib/detroit-gem.rb
Detroit.Gem.create_gemspec
def create_gemspec(file=nil) file = gemspec if !file #require 'gemdo/gemspec' yaml = project.to_gemspec.to_yaml File.open(file, 'w') do |f| f << yaml end status File.basename(file) + " updated." return file end
ruby
def create_gemspec(file=nil) file = gemspec if !file #require 'gemdo/gemspec' yaml = project.to_gemspec.to_yaml File.open(file, 'w') do |f| f << yaml end status File.basename(file) + " updated." return file end
[ "def", "create_gemspec", "(", "file", "=", "nil", ")", "file", "=", "gemspec", "if", "!", "file", "#require 'gemdo/gemspec'", "yaml", "=", "project", ".", "to_gemspec", ".", "to_yaml", "File", ".", "open", "(", "file", ",", "'w'", ")", "do", "|", "f", "|", "f", "<<", "yaml", "end", "status", "File", ".", "basename", "(", "file", ")", "+", "\" updated.\"", "return", "file", "end" ]
Create a gemspec file from project metadata.
[ "Create", "a", "gemspec", "file", "from", "project", "metadata", "." ]
3a018942038c430f3fdc73ed5c40783c8f0a7c8b
https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L171-L180
6,079
detroit/detroit-gem
lib/detroit-gem.rb
Detroit.Gem.lookup_gemspec
def lookup_gemspec dot_gemspec = (project.root + '.gemspec').to_s if File.exist?(dot_gemspec) dot_gemspec.to_s else project.metadata.name + '.gemspec' end end
ruby
def lookup_gemspec dot_gemspec = (project.root + '.gemspec').to_s if File.exist?(dot_gemspec) dot_gemspec.to_s else project.metadata.name + '.gemspec' end end
[ "def", "lookup_gemspec", "dot_gemspec", "=", "(", "project", ".", "root", "+", "'.gemspec'", ")", ".", "to_s", "if", "File", ".", "exist?", "(", "dot_gemspec", ")", "dot_gemspec", ".", "to_s", "else", "project", ".", "metadata", ".", "name", "+", "'.gemspec'", "end", "end" ]
Lookup gemspec file. If not found returns default path. Returns String of file path.
[ "Lookup", "gemspec", "file", ".", "If", "not", "found", "returns", "default", "path", "." ]
3a018942038c430f3fdc73ed5c40783c8f0a7c8b
https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L185-L192
6,080
detroit/detroit-gem
lib/detroit-gem.rb
Detroit.Gem.load_gemspec
def load_gemspec file = gemspec if yaml?(file) ::Gem::Specification.from_yaml(File.new(file)) else ::Gem::Specification.load(file) end end
ruby
def load_gemspec file = gemspec if yaml?(file) ::Gem::Specification.from_yaml(File.new(file)) else ::Gem::Specification.load(file) end end
[ "def", "load_gemspec", "file", "=", "gemspec", "if", "yaml?", "(", "file", ")", "::", "Gem", "::", "Specification", ".", "from_yaml", "(", "File", ".", "new", "(", "file", ")", ")", "else", "::", "Gem", "::", "Specification", ".", "load", "(", "file", ")", "end", "end" ]
Load gemspec file. Returns a ::Gem::Specification.
[ "Load", "gemspec", "file", "." ]
3a018942038c430f3fdc73ed5c40783c8f0a7c8b
https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L197-L204
6,081
detroit/detroit-gem
lib/detroit-gem.rb
Detroit.Gem.yaml?
def yaml?(file) line = open(file) { |f| line = f.gets } line.index "!ruby/object:Gem::Specification" end
ruby
def yaml?(file) line = open(file) { |f| line = f.gets } line.index "!ruby/object:Gem::Specification" end
[ "def", "yaml?", "(", "file", ")", "line", "=", "open", "(", "file", ")", "{", "|", "f", "|", "line", "=", "f", ".", "gets", "}", "line", ".", "index", "\"!ruby/object:Gem::Specification\"", "end" ]
If the gemspec a YAML gemspec?
[ "If", "the", "gemspec", "a", "YAML", "gemspec?" ]
3a018942038c430f3fdc73ed5c40783c8f0a7c8b
https://github.com/detroit/detroit-gem/blob/3a018942038c430f3fdc73ed5c40783c8f0a7c8b/lib/detroit-gem.rb#L207-L210
6,082
Thermatix/ruta
lib/ruta/handler.rb
Ruta.Handlers.default
def default handler_name = @handler_name proc { comp = @context.elements[handler_name][:content] if comp.kind_of?(Proc) comp.call else Context.wipe handler_name Context.render comp, handler_name end } end
ruby
def default handler_name = @handler_name proc { comp = @context.elements[handler_name][:content] if comp.kind_of?(Proc) comp.call else Context.wipe handler_name Context.render comp, handler_name end } end
[ "def", "default", "handler_name", "=", "@handler_name", "proc", "{", "comp", "=", "@context", ".", "elements", "[", "handler_name", "]", "[", ":content", "]", "if", "comp", ".", "kind_of?", "(", "Proc", ")", "comp", ".", "call", "else", "Context", ".", "wipe", "handler_name", "Context", ".", "render", "comp", ",", "handler_name", "end", "}", "end" ]
Render the default content for this component as it is defined in the context.
[ "Render", "the", "default", "content", "for", "this", "component", "as", "it", "is", "defined", "in", "the", "context", "." ]
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/handler.rb#L35-L46
6,083
lulibrary/aspire
lib/retry.rb
Retry.Engine.do
def do(delay: nil, exceptions: nil, handlers: nil, tries: nil, &block) Retry.do(delay: delay || self.delay, exceptions: exceptions || self.exceptions, handlers: handlers || self.handlers, tries: tries || self.tries, &block) end
ruby
def do(delay: nil, exceptions: nil, handlers: nil, tries: nil, &block) Retry.do(delay: delay || self.delay, exceptions: exceptions || self.exceptions, handlers: handlers || self.handlers, tries: tries || self.tries, &block) end
[ "def", "do", "(", "delay", ":", "nil", ",", "exceptions", ":", "nil", ",", "handlers", ":", "nil", ",", "tries", ":", "nil", ",", "&", "block", ")", "Retry", ".", "do", "(", "delay", ":", "delay", "||", "self", ".", "delay", ",", "exceptions", ":", "exceptions", "||", "self", ".", "exceptions", ",", "handlers", ":", "handlers", "||", "self", ".", "handlers", ",", "tries", ":", "tries", "||", "self", ".", "tries", ",", "block", ")", "end" ]
Initialises a new Engine instance @param delay [Float] the default delay before retrying @param exceptions [Hash<Exception, Boolean>] the default retriable exceptions @param handlers [Hash<Exception|Symbol, Proc>] the default exception handlers @param tries [Integer, Proc] the default maximum number of tries or a proc which accepts an Exception and returns true if a retry is allowed or false if not @return [void] Executes the class method do using instance default values
[ "Initialises", "a", "new", "Engine", "instance" ]
623f481a2e79b9cb0b5feb923da438eb1ed2abfe
https://github.com/lulibrary/aspire/blob/623f481a2e79b9cb0b5feb923da438eb1ed2abfe/lib/retry.rb#L53-L59
6,084
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.fmod_with_float
def fmod_with_float( other ) other = Node.match( other, typecode ).new other unless other.matched? if typecode < FLOAT_ or other.typecode < FLOAT_ fmod other else fmod_without_float other end end
ruby
def fmod_with_float( other ) other = Node.match( other, typecode ).new other unless other.matched? if typecode < FLOAT_ or other.typecode < FLOAT_ fmod other else fmod_without_float other end end
[ "def", "fmod_with_float", "(", "other", ")", "other", "=", "Node", ".", "match", "(", "other", ",", "typecode", ")", ".", "new", "other", "unless", "other", ".", "matched?", "if", "typecode", "<", "FLOAT_", "or", "other", ".", "typecode", "<", "FLOAT_", "fmod", "other", "else", "fmod_without_float", "other", "end", "end" ]
Modulo operation for floating point numbers This operation takes account of the problem that '%' does not work with floating-point numbers in C. @return [Node] Array with result of operation.
[ "Modulo", "operation", "for", "floating", "point", "numbers" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L122-L129
6,085
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.to_type
def to_type(dest) if dimension == 0 and variables.empty? target = typecode.to_type dest target.new(simplify.get).simplify else key = "to_#{dest.to_s.downcase}" Hornetseye::ElementWise( proc { |x| x.to_type dest }, key, proc { |t| t.to_type dest } ).new(self).force end end
ruby
def to_type(dest) if dimension == 0 and variables.empty? target = typecode.to_type dest target.new(simplify.get).simplify else key = "to_#{dest.to_s.downcase}" Hornetseye::ElementWise( proc { |x| x.to_type dest }, key, proc { |t| t.to_type dest } ).new(self).force end end
[ "def", "to_type", "(", "dest", ")", "if", "dimension", "==", "0", "and", "variables", ".", "empty?", "target", "=", "typecode", ".", "to_type", "dest", "target", ".", "new", "(", "simplify", ".", "get", ")", ".", "simplify", "else", "key", "=", "\"to_#{dest.to_s.downcase}\"", "Hornetseye", "::", "ElementWise", "(", "proc", "{", "|", "x", "|", "x", ".", "to_type", "dest", "}", ",", "key", ",", "proc", "{", "|", "t", "|", "t", ".", "to_type", "dest", "}", ")", ".", "new", "(", "self", ")", ".", "force", "end", "end" ]
Convert array elements to different element type @param [Class] dest Element type to convert to. @return [Node] Array based on the different element type.
[ "Convert", "array", "elements", "to", "different", "element", "type" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L138-L147
6,086
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.to_type_with_rgb
def to_type_with_rgb(dest) if typecode < RGB_ if dest < FLOAT_ lazy { r * 0.299 + g * 0.587 + b * 0.114 }.to_type dest elsif dest < INT_ lazy { (r * 0.299 + g * 0.587 + b * 0.114).round }.to_type dest else to_type_without_rgb dest end else to_type_without_rgb dest end end
ruby
def to_type_with_rgb(dest) if typecode < RGB_ if dest < FLOAT_ lazy { r * 0.299 + g * 0.587 + b * 0.114 }.to_type dest elsif dest < INT_ lazy { (r * 0.299 + g * 0.587 + b * 0.114).round }.to_type dest else to_type_without_rgb dest end else to_type_without_rgb dest end end
[ "def", "to_type_with_rgb", "(", "dest", ")", "if", "typecode", "<", "RGB_", "if", "dest", "<", "FLOAT_", "lazy", "{", "r", "*", "0.299", "+", "g", "*", "0.587", "+", "b", "*", "0.114", "}", ".", "to_type", "dest", "elsif", "dest", "<", "INT_", "lazy", "{", "(", "r", "*", "0.299", "+", "g", "*", "0.587", "+", "b", "*", "0.114", ")", ".", "round", "}", ".", "to_type", "dest", "else", "to_type_without_rgb", "dest", "end", "else", "to_type_without_rgb", "dest", "end", "end" ]
Convert RGB array to scalar array This operation is a special case handling colour to greyscale conversion. @param [Class] dest Element type to convert to. @return [Node] Array based on the different element type.
[ "Convert", "RGB", "array", "to", "scalar", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L156-L168
6,087
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.reshape
def reshape(*ret_shape) target_size = ret_shape.inject 1, :* if target_size != size raise "Target is of size #{target_size} but should be of size #{size}" end Hornetseye::MultiArray(typecode, ret_shape.size). new *(ret_shape + [:memory => memorise.memory]) end
ruby
def reshape(*ret_shape) target_size = ret_shape.inject 1, :* if target_size != size raise "Target is of size #{target_size} but should be of size #{size}" end Hornetseye::MultiArray(typecode, ret_shape.size). new *(ret_shape + [:memory => memorise.memory]) end
[ "def", "reshape", "(", "*", "ret_shape", ")", "target_size", "=", "ret_shape", ".", "inject", "1", ",", ":*", "if", "target_size", "!=", "size", "raise", "\"Target is of size #{target_size} but should be of size #{size}\"", "end", "Hornetseye", "::", "MultiArray", "(", "typecode", ",", "ret_shape", ".", "size", ")", ".", "new", "(", "ret_shape", "+", "[", ":memory", "=>", "memorise", ".", "memory", "]", ")", "end" ]
Get array with same elements but different shape The method returns an array with the same elements but with a different shape. The desired shape must have the same number of elements. @param [Array<Integer>] ret_shape Desired shape of return value @return [Node] Array with desired shape.
[ "Get", "array", "with", "same", "elements", "but", "different", "shape" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L197-L204
6,088
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.conditional
def conditional(a, b) a = Node.match(a, b.matched? ? b : nil).new a unless a.matched? b = Node.match(b, a.matched? ? a : nil).new b unless b.matched? if dimension == 0 and variables.empty? and a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = typecode.cond a.typecode, b.typecode target.new simplify.get.conditional(proc { a.simplify.get }, proc { b.simplify.get }) else Hornetseye::ElementWise(proc { |x,y,z| x.conditional y, z }, :conditional, proc { |t,u,v| t.cond u, v }). new(self, a, b).force end end
ruby
def conditional(a, b) a = Node.match(a, b.matched? ? b : nil).new a unless a.matched? b = Node.match(b, a.matched? ? a : nil).new b unless b.matched? if dimension == 0 and variables.empty? and a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = typecode.cond a.typecode, b.typecode target.new simplify.get.conditional(proc { a.simplify.get }, proc { b.simplify.get }) else Hornetseye::ElementWise(proc { |x,y,z| x.conditional y, z }, :conditional, proc { |t,u,v| t.cond u, v }). new(self, a, b).force end end
[ "def", "conditional", "(", "a", ",", "b", ")", "a", "=", "Node", ".", "match", "(", "a", ",", "b", ".", "matched?", "?", "b", ":", "nil", ")", ".", "new", "a", "unless", "a", ".", "matched?", "b", "=", "Node", ".", "match", "(", "b", ",", "a", ".", "matched?", "?", "a", ":", "nil", ")", ".", "new", "b", "unless", "b", ".", "matched?", "if", "dimension", "==", "0", "and", "variables", ".", "empty?", "and", "a", ".", "dimension", "==", "0", "and", "a", ".", "variables", ".", "empty?", "and", "b", ".", "dimension", "==", "0", "and", "b", ".", "variables", ".", "empty?", "target", "=", "typecode", ".", "cond", "a", ".", "typecode", ",", "b", ".", "typecode", "target", ".", "new", "simplify", ".", "get", ".", "conditional", "(", "proc", "{", "a", ".", "simplify", ".", "get", "}", ",", "proc", "{", "b", ".", "simplify", ".", "get", "}", ")", "else", "Hornetseye", "::", "ElementWise", "(", "proc", "{", "|", "x", ",", "y", ",", "z", "|", "x", ".", "conditional", "y", ",", "z", "}", ",", ":conditional", ",", "proc", "{", "|", "t", ",", "u", ",", "v", "|", "t", ".", "cond", "u", ",", "v", "}", ")", ".", "new", "(", "self", ",", "a", ",", "b", ")", ".", "force", "end", "end" ]
Element-wise conditional selection of values @param [Node] a First array of values. @param [Node] b Second array of values. @return [Node] Array with selected values.
[ "Element", "-", "wise", "conditional", "selection", "of", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L212-L226
6,089
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.transpose
def transpose(*order) if (0 ... dimension).to_a != order.sort raise 'Each array index must be specified exactly once!' end term = self variables = shape.reverse.collect do |i| var = Variable.new Hornetseye::INDEX( i ) term = term.element var var end.reverse order.collect { |o| variables[o] }. inject(term) { |retval,var| Lambda.new var, retval } end
ruby
def transpose(*order) if (0 ... dimension).to_a != order.sort raise 'Each array index must be specified exactly once!' end term = self variables = shape.reverse.collect do |i| var = Variable.new Hornetseye::INDEX( i ) term = term.element var var end.reverse order.collect { |o| variables[o] }. inject(term) { |retval,var| Lambda.new var, retval } end
[ "def", "transpose", "(", "*", "order", ")", "if", "(", "0", "...", "dimension", ")", ".", "to_a", "!=", "order", ".", "sort", "raise", "'Each array index must be specified exactly once!'", "end", "term", "=", "self", "variables", "=", "shape", ".", "reverse", ".", "collect", "do", "|", "i", "|", "var", "=", "Variable", ".", "new", "Hornetseye", "::", "INDEX", "(", "i", ")", "term", "=", "term", ".", "element", "var", "var", "end", ".", "reverse", "order", ".", "collect", "{", "|", "o", "|", "variables", "[", "o", "]", "}", ".", "inject", "(", "term", ")", "{", "|", "retval", ",", "var", "|", "Lambda", ".", "new", "var", ",", "retval", "}", "end" ]
Element-wise comparison of values @param [Node] other Array with values to compare with. @return [Node] Array with results. Lazy transpose of array Lazily compute transpose by swapping indices according to the specified order. @param [Array<Integer>] order New order of indices. @return [Node] Returns the transposed array.
[ "Element", "-", "wise", "comparison", "of", "values" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L275-L287
6,090
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.unroll
def unroll( n = 1 ) if n < 0 roll -n else order = ( 0 ... dimension ).to_a n.times { order = [ order.last ] + order[ 0 ... -1 ] } transpose *order end end
ruby
def unroll( n = 1 ) if n < 0 roll -n else order = ( 0 ... dimension ).to_a n.times { order = [ order.last ] + order[ 0 ... -1 ] } transpose *order end end
[ "def", "unroll", "(", "n", "=", "1", ")", "if", "n", "<", "0", "roll", "-", "n", "else", "order", "=", "(", "0", "...", "dimension", ")", ".", "to_a", "n", ".", "times", "{", "order", "=", "[", "order", ".", "last", "]", "+", "order", "[", "0", "...", "-", "1", "]", "}", "transpose", "order", "end", "end" ]
Reverse-cycle indices of array @param [Integer] n Number of times to cycle back indices of array. @return [Node] Resulting array expression with different order of indices.
[ "Reverse", "-", "cycle", "indices", "of", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L309-L317
6,091
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.collect
def collect(&action) var = Variable.new typecode block = action.call var conversion = proc { |t| t.to_type action.call(Variable.new(t.typecode)).typecode } Hornetseye::ElementWise( action, block.to_s, conversion ).new( self ).force end
ruby
def collect(&action) var = Variable.new typecode block = action.call var conversion = proc { |t| t.to_type action.call(Variable.new(t.typecode)).typecode } Hornetseye::ElementWise( action, block.to_s, conversion ).new( self ).force end
[ "def", "collect", "(", "&", "action", ")", "var", "=", "Variable", ".", "new", "typecode", "block", "=", "action", ".", "call", "var", "conversion", "=", "proc", "{", "|", "t", "|", "t", ".", "to_type", "action", ".", "call", "(", "Variable", ".", "new", "(", "t", ".", "typecode", ")", ")", ".", "typecode", "}", "Hornetseye", "::", "ElementWise", "(", "action", ",", "block", ".", "to_s", ",", "conversion", ")", ".", "new", "(", "self", ")", ".", "force", "end" ]
Perform element-wise operation on array @param [Proc] action Operation(s) to perform on elements. @return [Node] The resulting array.
[ "Perform", "element", "-", "wise", "operation", "on", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L324-L329
6,092
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.inject
def inject(*args, &action) options = args.last.is_a?(Hash) ? args.pop : {} unless action or options[:block] unless [1, 2].member? args.size raise "Inject expected 1 or 2 arguments but got #{args.size}" end initial, symbol = args[-2], args[-1] action = proc { |a,b| a.send symbol, b } else raise "Inject expected 0 or 1 arguments but got #{args.size}" if args.size > 1 initial = args.empty? ? nil : args.first end unless initial.nil? initial = Node.match( initial ).new initial unless initial.matched? initial_typecode = initial.typecode else initial_typecode = typecode end var1 = options[ :var1 ] || Variable.new( initial_typecode ) var2 = options[ :var2 ] || Variable.new( typecode ) block = options[ :block ] || action.call( var1, var2 ) if dimension == 0 if initial block.subst(var1 => initial, var2 => self).simplify else demand end else index = Variable.new Hornetseye::INDEX( nil ) value = element( index ).inject nil, :block => block, :var1 => var1, :var2 => var2 value = typecode.new value unless value.matched? if initial.nil? and index.size.get == 0 raise "Array was empty and no initial value for injection was given" end Inject.new( value, index, initial, block, var1, var2 ).force end end
ruby
def inject(*args, &action) options = args.last.is_a?(Hash) ? args.pop : {} unless action or options[:block] unless [1, 2].member? args.size raise "Inject expected 1 or 2 arguments but got #{args.size}" end initial, symbol = args[-2], args[-1] action = proc { |a,b| a.send symbol, b } else raise "Inject expected 0 or 1 arguments but got #{args.size}" if args.size > 1 initial = args.empty? ? nil : args.first end unless initial.nil? initial = Node.match( initial ).new initial unless initial.matched? initial_typecode = initial.typecode else initial_typecode = typecode end var1 = options[ :var1 ] || Variable.new( initial_typecode ) var2 = options[ :var2 ] || Variable.new( typecode ) block = options[ :block ] || action.call( var1, var2 ) if dimension == 0 if initial block.subst(var1 => initial, var2 => self).simplify else demand end else index = Variable.new Hornetseye::INDEX( nil ) value = element( index ).inject nil, :block => block, :var1 => var1, :var2 => var2 value = typecode.new value unless value.matched? if initial.nil? and index.size.get == 0 raise "Array was empty and no initial value for injection was given" end Inject.new( value, index, initial, block, var1, var2 ).force end end
[ "def", "inject", "(", "*", "args", ",", "&", "action", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "unless", "action", "or", "options", "[", ":block", "]", "unless", "[", "1", ",", "2", "]", ".", "member?", "args", ".", "size", "raise", "\"Inject expected 1 or 2 arguments but got #{args.size}\"", "end", "initial", ",", "symbol", "=", "args", "[", "-", "2", "]", ",", "args", "[", "-", "1", "]", "action", "=", "proc", "{", "|", "a", ",", "b", "|", "a", ".", "send", "symbol", ",", "b", "}", "else", "raise", "\"Inject expected 0 or 1 arguments but got #{args.size}\"", "if", "args", ".", "size", ">", "1", "initial", "=", "args", ".", "empty?", "?", "nil", ":", "args", ".", "first", "end", "unless", "initial", ".", "nil?", "initial", "=", "Node", ".", "match", "(", "initial", ")", ".", "new", "initial", "unless", "initial", ".", "matched?", "initial_typecode", "=", "initial", ".", "typecode", "else", "initial_typecode", "=", "typecode", "end", "var1", "=", "options", "[", ":var1", "]", "||", "Variable", ".", "new", "(", "initial_typecode", ")", "var2", "=", "options", "[", ":var2", "]", "||", "Variable", ".", "new", "(", "typecode", ")", "block", "=", "options", "[", ":block", "]", "||", "action", ".", "call", "(", "var1", ",", "var2", ")", "if", "dimension", "==", "0", "if", "initial", "block", ".", "subst", "(", "var1", "=>", "initial", ",", "var2", "=>", "self", ")", ".", "simplify", "else", "demand", "end", "else", "index", "=", "Variable", ".", "new", "Hornetseye", "::", "INDEX", "(", "nil", ")", "value", "=", "element", "(", "index", ")", ".", "inject", "nil", ",", ":block", "=>", "block", ",", ":var1", "=>", "var1", ",", ":var2", "=>", "var2", "value", "=", "typecode", ".", "new", "value", "unless", "value", ".", "matched?", "if", "initial", ".", "nil?", "and", "index", ".", "size", ".", "get", "==", "0", "raise", "\"Array was empty and no initial value for injection was given\"", "end", "Inject", ".", "new", "(", "value", ",", "index", ",", "initial", ",", "block", ",", "var1", ",", "var2", ")", ".", "force", "end", "end" ]
Perform cummulative operation on array @overload inject(initial = nil, options = {}, &action) @param [Object] initial Initial value for cummulative operation. @option options [Variable] :var1 First variable defining operation. @option options [Variable] :var1 Second variable defining operation. @option options [Variable] :block (action.call(var1, var2)) The operation to apply. @overload inject(initial = nil, symbol) @param [Object] initial Initial value for cummulative operation. @param [Symbol,String] symbol The operation to apply. @return [Object] Result of injection.
[ "Perform", "cummulative", "operation", "on", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L351-L388
6,093
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.range
def range( initial = nil ) min( initial ? initial.min : nil ) .. max( initial ? initial.max : nil ) end
ruby
def range( initial = nil ) min( initial ? initial.min : nil ) .. max( initial ? initial.max : nil ) end
[ "def", "range", "(", "initial", "=", "nil", ")", "min", "(", "initial", "?", "initial", ".", "min", ":", "nil", ")", "..", "max", "(", "initial", "?", "initial", ".", "max", ":", "nil", ")", "end" ]
Find range of values of array @return [Object] Range of values of array.
[ "Find", "range", "of", "values", "of", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L461-L463
6,094
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.normalise
def normalise( range = 0 .. 0xFF ) if range.exclude_end? raise "Normalisation does not support ranges with end value " + "excluded (such as #{range})" end lower, upper = min, max if lower.is_a? RGB or upper.is_a? RGB current = [ lower.r, lower.g, lower.b ].min .. [ upper.r, upper.g, upper.b ].max else current = min .. max end if current.last != current.first factor = ( range.last - range.first ).to_f / ( current.last - current.first ) collect { |x| x * factor + ( range.first - current.first * factor ) } else self + ( range.first - current.first ) end end
ruby
def normalise( range = 0 .. 0xFF ) if range.exclude_end? raise "Normalisation does not support ranges with end value " + "excluded (such as #{range})" end lower, upper = min, max if lower.is_a? RGB or upper.is_a? RGB current = [ lower.r, lower.g, lower.b ].min .. [ upper.r, upper.g, upper.b ].max else current = min .. max end if current.last != current.first factor = ( range.last - range.first ).to_f / ( current.last - current.first ) collect { |x| x * factor + ( range.first - current.first * factor ) } else self + ( range.first - current.first ) end end
[ "def", "normalise", "(", "range", "=", "0", "..", "0xFF", ")", "if", "range", ".", "exclude_end?", "raise", "\"Normalisation does not support ranges with end value \"", "+", "\"excluded (such as #{range})\"", "end", "lower", ",", "upper", "=", "min", ",", "max", "if", "lower", ".", "is_a?", "RGB", "or", "upper", ".", "is_a?", "RGB", "current", "=", "[", "lower", ".", "r", ",", "lower", ".", "g", ",", "lower", ".", "b", "]", ".", "min", "..", "[", "upper", ".", "r", ",", "upper", ".", "g", ",", "upper", ".", "b", "]", ".", "max", "else", "current", "=", "min", "..", "max", "end", "if", "current", ".", "last", "!=", "current", ".", "first", "factor", "=", "(", "range", ".", "last", "-", "range", ".", "first", ")", ".", "to_f", "/", "(", "current", ".", "last", "-", "current", ".", "first", ")", "collect", "{", "|", "x", "|", "x", "*", "factor", "+", "(", "range", ".", "first", "-", "current", ".", "first", "*", "factor", ")", "}", "else", "self", "+", "(", "range", ".", "first", "-", "current", ".", "first", ")", "end", "end" ]
Check values against boundaries @return [Node] Boolean array with result. Normalise values of array @param [Range] range Target range of normalisation. @return [Node] Array with normalised values.
[ "Check", "values", "against", "boundaries" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L477-L496
6,095
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.clip
def clip( range = 0 .. 0xFF ) if range.exclude_end? raise "Clipping does not support ranges with end value " + "excluded (such as #{range})" end collect { |x| x.major( range.begin ).minor range.end } end
ruby
def clip( range = 0 .. 0xFF ) if range.exclude_end? raise "Clipping does not support ranges with end value " + "excluded (such as #{range})" end collect { |x| x.major( range.begin ).minor range.end } end
[ "def", "clip", "(", "range", "=", "0", "..", "0xFF", ")", "if", "range", ".", "exclude_end?", "raise", "\"Clipping does not support ranges with end value \"", "+", "\"excluded (such as #{range})\"", "end", "collect", "{", "|", "x", "|", "x", ".", "major", "(", "range", ".", "begin", ")", ".", "minor", "range", ".", "end", "}", "end" ]
Clip values to specified range @param [Range] range Allowed range of values. @return [Node] Array with clipped values.
[ "Clip", "values", "to", "specified", "range" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L503-L509
6,096
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.stretch
def stretch(from = 0 .. 0xFF, to = 0 .. 0xFF) if from.exclude_end? raise "Stretching does not support ranges with end value " + "excluded (such as #{from})" end if to.exclude_end? raise "Stretching does not support ranges with end value " + "excluded (such as #{to})" end if from.last != from.first factor = (to.last - to.first).to_f / (from.last - from.first) collect { |x| ((x - from.first) * factor).major(to.first).minor to.last } else (self <= from.first).conditional to.first, to.last end end
ruby
def stretch(from = 0 .. 0xFF, to = 0 .. 0xFF) if from.exclude_end? raise "Stretching does not support ranges with end value " + "excluded (such as #{from})" end if to.exclude_end? raise "Stretching does not support ranges with end value " + "excluded (such as #{to})" end if from.last != from.first factor = (to.last - to.first).to_f / (from.last - from.first) collect { |x| ((x - from.first) * factor).major(to.first).minor to.last } else (self <= from.first).conditional to.first, to.last end end
[ "def", "stretch", "(", "from", "=", "0", "..", "0xFF", ",", "to", "=", "0", "..", "0xFF", ")", "if", "from", ".", "exclude_end?", "raise", "\"Stretching does not support ranges with end value \"", "+", "\"excluded (such as #{from})\"", "end", "if", "to", ".", "exclude_end?", "raise", "\"Stretching does not support ranges with end value \"", "+", "\"excluded (such as #{to})\"", "end", "if", "from", ".", "last", "!=", "from", ".", "first", "factor", "=", "(", "to", ".", "last", "-", "to", ".", "first", ")", ".", "to_f", "/", "(", "from", ".", "last", "-", "from", ".", "first", ")", "collect", "{", "|", "x", "|", "(", "(", "x", "-", "from", ".", "first", ")", "*", "factor", ")", ".", "major", "(", "to", ".", "first", ")", ".", "minor", "to", ".", "last", "}", "else", "(", "self", "<=", "from", ".", "first", ")", ".", "conditional", "to", ".", "first", ",", "to", ".", "last", "end", "end" ]
Stretch values from one range to another @param [Range] from Target range of values. @param [Range] to Source range of values. @return [Node] Array with stretched values.
[ "Stretch", "values", "from", "one", "range", "to", "another" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L517-L532
6,097
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.diagonal
def diagonal( initial = nil, options = {} ) if dimension == 0 demand else if initial initial = Node.match( initial ).new initial unless initial.matched? initial_typecode = initial.typecode else initial_typecode = typecode end index0 = Variable.new Hornetseye::INDEX( nil ) index1 = Variable.new Hornetseye::INDEX( nil ) index2 = Variable.new Hornetseye::INDEX( nil ) var1 = options[ :var1 ] || Variable.new( initial_typecode ) var2 = options[ :var2 ] || Variable.new( typecode ) block = options[ :block ] || yield( var1, var2 ) value = element( index1 ).element( index2 ). diagonal initial, :block => block, :var1 => var1, :var2 => var2 term = Diagonal.new( value, index0, index1, index2, initial, block, var1, var2 ) index0.size = index1.size Lambda.new( index0, term ).force end end
ruby
def diagonal( initial = nil, options = {} ) if dimension == 0 demand else if initial initial = Node.match( initial ).new initial unless initial.matched? initial_typecode = initial.typecode else initial_typecode = typecode end index0 = Variable.new Hornetseye::INDEX( nil ) index1 = Variable.new Hornetseye::INDEX( nil ) index2 = Variable.new Hornetseye::INDEX( nil ) var1 = options[ :var1 ] || Variable.new( initial_typecode ) var2 = options[ :var2 ] || Variable.new( typecode ) block = options[ :block ] || yield( var1, var2 ) value = element( index1 ).element( index2 ). diagonal initial, :block => block, :var1 => var1, :var2 => var2 term = Diagonal.new( value, index0, index1, index2, initial, block, var1, var2 ) index0.size = index1.size Lambda.new( index0, term ).force end end
[ "def", "diagonal", "(", "initial", "=", "nil", ",", "options", "=", "{", "}", ")", "if", "dimension", "==", "0", "demand", "else", "if", "initial", "initial", "=", "Node", ".", "match", "(", "initial", ")", ".", "new", "initial", "unless", "initial", ".", "matched?", "initial_typecode", "=", "initial", ".", "typecode", "else", "initial_typecode", "=", "typecode", "end", "index0", "=", "Variable", ".", "new", "Hornetseye", "::", "INDEX", "(", "nil", ")", "index1", "=", "Variable", ".", "new", "Hornetseye", "::", "INDEX", "(", "nil", ")", "index2", "=", "Variable", ".", "new", "Hornetseye", "::", "INDEX", "(", "nil", ")", "var1", "=", "options", "[", ":var1", "]", "||", "Variable", ".", "new", "(", "initial_typecode", ")", "var2", "=", "options", "[", ":var2", "]", "||", "Variable", ".", "new", "(", "typecode", ")", "block", "=", "options", "[", ":block", "]", "||", "yield", "(", "var1", ",", "var2", ")", "value", "=", "element", "(", "index1", ")", ".", "element", "(", "index2", ")", ".", "diagonal", "initial", ",", ":block", "=>", "block", ",", ":var1", "=>", "var1", ",", ":var2", "=>", "var2", "term", "=", "Diagonal", ".", "new", "(", "value", ",", "index0", ",", "index1", ",", "index2", ",", "initial", ",", "block", ",", "var1", ",", "var2", ")", "index0", ".", "size", "=", "index1", ".", "size", "Lambda", ".", "new", "(", "index0", ",", "term", ")", ".", "force", "end", "end" ]
Apply accumulative operation over elements diagonally This method is used internally to implement convolutions. @param [Object,Node] initial Initial value. @option options [Variable] :var1 First variable defining operation. @option options [Variable] :var2 Second variable defining operation. @option options [Variable] :block (yield( var1, var2 )) The operation to apply diagonally. @yield Optional operation to apply diagonally. @return [Node] Result of operation. @see #convolve @private
[ "Apply", "accumulative", "operation", "over", "elements", "diagonally" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L560-L583
6,098
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.table
def table( filter, &action ) filter = Node.match( filter, typecode ).new filter unless filter.matched? if filter.dimension > dimension raise "Filter has #{filter.dimension} dimension(s) but should " + "not have more than #{dimension}" end filter = Hornetseye::lazy( 1 ) { filter } while filter.dimension < dimension if filter.dimension == 0 action.call self, filter else Hornetseye::lazy { |i,j| self[j].table filter[i], &action } end end
ruby
def table( filter, &action ) filter = Node.match( filter, typecode ).new filter unless filter.matched? if filter.dimension > dimension raise "Filter has #{filter.dimension} dimension(s) but should " + "not have more than #{dimension}" end filter = Hornetseye::lazy( 1 ) { filter } while filter.dimension < dimension if filter.dimension == 0 action.call self, filter else Hornetseye::lazy { |i,j| self[j].table filter[i], &action } end end
[ "def", "table", "(", "filter", ",", "&", "action", ")", "filter", "=", "Node", ".", "match", "(", "filter", ",", "typecode", ")", ".", "new", "filter", "unless", "filter", ".", "matched?", "if", "filter", ".", "dimension", ">", "dimension", "raise", "\"Filter has #{filter.dimension} dimension(s) but should \"", "+", "\"not have more than #{dimension}\"", "end", "filter", "=", "Hornetseye", "::", "lazy", "(", "1", ")", "{", "filter", "}", "while", "filter", ".", "dimension", "<", "dimension", "if", "filter", ".", "dimension", "==", "0", "action", ".", "call", "self", ",", "filter", "else", "Hornetseye", "::", "lazy", "{", "|", "i", ",", "j", "|", "self", "[", "j", "]", ".", "table", "filter", "[", "i", "]", ",", "action", "}", "end", "end" ]
Compute table from two arrays Used internally to implement convolutions and other operations. @param [Node] filter Filter to form table with. @param [Proc] action Operation to make table for. @return [Node] Result of operation. @see #convolve @private
[ "Compute", "table", "from", "two", "arrays" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L597-L609
6,099
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.convolve
def convolve( filter ) filter = Node.match( filter, typecode ).new filter unless filter.matched? array = self (dimension - filter.dimension).times { array = array.roll } array.table(filter) { |a,b| a * b }.diagonal { |s,x| s + x } end
ruby
def convolve( filter ) filter = Node.match( filter, typecode ).new filter unless filter.matched? array = self (dimension - filter.dimension).times { array = array.roll } array.table(filter) { |a,b| a * b }.diagonal { |s,x| s + x } end
[ "def", "convolve", "(", "filter", ")", "filter", "=", "Node", ".", "match", "(", "filter", ",", "typecode", ")", ".", "new", "filter", "unless", "filter", ".", "matched?", "array", "=", "self", "(", "dimension", "-", "filter", ".", "dimension", ")", ".", "times", "{", "array", "=", "array", ".", "roll", "}", "array", ".", "table", "(", "filter", ")", "{", "|", "a", ",", "b", "|", "a", "*", "b", "}", ".", "diagonal", "{", "|", "s", ",", "x", "|", "s", "+", "x", "}", "end" ]
Convolution with other array of same dimension @param [Node] filter Filter to convolve with. @return [Node] Result of convolution.
[ "Convolution", "with", "other", "array", "of", "same", "dimension" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L616-L621