repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_server_info
def get_server_info params = MagicParams.format(user_id: @allscripts_username) results = magic("GetServerInfo", magic_params: params) results["getserverinfoinfo"][0] # infoinfo is an Allscript typo end
ruby
def get_server_info params = MagicParams.format(user_id: @allscripts_username) results = magic("GetServerInfo", magic_params: params) results["getserverinfoinfo"][0] # infoinfo is an Allscript typo end
[ "def", "get_server_info", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ")", "results", "=", "magic", "(", "\"GetServerInfo\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getserverinfoinfo\"", "]", "[", "0", "]", "end" ]
a wrapper around GetServerInfo, which returns the time zone of the server, unity version and date and license key @return [Array<Hash>, Array, MagicError] local information about the server hosting the Unity webservice.
[ "a", "wrapper", "around", "GetServerInfo", "which", "returns", "the", "time", "zone", "of", "the", "server", "unity", "version", "and", "date", "and", "license", "key" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L176-L180
train
bloom-solutions/borutus
app/models/borutus/account.rb
Borutus.Account.balance
def balance(options={}) if self.class == Borutus::Account raise(NoMethodError, "undefined method 'balance'") else if self.normal_credit_balance ^ contra credits_balance(options) - debits_balance(options) else debits_balance(options) - credits_balance(options) end end end
ruby
def balance(options={}) if self.class == Borutus::Account raise(NoMethodError, "undefined method 'balance'") else if self.normal_credit_balance ^ contra credits_balance(options) - debits_balance(options) else debits_balance(options) - credits_balance(options) end end end
[ "def", "balance", "(", "options", "=", "{", "}", ")", "if", "self", ".", "class", "==", "Borutus", "::", "Account", "raise", "(", "NoMethodError", ",", "\"undefined method 'balance'\"", ")", "else", "if", "self", ".", "normal_credit_balance", "^", "contra", "credits_balance", "(", "options", ")", "-", "debits_balance", "(", "options", ")", "else", "debits_balance", "(", "options", ")", "-", "credits_balance", "(", "options", ")", "end", "end", "end" ]
The balance of the account. This instance method is intended for use only on instances of account subclasses. If the account has a normal credit balance, the debits are subtracted from the credits unless this is a contra account, in which case credits are substracted from debits. For a normal debit balance, the credits are subtracted from the debits unless this is a contra account, in which case debits are subtracted from credits. Takes an optional hash specifying :from_date and :to_date for calculating balances during periods. :from_date and :to_date may be strings of the form "yyyy-mm-dd" or Ruby Date objects @example >> liability.balance({:from_date => "2000-01-01", :to_date => Date.today}) => #<BigDecimal:103259bb8,'0.1E4',4(12)> @example >> liability.balance => #<BigDecimal:103259bb8,'0.2E4',4(12)> @return [BigDecimal] The decimal value balance
[ "The", "balance", "of", "the", "account", ".", "This", "instance", "method", "is", "intended", "for", "use", "only", "on", "instances", "of", "account", "subclasses", "." ]
5b2e240f21f2ad67fa0a3f85e417cc10e3bef9e9
https://github.com/bloom-solutions/borutus/blob/5b2e240f21f2ad67fa0a3f85e417cc10e3bef9e9/app/models/borutus/account.rb#L115-L125
train
livingsocial/humperdink
lib/humperdink/tracker.rb
Humperdink.Tracker.shutdown
def shutdown(exception) begin notify_event(:shutdown, { :exception_message => exception.message }) rescue => e $stderr.puts([e.message, e.backtrace].join("\n")) rescue nil end @config = default_config @config[:enabled] = false end
ruby
def shutdown(exception) begin notify_event(:shutdown, { :exception_message => exception.message }) rescue => e $stderr.puts([e.message, e.backtrace].join("\n")) rescue nil end @config = default_config @config[:enabled] = false end
[ "def", "shutdown", "(", "exception", ")", "begin", "notify_event", "(", ":shutdown", ",", "{", ":exception_message", "=>", "exception", ".", "message", "}", ")", "rescue", "=>", "e", "$stderr", ".", "puts", "(", "[", "e", ".", "message", ",", "e", ".", "backtrace", "]", ".", "join", "(", "\"\\n\"", ")", ")", "rescue", "nil", "end", "@config", "=", "default_config", "@config", "[", ":enabled", "]", "=", "false", "end" ]
Anytime an exception happens, we want to skedaddle out of the way and let life roll on without any tracking in the loop.
[ "Anytime", "an", "exception", "happens", "we", "want", "to", "skedaddle", "out", "of", "the", "way", "and", "let", "life", "roll", "on", "without", "any", "tracking", "in", "the", "loop", "." ]
56b1f3bb6d45af5b59b8a33373ae3df5d8aab08b
https://github.com/livingsocial/humperdink/blob/56b1f3bb6d45af5b59b8a33373ae3df5d8aab08b/lib/humperdink/tracker.rb#L58-L66
train
jronallo/microdata
lib/microdata/item.rb
Microdata.Item.add_itemprop
def add_itemprop(itemprop) properties = Itemprop.parse(itemprop, @page_url) properties.each { |name, value| (@properties[name] ||= []) << value } end
ruby
def add_itemprop(itemprop) properties = Itemprop.parse(itemprop, @page_url) properties.each { |name, value| (@properties[name] ||= []) << value } end
[ "def", "add_itemprop", "(", "itemprop", ")", "properties", "=", "Itemprop", ".", "parse", "(", "itemprop", ",", "@page_url", ")", "properties", ".", "each", "{", "|", "name", ",", "value", "|", "(", "@properties", "[", "name", "]", "||=", "[", "]", ")", "<<", "value", "}", "end" ]
Add an 'itemprop' to the properties
[ "Add", "an", "itemprop", "to", "the", "properties" ]
9af0e41801a815b1d14d5bb56f35bdd6c35ab006
https://github.com/jronallo/microdata/blob/9af0e41801a815b1d14d5bb56f35bdd6c35ab006/lib/microdata/item.rb#L60-L63
train
jronallo/microdata
lib/microdata/item.rb
Microdata.Item.add_itemref_properties
def add_itemref_properties(element) itemref = element.attribute('itemref') if itemref itemref.value.split(' ').each {|id| parse_elements(find_with_id(id))} end end
ruby
def add_itemref_properties(element) itemref = element.attribute('itemref') if itemref itemref.value.split(' ').each {|id| parse_elements(find_with_id(id))} end end
[ "def", "add_itemref_properties", "(", "element", ")", "itemref", "=", "element", ".", "attribute", "(", "'itemref'", ")", "if", "itemref", "itemref", ".", "value", ".", "split", "(", "' '", ")", ".", "each", "{", "|", "id", "|", "parse_elements", "(", "find_with_id", "(", "id", ")", ")", "}", "end", "end" ]
Add any properties referred to by 'itemref'
[ "Add", "any", "properties", "referred", "to", "by", "itemref" ]
9af0e41801a815b1d14d5bb56f35bdd6c35ab006
https://github.com/jronallo/microdata/blob/9af0e41801a815b1d14d5bb56f35bdd6c35ab006/lib/microdata/item.rb#L66-L71
train
CoffeeAndCode/rubocop_method_order
lib/rubocop_method_order/method_node_collection.rb
RuboCopMethodOrder.MethodNodeCollection.replacements
def replacements nodes.reject { |node| method_order_correct?(node) }.each_with_object({}) do |node, obj| node_to_replace = nodes[expected_method_index(node)] obj[node] = { node => node_to_replace, node_to_replace => nodes[expected_method_index(node_to_replace)] } end end
ruby
def replacements nodes.reject { |node| method_order_correct?(node) }.each_with_object({}) do |node, obj| node_to_replace = nodes[expected_method_index(node)] obj[node] = { node => node_to_replace, node_to_replace => nodes[expected_method_index(node_to_replace)] } end end
[ "def", "replacements", "nodes", ".", "reject", "{", "|", "node", "|", "method_order_correct?", "(", "node", ")", "}", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "node", ",", "obj", "|", "node_to_replace", "=", "nodes", "[", "expected_method_index", "(", "node", ")", "]", "obj", "[", "node", "]", "=", "{", "node", "=>", "node_to_replace", ",", "node_to_replace", "=>", "nodes", "[", "expected_method_index", "(", "node_to_replace", ")", "]", "}", "end", "end" ]
Build a hash for every node that is not at the correct, final position which includes any nodes that need to be moved. Used for autocorrecting.
[ "Build", "a", "hash", "for", "every", "node", "that", "is", "not", "at", "the", "correct", "final", "position", "which", "includes", "any", "nodes", "that", "need", "to", "be", "moved", ".", "Used", "for", "autocorrecting", "." ]
d914c796432913b2b5688417fce205d276d212c6
https://github.com/CoffeeAndCode/rubocop_method_order/blob/d914c796432913b2b5688417fce205d276d212c6/lib/rubocop_method_order/method_node_collection.rb#L28-L37
train
markkorput/xsd-reader
lib/xsd_reader/shared.rb
XsdReader.Shared.class_for
def class_for(n) class_mapping = { "#{schema_namespace_prefix}schema" => Schema, "#{schema_namespace_prefix}element" => Element, "#{schema_namespace_prefix}attribute" => Attribute, "#{schema_namespace_prefix}choice" => Choice, "#{schema_namespace_prefix}complexType" => ComplexType, "#{schema_namespace_prefix}sequence" => Sequence, "#{schema_namespace_prefix}simpleContent" => SimpleContent, "#{schema_namespace_prefix}complexContent" => ComplexContent, "#{schema_namespace_prefix}extension" => Extension, "#{schema_namespace_prefix}import" => Import, "#{schema_namespace_prefix}simpleType" => SimpleType } return class_mapping[n.is_a?(Nokogiri::XML::Node) ? n.name : n] end
ruby
def class_for(n) class_mapping = { "#{schema_namespace_prefix}schema" => Schema, "#{schema_namespace_prefix}element" => Element, "#{schema_namespace_prefix}attribute" => Attribute, "#{schema_namespace_prefix}choice" => Choice, "#{schema_namespace_prefix}complexType" => ComplexType, "#{schema_namespace_prefix}sequence" => Sequence, "#{schema_namespace_prefix}simpleContent" => SimpleContent, "#{schema_namespace_prefix}complexContent" => ComplexContent, "#{schema_namespace_prefix}extension" => Extension, "#{schema_namespace_prefix}import" => Import, "#{schema_namespace_prefix}simpleType" => SimpleType } return class_mapping[n.is_a?(Nokogiri::XML::Node) ? n.name : n] end
[ "def", "class_for", "(", "n", ")", "class_mapping", "=", "{", "\"#{schema_namespace_prefix}schema\"", "=>", "Schema", ",", "\"#{schema_namespace_prefix}element\"", "=>", "Element", ",", "\"#{schema_namespace_prefix}attribute\"", "=>", "Attribute", ",", "\"#{schema_namespace_prefix}choice\"", "=>", "Choice", ",", "\"#{schema_namespace_prefix}complexType\"", "=>", "ComplexType", ",", "\"#{schema_namespace_prefix}sequence\"", "=>", "Sequence", ",", "\"#{schema_namespace_prefix}simpleContent\"", "=>", "SimpleContent", ",", "\"#{schema_namespace_prefix}complexContent\"", "=>", "ComplexContent", ",", "\"#{schema_namespace_prefix}extension\"", "=>", "Extension", ",", "\"#{schema_namespace_prefix}import\"", "=>", "Import", ",", "\"#{schema_namespace_prefix}simpleType\"", "=>", "SimpleType", "}", "return", "class_mapping", "[", "n", ".", "is_a?", "(", "Nokogiri", "::", "XML", "::", "Node", ")", "?", "n", ".", "name", ":", "n", "]", "end" ]
Node to class mapping
[ "Node", "to", "class", "mapping" ]
5d417f1380f26f6962d444e7f6a9a312b739113d
https://github.com/markkorput/xsd-reader/blob/5d417f1380f26f6962d444e7f6a9a312b739113d/lib/xsd_reader/shared.rb#L110-L126
train
emmanuel/aequitas
lib/aequitas/violation_set.rb
Aequitas.ViolationSet.full_messages
def full_messages violations.inject([]) do |list, (attribute_name, violations)| messages = violations messages = violations.full_messages if violations.respond_to?(:full_messages) list.concat(messages) end end
ruby
def full_messages violations.inject([]) do |list, (attribute_name, violations)| messages = violations messages = violations.full_messages if violations.respond_to?(:full_messages) list.concat(messages) end end
[ "def", "full_messages", "violations", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "(", "attribute_name", ",", "violations", ")", "|", "messages", "=", "violations", "messages", "=", "violations", ".", "full_messages", "if", "violations", ".", "respond_to?", "(", ":full_messages", ")", "list", ".", "concat", "(", "messages", ")", "end", "end" ]
Collect all violations into a single list. @api public
[ "Collect", "all", "violations", "into", "a", "single", "list", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/violation_set.rb#L68-L74
train
jaymcgavren/rubyonacid
lib/rubyonacid/factories/meta.rb
RubyOnAcid.MetaFactory.get_unit
def get_unit(key) @assigned_factories[key] ||= source_factories[rand(source_factories.length)] @assigned_factories[key].get_unit(key) end
ruby
def get_unit(key) @assigned_factories[key] ||= source_factories[rand(source_factories.length)] @assigned_factories[key].get_unit(key) end
[ "def", "get_unit", "(", "key", ")", "@assigned_factories", "[", "key", "]", "||=", "source_factories", "[", "rand", "(", "source_factories", ".", "length", ")", "]", "@assigned_factories", "[", "key", "]", ".", "get_unit", "(", "key", ")", "end" ]
Returns the value of get_unit from the Factory assigned to the given key. When a key is needed that a Factory is not already assigned to, one will be assigned at random from the pool of source factories.
[ "Returns", "the", "value", "of", "get_unit", "from", "the", "Factory", "assigned", "to", "the", "given", "key", ".", "When", "a", "key", "is", "needed", "that", "a", "Factory", "is", "not", "already", "assigned", "to", "one", "will", "be", "assigned", "at", "random", "from", "the", "pool", "of", "source", "factories", "." ]
2ee2af3e952b7290e18a4f7012f76af4a7fe059d
https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/meta.rb#L26-L29
train
jaymcgavren/rubyonacid
lib/rubyonacid/factories/example.rb
RubyOnAcid.ExampleFactory.generate_factories
def generate_factories random_factory = RubyOnAcid::RandomFactory.new factories = [] 5.times do factory = RubyOnAcid::LoopFactory.new factory.interval = random_factory.get(:increment, :min => -0.1, :max => 0.1) factories << factory end 3.times do factory = RubyOnAcid::ConstantFactory.new factory.value = random_factory.get(:constant) factories << factory end factories << RubyOnAcid::FlashFactory.new( :interval => random_factory.get(:interval, :max => 100) ) 2.times do factories << RubyOnAcid::LissajousFactory.new( :interval => random_factory.get(:interval, :max => 10.0), :scale => random_factory.get(:scale, :min => 0.1, :max => 2.0) ) end factories << RubyOnAcid::RandomWalkFactory.new( :interval => random_factory.get(:interval, :max => 0.1) ) 4.times do factory = RubyOnAcid::SineFactory.new factory.interval = random_factory.get(:increment, :min => -0.1, :max => 0.1) factories << factory end 2.times do factory = RubyOnAcid::RepeatFactory.new factory.repeat_count = random_factory.get(:interval, :min => 2, :max => 100) factory.source_factories << random_element(factories) factories << factory end 2.times do factories << RubyOnAcid::RoundingFactory.new( :source_factories => [random_element(factories)], :nearest => random_factory.get(:interval, :min => 0.1, :max => 0.5) ) end combination_factory = RubyOnAcid::CombinationFactory.new combination_factory.constrain_mode = random_factory.choose(:constrain_mode, CombinationFactory::CONSTRAIN, CombinationFactory::WRAP, CombinationFactory::REBOUND ) combination_factory.operation = random_factory.choose(:operation, CombinationFactory::ADD, CombinationFactory::SUBTRACT, CombinationFactory::MULTIPLY, CombinationFactory::DIVIDE ) 2.times do combination_factory.source_factories << random_element(factories) end factories << combination_factory weighted_factory = RubyOnAcid::WeightedFactory.new 2.times do source_factory = random_element(factories) weighted_factory.source_factories << source_factory weighted_factory.weights[source_factory] = rand end factories << weighted_factory proximity_factory = RubyOnAcid::ProximityFactory.new 2.times do proximity_factory.source_factories << random_element(factories) end factories << proximity_factory 8.times do attraction_factory = RubyOnAcid::AttractionFactory.new( :attractor_factory => random_element(factories) ) attraction_factory.source_factories << random_element(factories) factories << attraction_factory end factories end
ruby
def generate_factories random_factory = RubyOnAcid::RandomFactory.new factories = [] 5.times do factory = RubyOnAcid::LoopFactory.new factory.interval = random_factory.get(:increment, :min => -0.1, :max => 0.1) factories << factory end 3.times do factory = RubyOnAcid::ConstantFactory.new factory.value = random_factory.get(:constant) factories << factory end factories << RubyOnAcid::FlashFactory.new( :interval => random_factory.get(:interval, :max => 100) ) 2.times do factories << RubyOnAcid::LissajousFactory.new( :interval => random_factory.get(:interval, :max => 10.0), :scale => random_factory.get(:scale, :min => 0.1, :max => 2.0) ) end factories << RubyOnAcid::RandomWalkFactory.new( :interval => random_factory.get(:interval, :max => 0.1) ) 4.times do factory = RubyOnAcid::SineFactory.new factory.interval = random_factory.get(:increment, :min => -0.1, :max => 0.1) factories << factory end 2.times do factory = RubyOnAcid::RepeatFactory.new factory.repeat_count = random_factory.get(:interval, :min => 2, :max => 100) factory.source_factories << random_element(factories) factories << factory end 2.times do factories << RubyOnAcid::RoundingFactory.new( :source_factories => [random_element(factories)], :nearest => random_factory.get(:interval, :min => 0.1, :max => 0.5) ) end combination_factory = RubyOnAcid::CombinationFactory.new combination_factory.constrain_mode = random_factory.choose(:constrain_mode, CombinationFactory::CONSTRAIN, CombinationFactory::WRAP, CombinationFactory::REBOUND ) combination_factory.operation = random_factory.choose(:operation, CombinationFactory::ADD, CombinationFactory::SUBTRACT, CombinationFactory::MULTIPLY, CombinationFactory::DIVIDE ) 2.times do combination_factory.source_factories << random_element(factories) end factories << combination_factory weighted_factory = RubyOnAcid::WeightedFactory.new 2.times do source_factory = random_element(factories) weighted_factory.source_factories << source_factory weighted_factory.weights[source_factory] = rand end factories << weighted_factory proximity_factory = RubyOnAcid::ProximityFactory.new 2.times do proximity_factory.source_factories << random_element(factories) end factories << proximity_factory 8.times do attraction_factory = RubyOnAcid::AttractionFactory.new( :attractor_factory => random_element(factories) ) attraction_factory.source_factories << random_element(factories) factories << attraction_factory end factories end
[ "def", "generate_factories", "random_factory", "=", "RubyOnAcid", "::", "RandomFactory", ".", "new", "factories", "=", "[", "]", "5", ".", "times", "do", "factory", "=", "RubyOnAcid", "::", "LoopFactory", ".", "new", "factory", ".", "interval", "=", "random_factory", ".", "get", "(", ":increment", ",", ":min", "=>", "-", "0.1", ",", ":max", "=>", "0.1", ")", "factories", "<<", "factory", "end", "3", ".", "times", "do", "factory", "=", "RubyOnAcid", "::", "ConstantFactory", ".", "new", "factory", ".", "value", "=", "random_factory", ".", "get", "(", ":constant", ")", "factories", "<<", "factory", "end", "factories", "<<", "RubyOnAcid", "::", "FlashFactory", ".", "new", "(", ":interval", "=>", "random_factory", ".", "get", "(", ":interval", ",", ":max", "=>", "100", ")", ")", "2", ".", "times", "do", "factories", "<<", "RubyOnAcid", "::", "LissajousFactory", ".", "new", "(", ":interval", "=>", "random_factory", ".", "get", "(", ":interval", ",", ":max", "=>", "10.0", ")", ",", ":scale", "=>", "random_factory", ".", "get", "(", ":scale", ",", ":min", "=>", "0.1", ",", ":max", "=>", "2.0", ")", ")", "end", "factories", "<<", "RubyOnAcid", "::", "RandomWalkFactory", ".", "new", "(", ":interval", "=>", "random_factory", ".", "get", "(", ":interval", ",", ":max", "=>", "0.1", ")", ")", "4", ".", "times", "do", "factory", "=", "RubyOnAcid", "::", "SineFactory", ".", "new", "factory", ".", "interval", "=", "random_factory", ".", "get", "(", ":increment", ",", ":min", "=>", "-", "0.1", ",", ":max", "=>", "0.1", ")", "factories", "<<", "factory", "end", "2", ".", "times", "do", "factory", "=", "RubyOnAcid", "::", "RepeatFactory", ".", "new", "factory", ".", "repeat_count", "=", "random_factory", ".", "get", "(", ":interval", ",", ":min", "=>", "2", ",", ":max", "=>", "100", ")", "factory", ".", "source_factories", "<<", "random_element", "(", "factories", ")", "factories", "<<", "factory", "end", "2", ".", "times", "do", "factories", "<<", "RubyOnAcid", "::", "RoundingFactory", ".", "new", "(", ":source_factories", "=>", "[", "random_element", "(", "factories", ")", "]", ",", ":nearest", "=>", "random_factory", ".", "get", "(", ":interval", ",", ":min", "=>", "0.1", ",", ":max", "=>", "0.5", ")", ")", "end", "combination_factory", "=", "RubyOnAcid", "::", "CombinationFactory", ".", "new", "combination_factory", ".", "constrain_mode", "=", "random_factory", ".", "choose", "(", ":constrain_mode", ",", "CombinationFactory", "::", "CONSTRAIN", ",", "CombinationFactory", "::", "WRAP", ",", "CombinationFactory", "::", "REBOUND", ")", "combination_factory", ".", "operation", "=", "random_factory", ".", "choose", "(", ":operation", ",", "CombinationFactory", "::", "ADD", ",", "CombinationFactory", "::", "SUBTRACT", ",", "CombinationFactory", "::", "MULTIPLY", ",", "CombinationFactory", "::", "DIVIDE", ")", "2", ".", "times", "do", "combination_factory", ".", "source_factories", "<<", "random_element", "(", "factories", ")", "end", "factories", "<<", "combination_factory", "weighted_factory", "=", "RubyOnAcid", "::", "WeightedFactory", ".", "new", "2", ".", "times", "do", "source_factory", "=", "random_element", "(", "factories", ")", "weighted_factory", ".", "source_factories", "<<", "source_factory", "weighted_factory", ".", "weights", "[", "source_factory", "]", "=", "rand", "end", "factories", "<<", "weighted_factory", "proximity_factory", "=", "RubyOnAcid", "::", "ProximityFactory", ".", "new", "2", ".", "times", "do", "proximity_factory", ".", "source_factories", "<<", "random_element", "(", "factories", ")", "end", "factories", "<<", "proximity_factory", "8", ".", "times", "do", "attraction_factory", "=", "RubyOnAcid", "::", "AttractionFactory", ".", "new", "(", ":attractor_factory", "=>", "random_element", "(", "factories", ")", ")", "attraction_factory", ".", "source_factories", "<<", "random_element", "(", "factories", ")", "factories", "<<", "attraction_factory", "end", "factories", "end" ]
Takes a hash with all keys supported by Factory.
[ "Takes", "a", "hash", "with", "all", "keys", "supported", "by", "Factory", "." ]
2ee2af3e952b7290e18a4f7012f76af4a7fe059d
https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/example.rb#L16-L99
train
emmanuel/aequitas
lib/aequitas/macros.rb
Aequitas.Macros.validates_acceptance_of
def validates_acceptance_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Acceptance, attribute_names, options) end
ruby
def validates_acceptance_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Acceptance, attribute_names, options) end
[ "def", "validates_acceptance_of", "(", "*", "attribute_names", ")", "options", "=", "Macros", ".", "extract_options", "(", "attribute_names", ")", "validation_rules", ".", "add", "(", "Rule", "::", "Acceptance", ",", "attribute_names", ",", "options", ")", "end" ]
Validates that the attributes's value is in the set of accepted values. @option [Boolean] :allow_nil (true) true if nil is allowed, false if not allowed. @option [Array] :accept (["1", 1, "true", true, "t"]) A list of accepted values. @example Usage require 'virtus' require 'aequitas' class Page include Virtus include Aequitas attribute :license_agreement_accepted, String attribute :terms_accepted, String validates_acceptance_of :license_agreement, :accept => "1" validates_acceptance_of :terms_accepted, :allow_nil => false # a call to valid? will return false unless: # license_agreement is nil or "1" # and # terms_accepted is one of ["1", 1, "true", true, "t"] end
[ "Validates", "that", "the", "attributes", "s", "value", "is", "in", "the", "set", "of", "accepted", "values", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/macros.rb#L83-L86
train
emmanuel/aequitas
lib/aequitas/macros.rb
Aequitas.Macros.validates_confirmation_of
def validates_confirmation_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Confirmation, attribute_names, options) end
ruby
def validates_confirmation_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Confirmation, attribute_names, options) end
[ "def", "validates_confirmation_of", "(", "*", "attribute_names", ")", "options", "=", "Macros", ".", "extract_options", "(", "attribute_names", ")", "validation_rules", ".", "add", "(", "Rule", "::", "Confirmation", ",", "attribute_names", ",", "options", ")", "end" ]
Validates that the given attribute is confirmed by another attribute. A common use case scenario is when you require a user to confirm their password, for which you use both password and password_confirmation attributes. @option [Boolean] :allow_nil (true) true or false. @option [Boolean] :allow_blank (true) true or false. @option [Symbol] :confirm (firstattr_confirmation) The attribute that you want to validate against. @example Usage require 'virtus' require 'aequitas' class Page include Virtus include Aequitas attribute :password, String attribute :email, String attr_accessor :password_confirmation attr_accessor :email_repeated validates_confirmation_of :password validates_confirmation_of :email, :confirm => :email_repeated # a call to valid? will return false unless: # password == password_confirmation # and # email == email_repeated end
[ "Validates", "that", "the", "given", "attribute", "is", "confirmed", "by", "another", "attribute", ".", "A", "common", "use", "case", "scenario", "is", "when", "you", "require", "a", "user", "to", "confirm", "their", "password", "for", "which", "you", "use", "both", "password", "and", "password_confirmation", "attributes", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/macros.rb#L125-L128
train
emmanuel/aequitas
lib/aequitas/macros.rb
Aequitas.Macros.validates_numericalness_of
def validates_numericalness_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Value, attribute_names, options) validation_rules.add(Rule::Numericalness, attribute_names, options) end
ruby
def validates_numericalness_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Value, attribute_names, options) validation_rules.add(Rule::Numericalness, attribute_names, options) end
[ "def", "validates_numericalness_of", "(", "*", "attribute_names", ")", "options", "=", "Macros", ".", "extract_options", "(", "attribute_names", ")", "validation_rules", ".", "add", "(", "Rule", "::", "Value", ",", "attribute_names", ",", "options", ")", "validation_rules", ".", "add", "(", "Rule", "::", "Numericalness", ",", "attribute_names", ",", "options", ")", "end" ]
Validate whether a field is numeric. @option [Boolean] :allow_nil true if number can be nil, false if not. @option [Boolean] :allow_blank true if number can be blank, false if not. @option [String] :message Custom error message, also can be a callable object that takes an object (for pure Ruby objects) or object and property (for DM resources). @option [Numeric] :precision Required precision of a value. @option [Numeric] :scale Required scale of a value. @option [Numeric] :gte 'Greater than or equal to' requirement. @option [Numeric] :lte 'Less than or equal to' requirement. @option [Numeric] :lt 'Less than' requirement. @option [Numeric] :gt 'Greater than' requirement. @option [Numeric] :eq 'Equal' requirement. @option [Numeric] :ne 'Not equal' requirement. @option [Boolean] :integer_only Use to restrict allowed values to integers.
[ "Validate", "whether", "a", "field", "is", "numeric", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/macros.rb#L280-L284
train
emmanuel/aequitas
lib/aequitas/macros.rb
Aequitas.Macros.validates_presence_of
def validates_presence_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Presence::NotBlank, attribute_names, options) end
ruby
def validates_presence_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Presence::NotBlank, attribute_names, options) end
[ "def", "validates_presence_of", "(", "*", "attribute_names", ")", "options", "=", "Macros", ".", "extract_options", "(", "attribute_names", ")", "validation_rules", ".", "add", "(", "Rule", "::", "Presence", "::", "NotBlank", ",", "attribute_names", ",", "options", ")", "end" ]
Validates that the specified attribute is present. For most property types "being present" is the same as being "not blank" as determined by the attribute's #blank? method. However, in the case of Boolean, "being present" means not nil; i.e. true or false. @note dm-core's support lib adds the blank? method to many classes, @see lib/dm-core/support/blank.rb (dm-core) for more information. @example Usage require 'virtus' require 'aequitas' class Page include Virtus include Aequitas attribute :required_attribute, String attribute :another_required, String attribute :yet_again, String validates_presence_of :required_attribute validates_presence_of :another_required, :yet_again # a call to valid? will return false unless # all three attributes are not blank (according to Aequitas.blank?) end
[ "Validates", "that", "the", "specified", "attribute", "is", "present", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/macros.rb#L316-L319
train
emmanuel/aequitas
lib/aequitas/macros.rb
Aequitas.Macros.validates_primitive_type_of
def validates_primitive_type_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::PrimitiveType, attribute_names, options) end
ruby
def validates_primitive_type_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::PrimitiveType, attribute_names, options) end
[ "def", "validates_primitive_type_of", "(", "*", "attribute_names", ")", "options", "=", "Macros", ".", "extract_options", "(", "attribute_names", ")", "validation_rules", ".", "add", "(", "Rule", "::", "PrimitiveType", ",", "attribute_names", ",", "options", ")", "end" ]
Validates that the specified attribute is of the correct primitive type. @example Usage require 'virtus' require 'aequitas' class Person include Virtus include Aequitas attribute :birth_date, Date validates_primitive_type_of :birth_date # a call to valid? will return false unless # the birth_date is something that can be properly # casted into a Date object. end
[ "Validates", "that", "the", "specified", "attribute", "is", "of", "the", "correct", "primitive", "type", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/macros.rb#L340-L343
train
mnyrop/diane
lib/diane/player.rb
Diane.Player.all_recordings
def all_recordings opts = { headers: true, header_converters: :symbol, encoding: 'utf-8' } CSV.read(DIFILE, opts).map(&:to_hash) end
ruby
def all_recordings opts = { headers: true, header_converters: :symbol, encoding: 'utf-8' } CSV.read(DIFILE, opts).map(&:to_hash) end
[ "def", "all_recordings", "opts", "=", "{", "headers", ":", "true", ",", "header_converters", ":", ":symbol", ",", "encoding", ":", "'utf-8'", "}", "CSV", ".", "read", "(", "DIFILE", ",", "opts", ")", ".", "map", "(", "&", ":to_hash", ")", "end" ]
Returns hash array of all recordings in DIANE file
[ "Returns", "hash", "array", "of", "all", "recordings", "in", "DIANE", "file" ]
be98ff41b8e3c8b21a4a8548e9fba4007e64fc91
https://github.com/mnyrop/diane/blob/be98ff41b8e3c8b21a4a8548e9fba4007e64fc91/lib/diane/player.rb#L20-L27
train
mnyrop/diane
lib/diane/player.rb
Diane.Player.play
def play abort %(None from #{@user}. Fuck off.).magenta if @recordings.empty? stdout = preface @recordings.each do |r| stdout += "\n#{r[:time]} : ".cyan + "@#{r[:user]}".yellow stdout += "\n#{r[:message]}\n\n" end puts stdout stdout end
ruby
def play abort %(None from #{@user}. Fuck off.).magenta if @recordings.empty? stdout = preface @recordings.each do |r| stdout += "\n#{r[:time]} : ".cyan + "@#{r[:user]}".yellow stdout += "\n#{r[:message]}\n\n" end puts stdout stdout end
[ "def", "play", "abort", "%(None from #{@user}. Fuck off.)", ".", "magenta", "if", "@recordings", ".", "empty?", "stdout", "=", "preface", "@recordings", ".", "each", "do", "|", "r", "|", "stdout", "+=", "\"\\n#{r[:time]} : \"", ".", "cyan", "+", "\"@#{r[:user]}\"", ".", "yellow", "stdout", "+=", "\"\\n#{r[:message]}\\n\\n\"", "end", "puts", "stdout", "stdout", "end" ]
returns and puts formatted recordings returned by query
[ "returns", "and", "puts", "formatted", "recordings", "returned", "by", "query" ]
be98ff41b8e3c8b21a4a8548e9fba4007e64fc91
https://github.com/mnyrop/diane/blob/be98ff41b8e3c8b21a4a8548e9fba4007e64fc91/lib/diane/player.rb#L55-L64
train
flazz/schematron
lib/schematron.rb
Schematron.Schema.rule_hits
def rule_hits(results_doc, instance_doc, rule_type, xpath) results = [] results_doc.root.find(xpath, NS_PREFIXES).each do |hit| context = instance_doc.root.find_first hit['location'] hit.find('svrl:text/text()', NS_PREFIXES).each do |message| results << { :rule_type => rule_type, :type => context.node_type_name, :name => context.name, :line => context.line_num, :message => message.content.strip } end end results end
ruby
def rule_hits(results_doc, instance_doc, rule_type, xpath) results = [] results_doc.root.find(xpath, NS_PREFIXES).each do |hit| context = instance_doc.root.find_first hit['location'] hit.find('svrl:text/text()', NS_PREFIXES).each do |message| results << { :rule_type => rule_type, :type => context.node_type_name, :name => context.name, :line => context.line_num, :message => message.content.strip } end end results end
[ "def", "rule_hits", "(", "results_doc", ",", "instance_doc", ",", "rule_type", ",", "xpath", ")", "results", "=", "[", "]", "results_doc", ".", "root", ".", "find", "(", "xpath", ",", "NS_PREFIXES", ")", ".", "each", "do", "|", "hit", "|", "context", "=", "instance_doc", ".", "root", ".", "find_first", "hit", "[", "'location'", "]", "hit", ".", "find", "(", "'svrl:text/text()'", ",", "NS_PREFIXES", ")", ".", "each", "do", "|", "message", "|", "results", "<<", "{", ":rule_type", "=>", "rule_type", ",", ":type", "=>", "context", ".", "node_type_name", ",", ":name", "=>", "context", ".", "name", ",", ":line", "=>", "context", ".", "line_num", ",", ":message", "=>", "message", ".", "content", ".", "strip", "}", "end", "end", "results", "end" ]
Look for reported or failed rules of a particular type in the instance doc
[ "Look", "for", "reported", "or", "failed", "rules", "of", "a", "particular", "type", "in", "the", "instance", "doc" ]
1e67cecdd563ef2b82a4b0b0a3922b2d67b55c97
https://github.com/flazz/schematron/blob/1e67cecdd563ef2b82a4b0b0a3922b2d67b55c97/lib/schematron.rb#L52-L71
train
sdpatro/rlimiter
lib/rlimiter/redis_client.rb
Rlimiter.RedisClient.limit
def limit(key, count, duration) @key = key.to_s @duration = duration.to_i # :incr_count increases the hit count and simultaneously checks for breach if incr_count > count # :elapsed is the time window start Redis cache # If the time elapsed is less than window duration, the limit has been breached for the current window (return false). return false if @duration - elapsed > 0 # Else reset the hit count to zero and window start time. reset end true end
ruby
def limit(key, count, duration) @key = key.to_s @duration = duration.to_i # :incr_count increases the hit count and simultaneously checks for breach if incr_count > count # :elapsed is the time window start Redis cache # If the time elapsed is less than window duration, the limit has been breached for the current window (return false). return false if @duration - elapsed > 0 # Else reset the hit count to zero and window start time. reset end true end
[ "def", "limit", "(", "key", ",", "count", ",", "duration", ")", "@key", "=", "key", ".", "to_s", "@duration", "=", "duration", ".", "to_i", "if", "incr_count", ">", "count", "return", "false", "if", "@duration", "-", "elapsed", ">", "0", "reset", "end", "true", "end" ]
Initializes and returns a Redis object. Requires params hash i.e. { :host => [String] (The hostname of the Redis server) :port => [String] (Numeric port number) } For further documentation refer to https://github.com/redis/redis-rb Any errors thrown are generated by the redis-rb client. @param [Hash] params @return [Redis] Registers a hit corresponding to the key specified, requires the max hit count and the duration to be passed. @param [String] key : Should be unique for one operation, can be added for multiple operations if a single rate limiter is to be used for those operations. @param [Integer] count : Max rate limit count @param [Integer] duration : Duration of the time window. Count and duration params could change in each call and the limit breach value is returned corresponding to that. Ideally this method should be called with each param a constant on the application level. Returns false if the limit has been breached. Returns true if limit has not been breached. (duh)
[ "Initializes", "and", "returns", "a", "Redis", "object", "." ]
cc5c6bd5dbd6fff8de256571bcc03a51e496590a
https://github.com/sdpatro/rlimiter/blob/cc5c6bd5dbd6fff8de256571bcc03a51e496590a/lib/rlimiter/redis_client.rb#L48-L63
train
sdpatro/rlimiter
lib/rlimiter/redis_client.rb
Rlimiter.RedisClient.next_in
def next_in(key, count, duration) @key = key @duration = duration return 0 if current_count(key) < count [@duration - elapsed, 0].max end
ruby
def next_in(key, count, duration) @key = key @duration = duration return 0 if current_count(key) < count [@duration - elapsed, 0].max end
[ "def", "next_in", "(", "key", ",", "count", ",", "duration", ")", "@key", "=", "key", "@duration", "=", "duration", "return", "0", "if", "current_count", "(", "key", ")", "<", "count", "[", "@duration", "-", "elapsed", ",", "0", "]", ".", "max", "end" ]
Gets the ETA for the next window start only if the limit has been breached. Returns 0 if the limit has not been breached. @param [String] key @param [Integer] count @param [Integer] duration
[ "Gets", "the", "ETA", "for", "the", "next", "window", "start", "only", "if", "the", "limit", "has", "been", "breached", ".", "Returns", "0", "if", "the", "limit", "has", "not", "been", "breached", "." ]
cc5c6bd5dbd6fff8de256571bcc03a51e496590a
https://github.com/sdpatro/rlimiter/blob/cc5c6bd5dbd6fff8de256571bcc03a51e496590a/lib/rlimiter/redis_client.rb#L76-L81
train
jaymcgavren/rubyonacid
lib/rubyonacid/factories/rinda.rb
RubyOnAcid.RindaFactory.get_unit
def get_unit(key) @prior_values[key] ||= 0.0 begin key, value = @space.take([key, Float], @timeout) @prior_values[key] = value rescue Rinda::RequestExpiredError => exception if source_factories.empty? value = @prior_values[key] else value = super end end value end
ruby
def get_unit(key) @prior_values[key] ||= 0.0 begin key, value = @space.take([key, Float], @timeout) @prior_values[key] = value rescue Rinda::RequestExpiredError => exception if source_factories.empty? value = @prior_values[key] else value = super end end value end
[ "def", "get_unit", "(", "key", ")", "@prior_values", "[", "key", "]", "||=", "0.0", "begin", "key", ",", "value", "=", "@space", ".", "take", "(", "[", "key", ",", "Float", "]", ",", "@timeout", ")", "@prior_values", "[", "key", "]", "=", "value", "rescue", "Rinda", "::", "RequestExpiredError", "=>", "exception", "if", "source_factories", ".", "empty?", "value", "=", "@prior_values", "[", "key", "]", "else", "value", "=", "super", "end", "end", "value", "end" ]
Get key from Rinda server.
[ "Get", "key", "from", "Rinda", "server", "." ]
2ee2af3e952b7290e18a4f7012f76af4a7fe059d
https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/rinda.rb#L32-L45
train
DigitalNZ/contentful-redis
lib/contentful_redis/model_base.rb
ContentfulRedis.ModelBase.matching_attributes?
def matching_attributes?(attribute, filter) attribute.to_s.downcase == filter.to_s.delete('_').downcase end
ruby
def matching_attributes?(attribute, filter) attribute.to_s.downcase == filter.to_s.delete('_').downcase end
[ "def", "matching_attributes?", "(", "attribute", ",", "filter", ")", "attribute", ".", "to_s", ".", "downcase", "==", "filter", ".", "to_s", ".", "delete", "(", "'_'", ")", ".", "downcase", "end" ]
Parse the ids to the same string format. contentfulAttribute == ruby_attribute
[ "Parse", "the", "ids", "to", "the", "same", "string", "format", ".", "contentfulAttribute", "==", "ruby_attribute" ]
c08723f6fb6efbc19296ed47cf6476adfda70bf9
https://github.com/DigitalNZ/contentful-redis/blob/c08723f6fb6efbc19296ed47cf6476adfda70bf9/lib/contentful_redis/model_base.rb#L216-L218
train
emilsoman/cloudster
lib/cloudster/chef_client.rb
Cloudster.ChefClient.add_to
def add_to(ec2) ec2_template = ec2.template @instance_name = ec2.name chef_client_template = template ec2.template.inner_merge(chef_client_template) end
ruby
def add_to(ec2) ec2_template = ec2.template @instance_name = ec2.name chef_client_template = template ec2.template.inner_merge(chef_client_template) end
[ "def", "add_to", "(", "ec2", ")", "ec2_template", "=", "ec2", ".", "template", "@instance_name", "=", "ec2", ".", "name", "chef_client_template", "=", "template", "ec2", ".", "template", ".", "inner_merge", "(", "chef_client_template", ")", "end" ]
Initialize an ChefClient configuration ==== Notes options parameter must include values for :validation_key, :server_url and :node_name ==== Examples chef_client = Cloudster::ChefClient.new( :validation_key => 'asd3e33880889098asdnmnnasd8900890a8sdmasdjna9s880808asdnmnasd90-a', :server_url => 'http://10.50.60.70:4000', :node_name => 'project.environment.appserver_1', :validation_client_name => 'chef-validator', :interval => 1800 ) ==== Parameters * options<~Hash> - * :validation_key: String containing the key used for validating this client with the server. This can be taken from the chef-server validation.pem file. Mandatory field * :server_url: String containing the fully qualified domain name of the chef-server. Mandatory field * :node_name: String containing the name for the chef node. It has to be unique across all nodes in the particular chef client-server ecosystem. Mandatory field * :interval: Integer containing the interval(in seconds) between chef-client runs. Default value : 1800 seconds * :validation_client_name: String containing the name of the validation client. "ORGNAME-validator" if using hosted chef server. Default: 'chef-validator' Merges the required CloudFormation template for installing the Chef Client to the template of the EC2 instance ==== Examples chef_client = Cloudster::ChefClient.new( :validation_key => 'asd3e33880889098asdnmnnasd8900890a8sdmasdjna9s880808asdnmnasd90-a', :server_url => 'http://10.50.60.70:4000', :node_name => 'project.environment.appserver_1' ) ec2 = Cloudster::Ec2.new( :name => 'AppServer', :key_name => 'mykey', :image_id => 'ami_image_id', :instance_type => 't1.micro' ) chef_client.add_to ec2 ==== Parameters * instance of EC2
[ "Initialize", "an", "ChefClient", "configuration" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/chef_client.rb#L55-L60
train
emmanuel/aequitas
lib/aequitas/rule_set.rb
Aequitas.RuleSet.validate
def validate(resource) rules = rules_for_resource(resource) rules.map { |rule| rule.validate(resource) }.compact # TODO: # violations = rules.map { |rule| rule.validate(resource) }.compact # ViolationSet.new(resource).concat(violations) end
ruby
def validate(resource) rules = rules_for_resource(resource) rules.map { |rule| rule.validate(resource) }.compact # TODO: # violations = rules.map { |rule| rule.validate(resource) }.compact # ViolationSet.new(resource).concat(violations) end
[ "def", "validate", "(", "resource", ")", "rules", "=", "rules_for_resource", "(", "resource", ")", "rules", ".", "map", "{", "|", "rule", "|", "rule", ".", "validate", "(", "resource", ")", "}", ".", "compact", "end" ]
Execute all rules in this context against the resource. @param [Object] resource the resource to be validated @return [Array(Violation)] an Array of Violations
[ "Execute", "all", "rules", "in", "this", "context", "against", "the", "resource", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/rule_set.rb#L51-L57
train
emilsoman/cloudster
lib/cloudster/cloud.rb
Cloudster.Cloud.template
def template(options = {}) require_options(options, [:resources]) resources = options[:resources] description = options[:description] || 'This stack is created by Cloudster' resource_template = {} output_template = {} resources.each do |resource| resource_template.merge!(resource.template['Resources']) output_template.merge!(resource.template['Outputs']) unless resource.template['Outputs'].nil? end cloud_template = {'AWSTemplateFormatVersion' => '2010-09-09', 'Description' => description } cloud_template['Resources'] = resource_template if !resource_template.empty? cloud_template['Outputs'] = output_template if !output_template.empty? return cloud_template.delete_nil.to_json end
ruby
def template(options = {}) require_options(options, [:resources]) resources = options[:resources] description = options[:description] || 'This stack is created by Cloudster' resource_template = {} output_template = {} resources.each do |resource| resource_template.merge!(resource.template['Resources']) output_template.merge!(resource.template['Outputs']) unless resource.template['Outputs'].nil? end cloud_template = {'AWSTemplateFormatVersion' => '2010-09-09', 'Description' => description } cloud_template['Resources'] = resource_template if !resource_template.empty? cloud_template['Outputs'] = output_template if !output_template.empty? return cloud_template.delete_nil.to_json end
[ "def", "template", "(", "options", "=", "{", "}", ")", "require_options", "(", "options", ",", "[", ":resources", "]", ")", "resources", "=", "options", "[", ":resources", "]", "description", "=", "options", "[", ":description", "]", "||", "'This stack is created by Cloudster'", "resource_template", "=", "{", "}", "output_template", "=", "{", "}", "resources", ".", "each", "do", "|", "resource", "|", "resource_template", ".", "merge!", "(", "resource", ".", "template", "[", "'Resources'", "]", ")", "output_template", ".", "merge!", "(", "resource", ".", "template", "[", "'Outputs'", "]", ")", "unless", "resource", ".", "template", "[", "'Outputs'", "]", ".", "nil?", "end", "cloud_template", "=", "{", "'AWSTemplateFormatVersion'", "=>", "'2010-09-09'", ",", "'Description'", "=>", "description", "}", "cloud_template", "[", "'Resources'", "]", "=", "resource_template", "if", "!", "resource_template", ".", "empty?", "cloud_template", "[", "'Outputs'", "]", "=", "output_template", "if", "!", "output_template", ".", "empty?", "return", "cloud_template", ".", "delete_nil", ".", "to_json", "end" ]
Initialize a Cloud instance ==== Notes options parameter must include values for :access_key_id and :secret_access_key in order to create a connection ==== Parameters * options<~Hash> * :access_key_id : A string containing the AWS access key ID (Required) * :secret_access_key : A string containing the AWS secret access key (Required) * :region : A string containing the region where the stack should be created/updated (Optional). Can be one of us-east-1(default), us-west-1, us-west-2, eu-west-1, ap-southeast-1, ap-northeast-1, ap-southeast-2, sa-east-1 ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) Generates CloudFormation Template for the stack ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) cloud.template(:resources => [<AWS RESOURCES ARRAY>], :description => 'This is the description for the stack template') ==== Notes options parameter must include values for :resources ==== Parameters * options<~Hash> - * :resources : An array of Cloudster resource instances. Defaults to {}. * :description : A string which will be used as the Description of the CloudFormation template. ==== Returns * JSON cloud formation template
[ "Initialize", "a", "Cloud", "instance" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/cloud.rb#L58-L75
train
emilsoman/cloudster
lib/cloudster/cloud.rb
Cloudster.Cloud.get_rds_details
def get_rds_details(options = {}) stack_resources = resources(options) rds_resource_ids = get_resource_ids(stack_resources, "AWS::RDS::DBInstance") rds = Fog::AWS::RDS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) rds_details = {} rds_resource_ids.each do |key, value| rds_instance_details = rds.describe_db_instances(value) rds_details[key] = rds_instance_details.body["DescribeDBInstancesResult"]["DBInstances"][0] rescue nil end return rds_details end
ruby
def get_rds_details(options = {}) stack_resources = resources(options) rds_resource_ids = get_resource_ids(stack_resources, "AWS::RDS::DBInstance") rds = Fog::AWS::RDS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) rds_details = {} rds_resource_ids.each do |key, value| rds_instance_details = rds.describe_db_instances(value) rds_details[key] = rds_instance_details.body["DescribeDBInstancesResult"]["DBInstances"][0] rescue nil end return rds_details end
[ "def", "get_rds_details", "(", "options", "=", "{", "}", ")", "stack_resources", "=", "resources", "(", "options", ")", "rds_resource_ids", "=", "get_resource_ids", "(", "stack_resources", ",", "\"AWS::RDS::DBInstance\"", ")", "rds", "=", "Fog", "::", "AWS", "::", "RDS", ".", "new", "(", ":aws_access_key_id", "=>", "@access_key_id", ",", ":aws_secret_access_key", "=>", "@secret_access_key", ",", ":region", "=>", "@region", ")", "rds_details", "=", "{", "}", "rds_resource_ids", ".", "each", "do", "|", "key", ",", "value", "|", "rds_instance_details", "=", "rds", ".", "describe_db_instances", "(", "value", ")", "rds_details", "[", "key", "]", "=", "rds_instance_details", ".", "body", "[", "\"DescribeDBInstancesResult\"", "]", "[", "\"DBInstances\"", "]", "[", "0", "]", "rescue", "nil", "end", "return", "rds_details", "end" ]
Get details of all RDS resources in a stack ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) cloud.get_rds_details(:stack_name => 'ShittyStack') ==== Parameters * options<~Hash> * :stack_name : A string which will contain the name of the stack ==== Returns * A hash of RDS details where the key is the logical name and value is the RDS detail
[ "Get", "details", "of", "all", "RDS", "resources", "in", "a", "stack" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/cloud.rb#L228-L238
train
emilsoman/cloudster
lib/cloudster/cloud.rb
Cloudster.Cloud.get_ec2_details
def get_ec2_details(options = {}) stack_resources = resources(options) ec2_resource_ids = get_resource_ids(stack_resources, "AWS::EC2::Instance") ec2 = Fog::Compute::AWS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) ec2_details = {} ec2_resource_ids.each do |key, value| ec2_instance_details = ec2.describe_instances('instance-id' => value) ec2_details[key] = ec2_instance_details.body["reservationSet"][0]["instancesSet"][0] rescue nil end return ec2_details end
ruby
def get_ec2_details(options = {}) stack_resources = resources(options) ec2_resource_ids = get_resource_ids(stack_resources, "AWS::EC2::Instance") ec2 = Fog::Compute::AWS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) ec2_details = {} ec2_resource_ids.each do |key, value| ec2_instance_details = ec2.describe_instances('instance-id' => value) ec2_details[key] = ec2_instance_details.body["reservationSet"][0]["instancesSet"][0] rescue nil end return ec2_details end
[ "def", "get_ec2_details", "(", "options", "=", "{", "}", ")", "stack_resources", "=", "resources", "(", "options", ")", "ec2_resource_ids", "=", "get_resource_ids", "(", "stack_resources", ",", "\"AWS::EC2::Instance\"", ")", "ec2", "=", "Fog", "::", "Compute", "::", "AWS", ".", "new", "(", ":aws_access_key_id", "=>", "@access_key_id", ",", ":aws_secret_access_key", "=>", "@secret_access_key", ",", ":region", "=>", "@region", ")", "ec2_details", "=", "{", "}", "ec2_resource_ids", ".", "each", "do", "|", "key", ",", "value", "|", "ec2_instance_details", "=", "ec2", ".", "describe_instances", "(", "'instance-id'", "=>", "value", ")", "ec2_details", "[", "key", "]", "=", "ec2_instance_details", ".", "body", "[", "\"reservationSet\"", "]", "[", "0", "]", "[", "\"instancesSet\"", "]", "[", "0", "]", "rescue", "nil", "end", "return", "ec2_details", "end" ]
Get details of all EC2 instances in a stack ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) cloud.get_ec2_details(:stack_name => 'ShittyStack') ==== Parameters * options<~Hash> * :stack_name : A string which will contain the name of the stack ==== Returns * A hash of instance details where the key is the logical instance name and value is the instance detail
[ "Get", "details", "of", "all", "EC2", "instances", "in", "a", "stack" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/cloud.rb#L256-L266
train
emilsoman/cloudster
lib/cloudster/cloud.rb
Cloudster.Cloud.get_elb_details
def get_elb_details(options = {}) stack_resources = resources(options) elb_resource_ids = get_resource_ids(stack_resources, "AWS::ElasticLoadBalancing::LoadBalancer") elb = Fog::AWS::ELB.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) elb_details = {} elb_resource_ids.each do |key, value| elb_instance_details = elb.describe_load_balancers("LoadBalancerNames" => [value]) elb_details[key] = elb_instance_details.body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"][0] rescue nil end return elb_details end
ruby
def get_elb_details(options = {}) stack_resources = resources(options) elb_resource_ids = get_resource_ids(stack_resources, "AWS::ElasticLoadBalancing::LoadBalancer") elb = Fog::AWS::ELB.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) elb_details = {} elb_resource_ids.each do |key, value| elb_instance_details = elb.describe_load_balancers("LoadBalancerNames" => [value]) elb_details[key] = elb_instance_details.body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"][0] rescue nil end return elb_details end
[ "def", "get_elb_details", "(", "options", "=", "{", "}", ")", "stack_resources", "=", "resources", "(", "options", ")", "elb_resource_ids", "=", "get_resource_ids", "(", "stack_resources", ",", "\"AWS::ElasticLoadBalancing::LoadBalancer\"", ")", "elb", "=", "Fog", "::", "AWS", "::", "ELB", ".", "new", "(", ":aws_access_key_id", "=>", "@access_key_id", ",", ":aws_secret_access_key", "=>", "@secret_access_key", ",", ":region", "=>", "@region", ")", "elb_details", "=", "{", "}", "elb_resource_ids", ".", "each", "do", "|", "key", ",", "value", "|", "elb_instance_details", "=", "elb", ".", "describe_load_balancers", "(", "\"LoadBalancerNames\"", "=>", "[", "value", "]", ")", "elb_details", "[", "key", "]", "=", "elb_instance_details", ".", "body", "[", "\"DescribeLoadBalancersResult\"", "]", "[", "\"LoadBalancerDescriptions\"", "]", "[", "0", "]", "rescue", "nil", "end", "return", "elb_details", "end" ]
Get details of all Elastic Load Balancers in the stack ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) cloud.get_elb_details(:stack_name => 'ShittyStack') ==== Parameters * options<~Hash> * :stack_name : A string which will contain the name of the stack ==== Returns * A hash containing elb details where the key is the logical name and value contains the details
[ "Get", "details", "of", "all", "Elastic", "Load", "Balancers", "in", "the", "stack" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/cloud.rb#L284-L294
train
emilsoman/cloudster
lib/cloudster/cloud.rb
Cloudster.Cloud.outputs
def outputs(options = {}) require_options(options, [:stack_name]) stack_description = describe(:stack_name => options[:stack_name]) outputs = stack_description["Outputs"] rescue [] outputs_hash = {} outputs.each do |output| outputs_hash[output["OutputKey"]] = parse_outputs(output["OutputValue"]) end return outputs_hash end
ruby
def outputs(options = {}) require_options(options, [:stack_name]) stack_description = describe(:stack_name => options[:stack_name]) outputs = stack_description["Outputs"] rescue [] outputs_hash = {} outputs.each do |output| outputs_hash[output["OutputKey"]] = parse_outputs(output["OutputValue"]) end return outputs_hash end
[ "def", "outputs", "(", "options", "=", "{", "}", ")", "require_options", "(", "options", ",", "[", ":stack_name", "]", ")", "stack_description", "=", "describe", "(", ":stack_name", "=>", "options", "[", ":stack_name", "]", ")", "outputs", "=", "stack_description", "[", "\"Outputs\"", "]", "rescue", "[", "]", "outputs_hash", "=", "{", "}", "outputs", ".", "each", "do", "|", "output", "|", "outputs_hash", "[", "output", "[", "\"OutputKey\"", "]", "]", "=", "parse_outputs", "(", "output", "[", "\"OutputValue\"", "]", ")", "end", "return", "outputs_hash", "end" ]
Returns a hash containing the output values of each resource in the Stack ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) cloud.outputs(:stack_name => 'RDSStack') ==== Parameters * options<~Hash> * :stack_name : A string which will contain the name of the stack ==== Returns * Hash containing outputs of the stack
[ "Returns", "a", "hash", "containing", "the", "output", "values", "of", "each", "resource", "in", "the", "Stack" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/cloud.rb#L354-L363
train
emilsoman/cloudster
lib/cloudster/cloud.rb
Cloudster.Cloud.is_s3_bucket_name_available?
def is_s3_bucket_name_available?(bucket_name) s3 = Fog::Storage::AWS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key) begin response = s3.get_bucket(bucket_name) rescue Exception => e response = e.response end not_found_status = 404 return response[:status] == not_found_status end
ruby
def is_s3_bucket_name_available?(bucket_name) s3 = Fog::Storage::AWS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key) begin response = s3.get_bucket(bucket_name) rescue Exception => e response = e.response end not_found_status = 404 return response[:status] == not_found_status end
[ "def", "is_s3_bucket_name_available?", "(", "bucket_name", ")", "s3", "=", "Fog", "::", "Storage", "::", "AWS", ".", "new", "(", ":aws_access_key_id", "=>", "@access_key_id", ",", ":aws_secret_access_key", "=>", "@secret_access_key", ")", "begin", "response", "=", "s3", ".", "get_bucket", "(", "bucket_name", ")", "rescue", "Exception", "=>", "e", "response", "=", "e", ".", "response", "end", "not_found_status", "=", "404", "return", "response", "[", ":status", "]", "==", "not_found_status", "end" ]
Returns true if S3 bucket name is available, else returns false ==== Examples cloud = Cloudster::Cloud.new( :access_key_id => 'aws_access_key_id', :secret_access_key => 'aws_secret_access_key', :region => 'us-east-1' ) cloud.is_s3_bucket_name_available?('test-bucket-name') ==== Parameter * String containing the bucket name ==== Returns * true - If bucket name is available * false - If bucket name is not available
[ "Returns", "true", "if", "S3", "bucket", "name", "is", "available", "else", "returns", "false" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/cloud.rb#L451-L460
train
activenetwork/gattica
lib/gattica/convertible.rb
Gattica.Convertible.to_h
def to_h output = {} instance_variables.each do |var| output.merge!({ var[1..-1] => instance_variable_get(var) }) unless var == '@xml' # exclude the whole XML dump end output end
ruby
def to_h output = {} instance_variables.each do |var| output.merge!({ var[1..-1] => instance_variable_get(var) }) unless var == '@xml' # exclude the whole XML dump end output end
[ "def", "to_h", "output", "=", "{", "}", "instance_variables", ".", "each", "do", "|", "var", "|", "output", ".", "merge!", "(", "{", "var", "[", "1", "..", "-", "1", "]", "=>", "instance_variable_get", "(", "var", ")", "}", ")", "unless", "var", "==", "'@xml'", "end", "output", "end" ]
output as hash
[ "output", "as", "hash" ]
359a5a70eba67e0f9ddd6081cb4defbf14d2e74b
https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica/convertible.rb#L8-L14
train
nicstrong/android-adb
lib/android-adb/Adb.rb
AndroidAdb.Adb.get_devices
def get_devices devices = [] run_adb("devices") do |pout| pout.each do |line| line = line.strip if (!line.empty? && line !~ /^List of devices/) parts = line.split device = AndroidAdb::Device.new(parts[0], parts[1]) devices << device end end end return devices end
ruby
def get_devices devices = [] run_adb("devices") do |pout| pout.each do |line| line = line.strip if (!line.empty? && line !~ /^List of devices/) parts = line.split device = AndroidAdb::Device.new(parts[0], parts[1]) devices << device end end end return devices end
[ "def", "get_devices", "devices", "=", "[", "]", "run_adb", "(", "\"devices\"", ")", "do", "|", "pout", "|", "pout", ".", "each", "do", "|", "line", "|", "line", "=", "line", ".", "strip", "if", "(", "!", "line", ".", "empty?", "&&", "line", "!~", "/", "/", ")", "parts", "=", "line", ".", "split", "device", "=", "AndroidAdb", "::", "Device", ".", "new", "(", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ")", "devices", "<<", "device", "end", "end", "end", "return", "devices", "end" ]
Contructs an Adb object for issuing commands to the connected device or emulator. If the adb path is not specified in the +opts+ hash it is determined in the following order: 1. Try and use the unix which command to locate the adb binary. 2. Use the ANDROID_HOME environment variable. 3. Default to adb (no path specified). @param [Hash] opts The options to create the Adb object with. @option opts [Logger] :log A log4r logger that debug information can be sent too. @option opts [Boolean] :dry_run Does not execute the *adb* command but will log the command and set last_command. @option opts [Boolean] :adb_path Manually set the path to the adb binary. Returns a list of all connected devices. The collection is returned as a hash containing the device name <tt>:name</tt> and the serial <tt>:serial</tt>. @return [Array<Device>] THe list of connected devices/emulators.
[ "Contructs", "an", "Adb", "object", "for", "issuing", "commands", "to", "the", "connected", "device", "or", "emulator", "." ]
3db27394074c82342fe397bf18912c7dc9bef413
https://github.com/nicstrong/android-adb/blob/3db27394074c82342fe397bf18912c7dc9bef413/lib/android-adb/Adb.rb#L40-L53
train
nicstrong/android-adb
lib/android-adb/Adb.rb
AndroidAdb.Adb.get_packages
def get_packages(adb_opts = {}) packages = [] run_adb_shell("pm list packages -f", adb_opts) do |pout| pout.each do |line| @log.debug("{stdout} #{line}") unless @log.nil? parts = line.split(":") if (parts.length > 1) info = parts[1].strip.split("=") package = AndroidAdb::Package.new(info[1], info[0]); packages << package; end end end return packages end
ruby
def get_packages(adb_opts = {}) packages = [] run_adb_shell("pm list packages -f", adb_opts) do |pout| pout.each do |line| @log.debug("{stdout} #{line}") unless @log.nil? parts = line.split(":") if (parts.length > 1) info = parts[1].strip.split("=") package = AndroidAdb::Package.new(info[1], info[0]); packages << package; end end end return packages end
[ "def", "get_packages", "(", "adb_opts", "=", "{", "}", ")", "packages", "=", "[", "]", "run_adb_shell", "(", "\"pm list packages -f\"", ",", "adb_opts", ")", "do", "|", "pout", "|", "pout", ".", "each", "do", "|", "line", "|", "@log", ".", "debug", "(", "\"{stdout} #{line}\"", ")", "unless", "@log", ".", "nil?", "parts", "=", "line", ".", "split", "(", "\":\"", ")", "if", "(", "parts", ".", "length", ">", "1", ")", "info", "=", "parts", "[", "1", "]", ".", "strip", ".", "split", "(", "\"=\"", ")", "package", "=", "AndroidAdb", "::", "Package", ".", "new", "(", "info", "[", "1", "]", ",", "info", "[", "0", "]", ")", ";", "packages", "<<", "package", ";", "end", "end", "end", "return", "packages", "end" ]
Returns a list of all installed packages on the device. @param [Hash] adb_opts Options for the adb command (@see #run_adb) @return [Hash] THe list of installed packages. The hash returned contains the apk file name <tt>:apk</tt> and the name of the package <tt>:name</tt>.
[ "Returns", "a", "list", "of", "all", "installed", "packages", "on", "the", "device", "." ]
3db27394074c82342fe397bf18912c7dc9bef413
https://github.com/nicstrong/android-adb/blob/3db27394074c82342fe397bf18912c7dc9bef413/lib/android-adb/Adb.rb#L58-L72
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/helper.rb
CelluloidPubsub.Helper.setup_celluloid_logger
def setup_celluloid_logger return if !debug_enabled? || (respond_to?(:log_file_path) && log_file_path.blank?) setup_log_file Celluloid.logger = ::Logger.new(log_file_path.present? ? log_file_path : STDOUT) setup_celluloid_exception_handler end
ruby
def setup_celluloid_logger return if !debug_enabled? || (respond_to?(:log_file_path) && log_file_path.blank?) setup_log_file Celluloid.logger = ::Logger.new(log_file_path.present? ? log_file_path : STDOUT) setup_celluloid_exception_handler end
[ "def", "setup_celluloid_logger", "return", "if", "!", "debug_enabled?", "||", "(", "respond_to?", "(", ":log_file_path", ")", "&&", "log_file_path", ".", "blank?", ")", "setup_log_file", "Celluloid", ".", "logger", "=", "::", "Logger", ".", "new", "(", "log_file_path", ".", "present?", "?", "log_file_path", ":", "STDOUT", ")", "setup_celluloid_exception_handler", "end" ]
sets the celluloid logger and the celluloid exception handler @return [void] @api private
[ "sets", "the", "celluloid", "logger", "and", "the", "celluloid", "exception", "handler" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/helper.rb#L94-L99
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/helper.rb
CelluloidPubsub.Helper.setup_celluloid_exception_handler
def setup_celluloid_exception_handler Celluloid.task_class = defined?(Celluloid::TaskThread) ? Celluloid::TaskThread : Celluloid::Task::Threaded Celluloid.exception_handler do |ex| puts ex unless filtered_error?(ex) end end
ruby
def setup_celluloid_exception_handler Celluloid.task_class = defined?(Celluloid::TaskThread) ? Celluloid::TaskThread : Celluloid::Task::Threaded Celluloid.exception_handler do |ex| puts ex unless filtered_error?(ex) end end
[ "def", "setup_celluloid_exception_handler", "Celluloid", ".", "task_class", "=", "defined?", "(", "Celluloid", "::", "TaskThread", ")", "?", "Celluloid", "::", "TaskThread", ":", "Celluloid", "::", "Task", "::", "Threaded", "Celluloid", ".", "exception_handler", "do", "|", "ex", "|", "puts", "ex", "unless", "filtered_error?", "(", "ex", ")", "end", "end" ]
sets the celluloid exception handler @return [void] @api private
[ "sets", "the", "celluloid", "exception", "handler" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/helper.rb#L106-L111
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/helper.rb
CelluloidPubsub.Helper.setup_log_file
def setup_log_file return if !debug_enabled? || (respond_to?(:log_file_path) && log_file_path.blank?) FileUtils.mkdir_p(File.dirname(log_file_path)) unless File.directory?(log_file_path) log_file = File.open(log_file_path, 'w') log_file.sync = true end
ruby
def setup_log_file return if !debug_enabled? || (respond_to?(:log_file_path) && log_file_path.blank?) FileUtils.mkdir_p(File.dirname(log_file_path)) unless File.directory?(log_file_path) log_file = File.open(log_file_path, 'w') log_file.sync = true end
[ "def", "setup_log_file", "return", "if", "!", "debug_enabled?", "||", "(", "respond_to?", "(", ":log_file_path", ")", "&&", "log_file_path", ".", "blank?", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "log_file_path", ")", ")", "unless", "File", ".", "directory?", "(", "log_file_path", ")", "log_file", "=", "File", ".", "open", "(", "log_file_path", ",", "'w'", ")", "log_file", ".", "sync", "=", "true", "end" ]
creates the log file where the debug messages will be printed @return [void] @api private
[ "creates", "the", "log", "file", "where", "the", "debug", "messages", "will", "be", "printed" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/helper.rb#L118-L123
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/helper.rb
CelluloidPubsub.Helper.parse_options
def parse_options(options) options = options.is_a?(Array) ? options.first : options options = options.is_a?(Hash) ? options.stringify_keys : {} options end
ruby
def parse_options(options) options = options.is_a?(Array) ? options.first : options options = options.is_a?(Hash) ? options.stringify_keys : {} options end
[ "def", "parse_options", "(", "options", ")", "options", "=", "options", ".", "is_a?", "(", "Array", ")", "?", "options", ".", "first", ":", "options", "options", "=", "options", ".", "is_a?", "(", "Hash", ")", "?", "options", ".", "stringify_keys", ":", "{", "}", "options", "end" ]
receives a list of options that need to be parsed if it is an Array will return the first element , otherwise if it is an Hash will return the hash with string keys, otherwise an empty hash @param [Hash, Array] options the options that need to be parsed @return [Hash] @api private
[ "receives", "a", "list", "of", "options", "that", "need", "to", "be", "parsed", "if", "it", "is", "an", "Array", "will", "return", "the", "first", "element", "otherwise", "if", "it", "is", "an", "Hash", "will", "return", "the", "hash", "with", "string", "keys", "otherwise", "an", "empty", "hash" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/helper.rb#L145-L149
train
adjust/dumbo
lib/dumbo/dependency_resolver.rb
Dumbo.DependencyResolver.resolve
def resolve list = dependency_list.sort { |a, b| a.last.size <=> b.last.size } resolve_list(list) end
ruby
def resolve list = dependency_list.sort { |a, b| a.last.size <=> b.last.size } resolve_list(list) end
[ "def", "resolve", "list", "=", "dependency_list", ".", "sort", "{", "|", "a", ",", "b", "|", "a", ".", "last", ".", "size", "<=>", "b", ".", "last", ".", "size", "}", "resolve_list", "(", "list", ")", "end" ]
Constructor accepts an array of files
[ "Constructor", "accepts", "an", "array", "of", "files" ]
e4a4821e86f0be26be8eb07f692610ba1b4bad12
https://github.com/adjust/dumbo/blob/e4a4821e86f0be26be8eb07f692610ba1b4bad12/lib/dumbo/dependency_resolver.rb#L24-L27
train
jronallo/microdata
lib/microdata/itemprop.rb
Microdata.Itemprop.make_absolute_url
def make_absolute_url(url) return url unless URI.parse(url).relative? begin URI.parse(@page_url).merge(url).to_s rescue URI::Error url end end
ruby
def make_absolute_url(url) return url unless URI.parse(url).relative? begin URI.parse(@page_url).merge(url).to_s rescue URI::Error url end end
[ "def", "make_absolute_url", "(", "url", ")", "return", "url", "unless", "URI", ".", "parse", "(", "url", ")", ".", "relative?", "begin", "URI", ".", "parse", "(", "@page_url", ")", ".", "merge", "(", "url", ")", ".", "to_s", "rescue", "URI", "::", "Error", "url", "end", "end" ]
This returns an empty string if can't form a valid absolute url as per the Microdata spec.
[ "This", "returns", "an", "empty", "string", "if", "can", "t", "form", "a", "valid", "absolute", "url", "as", "per", "the", "Microdata", "spec", "." ]
9af0e41801a815b1d14d5bb56f35bdd6c35ab006
https://github.com/jronallo/microdata/blob/9af0e41801a815b1d14d5bb56f35bdd6c35ab006/lib/microdata/itemprop.rb#L49-L56
train
emmanuel/aequitas
lib/aequitas/support/ordered_hash.rb
Aequitas.OrderedHash.[]=
def []=(k, i=nil, v=nil) if v insert(i,k,v) else store(k,i) end end
ruby
def []=(k, i=nil, v=nil) if v insert(i,k,v) else store(k,i) end end
[ "def", "[]=", "(", "k", ",", "i", "=", "nil", ",", "v", "=", "nil", ")", "if", "v", "insert", "(", "i", ",", "k", ",", "v", ")", "else", "store", "(", "k", ",", "i", ")", "end", "end" ]
Store operator. h[key] = value Or with additional index. h[key,index] = value
[ "Store", "operator", "." ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/support/ordered_hash.rb#L232-L238
train
jonathanchrisp/fredapi
lib/fredapi/request.rb
FREDAPI.Request.request
def request method, path, opts={} conn_options = connection_options opts opts['api_key'] = api_key unless opts.has_key? 'api_key' opts['file_type'] = file_type unless opts.has_key? 'file_type' response = connection(conn_options).send(method) do |request| case method when :get request.url path, opts when :delete request.url path, opts when :patch, :post, :put if conn_options[:force_urlencoded] request.url path, opts else request.path = path request.body = MultiJson.dump(opts) unless opts.empty? end end end response end
ruby
def request method, path, opts={} conn_options = connection_options opts opts['api_key'] = api_key unless opts.has_key? 'api_key' opts['file_type'] = file_type unless opts.has_key? 'file_type' response = connection(conn_options).send(method) do |request| case method when :get request.url path, opts when :delete request.url path, opts when :patch, :post, :put if conn_options[:force_urlencoded] request.url path, opts else request.path = path request.body = MultiJson.dump(opts) unless opts.empty? end end end response end
[ "def", "request", "method", ",", "path", ",", "opts", "=", "{", "}", "conn_options", "=", "connection_options", "opts", "opts", "[", "'api_key'", "]", "=", "api_key", "unless", "opts", ".", "has_key?", "'api_key'", "opts", "[", "'file_type'", "]", "=", "file_type", "unless", "opts", ".", "has_key?", "'file_type'", "response", "=", "connection", "(", "conn_options", ")", ".", "send", "(", "method", ")", "do", "|", "request", "|", "case", "method", "when", ":get", "request", ".", "url", "path", ",", "opts", "when", ":delete", "request", ".", "url", "path", ",", "opts", "when", ":patch", ",", ":post", ",", ":put", "if", "conn_options", "[", ":force_urlencoded", "]", "request", ".", "url", "path", ",", "opts", "else", "request", ".", "path", "=", "path", "request", ".", "body", "=", "MultiJson", ".", "dump", "(", "opts", ")", "unless", "opts", ".", "empty?", "end", "end", "end", "response", "end" ]
Perform a request @param method [String] Type of request path @param path [String] URL path to send request @param opts [Hash] Request parameters @return [Hashie::Mash] Response
[ "Perform", "a", "request" ]
8eda87f0732d6c8b909c61fc0e260cd6848dbee3
https://github.com/jonathanchrisp/fredapi/blob/8eda87f0732d6c8b909c61fc0e260cd6848dbee3/lib/fredapi/request.rb#L74-L96
train
opyh/motion-state-machine
lib/motion-state-machine/state.rb
StateMachine.State.enter!
def enter! @state_machine.current_state = self @entry_actions.each do |entry_action| entry_action.call(@state_machine) end @transition_map.each do |type, events_to_transition_arrays| events_to_transition_arrays.each do |event, transitions| transitions.each(&:arm) end end end
ruby
def enter! @state_machine.current_state = self @entry_actions.each do |entry_action| entry_action.call(@state_machine) end @transition_map.each do |type, events_to_transition_arrays| events_to_transition_arrays.each do |event, transitions| transitions.each(&:arm) end end end
[ "def", "enter!", "@state_machine", ".", "current_state", "=", "self", "@entry_actions", ".", "each", "do", "|", "entry_action", "|", "entry_action", ".", "call", "(", "@state_machine", ")", "end", "@transition_map", ".", "each", "do", "|", "type", ",", "events_to_transition_arrays", "|", "events_to_transition_arrays", ".", "each", "do", "|", "event", ",", "transitions", "|", "transitions", ".", "each", "(", "&", ":arm", ")", "end", "end", "end" ]
Sets the state machine's current_state to self, calls all entry actions and activates triggering mechanisms of all outgoing transitions.
[ "Sets", "the", "state", "machine", "s", "current_state", "to", "self", "calls", "all", "entry", "actions", "and", "activates", "triggering", "mechanisms", "of", "all", "outgoing", "transitions", "." ]
baafa93de4b05fe4ba91a3dbb944ab3d28b8913d
https://github.com/opyh/motion-state-machine/blob/baafa93de4b05fe4ba91a3dbb944ab3d28b8913d/lib/motion-state-machine/state.rb#L283-L294
train
opyh/motion-state-machine
lib/motion-state-machine/state.rb
StateMachine.State.exit!
def exit! map = @transition_map map.each do |type, events_to_transition_arrays| events_to_transition_arrays.each do |event, transitions| transitions.each(&:unarm) end end @exit_actions.each do |exit_action| exit_action.call(@state_machine) end @state_machine.current_state = nil end
ruby
def exit! map = @transition_map map.each do |type, events_to_transition_arrays| events_to_transition_arrays.each do |event, transitions| transitions.each(&:unarm) end end @exit_actions.each do |exit_action| exit_action.call(@state_machine) end @state_machine.current_state = nil end
[ "def", "exit!", "map", "=", "@transition_map", "map", ".", "each", "do", "|", "type", ",", "events_to_transition_arrays", "|", "events_to_transition_arrays", ".", "each", "do", "|", "event", ",", "transitions", "|", "transitions", ".", "each", "(", "&", ":unarm", ")", "end", "end", "@exit_actions", ".", "each", "do", "|", "exit_action", "|", "exit_action", ".", "call", "(", "@state_machine", ")", "end", "@state_machine", ".", "current_state", "=", "nil", "end" ]
Sets the state machine's current_state to nil, calls all exit actions and deactivates triggering mechanisms of all outgoing transitions.
[ "Sets", "the", "state", "machine", "s", "current_state", "to", "nil", "calls", "all", "exit", "actions", "and", "deactivates", "triggering", "mechanisms", "of", "all", "outgoing", "transitions", "." ]
baafa93de4b05fe4ba91a3dbb944ab3d28b8913d
https://github.com/opyh/motion-state-machine/blob/baafa93de4b05fe4ba91a3dbb944ab3d28b8913d/lib/motion-state-machine/state.rb#L301-L313
train
opyh/motion-state-machine
lib/motion-state-machine/state.rb
StateMachine.State.cleanup
def cleanup @transition_map.each do |type, events_to_transition_arrays| events_to_transition_arrays.each do |event, transitions| transitions.clear end end @transition_map = nil @state_machine = nil @entry_actions = nil @exit_actions = nil end
ruby
def cleanup @transition_map.each do |type, events_to_transition_arrays| events_to_transition_arrays.each do |event, transitions| transitions.clear end end @transition_map = nil @state_machine = nil @entry_actions = nil @exit_actions = nil end
[ "def", "cleanup", "@transition_map", ".", "each", "do", "|", "type", ",", "events_to_transition_arrays", "|", "events_to_transition_arrays", ".", "each", "do", "|", "event", ",", "transitions", "|", "transitions", ".", "clear", "end", "end", "@transition_map", "=", "nil", "@state_machine", "=", "nil", "@entry_actions", "=", "nil", "@exit_actions", "=", "nil", "end" ]
Cleans up references to allow easier GC.
[ "Cleans", "up", "references", "to", "allow", "easier", "GC", "." ]
baafa93de4b05fe4ba91a3dbb944ab3d28b8913d
https://github.com/opyh/motion-state-machine/blob/baafa93de4b05fe4ba91a3dbb944ab3d28b8913d/lib/motion-state-machine/state.rb#L318-L329
train
opyh/motion-state-machine
lib/motion-state-machine/state.rb
StateMachine.State.guarded_execute
def guarded_execute(event_type, event_trigger_value) @state_machine.raise_outside_initial_queue return if terminating? if @transition_map[event_type].nil? || @transition_map[event_type][event_trigger_value].nil? raise ArgumentError, "No registered transition found "\ "for event #{event_type}:#{event_trigger_value}." end possible_transitions = @transition_map[event_type][event_trigger_value] return if possible_transitions.empty? allowed_transitions = possible_transitions.select(&:allowed?) if allowed_transitions.empty? @state_machine.log "All transitions are disallowed for "\ "#{event_type}:#{event_trigger_value}." elsif allowed_transitions.count > 1 list = allowed_transitions.collect do |t| "-> #{t.options[:to]}" end raise RuntimeError, "Not sure which transition to trigger "\ "when #{symbol} while #{self} (allowed: #{list}). "\ "Please make sure guard conditions exclude each other." else transition = allowed_transitions.first unless transition.nil? transition.send :unguarded_execute end end end
ruby
def guarded_execute(event_type, event_trigger_value) @state_machine.raise_outside_initial_queue return if terminating? if @transition_map[event_type].nil? || @transition_map[event_type][event_trigger_value].nil? raise ArgumentError, "No registered transition found "\ "for event #{event_type}:#{event_trigger_value}." end possible_transitions = @transition_map[event_type][event_trigger_value] return if possible_transitions.empty? allowed_transitions = possible_transitions.select(&:allowed?) if allowed_transitions.empty? @state_machine.log "All transitions are disallowed for "\ "#{event_type}:#{event_trigger_value}." elsif allowed_transitions.count > 1 list = allowed_transitions.collect do |t| "-> #{t.options[:to]}" end raise RuntimeError, "Not sure which transition to trigger "\ "when #{symbol} while #{self} (allowed: #{list}). "\ "Please make sure guard conditions exclude each other." else transition = allowed_transitions.first unless transition.nil? transition.send :unguarded_execute end end end
[ "def", "guarded_execute", "(", "event_type", ",", "event_trigger_value", ")", "@state_machine", ".", "raise_outside_initial_queue", "return", "if", "terminating?", "if", "@transition_map", "[", "event_type", "]", ".", "nil?", "||", "@transition_map", "[", "event_type", "]", "[", "event_trigger_value", "]", ".", "nil?", "raise", "ArgumentError", ",", "\"No registered transition found \"", "\"for event #{event_type}:#{event_trigger_value}.\"", "end", "possible_transitions", "=", "@transition_map", "[", "event_type", "]", "[", "event_trigger_value", "]", "return", "if", "possible_transitions", ".", "empty?", "allowed_transitions", "=", "possible_transitions", ".", "select", "(", "&", ":allowed?", ")", "if", "allowed_transitions", ".", "empty?", "@state_machine", ".", "log", "\"All transitions are disallowed for \"", "\"#{event_type}:#{event_trigger_value}.\"", "elsif", "allowed_transitions", ".", "count", ">", "1", "list", "=", "allowed_transitions", ".", "collect", "do", "|", "t", "|", "\"-> #{t.options[:to]}\"", "end", "raise", "RuntimeError", ",", "\"Not sure which transition to trigger \"", "\"when #{symbol} while #{self} (allowed: #{list}). \"", "\"Please make sure guard conditions exclude each other.\"", "else", "transition", "=", "allowed_transitions", ".", "first", "unless", "transition", ".", "nil?", "transition", ".", "send", ":unguarded_execute", "end", "end", "end" ]
Executes the registered transition for the given event type and event trigger value, if such a transition exists and it is allowed. @raise [RuntimeError] if multiple transitions would be allowed at the same time.
[ "Executes", "the", "registered", "transition", "for", "the", "given", "event", "type", "and", "event", "trigger", "value", "if", "such", "a", "transition", "exists", "and", "it", "is", "allowed", "." ]
baafa93de4b05fe4ba91a3dbb944ab3d28b8913d
https://github.com/opyh/motion-state-machine/blob/baafa93de4b05fe4ba91a3dbb944ab3d28b8913d/lib/motion-state-machine/state.rb#L339-L375
train
activenetwork/gattica
lib/gattica/user.rb
Gattica.User.validate
def validate raise GatticaError::InvalidEmail, "The email address '#{@email}' is not valid" if not @email.match(/^(?:[_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-zA-Z0-9\-\.]+)*(\.[a-z]{2,4})$/i) raise GatticaError::InvalidPassword, "The password cannot be blank" if @password.empty? || @password.nil? end
ruby
def validate raise GatticaError::InvalidEmail, "The email address '#{@email}' is not valid" if not @email.match(/^(?:[_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-zA-Z0-9\-\.]+)*(\.[a-z]{2,4})$/i) raise GatticaError::InvalidPassword, "The password cannot be blank" if @password.empty? || @password.nil? end
[ "def", "validate", "raise", "GatticaError", "::", "InvalidEmail", ",", "\"The email address '#{@email}' is not valid\"", "if", "not", "@email", ".", "match", "(", "/", "\\.", "\\.", "\\-", "\\.", "\\.", "/i", ")", "raise", "GatticaError", "::", "InvalidPassword", ",", "\"The password cannot be blank\"", "if", "@password", ".", "empty?", "||", "@password", ".", "nil?", "end" ]
Determine whether or not this is a valid user
[ "Determine", "whether", "or", "not", "this", "is", "a", "valid", "user" ]
359a5a70eba67e0f9ddd6081cb4defbf14d2e74b
https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica/user.rb#L25-L28
train
jonathanchrisp/fredapi
lib/fredapi/configuration.rb
FREDAPI.Configuration.options
def options OPTION_KEYS.inject({}){|o,k|o.merge!(k => send(k))} end
ruby
def options OPTION_KEYS.inject({}){|o,k|o.merge!(k => send(k))} end
[ "def", "options", "OPTION_KEYS", ".", "inject", "(", "{", "}", ")", "{", "|", "o", ",", "k", "|", "o", ".", "merge!", "(", "k", "=>", "send", "(", "k", ")", ")", "}", "end" ]
Convert option_keys to hash and return
[ "Convert", "option_keys", "to", "hash", "and", "return" ]
8eda87f0732d6c8b909c61fc0e260cd6848dbee3
https://github.com/jonathanchrisp/fredapi/blob/8eda87f0732d6c8b909c61fc0e260cd6848dbee3/lib/fredapi/configuration.rb#L33-L35
train
TheArtificial/rails-wiki
app/models/wiki/wiki.rb
Wiki.Wiki.recent_updates
def recent_updates(options) default_options = { path: nil, limit: 10 } options = default_options.merge(options) limit = [options[:limit], 1].max paging_window = limit * 2 updates_hash = {} offset = 0 until updates_hash.count >= limit changes = recent_changes(options[:path], paging_window, offset) break if changes.nil? # we ran out of commits first group_changes_into_updates(changes, updates_hash) offset += paging_window end return updates_hash.values.take(limit) end
ruby
def recent_updates(options) default_options = { path: nil, limit: 10 } options = default_options.merge(options) limit = [options[:limit], 1].max paging_window = limit * 2 updates_hash = {} offset = 0 until updates_hash.count >= limit changes = recent_changes(options[:path], paging_window, offset) break if changes.nil? # we ran out of commits first group_changes_into_updates(changes, updates_hash) offset += paging_window end return updates_hash.values.take(limit) end
[ "def", "recent_updates", "(", "options", ")", "default_options", "=", "{", "path", ":", "nil", ",", "limit", ":", "10", "}", "options", "=", "default_options", ".", "merge", "(", "options", ")", "limit", "=", "[", "options", "[", ":limit", "]", ",", "1", "]", ".", "max", "paging_window", "=", "limit", "*", "2", "updates_hash", "=", "{", "}", "offset", "=", "0", "until", "updates_hash", ".", "count", ">=", "limit", "changes", "=", "recent_changes", "(", "options", "[", ":path", "]", ",", "paging_window", ",", "offset", ")", "break", "if", "changes", ".", "nil?", "group_changes_into_updates", "(", "changes", ",", "updates_hash", ")", "offset", "+=", "paging_window", "end", "return", "updates_hash", ".", "values", ".", "take", "(", "limit", ")", "end" ]
one entry for each file
[ "one", "entry", "for", "each", "file" ]
234aafbd26ffaf57092cfe6a4cf834c9a18590e0
https://github.com/TheArtificial/rails-wiki/blob/234aafbd26ffaf57092cfe6a4cf834c9a18590e0/app/models/wiki/wiki.rb#L60-L78
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/client.rb
CelluloidPubsub.Client.supervise_actors
def supervise_actors current_actor = Actor.current @actor.link current_actor if @actor.respond_to?(:link) current_actor.link connection end
ruby
def supervise_actors current_actor = Actor.current @actor.link current_actor if @actor.respond_to?(:link) current_actor.link connection end
[ "def", "supervise_actors", "current_actor", "=", "Actor", ".", "current", "@actor", ".", "link", "current_actor", "if", "@actor", ".", "respond_to?", "(", ":link", ")", "current_actor", ".", "link", "connection", "end" ]
the method will link the current actor to the actor that is attached to, and the connection to the current actor @return [void] @api public
[ "the", "method", "will", "link", "the", "current", "actor", "to", "the", "actor", "that", "is", "attached", "to", "and", "the", "connection", "to", "the", "current", "actor" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/client.rb#L70-L74
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/client.rb
CelluloidPubsub.Client.on_message
def on_message(data) message = JSON.parse(data) log_debug("#{@actor.class} received JSON #{message}") if @actor.respond_to?(:async) @actor.async.on_message(message) else @actor.on_message(message) end end
ruby
def on_message(data) message = JSON.parse(data) log_debug("#{@actor.class} received JSON #{message}") if @actor.respond_to?(:async) @actor.async.on_message(message) else @actor.on_message(message) end end
[ "def", "on_message", "(", "data", ")", "message", "=", "JSON", ".", "parse", "(", "data", ")", "log_debug", "(", "\"#{@actor.class} received JSON #{message}\"", ")", "if", "@actor", ".", "respond_to?", "(", ":async", ")", "@actor", ".", "async", ".", "on_message", "(", "message", ")", "else", "@actor", ".", "on_message", "(", "message", ")", "end", "end" ]
callback executes when actor receives a message from a subscribed channel and parses the message using JSON.parse and dispatches the parsed message to the original actor that made the connection @param [JSON] data @return [void] @api public
[ "callback", "executes", "when", "actor", "receives", "a", "message", "from", "a", "subscribed", "channel", "and", "parses", "the", "message", "using", "JSON", ".", "parse", "and", "dispatches", "the", "parsed", "message", "to", "the", "original", "actor", "that", "made", "the", "connection" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/client.rb#L211-L219
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/client.rb
CelluloidPubsub.Client.on_close
def on_close(code, reason) connection.terminate terminate log_debug("#{@actor.class} dispatching on close #{code} #{reason}") if @actor.respond_to?(:async) @actor.async.on_close(code, reason) else @actor.on_close(code, reason) end end
ruby
def on_close(code, reason) connection.terminate terminate log_debug("#{@actor.class} dispatching on close #{code} #{reason}") if @actor.respond_to?(:async) @actor.async.on_close(code, reason) else @actor.on_close(code, reason) end end
[ "def", "on_close", "(", "code", ",", "reason", ")", "connection", ".", "terminate", "terminate", "log_debug", "(", "\"#{@actor.class} dispatching on close #{code} #{reason}\"", ")", "if", "@actor", ".", "respond_to?", "(", ":async", ")", "@actor", ".", "async", ".", "on_close", "(", "code", ",", "reason", ")", "else", "@actor", ".", "on_close", "(", "code", ",", "reason", ")", "end", "end" ]
callback executes when connection closes @param [String] code @param [String] reason @return [void] @api public
[ "callback", "executes", "when", "connection", "closes" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/client.rb#L230-L239
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/client.rb
CelluloidPubsub.Client.send_action
def send_action(action, channel = nil, data = {}) data = data.is_a?(Hash) ? data : {} publishing_data = { 'client_action' => action, 'channel' => channel, 'data' => data }.reject { |_key, value| value.blank? } async.chat(publishing_data) end
ruby
def send_action(action, channel = nil, data = {}) data = data.is_a?(Hash) ? data : {} publishing_data = { 'client_action' => action, 'channel' => channel, 'data' => data }.reject { |_key, value| value.blank? } async.chat(publishing_data) end
[ "def", "send_action", "(", "action", ",", "channel", "=", "nil", ",", "data", "=", "{", "}", ")", "data", "=", "data", ".", "is_a?", "(", "Hash", ")", "?", "data", ":", "{", "}", "publishing_data", "=", "{", "'client_action'", "=>", "action", ",", "'channel'", "=>", "channel", ",", "'data'", "=>", "data", "}", ".", "reject", "{", "|", "_key", ",", "value", "|", "value", ".", "blank?", "}", "async", ".", "chat", "(", "publishing_data", ")", "end" ]
method used to send an action to the webserver reactor , to a chanel and with data @param [String] action @param [String] channel @param [Hash] data @return [void] @api private
[ "method", "used", "to", "send", "an", "action", "to", "the", "webserver", "reactor", "to", "a", "chanel", "and", "with", "data" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/client.rb#L252-L256
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/client.rb
CelluloidPubsub.Client.chat
def chat(message) final_message = message.is_a?(Hash) ? message.to_json : JSON.dump(action: 'message', message: message) log_debug("#{@actor.class} sends JSON #{final_message}") connection.text final_message end
ruby
def chat(message) final_message = message.is_a?(Hash) ? message.to_json : JSON.dump(action: 'message', message: message) log_debug("#{@actor.class} sends JSON #{final_message}") connection.text final_message end
[ "def", "chat", "(", "message", ")", "final_message", "=", "message", ".", "is_a?", "(", "Hash", ")", "?", "message", ".", "to_json", ":", "JSON", ".", "dump", "(", "action", ":", "'message'", ",", "message", ":", "message", ")", "log_debug", "(", "\"#{@actor.class} sends JSON #{final_message}\"", ")", "connection", ".", "text", "final_message", "end" ]
method used to send messages to the webserver checks too see if the message is a hash and if it is it will transform it to JSON and send it to the webser otherwise will construct a JSON object that will have the key action with the value 'message" and the key message witth the parameter's value @param [Hash] message @return [void] @api private
[ "method", "used", "to", "send", "messages", "to", "the", "webserver", "checks", "too", "see", "if", "the", "message", "is", "a", "hash", "and", "if", "it", "is", "it", "will", "transform", "it", "to", "JSON", "and", "send", "it", "to", "the", "webser", "otherwise", "will", "construct", "a", "JSON", "object", "that", "will", "have", "the", "key", "action", "with", "the", "value", "message", "and", "the", "key", "message", "witth", "the", "parameter", "s", "value" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/client.rb#L267-L271
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.handle_parsed_websocket_message
def handle_parsed_websocket_message(json_data) data = json_data.is_a?(Hash) ? json_data.stringify_keys : {} if CelluloidPubsub::Reactor::AVAILABLE_ACTIONS.include?(data['client_action'].to_s) log_debug "#{self.class} finds actions for #{json_data}" delegate_action(data) if data['client_action'].present? else handle_unknown_action(data['channel'], json_data) end end
ruby
def handle_parsed_websocket_message(json_data) data = json_data.is_a?(Hash) ? json_data.stringify_keys : {} if CelluloidPubsub::Reactor::AVAILABLE_ACTIONS.include?(data['client_action'].to_s) log_debug "#{self.class} finds actions for #{json_data}" delegate_action(data) if data['client_action'].present? else handle_unknown_action(data['channel'], json_data) end end
[ "def", "handle_parsed_websocket_message", "(", "json_data", ")", "data", "=", "json_data", ".", "is_a?", "(", "Hash", ")", "?", "json_data", ".", "stringify_keys", ":", "{", "}", "if", "CelluloidPubsub", "::", "Reactor", "::", "AVAILABLE_ACTIONS", ".", "include?", "(", "data", "[", "'client_action'", "]", ".", "to_s", ")", "log_debug", "\"#{self.class} finds actions for #{json_data}\"", "delegate_action", "(", "data", ")", "if", "data", "[", "'client_action'", "]", ".", "present?", "else", "handle_unknown_action", "(", "data", "[", "'channel'", "]", ",", "json_data", ")", "end", "end" ]
method that checks if the data is a Hash if the data is a hash then will stringify the keys and will call the method {#delegate_action} that will handle the message, otherwise will call the method {#handle_unknown_action} @see #delegate_action @see #handle_unknown_action @param [Hash] json_data @return [void] @api public
[ "method", "that", "checks", "if", "the", "data", "is", "a", "Hash" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L149-L157
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.unsubscribe
def unsubscribe(channel, _json_data) log_debug "#{self.class} runs 'unsubscribe' method with #{channel}" return unless channel.present? forget_channel(channel) delete_server_subscribers(channel) end
ruby
def unsubscribe(channel, _json_data) log_debug "#{self.class} runs 'unsubscribe' method with #{channel}" return unless channel.present? forget_channel(channel) delete_server_subscribers(channel) end
[ "def", "unsubscribe", "(", "channel", ",", "_json_data", ")", "log_debug", "\"#{self.class} runs 'unsubscribe' method with #{channel}\"", "return", "unless", "channel", ".", "present?", "forget_channel", "(", "channel", ")", "delete_server_subscribers", "(", "channel", ")", "end" ]
the method will unsubscribe a client by closing the websocket connection if has unscribed from all channels and deleting the reactor from the channel list on the server @param [String] channel @return [void] @api public
[ "the", "method", "will", "unsubscribe", "a", "client", "by", "closing", "the", "websocket", "connection", "if", "has", "unscribed", "from", "all", "channels", "and", "deleting", "the", "reactor", "from", "the", "channel", "list", "on", "the", "server" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L222-L227
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.delete_server_subscribers
def delete_server_subscribers(channel) @server.mutex.synchronize do (@server.subscribers[channel] || []).delete_if do |hash| hash[:reactor] == Actor.current end end end
ruby
def delete_server_subscribers(channel) @server.mutex.synchronize do (@server.subscribers[channel] || []).delete_if do |hash| hash[:reactor] == Actor.current end end end
[ "def", "delete_server_subscribers", "(", "channel", ")", "@server", ".", "mutex", ".", "synchronize", "do", "(", "@server", ".", "subscribers", "[", "channel", "]", "||", "[", "]", ")", ".", "delete_if", "do", "|", "hash", "|", "hash", "[", ":reactor", "]", "==", "Actor", ".", "current", "end", "end", "end" ]
the method will delete the reactor from the channel list on the server @param [String] channel @return [void] @api public
[ "the", "method", "will", "delete", "the", "reactor", "from", "the", "channel", "list", "on", "the", "server" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L236-L242
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.unsubscribe_clients
def unsubscribe_clients(channel, _json_data) log_debug "#{self.class} runs 'unsubscribe_clients' method with #{channel}" return if channel.blank? unsubscribe_from_channel(channel) @server.subscribers[channel] = [] end
ruby
def unsubscribe_clients(channel, _json_data) log_debug "#{self.class} runs 'unsubscribe_clients' method with #{channel}" return if channel.blank? unsubscribe_from_channel(channel) @server.subscribers[channel] = [] end
[ "def", "unsubscribe_clients", "(", "channel", ",", "_json_data", ")", "log_debug", "\"#{self.class} runs 'unsubscribe_clients' method with #{channel}\"", "return", "if", "channel", ".", "blank?", "unsubscribe_from_channel", "(", "channel", ")", "@server", ".", "subscribers", "[", "channel", "]", "=", "[", "]", "end" ]
the method will unsubscribe all clients subscribed to a channel by closing the @param [String] channel @return [void] @api public
[ "the", "method", "will", "unsubscribe", "all", "clients", "subscribed", "to", "a", "channel", "by", "closing", "the" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L251-L256
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.add_subscriber_to_channel
def add_subscriber_to_channel(channel, message) registry_channels = CelluloidPubsub::Registry.channels @channels << channel registry_channels << channel unless registry_channels.include?(channel) @server.mutex.synchronize do @server.subscribers[channel] = channel_subscribers(channel).push(reactor: Actor.current, message: message) end end
ruby
def add_subscriber_to_channel(channel, message) registry_channels = CelluloidPubsub::Registry.channels @channels << channel registry_channels << channel unless registry_channels.include?(channel) @server.mutex.synchronize do @server.subscribers[channel] = channel_subscribers(channel).push(reactor: Actor.current, message: message) end end
[ "def", "add_subscriber_to_channel", "(", "channel", ",", "message", ")", "registry_channels", "=", "CelluloidPubsub", "::", "Registry", ".", "channels", "@channels", "<<", "channel", "registry_channels", "<<", "channel", "unless", "registry_channels", ".", "include?", "(", "channel", ")", "@server", ".", "mutex", ".", "synchronize", "do", "@server", ".", "subscribers", "[", "channel", "]", "=", "channel_subscribers", "(", "channel", ")", ".", "push", "(", "reactor", ":", "Actor", ".", "current", ",", "message", ":", "message", ")", "end", "end" ]
adds the curent actor the list of the subscribers for a particular channel and registers the new channel @param [String] channel @param [Object] message @return [void] @api public
[ "adds", "the", "curent", "actor", "the", "list", "of", "the", "subscribers", "for", "a", "particular", "channel", "and", "registers", "the", "new", "channel" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L309-L316
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.publish
def publish(current_topic, json_data) message = json_data['data'].to_json return if current_topic.blank? || message.blank? server_pusblish_event(current_topic, message) rescue => exception log_debug("could not publish message #{message} into topic #{current_topic} because of #{exception.inspect}") end
ruby
def publish(current_topic, json_data) message = json_data['data'].to_json return if current_topic.blank? || message.blank? server_pusblish_event(current_topic, message) rescue => exception log_debug("could not publish message #{message} into topic #{current_topic} because of #{exception.inspect}") end
[ "def", "publish", "(", "current_topic", ",", "json_data", ")", "message", "=", "json_data", "[", "'data'", "]", ".", "to_json", "return", "if", "current_topic", ".", "blank?", "||", "message", ".", "blank?", "server_pusblish_event", "(", "current_topic", ",", "message", ")", "rescue", "=>", "exception", "log_debug", "(", "\"could not publish message #{message} into topic #{current_topic} because of #{exception.inspect}\"", ")", "end" ]
method for publishing data to a channel @param [String] current_topic The Channel to which the reactor instance {CelluloidPubsub::Reactor} will publish the message to @param [Object] json_data The additional data that contains the message that needs to be sent @return [void] @api public
[ "method", "for", "publishing", "data", "to", "a", "channel" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L326-L332
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.server_pusblish_event
def server_pusblish_event(current_topic, message) @server.mutex.synchronize do (@server.subscribers[current_topic].dup || []).pmap do |hash| hash[:reactor].websocket << message end end end
ruby
def server_pusblish_event(current_topic, message) @server.mutex.synchronize do (@server.subscribers[current_topic].dup || []).pmap do |hash| hash[:reactor].websocket << message end end end
[ "def", "server_pusblish_event", "(", "current_topic", ",", "message", ")", "@server", ".", "mutex", ".", "synchronize", "do", "(", "@server", ".", "subscribers", "[", "current_topic", "]", ".", "dup", "||", "[", "]", ")", ".", "pmap", "do", "|", "hash", "|", "hash", "[", ":reactor", "]", ".", "websocket", "<<", "message", "end", "end", "end" ]
the method will publish to all subsribers of a channel a message @param [String] current_topic @param [#to_s] message @return [void] @api public
[ "the", "method", "will", "publish", "to", "all", "subsribers", "of", "a", "channel", "a", "message" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L342-L348
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.unsubscribe_all
def unsubscribe_all(_channel, json_data) log_debug "#{self.class} runs 'unsubscribe_all' method" CelluloidPubsub::Registry.channels.dup.pmap do |channel| unsubscribe_clients(channel, json_data) end log_debug 'clearing connections' shutdown end
ruby
def unsubscribe_all(_channel, json_data) log_debug "#{self.class} runs 'unsubscribe_all' method" CelluloidPubsub::Registry.channels.dup.pmap do |channel| unsubscribe_clients(channel, json_data) end log_debug 'clearing connections' shutdown end
[ "def", "unsubscribe_all", "(", "_channel", ",", "json_data", ")", "log_debug", "\"#{self.class} runs 'unsubscribe_all' method\"", "CelluloidPubsub", "::", "Registry", ".", "channels", ".", "dup", ".", "pmap", "do", "|", "channel", "|", "unsubscribe_clients", "(", "channel", ",", "json_data", ")", "end", "log_debug", "'clearing connections'", "shutdown", "end" ]
unsubscribes all actors from all channels and terminates the curent actor @param [String] _channel NOT USED - needed to maintain compatibility with the other methods @param [Object] _json_data NOT USED - needed to maintain compatibility with the other methods @return [void] @api public
[ "unsubscribes", "all", "actors", "from", "all", "channels", "and", "terminates", "the", "curent", "actor" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L358-L365
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/reactor.rb
CelluloidPubsub.Reactor.server_kill_reactors
def server_kill_reactors(channel) @server.mutex.synchronize do (@server.subscribers[channel].dup || []).pmap do |hash| reactor = hash[:reactor] reactor.websocket.close Celluloid::Actor.kill(reactor) end end end
ruby
def server_kill_reactors(channel) @server.mutex.synchronize do (@server.subscribers[channel].dup || []).pmap do |hash| reactor = hash[:reactor] reactor.websocket.close Celluloid::Actor.kill(reactor) end end end
[ "def", "server_kill_reactors", "(", "channel", ")", "@server", ".", "mutex", ".", "synchronize", "do", "(", "@server", ".", "subscribers", "[", "channel", "]", ".", "dup", "||", "[", "]", ")", ".", "pmap", "do", "|", "hash", "|", "reactor", "=", "hash", "[", ":reactor", "]", "reactor", ".", "websocket", ".", "close", "Celluloid", "::", "Actor", ".", "kill", "(", "reactor", ")", "end", "end", "end" ]
kills all reactors registered on a channel and closes their websocket connection @param [String] channel @return [void] @api public
[ "kills", "all", "reactors", "registered", "on", "a", "channel", "and", "closes", "their", "websocket", "connection" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/reactor.rb#L384-L392
train
LessonPlanet/emaildirect-ruby
lib/emaildirect/relay_send/email.rb
EmailDirect.RelaySend::Email.send
def send(options) response = EmailDirect.post "/RelaySends/#{category_id}", :body => options.to_json Hashie::Mash.new(response) end
ruby
def send(options) response = EmailDirect.post "/RelaySends/#{category_id}", :body => options.to_json Hashie::Mash.new(response) end
[ "def", "send", "(", "options", ")", "response", "=", "EmailDirect", ".", "post", "\"/RelaySends/#{category_id}\"", ",", ":body", "=>", "options", ".", "to_json", "Hashie", "::", "Mash", ".", "new", "(", "response", ")", "end" ]
Sends a custom message. See the docs for all the possible options @see https://docs.emaildirect.com/#RelaySendCustomEmail
[ "Sends", "a", "custom", "message", ".", "See", "the", "docs", "for", "all", "the", "possible", "options" ]
b785104fa867414f18c17981542edff3794d0224
https://github.com/LessonPlanet/emaildirect-ruby/blob/b785104fa867414f18c17981542edff3794d0224/lib/emaildirect/relay_send/email.rb#L16-L19
train
emmanuel/aequitas
lib/aequitas/contextual_rule_set.rb
Aequitas.ContextualRuleSet.concat
def concat(other) other.rule_sets.each do |context_name, rule_set| add_rules_to_context(context_name, rule_set) end self end
ruby
def concat(other) other.rule_sets.each do |context_name, rule_set| add_rules_to_context(context_name, rule_set) end self end
[ "def", "concat", "(", "other", ")", "other", ".", "rule_sets", ".", "each", "do", "|", "context_name", ",", "rule_set", "|", "add_rules_to_context", "(", "context_name", ",", "rule_set", ")", "end", "self", "end" ]
Assimilate all rules contained in +other+ into the receiver @param [ContextualRuleSet] other the ContextualRuleSet whose rules are to be assimilated @return [self] @api private
[ "Assimilate", "all", "rules", "contained", "in", "+", "other", "+", "into", "the", "receiver" ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/contextual_rule_set.rb#L134-L140
train
emmanuel/aequitas
lib/aequitas/contextual_rule_set.rb
Aequitas.ContextualRuleSet.define_context
def define_context(context_name) rule_sets.fetch(context_name) do |context_name| rule_sets[context_name] = RuleSet.new end self end
ruby
def define_context(context_name) rule_sets.fetch(context_name) do |context_name| rule_sets[context_name] = RuleSet.new end self end
[ "def", "define_context", "(", "context_name", ")", "rule_sets", ".", "fetch", "(", "context_name", ")", "do", "|", "context_name", "|", "rule_sets", "[", "context_name", "]", "=", "RuleSet", ".", "new", "end", "self", "end" ]
Initialize and assign a RuleSet for the named context @param [Symbol] context_name the name of the context to be defined. noop if already defined @return [self] @api private
[ "Initialize", "and", "assign", "a", "RuleSet", "for", "the", "named", "context" ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/contextual_rule_set.rb#L156-L162
train
activenetwork/gattica
lib/gattica.rb
Gattica.Engine.do_http_get
def do_http_get(query_string) response, data = @http.get(query_string, @headers) # error checking if response.code != '200' case response.code when '400' raise GatticaError::AnalyticsError, response.body + " (status code: #{response.code})" when '401' raise GatticaError::InvalidToken, "Your authorization token is invalid or has expired (status code: #{response.code})" else # some other unknown error raise GatticaError::UnknownAnalyticsError, response.body + " (status code: #{response.code})" end end return data end
ruby
def do_http_get(query_string) response, data = @http.get(query_string, @headers) # error checking if response.code != '200' case response.code when '400' raise GatticaError::AnalyticsError, response.body + " (status code: #{response.code})" when '401' raise GatticaError::InvalidToken, "Your authorization token is invalid or has expired (status code: #{response.code})" else # some other unknown error raise GatticaError::UnknownAnalyticsError, response.body + " (status code: #{response.code})" end end return data end
[ "def", "do_http_get", "(", "query_string", ")", "response", ",", "data", "=", "@http", ".", "get", "(", "query_string", ",", "@headers", ")", "if", "response", ".", "code", "!=", "'200'", "case", "response", ".", "code", "when", "'400'", "raise", "GatticaError", "::", "AnalyticsError", ",", "response", ".", "body", "+", "\" (status code: #{response.code})\"", "when", "'401'", "raise", "GatticaError", "::", "InvalidToken", ",", "\"Your authorization token is invalid or has expired (status code: #{response.code})\"", "else", "raise", "GatticaError", "::", "UnknownAnalyticsError", ",", "response", ".", "body", "+", "\" (status code: #{response.code})\"", "end", "end", "return", "data", "end" ]
Does the work of making HTTP calls and then going through a suite of tests on the response to make sure it's valid and not an error
[ "Does", "the", "work", "of", "making", "HTTP", "calls", "and", "then", "going", "through", "a", "suite", "of", "tests", "on", "the", "response", "to", "make", "sure", "it", "s", "valid", "and", "not", "an", "error" ]
359a5a70eba67e0f9ddd6081cb4defbf14d2e74b
https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica.rb#L241-L257
train
activenetwork/gattica
lib/gattica.rb
Gattica.Engine.build_query_string
def build_query_string(args,profile) query_params = args.clone ga_start_date = query_params.delete(:start_date) ga_end_date = query_params.delete(:end_date) ga_dimensions = query_params.delete(:dimensions) ga_metrics = query_params.delete(:metrics) ga_sort = query_params.delete(:sort) ga_filters = query_params.delete(:filters) output = "ids=ga:#{profile}&start-date=#{ga_start_date}&end-date=#{ga_end_date}" unless ga_dimensions.nil? || ga_dimensions.empty? output += '&dimensions=' + ga_dimensions.collect do |dimension| "ga:#{dimension}" end.join(',') end unless ga_metrics.nil? || ga_metrics.empty? output += '&metrics=' + ga_metrics.collect do |metric| "ga:#{metric}" end.join(',') end unless ga_sort.nil? || ga_sort.empty? output += '&sort=' + Array(ga_sort).collect do |sort| sort[0..0] == '-' ? "-ga:#{sort[1..-1]}" : "ga:#{sort}" # if the first character is a dash, move it before the ga: end.join(',') end # TODO: update so that in regular expression filters (=~ and !~), any initial special characters in the regular expression aren't also picked up as part of the operator (doesn't cause a problem, but just feels dirty) unless args[:filters].empty? # filters are a little more complicated because they can have all kinds of modifiers output += '&filters=' + args[:filters].collect do |filter| match, name, operator, expression = *filter.match(/^(\w*)\s*([=!<>~@]*)\s*(.*)$/) # splat the resulting Match object to pull out the parts automatically unless name.empty? || operator.empty? || expression.empty? # make sure they all contain something "ga:#{name}#{CGI::escape(operator.gsub(/ /,''))}#{CGI::escape(expression)}" # remove any whitespace from the operator before output else raise GatticaError::InvalidFilter, "The filter '#{filter}' is invalid. Filters should look like 'browser == Firefox' or 'browser==Firefox'" end end.join(';') end query_params.inject(output) {|m,(key,value)| m << "&#{key}=#{value}"} return output end
ruby
def build_query_string(args,profile) query_params = args.clone ga_start_date = query_params.delete(:start_date) ga_end_date = query_params.delete(:end_date) ga_dimensions = query_params.delete(:dimensions) ga_metrics = query_params.delete(:metrics) ga_sort = query_params.delete(:sort) ga_filters = query_params.delete(:filters) output = "ids=ga:#{profile}&start-date=#{ga_start_date}&end-date=#{ga_end_date}" unless ga_dimensions.nil? || ga_dimensions.empty? output += '&dimensions=' + ga_dimensions.collect do |dimension| "ga:#{dimension}" end.join(',') end unless ga_metrics.nil? || ga_metrics.empty? output += '&metrics=' + ga_metrics.collect do |metric| "ga:#{metric}" end.join(',') end unless ga_sort.nil? || ga_sort.empty? output += '&sort=' + Array(ga_sort).collect do |sort| sort[0..0] == '-' ? "-ga:#{sort[1..-1]}" : "ga:#{sort}" # if the first character is a dash, move it before the ga: end.join(',') end # TODO: update so that in regular expression filters (=~ and !~), any initial special characters in the regular expression aren't also picked up as part of the operator (doesn't cause a problem, but just feels dirty) unless args[:filters].empty? # filters are a little more complicated because they can have all kinds of modifiers output += '&filters=' + args[:filters].collect do |filter| match, name, operator, expression = *filter.match(/^(\w*)\s*([=!<>~@]*)\s*(.*)$/) # splat the resulting Match object to pull out the parts automatically unless name.empty? || operator.empty? || expression.empty? # make sure they all contain something "ga:#{name}#{CGI::escape(operator.gsub(/ /,''))}#{CGI::escape(expression)}" # remove any whitespace from the operator before output else raise GatticaError::InvalidFilter, "The filter '#{filter}' is invalid. Filters should look like 'browser == Firefox' or 'browser==Firefox'" end end.join(';') end query_params.inject(output) {|m,(key,value)| m << "&#{key}=#{value}"} return output end
[ "def", "build_query_string", "(", "args", ",", "profile", ")", "query_params", "=", "args", ".", "clone", "ga_start_date", "=", "query_params", ".", "delete", "(", ":start_date", ")", "ga_end_date", "=", "query_params", ".", "delete", "(", ":end_date", ")", "ga_dimensions", "=", "query_params", ".", "delete", "(", ":dimensions", ")", "ga_metrics", "=", "query_params", ".", "delete", "(", ":metrics", ")", "ga_sort", "=", "query_params", ".", "delete", "(", ":sort", ")", "ga_filters", "=", "query_params", ".", "delete", "(", ":filters", ")", "output", "=", "\"ids=ga:#{profile}&start-date=#{ga_start_date}&end-date=#{ga_end_date}\"", "unless", "ga_dimensions", ".", "nil?", "||", "ga_dimensions", ".", "empty?", "output", "+=", "'&dimensions='", "+", "ga_dimensions", ".", "collect", "do", "|", "dimension", "|", "\"ga:#{dimension}\"", "end", ".", "join", "(", "','", ")", "end", "unless", "ga_metrics", ".", "nil?", "||", "ga_metrics", ".", "empty?", "output", "+=", "'&metrics='", "+", "ga_metrics", ".", "collect", "do", "|", "metric", "|", "\"ga:#{metric}\"", "end", ".", "join", "(", "','", ")", "end", "unless", "ga_sort", ".", "nil?", "||", "ga_sort", ".", "empty?", "output", "+=", "'&sort='", "+", "Array", "(", "ga_sort", ")", ".", "collect", "do", "|", "sort", "|", "sort", "[", "0", "..", "0", "]", "==", "'-'", "?", "\"-ga:#{sort[1..-1]}\"", ":", "\"ga:#{sort}\"", "end", ".", "join", "(", "','", ")", "end", "unless", "args", "[", ":filters", "]", ".", "empty?", "output", "+=", "'&filters='", "+", "args", "[", ":filters", "]", ".", "collect", "do", "|", "filter", "|", "match", ",", "name", ",", "operator", ",", "expression", "=", "*", "filter", ".", "match", "(", "/", "\\w", "\\s", "\\s", "/", ")", "unless", "name", ".", "empty?", "||", "operator", ".", "empty?", "||", "expression", ".", "empty?", "\"ga:#{name}#{CGI::escape(operator.gsub(/ /,''))}#{CGI::escape(expression)}\"", "else", "raise", "GatticaError", "::", "InvalidFilter", ",", "\"The filter '#{filter}' is invalid. Filters should look like 'browser == Firefox' or 'browser==Firefox'\"", "end", "end", ".", "join", "(", "';'", ")", "end", "query_params", ".", "inject", "(", "output", ")", "{", "|", "m", ",", "(", "key", ",", "value", ")", "|", "m", "<<", "\"&#{key}=#{value}\"", "}", "return", "output", "end" ]
Creates a valid query string for GA
[ "Creates", "a", "valid", "query", "string", "for", "GA" ]
359a5a70eba67e0f9ddd6081cb4defbf14d2e74b
https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica.rb#L269-L310
train
Avhana/allscripts_api
lib/allscripts_api/client.rb
AllscriptsApi.Client.get_token
def get_token full_path = build_request_path("/GetToken") response = conn.post do |req| req.url(full_path) req.body = { Username: @username, Password: @password }.to_json end raise(GetTokenError, response.body) unless response.status == 200 @token = response.body end
ruby
def get_token full_path = build_request_path("/GetToken") response = conn.post do |req| req.url(full_path) req.body = { Username: @username, Password: @password }.to_json end raise(GetTokenError, response.body) unless response.status == 200 @token = response.body end
[ "def", "get_token", "full_path", "=", "build_request_path", "(", "\"/GetToken\"", ")", "response", "=", "conn", ".", "post", "do", "|", "req", "|", "req", ".", "url", "(", "full_path", ")", "req", ".", "body", "=", "{", "Username", ":", "@username", ",", "Password", ":", "@password", "}", ".", "to_json", "end", "raise", "(", "GetTokenError", ",", "response", ".", "body", ")", "unless", "response", ".", "status", "==", "200", "@token", "=", "response", ".", "body", "end" ]
Instantiation of the Client @param url [String] Allscripts URL to be used to make Unity API calls @param app_name [String] app name assigned by Allscripts @param app_username [String] the app username supplied by Allscripts @param app_password [String] the app password supplied by Allscripts Gets security token necessary in all workflows @return [String] security token
[ "Instantiation", "of", "the", "Client" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L35-L44
train
Avhana/allscripts_api
lib/allscripts_api/client.rb
AllscriptsApi.Client.get_user_authentication
def get_user_authentication(username, password) @allscripts_username = username params = MagicParams.format(user_id: username, parameter1: password) response = magic("GetUserAuthentication", magic_params: params) response["getuserauthenticationinfo"][0] end
ruby
def get_user_authentication(username, password) @allscripts_username = username params = MagicParams.format(user_id: username, parameter1: password) response = magic("GetUserAuthentication", magic_params: params) response["getuserauthenticationinfo"][0] end
[ "def", "get_user_authentication", "(", "username", ",", "password", ")", "@allscripts_username", "=", "username", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "username", ",", "parameter1", ":", "password", ")", "response", "=", "magic", "(", "\"GetUserAuthentication\"", ",", "magic_params", ":", "params", ")", "response", "[", "\"getuserauthenticationinfo\"", "]", "[", "0", "]", "end" ]
Assign a security token from `get_token` to a specific Allscripts user. This creates a link on the Allscripts server that allows that token to be used in subsequent `magic` calls passed that user's username. @param username [String] the Allscripts user's username (from Allscripts) @param password [String] the Allscripts user's password (from Allscripts) @return [Hash] user permissions, etc.
[ "Assign", "a", "security", "token", "from", "get_token", "to", "a", "specific", "Allscripts", "user", ".", "This", "creates", "a", "link", "on", "the", "Allscripts", "server", "that", "allows", "that", "token", "to", "be", "used", "in", "subsequent", "magic", "calls", "passed", "that", "user", "s", "username", "." ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L53-L58
train
Avhana/allscripts_api
lib/allscripts_api/client.rb
AllscriptsApi.Client.validate_sso_token
def validate_sso_token(sso_token = nil) sso_token ||= @sso_token params = MagicParams.format(parameter1: sso_token) response = magic("GetTokenValidation", magic_params: params) response["Table"][0] end
ruby
def validate_sso_token(sso_token = nil) sso_token ||= @sso_token params = MagicParams.format(parameter1: sso_token) response = magic("GetTokenValidation", magic_params: params) response["Table"][0] end
[ "def", "validate_sso_token", "(", "sso_token", "=", "nil", ")", "sso_token", "||=", "@sso_token", "params", "=", "MagicParams", ".", "format", "(", "parameter1", ":", "sso_token", ")", "response", "=", "magic", "(", "\"GetTokenValidation\"", ",", "magic_params", ":", "params", ")", "response", "[", "\"Table\"", "]", "[", "0", "]", "end" ]
Validate a token generated and passed by Allscripts during SSO Falls back and looks for sso_token on the client if not passed one Note that sso_token is not the token from `get_token`` TODO: test and validate. Add error handling @param sso_token [String] the Allscripts SSO token (from Allscripts)
[ "Validate", "a", "token", "generated", "and", "passed", "by", "Allscripts", "during", "SSO", "Falls", "back", "and", "looks", "for", "sso_token", "on", "the", "client", "if", "not", "passed", "one", "Note", "that", "sso_token", "is", "not", "the", "token", "from", "get_token" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L67-L72
train
Avhana/allscripts_api
lib/allscripts_api/client.rb
AllscriptsApi.Client.magic
def magic(action, magic_params: MagicParams.format) full_path = build_request_path("/MagicJson") body = build_magic_body(action, magic_params) response = conn.post do |req| req.url(full_path) req.body = body end read_magic_response(action, response) end
ruby
def magic(action, magic_params: MagicParams.format) full_path = build_request_path("/MagicJson") body = build_magic_body(action, magic_params) response = conn.post do |req| req.url(full_path) req.body = body end read_magic_response(action, response) end
[ "def", "magic", "(", "action", ",", "magic_params", ":", "MagicParams", ".", "format", ")", "full_path", "=", "build_request_path", "(", "\"/MagicJson\"", ")", "body", "=", "build_magic_body", "(", "action", ",", "magic_params", ")", "response", "=", "conn", ".", "post", "do", "|", "req", "|", "req", ".", "url", "(", "full_path", ")", "req", ".", "body", "=", "body", "end", "read_magic_response", "(", "action", ",", "response", ")", "end" ]
Main method for interacting with the Allscripts UnityAPI @param action [String] the API action to be performed @param magic_params [MagicParams] a params object used to build the Magic Action request body's user_id, patient_id, and magic parameters. The patient_id is sometimes oprional and the numbered params are generally optional, but must be sent as blank strings if unused. @return [Hash, MagicError] the parsed JSON response from Allscripts or a `MagicError` with the API error message(hopefully)
[ "Main", "method", "for", "interacting", "with", "the", "Allscripts", "UnityAPI" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/client.rb#L85-L94
train
skoona/skn_utils
lib/skn_utils/nested_result.rb
SknUtils.NestedResult.initialize_for_speed
def initialize_for_speed(hash) hash.each_pair do |k,v| key = key_as_sym(k) case v when Array value = v.map { |element| translate_value(element) } container.store(key, value) when Hash container.store(key, NestedResult.new(v)) else container.store(key, v) end end end
ruby
def initialize_for_speed(hash) hash.each_pair do |k,v| key = key_as_sym(k) case v when Array value = v.map { |element| translate_value(element) } container.store(key, value) when Hash container.store(key, NestedResult.new(v)) else container.store(key, v) end end end
[ "def", "initialize_for_speed", "(", "hash", ")", "hash", ".", "each_pair", "do", "|", "k", ",", "v", "|", "key", "=", "key_as_sym", "(", "k", ")", "case", "v", "when", "Array", "value", "=", "v", ".", "map", "{", "|", "element", "|", "translate_value", "(", "element", ")", "}", "container", ".", "store", "(", "key", ",", "value", ")", "when", "Hash", "container", ".", "store", "(", "key", ",", "NestedResult", ".", "new", "(", "v", ")", ")", "else", "container", ".", "store", "(", "key", ",", "v", ")", "end", "end", "end" ]
Don't create methods until first access
[ "Don", "t", "create", "methods", "until", "first", "access" ]
6bccc5e49490c9d3eee59056d6353d0cab6e5ed3
https://github.com/skoona/skn_utils/blob/6bccc5e49490c9d3eee59056d6353d0cab6e5ed3/lib/skn_utils/nested_result.rb#L262-L275
train
jphastings/AirVideo
lib/airvideo.rb
AirVideo.Client.set_proxy
def set_proxy(proxy_server_and_port = "") begin @proxy = URI.parse("http://"+((proxy_server_and_port.empty?) ? ENV['HTTP_PROXY'] : string_proxy)) @http = Net::HTTP::Proxy(@proxy.host, @proxy.port) rescue @proxy = nil @http = Net::HTTP end end
ruby
def set_proxy(proxy_server_and_port = "") begin @proxy = URI.parse("http://"+((proxy_server_and_port.empty?) ? ENV['HTTP_PROXY'] : string_proxy)) @http = Net::HTTP::Proxy(@proxy.host, @proxy.port) rescue @proxy = nil @http = Net::HTTP end end
[ "def", "set_proxy", "(", "proxy_server_and_port", "=", "\"\"", ")", "begin", "@proxy", "=", "URI", ".", "parse", "(", "\"http://\"", "+", "(", "(", "proxy_server_and_port", ".", "empty?", ")", "?", "ENV", "[", "'HTTP_PROXY'", "]", ":", "string_proxy", ")", ")", "@http", "=", "Net", "::", "HTTP", "::", "Proxy", "(", "@proxy", ".", "host", ",", "@proxy", ".", "port", ")", "rescue", "@proxy", "=", "nil", "@http", "=", "Net", "::", "HTTP", "end", "end" ]
Specify where your AirVideo Server lives. If your HTTP_PROXY environment variable is set, it will be honoured. At the moment I'm expecting ENV['HTTP_PROXY'] to have the form 'sub.domain.com:8080', I throw an http:// and bung it into URI.parse for convenience. Potentially confusing: * Sending 'server:port' will use that address as an HTTP proxy * An empty string (or something not recognisable as a URL with http:// put infront of it) will try to use the ENV['HTTP_PROXY'] variable * Sending nil or any object that can't be parsed to a string will remove the proxy NB. You can access the @proxy URI object externally, but changing it will *not* automatically call set_proxy
[ "Specify", "where", "your", "AirVideo", "Server", "lives", ".", "If", "your", "HTTP_PROXY", "environment", "variable", "is", "set", "it", "will", "be", "honoured", "." ]
be7f5f12bacf4f60936c1fc57d21cde10fc79e3e
https://github.com/jphastings/AirVideo/blob/be7f5f12bacf4f60936c1fc57d21cde10fc79e3e/lib/airvideo.rb#L48-L56
train
emilsoman/cloudster
lib/cloudster/output.rb
Cloudster.Output.output_template
def output_template(outputs) resource_name = outputs.keys[0] outputs_array = outputs.values[0].collect each_output_join = outputs_array.collect {|output| {"Fn::Join" => ["|", output]}} return resource_name => { 'Value' => { "Fn::Join" => [ ",", each_output_join] } } end
ruby
def output_template(outputs) resource_name = outputs.keys[0] outputs_array = outputs.values[0].collect each_output_join = outputs_array.collect {|output| {"Fn::Join" => ["|", output]}} return resource_name => { 'Value' => { "Fn::Join" => [ ",", each_output_join] } } end
[ "def", "output_template", "(", "outputs", ")", "resource_name", "=", "outputs", ".", "keys", "[", "0", "]", "outputs_array", "=", "outputs", ".", "values", "[", "0", "]", ".", "collect", "each_output_join", "=", "outputs_array", ".", "collect", "{", "|", "output", "|", "{", "\"Fn::Join\"", "=>", "[", "\"|\"", ",", "output", "]", "}", "}", "return", "resource_name", "=>", "{", "'Value'", "=>", "{", "\"Fn::Join\"", "=>", "[", "\",\"", ",", "each_output_join", "]", "}", "}", "end" ]
Returns the Output template for resources ==== Parameters * output: Hash containing the valid outputs and their cloudformation translations
[ "Returns", "the", "Output", "template", "for", "resources" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/output.rb#L7-L14
train
instructure/folio
lib/folio/ordinal.rb
Folio.Ordinal.configure_pagination
def configure_pagination(page, options) page = super(page, options) raise ::Folio::InvalidPage unless page.current_page.is_a?(Integer) raise ::Folio::InvalidPage if page.out_of_bounds? page rescue ::WillPaginate::InvalidPage raise ::Folio::InvalidPage end
ruby
def configure_pagination(page, options) page = super(page, options) raise ::Folio::InvalidPage unless page.current_page.is_a?(Integer) raise ::Folio::InvalidPage if page.out_of_bounds? page rescue ::WillPaginate::InvalidPage raise ::Folio::InvalidPage end
[ "def", "configure_pagination", "(", "page", ",", "options", ")", "page", "=", "super", "(", "page", ",", "options", ")", "raise", "::", "Folio", "::", "InvalidPage", "unless", "page", ".", "current_page", ".", "is_a?", "(", "Integer", ")", "raise", "::", "Folio", "::", "InvalidPage", "if", "page", ".", "out_of_bounds?", "page", "rescue", "::", "WillPaginate", "::", "InvalidPage", "raise", "::", "Folio", "::", "InvalidPage", "end" ]
validate the configured page before returning it
[ "validate", "the", "configured", "page", "before", "returning", "it" ]
fd4dd3a9b35922b8bec234a8bed00949f4b800f9
https://github.com/instructure/folio/blob/fd4dd3a9b35922b8bec234a8bed00949f4b800f9/lib/folio/ordinal.rb#L26-L33
train
emilsoman/cloudster
lib/cloudster/elastic_ip.rb
Cloudster.ElasticIp.add_to
def add_to(ec2) ec2_template = ec2.template @instance_name = ec2.name elastic_ip_template = template ec2.template.inner_merge(elastic_ip_template) end
ruby
def add_to(ec2) ec2_template = ec2.template @instance_name = ec2.name elastic_ip_template = template ec2.template.inner_merge(elastic_ip_template) end
[ "def", "add_to", "(", "ec2", ")", "ec2_template", "=", "ec2", ".", "template", "@instance_name", "=", "ec2", ".", "name", "elastic_ip_template", "=", "template", "ec2", ".", "template", ".", "inner_merge", "(", "elastic_ip_template", ")", "end" ]
Initialize an ElasticIp ==== Notes options parameter must include values for :name ==== Examples elastic_ip = Cloudster::ElasticIp.new(:name => 'ElasticIp') ==== Parameters * options<~Hash> - * :name: String containing the name of ElastiCache resource Merges the required CloudFormation template for adding an ElasticIp to an EC2 instance ==== Examples elastic_ip = Cloudster::ElasticIp.new(:name => 'AppServerEIp') ec2 = Cloudster::Ec2.new( :name => 'AppServer', :key_name => 'mykey', :image_id => 'ami_image_id', :instance_type => 't1.micro' ) elastic_ip.add_to ec2 ==== Parameters * instance of EC2
[ "Initialize", "an", "ElasticIp" ]
fd0e03758c2c08c1621212b9daa28e0be9a812ff
https://github.com/emilsoman/cloudster/blob/fd0e03758c2c08c1621212b9daa28e0be9a812ff/lib/cloudster/elastic_ip.rb#L39-L44
train
jaymcgavren/rubyonacid
lib/rubyonacid/factories/input.rb
RubyOnAcid.InputFactory.put
def put(key, value) value = value.to_f @input_values[key] = value @smallest_seen_values[key] ||= 0.0 if @largest_seen_values[key] == nil or @smallest_seen_values[key] > @largest_seen_values[key] @largest_seen_values[key] = @smallest_seen_values[key] + 1.0 end @smallest_seen_values[key] = value if value < @smallest_seen_values[key] @largest_seen_values[key] = value if value > @largest_seen_values[key] end
ruby
def put(key, value) value = value.to_f @input_values[key] = value @smallest_seen_values[key] ||= 0.0 if @largest_seen_values[key] == nil or @smallest_seen_values[key] > @largest_seen_values[key] @largest_seen_values[key] = @smallest_seen_values[key] + 1.0 end @smallest_seen_values[key] = value if value < @smallest_seen_values[key] @largest_seen_values[key] = value if value > @largest_seen_values[key] end
[ "def", "put", "(", "key", ",", "value", ")", "value", "=", "value", ".", "to_f", "@input_values", "[", "key", "]", "=", "value", "@smallest_seen_values", "[", "key", "]", "||=", "0.0", "if", "@largest_seen_values", "[", "key", "]", "==", "nil", "or", "@smallest_seen_values", "[", "key", "]", ">", "@largest_seen_values", "[", "key", "]", "@largest_seen_values", "[", "key", "]", "=", "@smallest_seen_values", "[", "key", "]", "+", "1.0", "end", "@smallest_seen_values", "[", "key", "]", "=", "value", "if", "value", "<", "@smallest_seen_values", "[", "key", "]", "@largest_seen_values", "[", "key", "]", "=", "value", "if", "value", ">", "@largest_seen_values", "[", "key", "]", "end" ]
Store a value for the given key. Values will be scaled to the range 0 to 1 - the largest value yet seen will be scaled to 1.0, the smallest yet seen to 0.0.
[ "Store", "a", "value", "for", "the", "given", "key", ".", "Values", "will", "be", "scaled", "to", "the", "range", "0", "to", "1", "-", "the", "largest", "value", "yet", "seen", "will", "be", "scaled", "to", "1", ".", "0", "the", "smallest", "yet", "seen", "to", "0", ".", "0", "." ]
2ee2af3e952b7290e18a4f7012f76af4a7fe059d
https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/input.rb#L31-L40
train
jaymcgavren/rubyonacid
lib/rubyonacid/factories/input.rb
RubyOnAcid.InputFactory.assigned_key
def assigned_key(key) return @key_assignments[key] if @key_assignments[key] available_keys = @input_values.keys - @key_assignments.values return nil if available_keys.empty? if available_keys.include?(key) @key_assignments[key] = key else @key_assignments[key] = available_keys[rand(available_keys.length)] end @key_assignments[key] end
ruby
def assigned_key(key) return @key_assignments[key] if @key_assignments[key] available_keys = @input_values.keys - @key_assignments.values return nil if available_keys.empty? if available_keys.include?(key) @key_assignments[key] = key else @key_assignments[key] = available_keys[rand(available_keys.length)] end @key_assignments[key] end
[ "def", "assigned_key", "(", "key", ")", "return", "@key_assignments", "[", "key", "]", "if", "@key_assignments", "[", "key", "]", "available_keys", "=", "@input_values", ".", "keys", "-", "@key_assignments", ".", "values", "return", "nil", "if", "available_keys", ".", "empty?", "if", "available_keys", ".", "include?", "(", "key", ")", "@key_assignments", "[", "key", "]", "=", "key", "else", "@key_assignments", "[", "key", "]", "=", "available_keys", "[", "rand", "(", "available_keys", ".", "length", ")", "]", "end", "@key_assignments", "[", "key", "]", "end" ]
Returns the input key assigned to the given get_unit key. If none is assigned, randomly assigns one of the available input keys.
[ "Returns", "the", "input", "key", "assigned", "to", "the", "given", "get_unit", "key", ".", "If", "none", "is", "assigned", "randomly", "assigns", "one", "of", "the", "available", "input", "keys", "." ]
2ee2af3e952b7290e18a4f7012f76af4a7fe059d
https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factories/input.rb#L67-L77
train
mkdynamic/vss
lib/vss/engine.rb
VSS.Engine.search
def search(query) # get ranks query_vector = make_query_vector(query) ranks = @documents.map do |document| document_vector = make_vector(document) cosine_rank(query_vector, document_vector) end # now annotate records and return them @records.each_with_index do |record, i| # TODO: do this in a sensible way... record.instance_eval %{def rank; #{ranks[i]}; end} end # exclude 0 rank (no match) and sort by rank @records.reject { |r| r.rank == 0 }.sort { |a,b| b.rank <=> a.rank } end
ruby
def search(query) # get ranks query_vector = make_query_vector(query) ranks = @documents.map do |document| document_vector = make_vector(document) cosine_rank(query_vector, document_vector) end # now annotate records and return them @records.each_with_index do |record, i| # TODO: do this in a sensible way... record.instance_eval %{def rank; #{ranks[i]}; end} end # exclude 0 rank (no match) and sort by rank @records.reject { |r| r.rank == 0 }.sort { |a,b| b.rank <=> a.rank } end
[ "def", "search", "(", "query", ")", "query_vector", "=", "make_query_vector", "(", "query", ")", "ranks", "=", "@documents", ".", "map", "do", "|", "document", "|", "document_vector", "=", "make_vector", "(", "document", ")", "cosine_rank", "(", "query_vector", ",", "document_vector", ")", "end", "@records", ".", "each_with_index", "do", "|", "record", ",", "i", "|", "record", ".", "instance_eval", "%{def rank; #{ranks[i]}; end}", "end", "@records", ".", "reject", "{", "|", "r", "|", "r", ".", "rank", "==", "0", "}", ".", "sort", "{", "|", "a", ",", "b", "|", "b", ".", "rank", "<=>", "a", ".", "rank", "}", "end" ]
`documentizer` just takes a record and converts it to a string
[ "documentizer", "just", "takes", "a", "record", "and", "converts", "it", "to", "a", "string" ]
f4e62e94f0381174f26debc5c31d282997591188
https://github.com/mkdynamic/vss/blob/f4e62e94f0381174f26debc5c31d282997591188/lib/vss/engine.rb#L13-L29
train
ideonetwork/evnt
lib/evnt/event.rb
Evnt.Event._init_event_data
def _init_event_data(params) # set state @state = { reloaded: !params[:evnt].nil?, saved: true } # set options initial_options = { exceptions: false, silent: false } default_options = _safe_default_options || {} params_options = params[:_options] || {} @options = initial_options.merge(default_options) .merge(params_options) # set name and attributes @name = _safe_name @attributes = _safe_attributes # set payload payload = params.reject { |k, _v| k[0] == '_' } @payload = @state[:reloaded] ? payload : _generate_payload(payload) # set extras @extras = {} extras = params.select { |k, _v| k[0] == '_' } extras.each { |k, v| @extras[k[1..-1].to_sym] = v } end
ruby
def _init_event_data(params) # set state @state = { reloaded: !params[:evnt].nil?, saved: true } # set options initial_options = { exceptions: false, silent: false } default_options = _safe_default_options || {} params_options = params[:_options] || {} @options = initial_options.merge(default_options) .merge(params_options) # set name and attributes @name = _safe_name @attributes = _safe_attributes # set payload payload = params.reject { |k, _v| k[0] == '_' } @payload = @state[:reloaded] ? payload : _generate_payload(payload) # set extras @extras = {} extras = params.select { |k, _v| k[0] == '_' } extras.each { |k, v| @extras[k[1..-1].to_sym] = v } end
[ "def", "_init_event_data", "(", "params", ")", "@state", "=", "{", "reloaded", ":", "!", "params", "[", ":evnt", "]", ".", "nil?", ",", "saved", ":", "true", "}", "initial_options", "=", "{", "exceptions", ":", "false", ",", "silent", ":", "false", "}", "default_options", "=", "_safe_default_options", "||", "{", "}", "params_options", "=", "params", "[", ":_options", "]", "||", "{", "}", "@options", "=", "initial_options", ".", "merge", "(", "default_options", ")", ".", "merge", "(", "params_options", ")", "@name", "=", "_safe_name", "@attributes", "=", "_safe_attributes", "payload", "=", "params", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", "[", "0", "]", "==", "'_'", "}", "@payload", "=", "@state", "[", ":reloaded", "]", "?", "payload", ":", "_generate_payload", "(", "payload", ")", "@extras", "=", "{", "}", "extras", "=", "params", ".", "select", "{", "|", "k", ",", "_v", "|", "k", "[", "0", "]", "==", "'_'", "}", "extras", ".", "each", "{", "|", "k", ",", "v", "|", "@extras", "[", "k", "[", "1", "..", "-", "1", "]", ".", "to_sym", "]", "=", "v", "}", "end" ]
This function initializes the event required data.
[ "This", "function", "initializes", "the", "event", "required", "data", "." ]
01331ab48f3fe92c6189b6f4db256606d397d177
https://github.com/ideonetwork/evnt/blob/01331ab48f3fe92c6189b6f4db256606d397d177/lib/evnt/event.rb#L95-L124
train
Acornsgrow/optional_logger
lib/optional_logger/logger.rb
OptionalLogger.Logger.add
def add(severity, message = nil, progname_or_message = nil, &block) @logger.add(severity, message, progname_or_message, &block) if @logger end
ruby
def add(severity, message = nil, progname_or_message = nil, &block) @logger.add(severity, message, progname_or_message, &block) if @logger end
[ "def", "add", "(", "severity", ",", "message", "=", "nil", ",", "progname_or_message", "=", "nil", ",", "&", "block", ")", "@logger", ".", "add", "(", "severity", ",", "message", ",", "progname_or_message", ",", "&", "block", ")", "if", "@logger", "end" ]
Log a message at the given level if the logger is present This isn't generally a recommended method to use while logging in your libraries. Instead see {#debug}, {#info}, {#warn}, {#error}, {#fatal}, and {#unknown} as they simplify messaging considerably. If you don't want to use the recommended methods and want more control for some reason. There are a few ways to log a message depending on your usecase. The first is probably the most generally useful, which is logging messages that aren't costly to build. This is accomplished as follows: add(::Logger::INFO, 'some message', nil) The second is for use cases in which it is costly to build the log message as it avoids executing the block until the logger knows that the message level will be displayed. If the message level would not be displayed then the block is not executed, saving the performance cost of building the message. add(::Logger::INFO) { 'some expensive message' } The third gives you the benefits of preventing uneeded expensive messages but also allows you to override the program name that will be prefixed on that log message. This is accomplished as follows. add(::Logger::INFO, nil, 'overridden progname') { 'some expensive message' } It is important to realize that if the wrapped logger is nil then this method will simply do nothing. @param severity ::Logger::DEBUG, ::Logger::INFO, ::Logger::WARN, ::Logger::ERROR, ::Logger::FATAL, ::Logger::UNKNOWN @param message the optional message to log @param progname_or_message the optional program name or message, if message is nil, and a block is NOT provided, then progname_or_message is treated as a message rather than progname @param block the block to evaluate and yield a message, generally useful preventing building of expensive messages when message of that level aren't allowed
[ "Log", "a", "message", "at", "the", "given", "level", "if", "the", "logger", "is", "present" ]
b88df218f3da39070ff4dee1f55e2aee2c30c1a7
https://github.com/Acornsgrow/optional_logger/blob/b88df218f3da39070ff4dee1f55e2aee2c30c1a7/lib/optional_logger/logger.rb#L67-L69
train
kkaempf/ruby-wbem
lib/wbem/cimxml.rb
Wbem.CimxmlClient._identify
def _identify begin product = nil { "sfcb" => [ "root/interop", "CIM_ObjectManager" ], "pegasus" => [ "root/PG_Internal", "PG_ConfigSetting" ] }.each do |cimom, op| obj = objectpath *op @client.instances(obj).each do |inst| product = inst.Description || cimom break end break if product end rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace raise "Unknown CIMOM" end product end
ruby
def _identify begin product = nil { "sfcb" => [ "root/interop", "CIM_ObjectManager" ], "pegasus" => [ "root/PG_Internal", "PG_ConfigSetting" ] }.each do |cimom, op| obj = objectpath *op @client.instances(obj).each do |inst| product = inst.Description || cimom break end break if product end rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace raise "Unknown CIMOM" end product end
[ "def", "_identify", "begin", "product", "=", "nil", "{", "\"sfcb\"", "=>", "[", "\"root/interop\"", ",", "\"CIM_ObjectManager\"", "]", ",", "\"pegasus\"", "=>", "[", "\"root/PG_Internal\"", ",", "\"PG_ConfigSetting\"", "]", "}", ".", "each", "do", "|", "cimom", ",", "op", "|", "obj", "=", "objectpath", "*", "op", "@client", ".", "instances", "(", "obj", ")", ".", "each", "do", "|", "inst", "|", "product", "=", "inst", ".", "Description", "||", "cimom", "break", "end", "break", "if", "product", "end", "rescue", "Sfcc", "::", "Cim", "::", "ErrorInvalidClass", ",", "Sfcc", "::", "Cim", "::", "ErrorInvalidNamespace", "raise", "\"Unknown CIMOM\"", "end", "product", "end" ]
identify client return identification string on error return nil and set @response to http response code
[ "identify", "client", "return", "identification", "string", "on", "error", "return", "nil", "and", "set" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L33-L50
train
kkaempf/ruby-wbem
lib/wbem/cimxml.rb
Wbem.CimxmlClient.each_instance
def each_instance( namespace_or_objectpath, classname = nil ) op = if namespace_or_objectpath.is_a? Sfcc::Cim::ObjectPath namespace_or_objectpath else objectpath namespace_or_objectpath, classname end begin @client.instances(op).each do |inst| yield inst end rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace end end
ruby
def each_instance( namespace_or_objectpath, classname = nil ) op = if namespace_or_objectpath.is_a? Sfcc::Cim::ObjectPath namespace_or_objectpath else objectpath namespace_or_objectpath, classname end begin @client.instances(op).each do |inst| yield inst end rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace end end
[ "def", "each_instance", "(", "namespace_or_objectpath", ",", "classname", "=", "nil", ")", "op", "=", "if", "namespace_or_objectpath", ".", "is_a?", "Sfcc", "::", "Cim", "::", "ObjectPath", "namespace_or_objectpath", "else", "objectpath", "namespace_or_objectpath", ",", "classname", "end", "begin", "@client", ".", "instances", "(", "op", ")", ".", "each", "do", "|", "inst", "|", "yield", "inst", "end", "rescue", "Sfcc", "::", "Cim", "::", "ErrorInvalidClass", ",", "Sfcc", "::", "Cim", "::", "ErrorInvalidNamespace", "end", "end" ]
Return instances for namespace and classname
[ "Return", "instances", "for", "namespace", "and", "classname" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L125-L137
train
kkaempf/ruby-wbem
lib/wbem/cimxml.rb
Wbem.CimxmlClient.class_names
def class_names op, deep_inheritance = false ret = [] unless op.is_a? Sfcc::Cim::ObjectPath op = Sfcc::Cim::ObjectPath.new(op.to_s, nil) # assume namespace end flags = deep_inheritance ? Sfcc::Flags::DeepInheritance : 0 begin @client.class_names(op, flags).each do |name| ret << name.to_s end rescue Sfcc::Cim::ErrorInvalidNamespace end ret end
ruby
def class_names op, deep_inheritance = false ret = [] unless op.is_a? Sfcc::Cim::ObjectPath op = Sfcc::Cim::ObjectPath.new(op.to_s, nil) # assume namespace end flags = deep_inheritance ? Sfcc::Flags::DeepInheritance : 0 begin @client.class_names(op, flags).each do |name| ret << name.to_s end rescue Sfcc::Cim::ErrorInvalidNamespace end ret end
[ "def", "class_names", "op", ",", "deep_inheritance", "=", "false", "ret", "=", "[", "]", "unless", "op", ".", "is_a?", "Sfcc", "::", "Cim", "::", "ObjectPath", "op", "=", "Sfcc", "::", "Cim", "::", "ObjectPath", ".", "new", "(", "op", ".", "to_s", ",", "nil", ")", "end", "flags", "=", "deep_inheritance", "?", "Sfcc", "::", "Flags", "::", "DeepInheritance", ":", "0", "begin", "@client", ".", "class_names", "(", "op", ",", "flags", ")", ".", "each", "do", "|", "name", "|", "ret", "<<", "name", ".", "to_s", "end", "rescue", "Sfcc", "::", "Cim", "::", "ErrorInvalidNamespace", "end", "ret", "end" ]
Return list of classnames for given object_path
[ "Return", "list", "of", "classnames", "for", "given", "object_path" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L142-L155
train
kkaempf/ruby-wbem
lib/wbem/cimxml.rb
Wbem.CimxmlClient.each_association
def each_association( objectpath ) begin @client.associators(objectpath).each do |assoc| yield assoc end rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace end end
ruby
def each_association( objectpath ) begin @client.associators(objectpath).each do |assoc| yield assoc end rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace end end
[ "def", "each_association", "(", "objectpath", ")", "begin", "@client", ".", "associators", "(", "objectpath", ")", ".", "each", "do", "|", "assoc", "|", "yield", "assoc", "end", "rescue", "Sfcc", "::", "Cim", "::", "ErrorInvalidClass", ",", "Sfcc", "::", "Cim", "::", "ErrorInvalidNamespace", "end", "end" ]
Return associations for instance
[ "Return", "associations", "for", "instance" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/cimxml.rb#L249-L256
train
acenqiu/weibo2
lib/weibo2/client.rb
Weibo2.Client.get_token_from_hash
def get_token_from_hash(hash) access_token = hash.delete('access_token') || hash.delete(:access_token) || hash.delete('oauth_token') || hash.delete(:oauth_token) opts = {:expires_at => hash["expires"] || hash[:expires], :header_format => "OAuth2 %s", :param_name => "access_token"} @token = OAuth2::AccessToken.new(self, access_token, opts) end
ruby
def get_token_from_hash(hash) access_token = hash.delete('access_token') || hash.delete(:access_token) || hash.delete('oauth_token') || hash.delete(:oauth_token) opts = {:expires_at => hash["expires"] || hash[:expires], :header_format => "OAuth2 %s", :param_name => "access_token"} @token = OAuth2::AccessToken.new(self, access_token, opts) end
[ "def", "get_token_from_hash", "(", "hash", ")", "access_token", "=", "hash", ".", "delete", "(", "'access_token'", ")", "||", "hash", ".", "delete", "(", ":access_token", ")", "||", "hash", ".", "delete", "(", "'oauth_token'", ")", "||", "hash", ".", "delete", "(", ":oauth_token", ")", "opts", "=", "{", ":expires_at", "=>", "hash", "[", "\"expires\"", "]", "||", "hash", "[", ":expires", "]", ",", ":header_format", "=>", "\"OAuth2 %s\"", ",", ":param_name", "=>", "\"access_token\"", "}", "@token", "=", "OAuth2", "::", "AccessToken", ".", "new", "(", "self", ",", "access_token", ",", "opts", ")", "end" ]
Initializes an AccessToken from a hash @param [Hash] hash a Hash contains access_token and expires @return [AccessToken] the initalized AccessToken
[ "Initializes", "an", "AccessToken", "from", "a", "hash" ]
3eb07f64139a87bcfb8926a04fe054f6fa6806b2
https://github.com/acenqiu/weibo2/blob/3eb07f64139a87bcfb8926a04fe054f6fa6806b2/lib/weibo2/client.rb#L96-L103
train
kkaempf/ruby-wbem
lib/wbem/wsman.rb
Wbem.WsmanClient.epr_uri_for
def epr_uri_for(namespace,classname) case @product when :winrm # winrm embeds namespace in resource URI Openwsman::epr_uri_for(namespace,classname) rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{namespace}/#{classname}" else (Openwsman::epr_prefix_for(classname)+"/#{classname}") rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{classname}" end end
ruby
def epr_uri_for(namespace,classname) case @product when :winrm # winrm embeds namespace in resource URI Openwsman::epr_uri_for(namespace,classname) rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{namespace}/#{classname}" else (Openwsman::epr_prefix_for(classname)+"/#{classname}") rescue "http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{classname}" end end
[ "def", "epr_uri_for", "(", "namespace", ",", "classname", ")", "case", "@product", "when", ":winrm", "Openwsman", "::", "epr_uri_for", "(", "namespace", ",", "classname", ")", "rescue", "\"http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{namespace}/#{classname}\"", "else", "(", "Openwsman", "::", "epr_prefix_for", "(", "classname", ")", "+", "\"/#{classname}\"", ")", "rescue", "\"http://schema.suse.com/wbem/wscim/1/cim-schema/2/#{classname}\"", "end", "end" ]
create end point reference URI
[ "create", "end", "point", "reference", "URI" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L25-L33
train
kkaempf/ruby-wbem
lib/wbem/wsman.rb
Wbem.WsmanClient._handle_fault
def _handle_fault client, result if result.nil? STDERR.puts "Client connection failed:\n\tResult code #{client.response_code}, Fault: #{client.fault_string}" if Wbem.debug return true end if result.fault? fault = Openwsman::Fault.new result if Wbem.debug STDERR.puts "Client protocol failed for (#{client})" STDERR.puts "\tFault code #{fault.code}, subcode #{fault.subcode}" STDERR.puts "\t\treason #{fault.reason}" STDERR.puts "\t\tdetail #{fault.detail}" end return true end false end
ruby
def _handle_fault client, result if result.nil? STDERR.puts "Client connection failed:\n\tResult code #{client.response_code}, Fault: #{client.fault_string}" if Wbem.debug return true end if result.fault? fault = Openwsman::Fault.new result if Wbem.debug STDERR.puts "Client protocol failed for (#{client})" STDERR.puts "\tFault code #{fault.code}, subcode #{fault.subcode}" STDERR.puts "\t\treason #{fault.reason}" STDERR.puts "\t\tdetail #{fault.detail}" end return true end false end
[ "def", "_handle_fault", "client", ",", "result", "if", "result", ".", "nil?", "STDERR", ".", "puts", "\"Client connection failed:\\n\\tResult code #{client.response_code}, Fault: #{client.fault_string}\"", "if", "Wbem", ".", "debug", "return", "true", "end", "if", "result", ".", "fault?", "fault", "=", "Openwsman", "::", "Fault", ".", "new", "result", "if", "Wbem", ".", "debug", "STDERR", ".", "puts", "\"Client protocol failed for (#{client})\"", "STDERR", ".", "puts", "\"\\tFault code #{fault.code}, subcode #{fault.subcode}\"", "STDERR", ".", "puts", "\"\\t\\treason #{fault.reason}\"", "STDERR", ".", "puts", "\"\\t\\tdetail #{fault.detail}\"", "end", "return", "true", "end", "false", "end" ]
Handle client connection or protocol fault @return: true if fault
[ "Handle", "client", "connection", "or", "protocol", "fault" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L40-L56
train
kkaempf/ruby-wbem
lib/wbem/wsman.rb
Wbem.WsmanClient.namespaces
def namespaces ns = "root", cn = "__Namespace" result = [] each_instance( ns, cn ) do |inst| name = "#{ns}/#{inst.Name}" result << name result.concat namespaces name, cn end result.uniq end
ruby
def namespaces ns = "root", cn = "__Namespace" result = [] each_instance( ns, cn ) do |inst| name = "#{ns}/#{inst.Name}" result << name result.concat namespaces name, cn end result.uniq end
[ "def", "namespaces", "ns", "=", "\"root\"", ",", "cn", "=", "\"__Namespace\"", "result", "=", "[", "]", "each_instance", "(", "ns", ",", "cn", ")", "do", "|", "inst", "|", "name", "=", "\"#{ns}/#{inst.Name}\"", "result", "<<", "name", "result", ".", "concat", "namespaces", "name", ",", "cn", "end", "result", ".", "uniq", "end" ]
return list of namespaces
[ "return", "list", "of", "namespaces" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L192-L200
train
kkaempf/ruby-wbem
lib/wbem/wsman.rb
Wbem.WsmanClient.class_names
def class_names op, deep_inheritance = false @options.flags = Openwsman::FLAG_ENUMERATION_OPTIMIZATION @options.max_elements = 999 namespace = (op.is_a? Sfcc::Cim::ObjectPath) ? op.namespace : op classname = (op.is_a? Sfcc::Cim::ObjectPath) ? op.classname : nil case @product when :openwsman if @product_version < "2.2" STDERR.puts "ENUMERATE_CLASS_NAMES unsupported for #{@product_vendor} #{@product_version}, please upgrade" return [] end method = Openwsman::CIM_ACTION_ENUMERATE_CLASS_NAMES uri = Openwsman::XML_NS_CIM_INTRINSIC @options.cim_namespace = namespace @options.add_selector("DeepInheritance", "True") if deep_inheritance result = @client.invoke( @options, uri, method ) when :winrm # see https://github.com/kkaempf/openwsman/blob/master/bindings/ruby/tests/winenum.rb filter = Openwsman::Filter.new query = "select * from meta_class" query << " where __SuperClass is #{classname?classname:'null'}" unless deep_inheritance filter.wql query uri = "#{@prefix}#{namespace}/*" result = @client.enumerate( @options, filter, uri ) else raise "Unsupported for WSMAN product #{@product}" end if _handle_fault @client, result return [] end classes = [] case @product when :openwsman # extract invoke result output = result.body[method] output.each do |c| classes << c.to_s end when :winrm # extract enumerate/pull result loop do output = result.Items output.each do |node| classes << node.name.to_s end if output context = result.context break unless context # get the next chunk result = @client.pull( @options, nil, uri, context) break if _handle_fault @client, result end end return classes end
ruby
def class_names op, deep_inheritance = false @options.flags = Openwsman::FLAG_ENUMERATION_OPTIMIZATION @options.max_elements = 999 namespace = (op.is_a? Sfcc::Cim::ObjectPath) ? op.namespace : op classname = (op.is_a? Sfcc::Cim::ObjectPath) ? op.classname : nil case @product when :openwsman if @product_version < "2.2" STDERR.puts "ENUMERATE_CLASS_NAMES unsupported for #{@product_vendor} #{@product_version}, please upgrade" return [] end method = Openwsman::CIM_ACTION_ENUMERATE_CLASS_NAMES uri = Openwsman::XML_NS_CIM_INTRINSIC @options.cim_namespace = namespace @options.add_selector("DeepInheritance", "True") if deep_inheritance result = @client.invoke( @options, uri, method ) when :winrm # see https://github.com/kkaempf/openwsman/blob/master/bindings/ruby/tests/winenum.rb filter = Openwsman::Filter.new query = "select * from meta_class" query << " where __SuperClass is #{classname?classname:'null'}" unless deep_inheritance filter.wql query uri = "#{@prefix}#{namespace}/*" result = @client.enumerate( @options, filter, uri ) else raise "Unsupported for WSMAN product #{@product}" end if _handle_fault @client, result return [] end classes = [] case @product when :openwsman # extract invoke result output = result.body[method] output.each do |c| classes << c.to_s end when :winrm # extract enumerate/pull result loop do output = result.Items output.each do |node| classes << node.name.to_s end if output context = result.context break unless context # get the next chunk result = @client.pull( @options, nil, uri, context) break if _handle_fault @client, result end end return classes end
[ "def", "class_names", "op", ",", "deep_inheritance", "=", "false", "@options", ".", "flags", "=", "Openwsman", "::", "FLAG_ENUMERATION_OPTIMIZATION", "@options", ".", "max_elements", "=", "999", "namespace", "=", "(", "op", ".", "is_a?", "Sfcc", "::", "Cim", "::", "ObjectPath", ")", "?", "op", ".", "namespace", ":", "op", "classname", "=", "(", "op", ".", "is_a?", "Sfcc", "::", "Cim", "::", "ObjectPath", ")", "?", "op", ".", "classname", ":", "nil", "case", "@product", "when", ":openwsman", "if", "@product_version", "<", "\"2.2\"", "STDERR", ".", "puts", "\"ENUMERATE_CLASS_NAMES unsupported for #{@product_vendor} #{@product_version}, please upgrade\"", "return", "[", "]", "end", "method", "=", "Openwsman", "::", "CIM_ACTION_ENUMERATE_CLASS_NAMES", "uri", "=", "Openwsman", "::", "XML_NS_CIM_INTRINSIC", "@options", ".", "cim_namespace", "=", "namespace", "@options", ".", "add_selector", "(", "\"DeepInheritance\"", ",", "\"True\"", ")", "if", "deep_inheritance", "result", "=", "@client", ".", "invoke", "(", "@options", ",", "uri", ",", "method", ")", "when", ":winrm", "filter", "=", "Openwsman", "::", "Filter", ".", "new", "query", "=", "\"select * from meta_class\"", "query", "<<", "\" where __SuperClass is #{classname?classname:'null'}\"", "unless", "deep_inheritance", "filter", ".", "wql", "query", "uri", "=", "\"#{@prefix}#{namespace}/*\"", "result", "=", "@client", ".", "enumerate", "(", "@options", ",", "filter", ",", "uri", ")", "else", "raise", "\"Unsupported for WSMAN product #{@product}\"", "end", "if", "_handle_fault", "@client", ",", "result", "return", "[", "]", "end", "classes", "=", "[", "]", "case", "@product", "when", ":openwsman", "output", "=", "result", ".", "body", "[", "method", "]", "output", ".", "each", "do", "|", "c", "|", "classes", "<<", "c", ".", "to_s", "end", "when", ":winrm", "loop", "do", "output", "=", "result", ".", "Items", "output", ".", "each", "do", "|", "node", "|", "classes", "<<", "node", ".", "name", ".", "to_s", "end", "if", "output", "context", "=", "result", ".", "context", "break", "unless", "context", "result", "=", "@client", ".", "pull", "(", "@options", ",", "nil", ",", "uri", ",", "context", ")", "break", "if", "_handle_fault", "@client", ",", "result", "end", "end", "return", "classes", "end" ]
Enumerate class names
[ "Enumerate", "class", "names" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/wsman.rb#L241-L297
train
ableco/heroku_s3_backups
lib/heroku_s3_backups.rb
HerokuS3Backups.Heroku.download
def download(output_filename, options = {target_backup: nil}) raise "Please specify a filename" if output_filename.length.eql?(0) HerokuCLI.cmd("pg:backups:download #{target_backup} --output #{output_filename}", @app_name) end
ruby
def download(output_filename, options = {target_backup: nil}) raise "Please specify a filename" if output_filename.length.eql?(0) HerokuCLI.cmd("pg:backups:download #{target_backup} --output #{output_filename}", @app_name) end
[ "def", "download", "(", "output_filename", ",", "options", "=", "{", "target_backup", ":", "nil", "}", ")", "raise", "\"Please specify a filename\"", "if", "output_filename", ".", "length", ".", "eql?", "(", "0", ")", "HerokuCLI", ".", "cmd", "(", "\"pg:backups:download #{target_backup} --output #{output_filename}\"", ",", "@app_name", ")", "end" ]
Download the latest backup @param {string} output_filename @param {hash} options Valid options: => {string?} target_backup - If a target is set, a backup will be pulled from there, otherwise, we'll pull from the latest backup @param {hash} options
[ "Download", "the", "latest", "backup" ]
0c568f6774243cb276ed2fa8546d601f2f9e21a2
https://github.com/ableco/heroku_s3_backups/blob/0c568f6774243cb276ed2fa8546d601f2f9e21a2/lib/heroku_s3_backups.rb#L62-L65
train
ableco/heroku_s3_backups
lib/heroku_s3_backups.rb
HerokuS3Backups.Heroku.store_on_s3
def store_on_s3(backup_location, backup_filename) prod_backup_folder = AWS_S3().buckets.find(ENV["S3_PRODUCTION_BACKUP_BUCKET"]).objects(prefix: backup_location) backup_obj = prod_backup_folder.build("#{backup_location}/#{backup_filename}") # Need to do this to set content length for some reason backup_obj.content = open(@backup_filename) backup_obj.save end
ruby
def store_on_s3(backup_location, backup_filename) prod_backup_folder = AWS_S3().buckets.find(ENV["S3_PRODUCTION_BACKUP_BUCKET"]).objects(prefix: backup_location) backup_obj = prod_backup_folder.build("#{backup_location}/#{backup_filename}") # Need to do this to set content length for some reason backup_obj.content = open(@backup_filename) backup_obj.save end
[ "def", "store_on_s3", "(", "backup_location", ",", "backup_filename", ")", "prod_backup_folder", "=", "AWS_S3", "(", ")", ".", "buckets", ".", "find", "(", "ENV", "[", "\"S3_PRODUCTION_BACKUP_BUCKET\"", "]", ")", ".", "objects", "(", "prefix", ":", "backup_location", ")", "backup_obj", "=", "prod_backup_folder", ".", "build", "(", "\"#{backup_location}/#{backup_filename}\"", ")", "backup_obj", ".", "content", "=", "open", "(", "@backup_filename", ")", "backup_obj", ".", "save", "end" ]
Stores the recently backed up file in a specified S3 bucket @param {string} backup_location
[ "Stores", "the", "recently", "backed", "up", "file", "in", "a", "specified", "S3", "bucket" ]
0c568f6774243cb276ed2fa8546d601f2f9e21a2
https://github.com/ableco/heroku_s3_backups/blob/0c568f6774243cb276ed2fa8546d601f2f9e21a2/lib/heroku_s3_backups.rb#L76-L85
train
kkaempf/ruby-wbem
lib/wbem/class_factory.rb
Wbem.ClassFactory.gen_method_parameters
def gen_method_parameters direction, parameters, file return if parameters.empty? file.print "#{direction.inspect} => [" first = true parameters.each do |p| if first first = false else file.print ", " end # [ <name>, <type>, <out>? ] file.print "#{p.name.inspect}, #{p.type.to_sym.inspect}" end file.print "]" return true end
ruby
def gen_method_parameters direction, parameters, file return if parameters.empty? file.print "#{direction.inspect} => [" first = true parameters.each do |p| if first first = false else file.print ", " end # [ <name>, <type>, <out>? ] file.print "#{p.name.inspect}, #{p.type.to_sym.inspect}" end file.print "]" return true end
[ "def", "gen_method_parameters", "direction", ",", "parameters", ",", "file", "return", "if", "parameters", ".", "empty?", "file", ".", "print", "\"#{direction.inspect} => [\"", "first", "=", "true", "parameters", ".", "each", "do", "|", "p", "|", "if", "first", "first", "=", "false", "else", "file", ".", "print", "\", \"", "end", "file", ".", "print", "\"#{p.name.inspect}, #{p.type.to_sym.inspect}\"", "end", "file", ".", "print", "\"]\"", "return", "true", "end" ]
generate method parameter information return nil if no parameters
[ "generate", "method", "parameter", "information", "return", "nil", "if", "no", "parameters" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/class_factory.rb#L68-L83
train
kkaempf/ruby-wbem
lib/wbem/class_factory.rb
Wbem.ClassFactory.generate
def generate name, file require 'erb' template = File.read(File.join(File.dirname(__FILE__), "class_template.erb")) erb = ERB.new(template) code = erb.result(binding) Dir.mkdir(@basedir) unless File.directory?(@basedir) File.open(file, "w+") do |f| f.puts code end end
ruby
def generate name, file require 'erb' template = File.read(File.join(File.dirname(__FILE__), "class_template.erb")) erb = ERB.new(template) code = erb.result(binding) Dir.mkdir(@basedir) unless File.directory?(@basedir) File.open(file, "w+") do |f| f.puts code end end
[ "def", "generate", "name", ",", "file", "require", "'erb'", "template", "=", "File", ".", "read", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "\"class_template.erb\"", ")", ")", "erb", "=", "ERB", ".", "new", "(", "template", ")", "code", "=", "erb", ".", "result", "(", "binding", ")", "Dir", ".", "mkdir", "(", "@basedir", ")", "unless", "File", ".", "directory?", "(", "@basedir", ")", "File", ".", "open", "(", "file", ",", "\"w+\"", ")", "do", "|", "f", "|", "f", ".", "puts", "code", "end", "end" ]
generate .rb class declaration
[ "generate", ".", "rb", "class", "declaration" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/class_factory.rb#L87-L96
train
kkaempf/ruby-wbem
lib/wbem/class_factory.rb
Wbem.ClassFactory.classmap
def classmap return @classmap if @classmap # read SCHEMA and build class index to find .mof files quickly @classmap = Hash.new @includes = [ Pathname.new(".") ] SCHEMATA.each do |base, file| @includes << base allow_cim = (file =~ /^CIM_/) # allow CIM_ only for CIM_Schema.mof File.open(File.join(base, file)) do |f| f.each do |l| if l =~ /^\#pragma\sinclude\s?\(\"(([\w\/_]+)\.mof)\"\).*/ # $1 Foo/Bar.mof # $2 Foo/Bar path = $1 names = $2.split("/") name = names[1] || names[0] next unless name =~ /_/ # class name must have underscore (rules out 'qualifiers.mof') # puts "#{path}:#{name}" next if !allow_cim && name =~ /^CIM_/ # skip CIM_ mofs unless allowed if @classmap[name] raise "Dup #{name} : #{@classmap[name]}" else @classmap[name] = { :path => path } end end end end end STDERR.puts "Found MOFs for #{@classmap.size} classes" if Wbem.debug @classmap end
ruby
def classmap return @classmap if @classmap # read SCHEMA and build class index to find .mof files quickly @classmap = Hash.new @includes = [ Pathname.new(".") ] SCHEMATA.each do |base, file| @includes << base allow_cim = (file =~ /^CIM_/) # allow CIM_ only for CIM_Schema.mof File.open(File.join(base, file)) do |f| f.each do |l| if l =~ /^\#pragma\sinclude\s?\(\"(([\w\/_]+)\.mof)\"\).*/ # $1 Foo/Bar.mof # $2 Foo/Bar path = $1 names = $2.split("/") name = names[1] || names[0] next unless name =~ /_/ # class name must have underscore (rules out 'qualifiers.mof') # puts "#{path}:#{name}" next if !allow_cim && name =~ /^CIM_/ # skip CIM_ mofs unless allowed if @classmap[name] raise "Dup #{name} : #{@classmap[name]}" else @classmap[name] = { :path => path } end end end end end STDERR.puts "Found MOFs for #{@classmap.size} classes" if Wbem.debug @classmap end
[ "def", "classmap", "return", "@classmap", "if", "@classmap", "@classmap", "=", "Hash", ".", "new", "@includes", "=", "[", "Pathname", ".", "new", "(", "\".\"", ")", "]", "SCHEMATA", ".", "each", "do", "|", "base", ",", "file", "|", "@includes", "<<", "base", "allow_cim", "=", "(", "file", "=~", "/", "/", ")", "File", ".", "open", "(", "File", ".", "join", "(", "base", ",", "file", ")", ")", "do", "|", "f", "|", "f", ".", "each", "do", "|", "l", "|", "if", "l", "=~", "/", "\\#", "\\s", "\\s", "\\(", "\\\"", "\\w", "\\/", "\\.", "\\\"", "\\)", "/", "path", "=", "$1", "names", "=", "$2", ".", "split", "(", "\"/\"", ")", "name", "=", "names", "[", "1", "]", "||", "names", "[", "0", "]", "next", "unless", "name", "=~", "/", "/", "next", "if", "!", "allow_cim", "&&", "name", "=~", "/", "/", "if", "@classmap", "[", "name", "]", "raise", "\"Dup #{name} : #{@classmap[name]}\"", "else", "@classmap", "[", "name", "]", "=", "{", ":path", "=>", "path", "}", "end", "end", "end", "end", "end", "STDERR", ".", "puts", "\"Found MOFs for #{@classmap.size} classes\"", "if", "Wbem", ".", "debug", "@classmap", "end" ]
classmap - generate map of classes and their .mof files
[ "classmap", "-", "generate", "map", "of", "classes", "and", "their", ".", "mof", "files" ]
ce813d911b8b67ef23fb6171f6910ebbca602121
https://github.com/kkaempf/ruby-wbem/blob/ce813d911b8b67ef23fb6171f6910ebbca602121/lib/wbem/class_factory.rb#L101-L131
train
baltavay/dawg
lib/dawg/finder.rb
Dawg.Finder.query
def query(word) node = @the_node results = [] word.split("").each do |letter| next_node = node[letter] if next_node != nil node = next_node next else return [''] end end results << Word.new(word, node.final) results += get_childs(node).map{|s| Word.new(word) + s} results.select{|r| r.final}.map{|r| r.to_s } end
ruby
def query(word) node = @the_node results = [] word.split("").each do |letter| next_node = node[letter] if next_node != nil node = next_node next else return [''] end end results << Word.new(word, node.final) results += get_childs(node).map{|s| Word.new(word) + s} results.select{|r| r.final}.map{|r| r.to_s } end
[ "def", "query", "(", "word", ")", "node", "=", "@the_node", "results", "=", "[", "]", "word", ".", "split", "(", "\"\"", ")", ".", "each", "do", "|", "letter", "|", "next_node", "=", "node", "[", "letter", "]", "if", "next_node", "!=", "nil", "node", "=", "next_node", "next", "else", "return", "[", "''", "]", "end", "end", "results", "<<", "Word", ".", "new", "(", "word", ",", "node", ".", "final", ")", "results", "+=", "get_childs", "(", "node", ")", ".", "map", "{", "|", "s", "|", "Word", ".", "new", "(", "word", ")", "+", "s", "}", "results", ".", "select", "{", "|", "r", "|", "r", ".", "final", "}", ".", "map", "{", "|", "r", "|", "r", ".", "to_s", "}", "end" ]
get all words with given prefix
[ "get", "all", "words", "with", "given", "prefix" ]
2f08b319b1d6ba6c98d938bd0742c3c74dc6acd9
https://github.com/baltavay/dawg/blob/2f08b319b1d6ba6c98d938bd0742c3c74dc6acd9/lib/dawg/finder.rb#L22-L37
train
flajann2/deep_dive
lib/deep_dive/deep_dive.rb
DeepDive.::Enumerable._add
def _add(v: nil, dupit: nil, oc: nil, patch: {}) unless _pairs? case when self.kind_of?(::Set) when self.kind_of?(::Array) self << _ob_maybe_repl(v: v, dupit: dupit, oc: oc, patch: patch) else raise DeepDiveException.new("Don't know how to add new elements for class #{self.class}") end else self[v.first] = _ob_maybe_repl(v: v.last, dupit: dupit, oc: oc, patch: patch) end end
ruby
def _add(v: nil, dupit: nil, oc: nil, patch: {}) unless _pairs? case when self.kind_of?(::Set) when self.kind_of?(::Array) self << _ob_maybe_repl(v: v, dupit: dupit, oc: oc, patch: patch) else raise DeepDiveException.new("Don't know how to add new elements for class #{self.class}") end else self[v.first] = _ob_maybe_repl(v: v.last, dupit: dupit, oc: oc, patch: patch) end end
[ "def", "_add", "(", "v", ":", "nil", ",", "dupit", ":", "nil", ",", "oc", ":", "nil", ",", "patch", ":", "{", "}", ")", "unless", "_pairs?", "case", "when", "self", ".", "kind_of?", "(", "::", "Set", ")", "when", "self", ".", "kind_of?", "(", "::", "Array", ")", "self", "<<", "_ob_maybe_repl", "(", "v", ":", "v", ",", "dupit", ":", "dupit", ",", "oc", ":", "oc", ",", "patch", ":", "patch", ")", "else", "raise", "DeepDiveException", ".", "new", "(", "\"Don't know how to add new elements for class #{self.class}\"", ")", "end", "else", "self", "[", "v", ".", "first", "]", "=", "_ob_maybe_repl", "(", "v", ":", "v", ".", "last", ",", "dupit", ":", "dupit", ",", "oc", ":", "oc", ",", "patch", ":", "patch", ")", "end", "end" ]
add a single element to the enumerable. You may pass a single parameter, or a key, value. In any case, all will added. Here all the logic will be present to handle the "special case" enumerables. Most notedly, Hash and Array will require special treatment.
[ "add", "a", "single", "element", "to", "the", "enumerable", ".", "You", "may", "pass", "a", "single", "parameter", "or", "a", "key", "value", ".", "In", "any", "case", "all", "will", "added", "." ]
dae12cefe5706d76c4c3a37735ebef2e0d3f6cb0
https://github.com/flajann2/deep_dive/blob/dae12cefe5706d76c4c3a37735ebef2e0d3f6cb0/lib/deep_dive/deep_dive.rb#L110-L122
train
rightscale/right_chimp
lib/right_chimp/queue/chimp_queue.rb
Chimp.ChimpQueue.start
def start self.sort_queues! for i in (1..max_threads) @threads << Thread.new(i) do worker = QueueWorker.new worker.delay = @delay worker.retry_count = @retry_count worker.run end end end
ruby
def start self.sort_queues! for i in (1..max_threads) @threads << Thread.new(i) do worker = QueueWorker.new worker.delay = @delay worker.retry_count = @retry_count worker.run end end end
[ "def", "start", "self", ".", "sort_queues!", "for", "i", "in", "(", "1", "..", "max_threads", ")", "@threads", "<<", "Thread", ".", "new", "(", "i", ")", "do", "worker", "=", "QueueWorker", ".", "new", "worker", ".", "delay", "=", "@delay", "worker", ".", "retry_count", "=", "@retry_count", "worker", ".", "run", "end", "end", "end" ]
Start up queue runners
[ "Start", "up", "queue", "runners" ]
290d3e01f7bf4b505722a080cb0abbb0314222f8
https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L35-L46
train
rightscale/right_chimp
lib/right_chimp/queue/chimp_queue.rb
Chimp.ChimpQueue.push
def push(g, w) raise "no group specified" unless g create_group(g) if not ChimpQueue[g] ChimpQueue[g].push(w) unless ChimpQueue[g].get_job(w.job_id) end
ruby
def push(g, w) raise "no group specified" unless g create_group(g) if not ChimpQueue[g] ChimpQueue[g].push(w) unless ChimpQueue[g].get_job(w.job_id) end
[ "def", "push", "(", "g", ",", "w", ")", "raise", "\"no group specified\"", "unless", "g", "create_group", "(", "g", ")", "if", "not", "ChimpQueue", "[", "g", "]", "ChimpQueue", "[", "g", "]", ".", "push", "(", "w", ")", "unless", "ChimpQueue", "[", "g", "]", ".", "get_job", "(", "w", ".", "job_id", ")", "end" ]
Push a task into the queue
[ "Push", "a", "task", "into", "the", "queue" ]
290d3e01f7bf4b505722a080cb0abbb0314222f8
https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L51-L56
train
rightscale/right_chimp
lib/right_chimp/queue/chimp_queue.rb
Chimp.ChimpQueue.shift
def shift r = nil @semaphore.synchronize do @group.values.each do |group| if group.ready? r = group.shift Log.debug "Shifting job '#{r.job_id}' from group '#{group.group_id}'" unless r.nil? break end end end return(r) end
ruby
def shift r = nil @semaphore.synchronize do @group.values.each do |group| if group.ready? r = group.shift Log.debug "Shifting job '#{r.job_id}' from group '#{group.group_id}'" unless r.nil? break end end end return(r) end
[ "def", "shift", "r", "=", "nil", "@semaphore", ".", "synchronize", "do", "@group", ".", "values", ".", "each", "do", "|", "group", "|", "if", "group", ".", "ready?", "r", "=", "group", ".", "shift", "Log", ".", "debug", "\"Shifting job '#{r.job_id}' from group '#{group.group_id}'\"", "unless", "r", ".", "nil?", "break", "end", "end", "end", "return", "(", "r", ")", "end" ]
Grab the oldest work item available
[ "Grab", "the", "oldest", "work", "item", "available" ]
290d3e01f7bf4b505722a080cb0abbb0314222f8
https://github.com/rightscale/right_chimp/blob/290d3e01f7bf4b505722a080cb0abbb0314222f8/lib/right_chimp/queue/chimp_queue.rb#L69-L81
train