id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
1,000
Atrox/sweetify
lib/sweetify/sweetalert.rb
Sweetify.SweetAlert.sweetalert
def sweetalert(text, title = '', opts = {}) opts = { showConfirmButton: false, timer: 2000, allowOutsideClick: true, confirmButtonText: 'OK' }.merge(opts) opts[:text] = text opts[:title] = title if opts[:button] opts[:showConfirmButton] = true opts[:confirmButtonText] = opts[:button] if opts[:button].is_a?(String) opts.delete(:button) end if opts[:persistent] opts[:showConfirmButton] = true opts[:allowOutsideClick] = false opts[:timer] = nil opts[:confirmButtonText] = opts[:persistent] if opts[:persistent].is_a?(String) opts.delete(:persistent) end flash_config(opts) end
ruby
def sweetalert(text, title = '', opts = {}) opts = { showConfirmButton: false, timer: 2000, allowOutsideClick: true, confirmButtonText: 'OK' }.merge(opts) opts[:text] = text opts[:title] = title if opts[:button] opts[:showConfirmButton] = true opts[:confirmButtonText] = opts[:button] if opts[:button].is_a?(String) opts.delete(:button) end if opts[:persistent] opts[:showConfirmButton] = true opts[:allowOutsideClick] = false opts[:timer] = nil opts[:confirmButtonText] = opts[:persistent] if opts[:persistent].is_a?(String) opts.delete(:persistent) end flash_config(opts) end
[ "def", "sweetalert", "(", "text", ",", "title", "=", "''", ",", "opts", "=", "{", "}", ")", "opts", "=", "{", "showConfirmButton", ":", "false", ",", "timer", ":", "2000", ",", "allowOutsideClick", ":", "true", ",", "confirmButtonText", ":", "'OK'", "}", ".", "merge", "(", "opts", ")", "opts", "[", ":text", "]", "=", "text", "opts", "[", ":title", "]", "=", "title", "if", "opts", "[", ":button", "]", "opts", "[", ":showConfirmButton", "]", "=", "true", "opts", "[", ":confirmButtonText", "]", "=", "opts", "[", ":button", "]", "if", "opts", "[", ":button", "]", ".", "is_a?", "(", "String", ")", "opts", ".", "delete", "(", ":button", ")", "end", "if", "opts", "[", ":persistent", "]", "opts", "[", ":showConfirmButton", "]", "=", "true", "opts", "[", ":allowOutsideClick", "]", "=", "false", "opts", "[", ":timer", "]", "=", "nil", "opts", "[", ":confirmButtonText", "]", "=", "opts", "[", ":persistent", "]", "if", "opts", "[", ":persistent", "]", ".", "is_a?", "(", "String", ")", "opts", ".", "delete", "(", ":persistent", ")", "end", "flash_config", "(", "opts", ")", "end" ]
Display an alert with a text and an optional title Default without an specific type @param [String] text Body of the alert (gets automatically the title if no title is specified) @param [String] title Title of the alert @param [Hash] opts Optional Parameters
[ "Display", "an", "alert", "with", "a", "text", "and", "an", "optional", "title", "Default", "without", "an", "specific", "type" ]
299e91e6407f17912f351f9492d42a4eb44c063f
https://github.com/Atrox/sweetify/blob/299e91e6407f17912f351f9492d42a4eb44c063f/lib/sweetify/sweetalert.rb#L9-L37
1,001
Atrox/sweetify
lib/sweetify/sweetalert.rb
Sweetify.SweetAlert.flash_config
def flash_config(opts) if opts[:title].blank? opts[:title] = opts[:text] opts.delete(:text) end flash[:sweetify] = opts.to_json end
ruby
def flash_config(opts) if opts[:title].blank? opts[:title] = opts[:text] opts.delete(:text) end flash[:sweetify] = opts.to_json end
[ "def", "flash_config", "(", "opts", ")", "if", "opts", "[", ":title", "]", ".", "blank?", "opts", "[", ":title", "]", "=", "opts", "[", ":text", "]", "opts", ".", "delete", "(", ":text", ")", "end", "flash", "[", ":sweetify", "]", "=", "opts", ".", "to_json", "end" ]
Flash the configuration as json If no title is specified, use the text as the title @param [Hash] opts @return [Void]
[ "Flash", "the", "configuration", "as", "json", "If", "no", "title", "is", "specified", "use", "the", "text", "as", "the", "title" ]
299e91e6407f17912f351f9492d42a4eb44c063f
https://github.com/Atrox/sweetify/blob/299e91e6407f17912f351f9492d42a4eb44c063f/lib/sweetify/sweetalert.rb#L86-L93
1,002
ebeigarts/exchanger
lib/exchanger/element.rb
Exchanger.Element.to_xml
def to_xml(options = {}) doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) self.class.keys.each do |name| value = read_attribute(name) next if value.blank? root[name.to_s.camelize] = value end self.class.elements.each do |name, field| next if options[:only] && !options[:only].include?(name) next if field.options[:readonly] value = read_attribute(name) next if field.type.is_a?(Array) && value.blank? next if new_record? && field.type == Identifier next if new_record? && value.blank? if name == :text root << value.to_s else root << field.to_xml(value) end end root end
ruby
def to_xml(options = {}) doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) self.class.keys.each do |name| value = read_attribute(name) next if value.blank? root[name.to_s.camelize] = value end self.class.elements.each do |name, field| next if options[:only] && !options[:only].include?(name) next if field.options[:readonly] value = read_attribute(name) next if field.type.is_a?(Array) && value.blank? next if new_record? && field.type == Identifier next if new_record? && value.blank? if name == :text root << value.to_s else root << field.to_xml(value) end end root end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "new", "root", "=", "doc", ".", "create_element", "(", "tag_name", ")", "self", ".", "class", ".", "keys", ".", "each", "do", "|", "name", "|", "value", "=", "read_attribute", "(", "name", ")", "next", "if", "value", ".", "blank?", "root", "[", "name", ".", "to_s", ".", "camelize", "]", "=", "value", "end", "self", ".", "class", ".", "elements", ".", "each", "do", "|", "name", ",", "field", "|", "next", "if", "options", "[", ":only", "]", "&&", "!", "options", "[", ":only", "]", ".", "include?", "(", "name", ")", "next", "if", "field", ".", "options", "[", ":readonly", "]", "value", "=", "read_attribute", "(", "name", ")", "next", "if", "field", ".", "type", ".", "is_a?", "(", "Array", ")", "&&", "value", ".", "blank?", "next", "if", "new_record?", "&&", "field", ".", "type", "==", "Identifier", "next", "if", "new_record?", "&&", "value", ".", "blank?", "if", "name", "==", ":text", "root", "<<", "value", ".", "to_s", "else", "root", "<<", "field", ".", "to_xml", "(", "value", ")", "end", "end", "root", "end" ]
Builds XML from elements and attributes
[ "Builds", "XML", "from", "elements", "and", "attributes" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/element.rb#L97-L119
1,003
mitchellh/middleware
lib/middleware/builder.rb
Middleware.Builder.insert
def insert(index, middleware, *args, &block) index = self.index(index) unless index.is_a?(Integer) raise "no such middleware to insert before: #{index.inspect}" unless index stack.insert(index, [middleware, args, block]) end
ruby
def insert(index, middleware, *args, &block) index = self.index(index) unless index.is_a?(Integer) raise "no such middleware to insert before: #{index.inspect}" unless index stack.insert(index, [middleware, args, block]) end
[ "def", "insert", "(", "index", ",", "middleware", ",", "*", "args", ",", "&", "block", ")", "index", "=", "self", ".", "index", "(", "index", ")", "unless", "index", ".", "is_a?", "(", "Integer", ")", "raise", "\"no such middleware to insert before: #{index.inspect}\"", "unless", "index", "stack", ".", "insert", "(", "index", ",", "[", "middleware", ",", "args", ",", "block", "]", ")", "end" ]
Inserts a middleware at the given index or directly before the given middleware object.
[ "Inserts", "a", "middleware", "at", "the", "given", "index", "or", "directly", "before", "the", "given", "middleware", "object", "." ]
23d4741d15c5999d81493ec43448f72032119bee
https://github.com/mitchellh/middleware/blob/23d4741d15c5999d81493ec43448f72032119bee/lib/middleware/builder.rb#L68-L72
1,004
mitchellh/middleware
lib/middleware/builder.rb
Middleware.Builder.replace
def replace(index, middleware, *args, &block) if index.is_a?(Integer) delete(index) insert(index, middleware, *args, &block) else insert_before(index, middleware, *args, &block) delete(index) end end
ruby
def replace(index, middleware, *args, &block) if index.is_a?(Integer) delete(index) insert(index, middleware, *args, &block) else insert_before(index, middleware, *args, &block) delete(index) end end
[ "def", "replace", "(", "index", ",", "middleware", ",", "*", "args", ",", "&", "block", ")", "if", "index", ".", "is_a?", "(", "Integer", ")", "delete", "(", "index", ")", "insert", "(", "index", ",", "middleware", ",", "args", ",", "block", ")", "else", "insert_before", "(", "index", ",", "middleware", ",", "args", ",", "block", ")", "delete", "(", "index", ")", "end", "end" ]
Replaces the given middleware object or index with the new middleware.
[ "Replaces", "the", "given", "middleware", "object", "or", "index", "with", "the", "new", "middleware", "." ]
23d4741d15c5999d81493ec43448f72032119bee
https://github.com/mitchellh/middleware/blob/23d4741d15c5999d81493ec43448f72032119bee/lib/middleware/builder.rb#L85-L93
1,005
ebeigarts/exchanger
lib/exchanger/persistence.rb
Exchanger.Persistence.reload
def reload if new_record? false else reloaded_element = self.class.find(self.id) @attributes = reloaded_element.attributes reset_modifications true end end
ruby
def reload if new_record? false else reloaded_element = self.class.find(self.id) @attributes = reloaded_element.attributes reset_modifications true end end
[ "def", "reload", "if", "new_record?", "false", "else", "reloaded_element", "=", "self", ".", "class", ".", "find", "(", "self", ".", "id", ")", "@attributes", "=", "reloaded_element", ".", "attributes", "reset_modifications", "true", "end", "end" ]
Reloads the +Element+ attributes from Exchanger.
[ "Reloads", "the", "+", "Element", "+", "attributes", "from", "Exchanger", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/persistence.rb#L28-L37
1,006
ebeigarts/exchanger
lib/exchanger/field.rb
Exchanger.Field.to_xml
def to_xml(value, options = {}) if value.is_a?(Exchanger::Element) value.tag_name = tag_name value.to_xml(options) else doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) case value when Array value.each do |sub_value| root << sub_field.to_xml(sub_value, options) end when Boolean root << doc.create_text_node(value == true) when Time root << doc.create_text_node(value.xmlschema) else # String, Integer, etc root << doc.create_text_node(value.to_s) end root end end
ruby
def to_xml(value, options = {}) if value.is_a?(Exchanger::Element) value.tag_name = tag_name value.to_xml(options) else doc = Nokogiri::XML::Document.new root = doc.create_element(tag_name) case value when Array value.each do |sub_value| root << sub_field.to_xml(sub_value, options) end when Boolean root << doc.create_text_node(value == true) when Time root << doc.create_text_node(value.xmlschema) else # String, Integer, etc root << doc.create_text_node(value.to_s) end root end end
[ "def", "to_xml", "(", "value", ",", "options", "=", "{", "}", ")", "if", "value", ".", "is_a?", "(", "Exchanger", "::", "Element", ")", "value", ".", "tag_name", "=", "tag_name", "value", ".", "to_xml", "(", "options", ")", "else", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "new", "root", "=", "doc", ".", "create_element", "(", "tag_name", ")", "case", "value", "when", "Array", "value", ".", "each", "do", "|", "sub_value", "|", "root", "<<", "sub_field", ".", "to_xml", "(", "sub_value", ",", "options", ")", "end", "when", "Boolean", "root", "<<", "doc", ".", "create_text_node", "(", "value", "==", "true", ")", "when", "Time", "root", "<<", "doc", ".", "create_text_node", "(", "value", ".", "xmlschema", ")", "else", "# String, Integer, etc", "root", "<<", "doc", ".", "create_text_node", "(", "value", ".", "to_s", ")", "end", "root", "end", "end" ]
Convert Ruby value to XML
[ "Convert", "Ruby", "value", "to", "XML" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/field.rb#L97-L118
1,007
ebeigarts/exchanger
lib/exchanger/field.rb
Exchanger.Field.value_from_xml
def value_from_xml(node) if type.respond_to?(:new_from_xml) type.new_from_xml(node) elsif type.is_a?(Array) node.children.map do |sub_node| sub_field.value_from_xml(sub_node) end elsif type == Boolean node.text == "true" elsif type == Integer node.text.to_i unless node.text.empty? elsif type == Time Time.xmlschema(node.text) unless node.text.empty? else node.text end end
ruby
def value_from_xml(node) if type.respond_to?(:new_from_xml) type.new_from_xml(node) elsif type.is_a?(Array) node.children.map do |sub_node| sub_field.value_from_xml(sub_node) end elsif type == Boolean node.text == "true" elsif type == Integer node.text.to_i unless node.text.empty? elsif type == Time Time.xmlschema(node.text) unless node.text.empty? else node.text end end
[ "def", "value_from_xml", "(", "node", ")", "if", "type", ".", "respond_to?", "(", ":new_from_xml", ")", "type", ".", "new_from_xml", "(", "node", ")", "elsif", "type", ".", "is_a?", "(", "Array", ")", "node", ".", "children", ".", "map", "do", "|", "sub_node", "|", "sub_field", ".", "value_from_xml", "(", "sub_node", ")", "end", "elsif", "type", "==", "Boolean", "node", ".", "text", "==", "\"true\"", "elsif", "type", "==", "Integer", "node", ".", "text", ".", "to_i", "unless", "node", ".", "text", ".", "empty?", "elsif", "type", "==", "Time", "Time", ".", "xmlschema", "(", "node", ".", "text", ")", "unless", "node", ".", "text", ".", "empty?", "else", "node", ".", "text", "end", "end" ]
Convert XML to Ruby value
[ "Convert", "XML", "to", "Ruby", "value" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/field.rb#L121-L137
1,008
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.reset_attribute!
def reset_attribute!(name) value = attribute_was(name) if value @attributes[name] = value modifications.delete(name) end end
ruby
def reset_attribute!(name) value = attribute_was(name) if value @attributes[name] = value modifications.delete(name) end end
[ "def", "reset_attribute!", "(", "name", ")", "value", "=", "attribute_was", "(", "name", ")", "if", "value", "@attributes", "[", "name", "]", "=", "value", "modifications", ".", "delete", "(", "name", ")", "end", "end" ]
Resets a changed field back to its old value. Example: person = Person.new(:title => "Sir") person.title = "Madam" person.reset_attribute!("title") person.title # "Sir" Returns: The old field value.
[ "Resets", "a", "changed", "field", "back", "to", "its", "old", "value", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L139-L145
1,009
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.accessed
def accessed(name, value) @accessed ||= {} @accessed[name] = value.dup if (value.is_a?(Array) || value.is_a?(Hash)) && [email protected]_key?(name) value end
ruby
def accessed(name, value) @accessed ||= {} @accessed[name] = value.dup if (value.is_a?(Array) || value.is_a?(Hash)) && [email protected]_key?(name) value end
[ "def", "accessed", "(", "name", ",", "value", ")", "@accessed", "||=", "{", "}", "@accessed", "[", "name", "]", "=", "value", ".", "dup", "if", "(", "value", ".", "is_a?", "(", "Array", ")", "||", "value", ".", "is_a?", "(", "Hash", ")", ")", "&&", "!", "@accessed", ".", "has_key?", "(", "name", ")", "value", "end" ]
Audit the original value for a field that can be modified in place. Example: <tt>person.accessed("aliases", [ "007" ])</tt>
[ "Audit", "the", "original", "value", "for", "a", "field", "that", "can", "be", "modified", "in", "place", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L177-L181
1,010
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.modifications
def modifications @accessed.each_pair do |field, value| current = @attributes[field] if current != value || (current.is_a?(Array) && current.any? { |v| v.respond_to?(:changed?) && v.changed? }) @modifications[field] = [ value, current ] end end @accessed.clear @modifications end
ruby
def modifications @accessed.each_pair do |field, value| current = @attributes[field] if current != value || (current.is_a?(Array) && current.any? { |v| v.respond_to?(:changed?) && v.changed? }) @modifications[field] = [ value, current ] end end @accessed.clear @modifications end
[ "def", "modifications", "@accessed", ".", "each_pair", "do", "|", "field", ",", "value", "|", "current", "=", "@attributes", "[", "field", "]", "if", "current", "!=", "value", "||", "(", "current", ".", "is_a?", "(", "Array", ")", "&&", "current", ".", "any?", "{", "|", "v", "|", "v", ".", "respond_to?", "(", ":changed?", ")", "&&", "v", ".", "changed?", "}", ")", "@modifications", "[", "field", "]", "=", "[", "value", ",", "current", "]", "end", "end", "@accessed", ".", "clear", "@modifications", "end" ]
Get all normal modifications plus in place potential changes. Also checks changes in array attributes with +Element+ objects. Example: <tt>person.modifications</tt> Returns: All changes to the document.
[ "Get", "all", "normal", "modifications", "plus", "in", "place", "potential", "changes", ".", "Also", "checks", "changes", "in", "array", "attributes", "with", "+", "Element", "+", "objects", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L193-L203
1,011
ebeigarts/exchanger
lib/exchanger/dirty.rb
Exchanger.Dirty.modify
def modify(name, old_value, new_value) @attributes[name] = new_value if @modifications && (old_value != new_value) original = @modifications[name].first if @modifications[name] @modifications[name] = [ (original || old_value), new_value ] end end
ruby
def modify(name, old_value, new_value) @attributes[name] = new_value if @modifications && (old_value != new_value) original = @modifications[name].first if @modifications[name] @modifications[name] = [ (original || old_value), new_value ] end end
[ "def", "modify", "(", "name", ",", "old_value", ",", "new_value", ")", "@attributes", "[", "name", "]", "=", "new_value", "if", "@modifications", "&&", "(", "old_value", "!=", "new_value", ")", "original", "=", "@modifications", "[", "name", "]", ".", "first", "if", "@modifications", "[", "name", "]", "@modifications", "[", "name", "]", "=", "[", "(", "original", "||", "old_value", ")", ",", "new_value", "]", "end", "end" ]
Audit the change of a field's value. Example: <tt>person.modify("name", "Jack", "John")</tt>
[ "Audit", "the", "change", "of", "a", "field", "s", "value", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/dirty.rb#L210-L216
1,012
ebeigarts/exchanger
lib/exchanger/attributes.rb
Exchanger.Attributes.method_missing
def method_missing(name, *args) attr = name.to_s.sub("=", "") return super unless attributes.has_key?(attr) if name.to_s.ends_with?("=") write_attribute(attr, *args) else read_attribute(attr) end end
ruby
def method_missing(name, *args) attr = name.to_s.sub("=", "") return super unless attributes.has_key?(attr) if name.to_s.ends_with?("=") write_attribute(attr, *args) else read_attribute(attr) end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "attr", "=", "name", ".", "to_s", ".", "sub", "(", "\"=\"", ",", "\"\"", ")", "return", "super", "unless", "attributes", ".", "has_key?", "(", "attr", ")", "if", "name", ".", "to_s", ".", "ends_with?", "(", "\"=\"", ")", "write_attribute", "(", "attr", ",", "args", ")", "else", "read_attribute", "(", "attr", ")", "end", "end" ]
Used for allowing accessor methods for dynamic attributes
[ "Used", "for", "allowing", "accessor", "methods", "for", "dynamic", "attributes" ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/attributes.rb#L51-L59
1,013
ebeigarts/exchanger
lib/exchanger/client.rb
Exchanger.Client.request
def request(post_body, headers) response = @client.post(endpoint, post_body, headers) return { :status => response.status, :body => response.content, :content_type => response.contenttype } end
ruby
def request(post_body, headers) response = @client.post(endpoint, post_body, headers) return { :status => response.status, :body => response.content, :content_type => response.contenttype } end
[ "def", "request", "(", "post_body", ",", "headers", ")", "response", "=", "@client", ".", "post", "(", "endpoint", ",", "post_body", ",", "headers", ")", "return", "{", ":status", "=>", "response", ".", "status", ",", ":body", "=>", "response", ".", "content", ",", ":content_type", "=>", "response", ".", "contenttype", "}", "end" ]
Does the actual HTTP level interaction.
[ "Does", "the", "actual", "HTTP", "level", "interaction", "." ]
10f24ffaaa69881bebb9823b1756cb18ca96e2f8
https://github.com/ebeigarts/exchanger/blob/10f24ffaaa69881bebb9823b1756cb18ca96e2f8/lib/exchanger/client.rb#L15-L18
1,014
Arcath/Adauth
lib/adauth/connection.rb
Adauth.Connection.bind
def bind conn = Net::LDAP.new :host => @config[:server], :port => @config[:port], :base => @config[:base] if @config[:encryption] conn.encryption @config[:encryption] end raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind]) conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password] begin Timeout::timeout(10){ if conn.bind return conn else raise 'Query User Rejected' end } rescue Timeout::Error raise 'Unable to connect to LDAP Server' rescue Errno::ECONNRESET if @config[:allow_fallback] @config[:port] = @config[:allow_fallback] @config[:encryption] = false return Adauth::Connection.new(@config).bind end end end
ruby
def bind conn = Net::LDAP.new :host => @config[:server], :port => @config[:port], :base => @config[:base] if @config[:encryption] conn.encryption @config[:encryption] end raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind]) conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password] begin Timeout::timeout(10){ if conn.bind return conn else raise 'Query User Rejected' end } rescue Timeout::Error raise 'Unable to connect to LDAP Server' rescue Errno::ECONNRESET if @config[:allow_fallback] @config[:port] = @config[:allow_fallback] @config[:encryption] = false return Adauth::Connection.new(@config).bind end end end
[ "def", "bind", "conn", "=", "Net", "::", "LDAP", ".", "new", ":host", "=>", "@config", "[", ":server", "]", ",", ":port", "=>", "@config", "[", ":port", "]", ",", ":base", "=>", "@config", "[", ":base", "]", "if", "@config", "[", ":encryption", "]", "conn", ".", "encryption", "@config", "[", ":encryption", "]", "end", "raise", "\"Anonymous Bind is disabled\"", "if", "@config", "[", ":password", "]", "==", "\"\"", "&&", "!", "(", "@config", "[", ":anonymous_bind", "]", ")", "conn", ".", "auth", "\"#{@config[:username]}@#{@config[:domain]}\"", ",", "@config", "[", ":password", "]", "begin", "Timeout", "::", "timeout", "(", "10", ")", "{", "if", "conn", ".", "bind", "return", "conn", "else", "raise", "'Query User Rejected'", "end", "}", "rescue", "Timeout", "::", "Error", "raise", "'Unable to connect to LDAP Server'", "rescue", "Errno", "::", "ECONNRESET", "if", "@config", "[", ":allow_fallback", "]", "@config", "[", ":port", "]", "=", "@config", "[", ":allow_fallback", "]", "@config", "[", ":encryption", "]", "=", "false", "return", "Adauth", "::", "Connection", ".", "new", "(", "@config", ")", ".", "bind", "end", "end", "end" ]
Attempts to bind to Active Directory If it works it returns the connection If it fails it raises and exception
[ "Attempts", "to", "bind", "to", "Active", "Directory" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/connection.rb#L18-L47
1,015
dachinat/nextcloud
lib/nextcloud/api.rb
Nextcloud.Api.request
def request(method, path, params = nil, body = nil, depth = nil, destination = nil, raw = false) response = Net::HTTP.start(@url.host, @url.port, use_ssl: @url.scheme == "https") do |http| req = Kernel.const_get("Net::HTTP::#{method.capitalize}").new(@url.request_uri + path) req["OCS-APIRequest"] = true req.basic_auth @username, @password req["Content-Type"] = "application/x-www-form-urlencoded" req["Depth"] = 0 if depth req["Destination"] = destination if destination req.set_form_data(params) if params req.body = body if body http.request(req) end # if ![201, 204, 207].include? response.code # raise Errors::Error.new("Nextcloud received invalid status code") # end raw ? response.body : Nokogiri::XML.parse(response.body) end
ruby
def request(method, path, params = nil, body = nil, depth = nil, destination = nil, raw = false) response = Net::HTTP.start(@url.host, @url.port, use_ssl: @url.scheme == "https") do |http| req = Kernel.const_get("Net::HTTP::#{method.capitalize}").new(@url.request_uri + path) req["OCS-APIRequest"] = true req.basic_auth @username, @password req["Content-Type"] = "application/x-www-form-urlencoded" req["Depth"] = 0 if depth req["Destination"] = destination if destination req.set_form_data(params) if params req.body = body if body http.request(req) end # if ![201, 204, 207].include? response.code # raise Errors::Error.new("Nextcloud received invalid status code") # end raw ? response.body : Nokogiri::XML.parse(response.body) end
[ "def", "request", "(", "method", ",", "path", ",", "params", "=", "nil", ",", "body", "=", "nil", ",", "depth", "=", "nil", ",", "destination", "=", "nil", ",", "raw", "=", "false", ")", "response", "=", "Net", "::", "HTTP", ".", "start", "(", "@url", ".", "host", ",", "@url", ".", "port", ",", "use_ssl", ":", "@url", ".", "scheme", "==", "\"https\"", ")", "do", "|", "http", "|", "req", "=", "Kernel", ".", "const_get", "(", "\"Net::HTTP::#{method.capitalize}\"", ")", ".", "new", "(", "@url", ".", "request_uri", "+", "path", ")", "req", "[", "\"OCS-APIRequest\"", "]", "=", "true", "req", ".", "basic_auth", "@username", ",", "@password", "req", "[", "\"Content-Type\"", "]", "=", "\"application/x-www-form-urlencoded\"", "req", "[", "\"Depth\"", "]", "=", "0", "if", "depth", "req", "[", "\"Destination\"", "]", "=", "destination", "if", "destination", "req", ".", "set_form_data", "(", "params", ")", "if", "params", "req", ".", "body", "=", "body", "if", "body", "http", ".", "request", "(", "req", ")", "end", "# if ![201, 204, 207].include? response.code", "# raise Errors::Error.new(\"Nextcloud received invalid status code\")", "# end", "raw", "?", "response", ".", "body", ":", "Nokogiri", "::", "XML", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Gathers credentials for communicating with Nextcloud instance @param [Hash] args authentication credentials. @option args [String] :url Nextcloud instance URL @option args [String] :username Nextcloud instance administrator username @option args [String] :password Nextcloud instance administrator password Sends API request to Nextcloud @param method [Symbol] Request type. Can be :get, :post, :put, etc. @param path [String] Nextcloud OCS API request path @param params [Hash, nil] Parameters to send @return [Object] Nokogiri::XML::Document
[ "Gathers", "credentials", "for", "communicating", "with", "Nextcloud", "instance" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/api.rb#L26-L47
1,016
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.parse_with_meta
def parse_with_meta(doc, xpath) groups = [] doc.xpath(xpath).each do |prop| groups << prop.text end meta = get_meta(doc) groups.send(:define_singleton_method, :meta) do meta end groups end
ruby
def parse_with_meta(doc, xpath) groups = [] doc.xpath(xpath).each do |prop| groups << prop.text end meta = get_meta(doc) groups.send(:define_singleton_method, :meta) do meta end groups end
[ "def", "parse_with_meta", "(", "doc", ",", "xpath", ")", "groups", "=", "[", "]", "doc", ".", "xpath", "(", "xpath", ")", ".", "each", "do", "|", "prop", "|", "groups", "<<", "prop", ".", "text", "end", "meta", "=", "get_meta", "(", "doc", ")", "groups", ".", "send", "(", ":define_singleton_method", ",", ":meta", ")", "do", "meta", "end", "groups", "end" ]
Makes an array out of repeated elements @param doc [Object] Nokogiri::XML::Document @param xpath [String] Path to element that is being repeated @return [Array] Parsed array
[ "Makes", "an", "array", "out", "of", "repeated", "elements" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L12-L22
1,017
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.get_meta
def get_meta(doc) meta = doc.xpath("//meta/*").each_with_object({}) do |node, meta| meta[node.name] = node.text end end
ruby
def get_meta(doc) meta = doc.xpath("//meta/*").each_with_object({}) do |node, meta| meta[node.name] = node.text end end
[ "def", "get_meta", "(", "doc", ")", "meta", "=", "doc", ".", "xpath", "(", "\"//meta/*\"", ")", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "node", ",", "meta", "|", "meta", "[", "node", ".", "name", "]", "=", "node", ".", "text", "end", "end" ]
Parses meta information returned by API, may include a status, status code and a message @param doc [Object] Nokogiri::XML::Document @return [Hash] Parsed hash
[ "Parses", "meta", "information", "returned", "by", "API", "may", "include", "a", "status", "status", "code", "and", "a", "message" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L28-L32
1,018
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.doc_to_hash
def doc_to_hash(doc, xpath = "/") h = Hash.from_xml(doc.xpath(xpath).to_xml) h end
ruby
def doc_to_hash(doc, xpath = "/") h = Hash.from_xml(doc.xpath(xpath).to_xml) h end
[ "def", "doc_to_hash", "(", "doc", ",", "xpath", "=", "\"/\"", ")", "h", "=", "Hash", ".", "from_xml", "(", "doc", ".", "xpath", "(", "xpath", ")", ".", "to_xml", ")", "h", "end" ]
Converts document to hash @param doc [Object] Nokogiri::XML::Document @param xpath [String] Document path to convert to hash @return [Hash] Hash that was produced from XML document
[ "Converts", "document", "to", "hash" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L39-L42
1,019
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.add_meta
def add_meta(doc, obj) meta = get_meta(doc) obj.define_singleton_method(:meta) { meta } && obj end
ruby
def add_meta(doc, obj) meta = get_meta(doc) obj.define_singleton_method(:meta) { meta } && obj end
[ "def", "add_meta", "(", "doc", ",", "obj", ")", "meta", "=", "get_meta", "(", "doc", ")", "obj", ".", "define_singleton_method", "(", ":meta", ")", "{", "meta", "}", "&&", "obj", "end" ]
Adds meta method to an object @param doc [Object] Nokogiri::XML::Document to take meta information from @param obj [#define_singleton_method] Object to add meta method to @return [#define_singleton_method] Object with meta method defined
[ "Adds", "meta", "method", "to", "an", "object" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L49-L52
1,020
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.parse_dav_response
def parse_dav_response(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } elsif doc.at_xpath("//status") { status: doc.xpath("//status").text } else { status: "ok" } end end
ruby
def parse_dav_response(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } elsif doc.at_xpath("//status") { status: doc.xpath("//status").text } else { status: "ok" } end end
[ "def", "parse_dav_response", "(", "doc", ")", "doc", ".", "remove_namespaces!", "if", "doc", ".", "at_xpath", "(", "\"//error\"", ")", "{", "exception", ":", "doc", ".", "xpath", "(", "\"//exception\"", ")", ".", "text", ",", "message", ":", "doc", ".", "xpath", "(", "\"//message\"", ")", ".", "text", "}", "elsif", "doc", ".", "at_xpath", "(", "\"//status\"", ")", "{", "status", ":", "doc", ".", "xpath", "(", "\"//status\"", ")", ".", "text", "}", "else", "{", "status", ":", "\"ok\"", "}", "end", "end" ]
Shows errors, or success message @param doc [Object] Nokogiri::XML::Document @return [Hash] State response
[ "Shows", "errors", "or", "success", "message" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L67-L83
1,021
dachinat/nextcloud
lib/nextcloud/helpers/nextcloud.rb
Nextcloud.Helpers.has_dav_errors
def has_dav_errors(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } else false end end
ruby
def has_dav_errors(doc) doc.remove_namespaces! if doc.at_xpath("//error") { exception: doc.xpath("//exception").text, message: doc.xpath("//message").text } else false end end
[ "def", "has_dav_errors", "(", "doc", ")", "doc", ".", "remove_namespaces!", "if", "doc", ".", "at_xpath", "(", "\"//error\"", ")", "{", "exception", ":", "doc", ".", "xpath", "(", "\"//exception\"", ")", ".", "text", ",", "message", ":", "doc", ".", "xpath", "(", "\"//message\"", ")", ".", "text", "}", "else", "false", "end", "end" ]
Shows error or returns false @param doc [Object] Nokogiri::XML::Document @return [Hash,Boolean] Returns error message if found, false otherwise
[ "Shows", "error", "or", "returns", "false" ]
717e5a0f5971fdd35210f256125234ce6b92006a
https://github.com/dachinat/nextcloud/blob/717e5a0f5971fdd35210f256125234ce6b92006a/lib/nextcloud/helpers/nextcloud.rb#L89-L99
1,022
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.handle_field
def handle_field(field) case field when Symbol then return return_symbol_value(field) when Array then return @ldap_object.try(field.first).try(:collect, &field.last) end end
ruby
def handle_field(field) case field when Symbol then return return_symbol_value(field) when Array then return @ldap_object.try(field.first).try(:collect, &field.last) end end
[ "def", "handle_field", "(", "field", ")", "case", "field", "when", "Symbol", "then", "return", "return_symbol_value", "(", "field", ")", "when", "Array", "then", "return", "@ldap_object", ".", "try", "(", "field", ".", "first", ")", ".", "try", "(", ":collect", ",", "field", ".", "last", ")", "end", "end" ]
Handle the output for the given field
[ "Handle", "the", "output", "for", "the", "given", "field" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L93-L98
1,023
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.cn_groups_nested
def cn_groups_nested @cn_groups_nested = cn_groups cn_groups.each do |group| ado = Adauth::AdObjects::Group.where('name', group).first if ado groups = convert_to_objects ado.cn_groups groups.each do |g| @cn_groups_nested.push g if !(@cn_groups_nested.include?(g)) end end end return @cn_groups_nested end
ruby
def cn_groups_nested @cn_groups_nested = cn_groups cn_groups.each do |group| ado = Adauth::AdObjects::Group.where('name', group).first if ado groups = convert_to_objects ado.cn_groups groups.each do |g| @cn_groups_nested.push g if !(@cn_groups_nested.include?(g)) end end end return @cn_groups_nested end
[ "def", "cn_groups_nested", "@cn_groups_nested", "=", "cn_groups", "cn_groups", ".", "each", "do", "|", "group", "|", "ado", "=", "Adauth", "::", "AdObjects", "::", "Group", ".", "where", "(", "'name'", ",", "group", ")", ".", "first", "if", "ado", "groups", "=", "convert_to_objects", "ado", ".", "cn_groups", "groups", ".", "each", "do", "|", "g", "|", "@cn_groups_nested", ".", "push", "g", "if", "!", "(", "@cn_groups_nested", ".", "include?", "(", "g", ")", ")", "end", "end", "end", "return", "@cn_groups_nested", "end" ]
The same as cn_groups, but with the parent groups included
[ "The", "same", "as", "cn_groups", "but", "with", "the", "parent", "groups", "included" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L109-L121
1,024
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.ous
def ous unless @ous @ous = [] @ldap_object.dn.split(/,/).each do |entry| @ous.push Adauth::AdObjects::OU.where('name', entry.gsub(/OU=/, '')).first if entry =~ /OU=/ end end @ous end
ruby
def ous unless @ous @ous = [] @ldap_object.dn.split(/,/).each do |entry| @ous.push Adauth::AdObjects::OU.where('name', entry.gsub(/OU=/, '')).first if entry =~ /OU=/ end end @ous end
[ "def", "ous", "unless", "@ous", "@ous", "=", "[", "]", "@ldap_object", ".", "dn", ".", "split", "(", "/", "/", ")", ".", "each", "do", "|", "entry", "|", "@ous", ".", "push", "Adauth", "::", "AdObjects", "::", "OU", ".", "where", "(", "'name'", ",", "entry", ".", "gsub", "(", "/", "/", ",", "''", ")", ")", ".", "first", "if", "entry", "=~", "/", "/", "end", "end", "@ous", "end" ]
Returns all the ous the object is in
[ "Returns", "all", "the", "ous", "the", "object", "is", "in" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L124-L132
1,025
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.modify
def modify(operations) Adauth.logger.info(self.class.inspect) { "Attempting modify operation" } unless Adauth.connection.modify :dn => @ldap_object.dn, :operations => operations Adauth.logger.fatal(self.class.inspect) { "Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}" } raise 'Modify Operation Failed (see log for details)' end end
ruby
def modify(operations) Adauth.logger.info(self.class.inspect) { "Attempting modify operation" } unless Adauth.connection.modify :dn => @ldap_object.dn, :operations => operations Adauth.logger.fatal(self.class.inspect) { "Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}" } raise 'Modify Operation Failed (see log for details)' end end
[ "def", "modify", "(", "operations", ")", "Adauth", ".", "logger", ".", "info", "(", "self", ".", "class", ".", "inspect", ")", "{", "\"Attempting modify operation\"", "}", "unless", "Adauth", ".", "connection", ".", "modify", ":dn", "=>", "@ldap_object", ".", "dn", ",", ":operations", "=>", "operations", "Adauth", ".", "logger", ".", "fatal", "(", "self", ".", "class", ".", "inspect", ")", "{", "\"Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}\"", "}", "raise", "'Modify Operation Failed (see log for details)'", "end", "end" ]
Runs a modify action on the current object, takes an aray of operations
[ "Runs", "a", "modify", "action", "on", "the", "current", "object", "takes", "an", "aray", "of", "operations" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L146-L152
1,026
Arcath/Adauth
lib/adauth/ad_object.rb
Adauth.AdObject.members
def members unless @members @members = [] [Adauth::AdObjects::Computer, Adauth::AdObjects::OU, Adauth::AdObjects::User, Adauth::AdObjects::Group].each do |object| object.all.each do |entity| @members.push entity if entity.is_a_member?(self) end end end @members end
ruby
def members unless @members @members = [] [Adauth::AdObjects::Computer, Adauth::AdObjects::OU, Adauth::AdObjects::User, Adauth::AdObjects::Group].each do |object| object.all.each do |entity| @members.push entity if entity.is_a_member?(self) end end end @members end
[ "def", "members", "unless", "@members", "@members", "=", "[", "]", "[", "Adauth", "::", "AdObjects", "::", "Computer", ",", "Adauth", "::", "AdObjects", "::", "OU", ",", "Adauth", "::", "AdObjects", "::", "User", ",", "Adauth", "::", "AdObjects", "::", "Group", "]", ".", "each", "do", "|", "object", "|", "object", ".", "all", ".", "each", "do", "|", "entity", "|", "@members", ".", "push", "entity", "if", "entity", ".", "is_a_member?", "(", "self", ")", "end", "end", "end", "@members", "end" ]
Returns an array of member objects for this object
[ "Returns", "an", "array", "of", "member", "objects", "for", "this", "object" ]
5017ceded89d8927fd3d772c9046395706b39570
https://github.com/Arcath/Adauth/blob/5017ceded89d8927fd3d772c9046395706b39570/lib/adauth/ad_object.rb#L155-L165
1,027
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_and_collect_multiple_changes
def run_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, false, directory, *flags, &block) end
ruby
def run_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, false, directory, *flags, &block) end
[ "def", "run_and_collect_multiple_changes", "(", "monitor", ",", "times", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "watch_and_run", "(", "monitor", ",", "times", ",", "false", ",", "directory", ",", "flags", ",", "block", ")", "end" ]
Runs the monitor and collects changes for the specified amount of times on the given directory. It stops the monitor afterwards. @yield
[ "Runs", "the", "monitor", "and", "collects", "changes", "for", "the", "specified", "amount", "of", "times", "on", "the", "given", "directory", ".", "It", "stops", "the", "monitor", "afterwards", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L12-L14
1,028
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run
def run(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, false, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
ruby
def run(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, false, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
[ "def", "run", "(", "monitor", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "result", "=", "watch_and_run", "(", "monitor", ",", "1", ",", "false", ",", "directory", ",", "flags", ",", "block", ")", "result", ".", "changes", "[", "0", "]", ".", "directory", "=", "result", ".", "directory", "result", ".", "changes", "[", "0", "]", "end" ]
Helper method for running the monitor one time. @yield
[ "Helper", "method", "for", "running", "the", "monitor", "one", "time", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L20-L24
1,029
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_with_fixture
def run_with_fixture(monitor, *flags, &block) fixture do |f| run(monitor, f, *flags, &block) end end
ruby
def run_with_fixture(monitor, *flags, &block) fixture do |f| run(monitor, f, *flags, &block) end end
[ "def", "run_with_fixture", "(", "monitor", ",", "*", "flags", ",", "&", "block", ")", "fixture", "do", "|", "f", "|", "run", "(", "monitor", ",", "f", ",", "flags", ",", "block", ")", "end", "end" ]
Helper method for using the run method with the fixture helper. @yield
[ "Helper", "method", "for", "using", "the", "run", "method", "with", "the", "fixture", "helper", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L30-L34
1,030
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_recursively_and_collect_multiple_changes
def run_recursively_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, true, directory, *flags, &block) end
ruby
def run_recursively_and_collect_multiple_changes(monitor, times, directory, *flags, &block) watch_and_run(monitor, times, true, directory, *flags, &block) end
[ "def", "run_recursively_and_collect_multiple_changes", "(", "monitor", ",", "times", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "watch_and_run", "(", "monitor", ",", "times", ",", "true", ",", "directory", ",", "flags", ",", "block", ")", "end" ]
Runs the monitor recursively and collects changes for the specified amount of times on the given directory. It stops the monitor afterwards. @yield
[ "Runs", "the", "monitor", "recursively", "and", "collects", "changes", "for", "the", "specified", "amount", "of", "times", "on", "the", "given", "directory", ".", "It", "stops", "the", "monitor", "afterwards", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L41-L43
1,031
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_recursively
def run_recursively(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, true, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
ruby
def run_recursively(monitor, directory, *flags, &block) result = watch_and_run(monitor, 1, true, directory, *flags, &block) result.changes[0].directory = result.directory result.changes[0] end
[ "def", "run_recursively", "(", "monitor", ",", "directory", ",", "*", "flags", ",", "&", "block", ")", "result", "=", "watch_and_run", "(", "monitor", ",", "1", ",", "true", ",", "directory", ",", "flags", ",", "block", ")", "result", ".", "changes", "[", "0", "]", ".", "directory", "=", "result", ".", "directory", "result", ".", "changes", "[", "0", "]", "end" ]
Helper method for running the monitor recursively one time. @yield
[ "Helper", "method", "for", "running", "the", "monitor", "recursively", "one", "time", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L49-L53
1,032
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.run_recursively_with_fixture
def run_recursively_with_fixture(monitor, *flags, &block) fixture do |f| run_recursively(monitor, f, *flags, &block) end end
ruby
def run_recursively_with_fixture(monitor, *flags, &block) fixture do |f| run_recursively(monitor, f, *flags, &block) end end
[ "def", "run_recursively_with_fixture", "(", "monitor", ",", "*", "flags", ",", "&", "block", ")", "fixture", "do", "|", "f", "|", "run_recursively", "(", "monitor", ",", "f", ",", "flags", ",", "block", ")", "end", "end" ]
Helper method for using the run method recursively with the fixture helper. @yield
[ "Helper", "method", "for", "using", "the", "run", "method", "recursively", "with", "the", "fixture", "helper", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L59-L63
1,033
Maher4Ever/wdm
spec/support/monitor_helper.rb
WDM.SpecSupport.watch_and_run
def watch_and_run(monitor, times, recursively, directory, *flags) result = OpenStruct.new(directory: directory, changes: []) i = 0 result.changes[i] = OpenStruct.new(called: false) can_return = false callback = Proc.new do |change| next if can_return result.changes[i].called = true; result.changes[i].change = change i += 1 if i < times result.changes[i] = OpenStruct.new(called: false) else can_return = true end end if recursively monitor.watch_recursively(directory, *flags, &callback) else monitor.watch(directory, *flags, &callback) end thread = Thread.new(monitor) { |m| m.run! } sleep(0.2) # give time for the monitor to bootup yield # So much boilerplate code to get here :S sleep(0.2) # allow the monitor to run the callbacks # Nothing can change after the callback if there is only one of them, # so never wait for one callback if times > 1 until can_return sleep(0.1) end end return result ensure monitor.stop thread.join if thread end
ruby
def watch_and_run(monitor, times, recursively, directory, *flags) result = OpenStruct.new(directory: directory, changes: []) i = 0 result.changes[i] = OpenStruct.new(called: false) can_return = false callback = Proc.new do |change| next if can_return result.changes[i].called = true; result.changes[i].change = change i += 1 if i < times result.changes[i] = OpenStruct.new(called: false) else can_return = true end end if recursively monitor.watch_recursively(directory, *flags, &callback) else monitor.watch(directory, *flags, &callback) end thread = Thread.new(monitor) { |m| m.run! } sleep(0.2) # give time for the monitor to bootup yield # So much boilerplate code to get here :S sleep(0.2) # allow the monitor to run the callbacks # Nothing can change after the callback if there is only one of them, # so never wait for one callback if times > 1 until can_return sleep(0.1) end end return result ensure monitor.stop thread.join if thread end
[ "def", "watch_and_run", "(", "monitor", ",", "times", ",", "recursively", ",", "directory", ",", "*", "flags", ")", "result", "=", "OpenStruct", ".", "new", "(", "directory", ":", "directory", ",", "changes", ":", "[", "]", ")", "i", "=", "0", "result", ".", "changes", "[", "i", "]", "=", "OpenStruct", ".", "new", "(", "called", ":", "false", ")", "can_return", "=", "false", "callback", "=", "Proc", ".", "new", "do", "|", "change", "|", "next", "if", "can_return", "result", ".", "changes", "[", "i", "]", ".", "called", "=", "true", ";", "result", ".", "changes", "[", "i", "]", ".", "change", "=", "change", "i", "+=", "1", "if", "i", "<", "times", "result", ".", "changes", "[", "i", "]", "=", "OpenStruct", ".", "new", "(", "called", ":", "false", ")", "else", "can_return", "=", "true", "end", "end", "if", "recursively", "monitor", ".", "watch_recursively", "(", "directory", ",", "flags", ",", "callback", ")", "else", "monitor", ".", "watch", "(", "directory", ",", "flags", ",", "callback", ")", "end", "thread", "=", "Thread", ".", "new", "(", "monitor", ")", "{", "|", "m", "|", "m", ".", "run!", "}", "sleep", "(", "0.2", ")", "# give time for the monitor to bootup", "yield", "# So much boilerplate code to get here :S", "sleep", "(", "0.2", ")", "# allow the monitor to run the callbacks", "# Nothing can change after the callback if there is only one of them,", "# so never wait for one callback", "if", "times", ">", "1", "until", "can_return", "sleep", "(", "0.1", ")", "end", "end", "return", "result", "ensure", "monitor", ".", "stop", "thread", ".", "join", "if", "thread", "end" ]
Very customizable method to watch directories and then run the monitor @yield
[ "Very", "customizable", "method", "to", "watch", "directories", "and", "then", "run", "the", "monitor" ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/monitor_helper.rb#L71-L116
1,034
Maher4Ever/wdm
spec/support/fixture_helper.rb
WDM.SpecSupport.fixture
def fixture pwd = FileUtils.pwd path = File.expand_path(File.join(pwd, "spec/.fixtures/#{rand(99999)}")) FileUtils.mkdir_p(path) FileUtils.cd(path) yield(path) ensure FileUtils.cd pwd FileUtils.rm_rf(path) if File.exists?(path) end
ruby
def fixture pwd = FileUtils.pwd path = File.expand_path(File.join(pwd, "spec/.fixtures/#{rand(99999)}")) FileUtils.mkdir_p(path) FileUtils.cd(path) yield(path) ensure FileUtils.cd pwd FileUtils.rm_rf(path) if File.exists?(path) end
[ "def", "fixture", "pwd", "=", "FileUtils", ".", "pwd", "path", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "pwd", ",", "\"spec/.fixtures/#{rand(99999)}\"", ")", ")", "FileUtils", ".", "mkdir_p", "(", "path", ")", "FileUtils", ".", "cd", "(", "path", ")", "yield", "(", "path", ")", "ensure", "FileUtils", ".", "cd", "pwd", "FileUtils", ".", "rm_rf", "(", "path", ")", "if", "File", ".", "exists?", "(", "path", ")", "end" ]
Prepares the temporary fixture directory and cleans it afterwards. @yield [path] an empty fixture directory @yieldparam [String] path the path to the fixture directory
[ "Prepares", "the", "temporary", "fixture", "directory", "and", "cleans", "it", "afterwards", "." ]
41aaa6d7bb228e0721a36681b789295467494fb6
https://github.com/Maher4Ever/wdm/blob/41aaa6d7bb228e0721a36681b789295467494fb6/spec/support/fixture_helper.rb#L13-L25
1,035
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.to_term
def to_term(color_model = 256) term = case color_model when 256 then PryTheme::RGB::TABLE.index(@value) when 16 then PryTheme::RGB::SYSTEM.index(@value) when 8 then PryTheme::RGB::LINUX.index(@value) else raise ArgumentError, "invalid value for PryTheme::HEX#to_term(): #{ @value }" end term = find_among_term_colors(term, color_model) if term.nil? PryTheme::TERM.new(term, color_model) end
ruby
def to_term(color_model = 256) term = case color_model when 256 then PryTheme::RGB::TABLE.index(@value) when 16 then PryTheme::RGB::SYSTEM.index(@value) when 8 then PryTheme::RGB::LINUX.index(@value) else raise ArgumentError, "invalid value for PryTheme::HEX#to_term(): #{ @value }" end term = find_among_term_colors(term, color_model) if term.nil? PryTheme::TERM.new(term, color_model) end
[ "def", "to_term", "(", "color_model", "=", "256", ")", "term", "=", "case", "color_model", "when", "256", "then", "PryTheme", "::", "RGB", "::", "TABLE", ".", "index", "(", "@value", ")", "when", "16", "then", "PryTheme", "::", "RGB", "::", "SYSTEM", ".", "index", "(", "@value", ")", "when", "8", "then", "PryTheme", "::", "RGB", "::", "LINUX", ".", "index", "(", "@value", ")", "else", "raise", "ArgumentError", ",", "\"invalid value for PryTheme::HEX#to_term(): #{ @value }\"", "end", "term", "=", "find_among_term_colors", "(", "term", ",", "color_model", ")", "if", "term", ".", "nil?", "PryTheme", "::", "TERM", ".", "new", "(", "term", ",", "color_model", ")", "end" ]
Converts the RGB to a terminal colour equivalent. @note Accepts the following numbers: 256, 16, 8. @param [Integer] color_model @raise [ArgumentError] if +color_model+ parameter is incorrect @return [TERM] a TERM representation of the RGB
[ "Converts", "the", "RGB", "to", "a", "terminal", "colour", "equivalent", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L128-L138
1,036
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.validate_array
def validate_array(ary) correct_size = ary.size.equal?(3) correct_vals = ary.all?{ |val| val.is_a?(Integer) && val.between?(0, 255) } return true if correct_size && correct_vals raise ArgumentError, %|invalid value for PryTheme::RGB#validate_array(): "#{ ary }"| end
ruby
def validate_array(ary) correct_size = ary.size.equal?(3) correct_vals = ary.all?{ |val| val.is_a?(Integer) && val.between?(0, 255) } return true if correct_size && correct_vals raise ArgumentError, %|invalid value for PryTheme::RGB#validate_array(): "#{ ary }"| end
[ "def", "validate_array", "(", "ary", ")", "correct_size", "=", "ary", ".", "size", ".", "equal?", "(", "3", ")", "correct_vals", "=", "ary", ".", "all?", "{", "|", "val", "|", "val", ".", "is_a?", "(", "Integer", ")", "&&", "val", ".", "between?", "(", "0", ",", "255", ")", "}", "return", "true", "if", "correct_size", "&&", "correct_vals", "raise", "ArgumentError", ",", "%|invalid value for PryTheme::RGB#validate_array(): \"#{ ary }\"|", "end" ]
Checks whether the +ary+ has correct number of elements and these elements are valid RGB numbers. @param [Array<Integer>] ary @raise [ArgumentError] if the +ary+ is invalid @return [void]
[ "Checks", "whether", "the", "+", "ary", "+", "has", "correct", "number", "of", "elements", "and", "these", "elements", "are", "valid", "RGB", "numbers", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L175-L181
1,037
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.nearest_term_256
def nearest_term_256(byte) for i in 0..4 lower, upper = BYTEPOINTS_256[i], BYTEPOINTS_256[i + 1] next unless byte.between?(lower, upper) distance_from_lower = (lower - byte).abs distance_from_upper = (upper - byte).abs closest = distance_from_lower < distance_from_upper ? lower : upper end closest end
ruby
def nearest_term_256(byte) for i in 0..4 lower, upper = BYTEPOINTS_256[i], BYTEPOINTS_256[i + 1] next unless byte.between?(lower, upper) distance_from_lower = (lower - byte).abs distance_from_upper = (upper - byte).abs closest = distance_from_lower < distance_from_upper ? lower : upper end closest end
[ "def", "nearest_term_256", "(", "byte", ")", "for", "i", "in", "0", "..", "4", "lower", ",", "upper", "=", "BYTEPOINTS_256", "[", "i", "]", ",", "BYTEPOINTS_256", "[", "i", "+", "1", "]", "next", "unless", "byte", ".", "between?", "(", "lower", ",", "upper", ")", "distance_from_lower", "=", "(", "lower", "-", "byte", ")", ".", "abs", "distance_from_upper", "=", "(", "upper", "-", "byte", ")", ".", "abs", "closest", "=", "distance_from_lower", "<", "distance_from_upper", "?", "lower", ":", "upper", "end", "closest", "end" ]
Approximates the given +byte+ to a terminal colour value within range of 256 colours. @param [Integer] byte a number between 0 and 255 @return [Integer] approximated number
[ "Approximates", "the", "given", "+", "byte", "+", "to", "a", "terminal", "colour", "value", "within", "range", "of", "256", "colours", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L188-L198
1,038
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.find_among_term_colors
def find_among_term_colors(term, color_model) rgb = @value.map { |byte| nearest_term_256(byte) } term = PryTheme::RGB::TABLE.index(rgb) approximate(term, color_model) end
ruby
def find_among_term_colors(term, color_model) rgb = @value.map { |byte| nearest_term_256(byte) } term = PryTheme::RGB::TABLE.index(rgb) approximate(term, color_model) end
[ "def", "find_among_term_colors", "(", "term", ",", "color_model", ")", "rgb", "=", "@value", ".", "map", "{", "|", "byte", "|", "nearest_term_256", "(", "byte", ")", "}", "term", "=", "PryTheme", "::", "RGB", "::", "TABLE", ".", "index", "(", "rgb", ")", "approximate", "(", "term", ",", "color_model", ")", "end" ]
Finds an approximated +term+ colour among the colour numbers within the given +color_model+. @param [Integer] term a colour to be approximated @param [Integer] color_model possible values {#to_term} @return [Integer] approximated number, which fits in range of color_model
[ "Finds", "an", "approximated", "+", "term", "+", "colour", "among", "the", "colour", "numbers", "within", "the", "given", "+", "color_model", "+", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L222-L226
1,039
kyrylo/pry-theme
lib/pry-theme/rgb.rb
PryTheme.RGB.approximate
def approximate(term, color_model) needs_approximation = (term > color_model - 1) if needs_approximation case color_model when 16 then nearest_term_16(term) when 8 then nearest_term_8(term) end else term end end
ruby
def approximate(term, color_model) needs_approximation = (term > color_model - 1) if needs_approximation case color_model when 16 then nearest_term_16(term) when 8 then nearest_term_8(term) end else term end end
[ "def", "approximate", "(", "term", ",", "color_model", ")", "needs_approximation", "=", "(", "term", ">", "color_model", "-", "1", ")", "if", "needs_approximation", "case", "color_model", "when", "16", "then", "nearest_term_16", "(", "term", ")", "when", "8", "then", "nearest_term_8", "(", "term", ")", "end", "else", "term", "end", "end" ]
Approximates +term+ in correspondence with +color_model+ @see #nearest_term_16 @see #nearest_term_8 @param [Integer] term a colour to be approximated @param [Integer] color_model possible values {#to_term} @return [Integer] approximated number, which fits in range of color_model
[ "Approximates", "+", "term", "+", "in", "correspondence", "with", "+", "color_model", "+" ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/rgb.rb#L235-L246
1,040
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.endpoint_parameter
def endpoint_parameter(name, description, how_to_pass, required, type, params = {}) parameters = settings.swagger_current_endpoint_parameters check_if_not_duplicate(name, parameters, 'Parameter') parameters[name] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointParameter.new( name, description, how_to_pass, required, type, params, settings.swagger_types.types_names) end
ruby
def endpoint_parameter(name, description, how_to_pass, required, type, params = {}) parameters = settings.swagger_current_endpoint_parameters check_if_not_duplicate(name, parameters, 'Parameter') parameters[name] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointParameter.new( name, description, how_to_pass, required, type, params, settings.swagger_types.types_names) end
[ "def", "endpoint_parameter", "(", "name", ",", "description", ",", "how_to_pass", ",", "required", ",", "type", ",", "params", "=", "{", "}", ")", "parameters", "=", "settings", ".", "swagger_current_endpoint_parameters", "check_if_not_duplicate", "(", "name", ",", "parameters", ",", "'Parameter'", ")", "parameters", "[", "name", "]", "=", "Sinatra", "::", "SwaggerExposer", "::", "Configuration", "::", "SwaggerEndpointParameter", ".", "new", "(", "name", ",", "description", ",", "how_to_pass", ",", "required", ",", "type", ",", "params", ",", "settings", ".", "swagger_types", ".", "types_names", ")", "end" ]
Define parameter for the endpoint
[ "Define", "parameter", "for", "the", "endpoint" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L95-L106
1,041
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.endpoint
def endpoint(params) params.each_pair do |param_name, param_value| case param_name when :summary endpoint_summary param_value when :description endpoint_description param_value when :tags endpoint_tags *param_value when :produces endpoint_produces *param_value when :path endpoint_path param_value when :parameters param_value.each do |param, args_param| endpoint_parameter param, *args_param end when :responses param_value.each do |code, args_response| endpoint_response code, *args_response end else raise SwaggerInvalidException.new("Invalid endpoint parameter [#{param_name}]") end end end
ruby
def endpoint(params) params.each_pair do |param_name, param_value| case param_name when :summary endpoint_summary param_value when :description endpoint_description param_value when :tags endpoint_tags *param_value when :produces endpoint_produces *param_value when :path endpoint_path param_value when :parameters param_value.each do |param, args_param| endpoint_parameter param, *args_param end when :responses param_value.each do |code, args_response| endpoint_response code, *args_response end else raise SwaggerInvalidException.new("Invalid endpoint parameter [#{param_name}]") end end end
[ "def", "endpoint", "(", "params", ")", "params", ".", "each_pair", "do", "|", "param_name", ",", "param_value", "|", "case", "param_name", "when", ":summary", "endpoint_summary", "param_value", "when", ":description", "endpoint_description", "param_value", "when", ":tags", "endpoint_tags", "param_value", "when", ":produces", "endpoint_produces", "param_value", "when", ":path", "endpoint_path", "param_value", "when", ":parameters", "param_value", ".", "each", "do", "|", "param", ",", "args_param", "|", "endpoint_parameter", "param", ",", "args_param", "end", "when", ":responses", "param_value", ".", "each", "do", "|", "code", ",", "args_response", "|", "endpoint_response", "code", ",", "args_response", "end", "else", "raise", "SwaggerInvalidException", ".", "new", "(", "\"Invalid endpoint parameter [#{param_name}]\"", ")", "end", "end", "end" ]
Define fluent endpoint dispatcher @param params [Hash] the parameters
[ "Define", "fluent", "endpoint", "dispatcher" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L110-L135
1,042
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.response_header
def response_header(name, type, description) settings.swagger_response_headers.add_response_header(name, type, description) end
ruby
def response_header(name, type, description) settings.swagger_response_headers.add_response_header(name, type, description) end
[ "def", "response_header", "(", "name", ",", "type", ",", "description", ")", "settings", ".", "swagger_response_headers", ".", "add_response_header", "(", "name", ",", "type", ",", "description", ")", "end" ]
Declare a response header
[ "Declare", "a", "response", "header" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L148-L150
1,043
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.endpoint_response
def endpoint_response(code, type = nil, description = nil, headers = []) responses = settings.swagger_current_endpoint_responses check_if_not_duplicate(code, responses, 'Response') responses[code] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointResponse.new( type, description, settings.swagger_types.types_names, headers, settings.swagger_response_headers ) end
ruby
def endpoint_response(code, type = nil, description = nil, headers = []) responses = settings.swagger_current_endpoint_responses check_if_not_duplicate(code, responses, 'Response') responses[code] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointResponse.new( type, description, settings.swagger_types.types_names, headers, settings.swagger_response_headers ) end
[ "def", "endpoint_response", "(", "code", ",", "type", "=", "nil", ",", "description", "=", "nil", ",", "headers", "=", "[", "]", ")", "responses", "=", "settings", ".", "swagger_current_endpoint_responses", "check_if_not_duplicate", "(", "code", ",", "responses", ",", "'Response'", ")", "responses", "[", "code", "]", "=", "Sinatra", "::", "SwaggerExposer", "::", "Configuration", "::", "SwaggerEndpointResponse", ".", "new", "(", "type", ",", "description", ",", "settings", ".", "swagger_types", ".", "types_names", ",", "headers", ",", "settings", ".", "swagger_response_headers", ")", "end" ]
Declare a response @param code [Integer] the response code @param type the type @param description [String] the description @param headers [Array<String>] the headers names
[ "Declare", "a", "response" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L157-L167
1,044
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.route
def route(verb, path, options = {}, &block) no_swagger = options[:no_swagger] options.delete(:no_swagger) if (verb == 'HEAD') || no_swagger super(verb, path, options, &block) else request_processor = create_request_processor(verb.downcase, path, options) super(verb, path, options) do |*params| response = catch(:halt) do request_processor.run(self, params, &block) end if settings.result_validation begin # Inspired from Sinatra#invoke if (Fixnum === response) or (String === response) response = [response] end if (Array === response) and (Fixnum === response.first) response_for_validation = response.dup response_status = response_for_validation.shift response_body = response_for_validation.pop response_headers = (response_for_validation.pop || {}).merge(self.response.header) response_content_type = response_headers['Content-Type'] request_processor.validate_response(response_body, response_content_type, response_status) elsif response.respond_to? :each request_processor.validate_response(response.first.dup, self.response.header['Content-Type'], 200) end rescue Sinatra::SwaggerExposer::SwaggerInvalidException => e content_type :json throw :halt, [400, {:code => 400, :message => e.message}.to_json] end end throw :halt, response end end end
ruby
def route(verb, path, options = {}, &block) no_swagger = options[:no_swagger] options.delete(:no_swagger) if (verb == 'HEAD') || no_swagger super(verb, path, options, &block) else request_processor = create_request_processor(verb.downcase, path, options) super(verb, path, options) do |*params| response = catch(:halt) do request_processor.run(self, params, &block) end if settings.result_validation begin # Inspired from Sinatra#invoke if (Fixnum === response) or (String === response) response = [response] end if (Array === response) and (Fixnum === response.first) response_for_validation = response.dup response_status = response_for_validation.shift response_body = response_for_validation.pop response_headers = (response_for_validation.pop || {}).merge(self.response.header) response_content_type = response_headers['Content-Type'] request_processor.validate_response(response_body, response_content_type, response_status) elsif response.respond_to? :each request_processor.validate_response(response.first.dup, self.response.header['Content-Type'], 200) end rescue Sinatra::SwaggerExposer::SwaggerInvalidException => e content_type :json throw :halt, [400, {:code => 400, :message => e.message}.to_json] end end throw :halt, response end end end
[ "def", "route", "(", "verb", ",", "path", ",", "options", "=", "{", "}", ",", "&", "block", ")", "no_swagger", "=", "options", "[", ":no_swagger", "]", "options", ".", "delete", "(", ":no_swagger", ")", "if", "(", "verb", "==", "'HEAD'", ")", "||", "no_swagger", "super", "(", "verb", ",", "path", ",", "options", ",", "block", ")", "else", "request_processor", "=", "create_request_processor", "(", "verb", ".", "downcase", ",", "path", ",", "options", ")", "super", "(", "verb", ",", "path", ",", "options", ")", "do", "|", "*", "params", "|", "response", "=", "catch", "(", ":halt", ")", "do", "request_processor", ".", "run", "(", "self", ",", "params", ",", "block", ")", "end", "if", "settings", ".", "result_validation", "begin", "# Inspired from Sinatra#invoke", "if", "(", "Fixnum", "===", "response", ")", "or", "(", "String", "===", "response", ")", "response", "=", "[", "response", "]", "end", "if", "(", "Array", "===", "response", ")", "and", "(", "Fixnum", "===", "response", ".", "first", ")", "response_for_validation", "=", "response", ".", "dup", "response_status", "=", "response_for_validation", ".", "shift", "response_body", "=", "response_for_validation", ".", "pop", "response_headers", "=", "(", "response_for_validation", ".", "pop", "||", "{", "}", ")", ".", "merge", "(", "self", ".", "response", ".", "header", ")", "response_content_type", "=", "response_headers", "[", "'Content-Type'", "]", "request_processor", ".", "validate_response", "(", "response_body", ",", "response_content_type", ",", "response_status", ")", "elsif", "response", ".", "respond_to?", ":each", "request_processor", ".", "validate_response", "(", "response", ".", "first", ".", "dup", ",", "self", ".", "response", ".", "header", "[", "'Content-Type'", "]", ",", "200", ")", "end", "rescue", "Sinatra", "::", "SwaggerExposer", "::", "SwaggerInvalidException", "=>", "e", "content_type", ":json", "throw", ":halt", ",", "[", "400", ",", "{", ":code", "=>", "400", ",", ":message", "=>", "e", ".", "message", "}", ".", "to_json", "]", "end", "end", "throw", ":halt", ",", "response", "end", "end", "end" ]
Override Sinatra route method
[ "Override", "Sinatra", "route", "method" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L170-L205
1,045
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.create_request_processor
def create_request_processor(type, path, opts) current_endpoint_info = settings.swagger_current_endpoint_info current_endpoint_parameters = settings.swagger_current_endpoint_parameters current_endpoint_responses = settings.swagger_current_endpoint_responses endpoint = Sinatra::SwaggerExposer::Configuration::SwaggerEndpoint.new( type, path, current_endpoint_parameters.values, current_endpoint_responses.clone, current_endpoint_info[:summary], current_endpoint_info[:description], current_endpoint_info[:tags], current_endpoint_info[:path], current_endpoint_info[:produces]) settings.swagger_endpoints << endpoint current_endpoint_info.clear current_endpoint_parameters.clear current_endpoint_responses.clear settings.swagger_processor_creator.create_request_processor(endpoint) end
ruby
def create_request_processor(type, path, opts) current_endpoint_info = settings.swagger_current_endpoint_info current_endpoint_parameters = settings.swagger_current_endpoint_parameters current_endpoint_responses = settings.swagger_current_endpoint_responses endpoint = Sinatra::SwaggerExposer::Configuration::SwaggerEndpoint.new( type, path, current_endpoint_parameters.values, current_endpoint_responses.clone, current_endpoint_info[:summary], current_endpoint_info[:description], current_endpoint_info[:tags], current_endpoint_info[:path], current_endpoint_info[:produces]) settings.swagger_endpoints << endpoint current_endpoint_info.clear current_endpoint_parameters.clear current_endpoint_responses.clear settings.swagger_processor_creator.create_request_processor(endpoint) end
[ "def", "create_request_processor", "(", "type", ",", "path", ",", "opts", ")", "current_endpoint_info", "=", "settings", ".", "swagger_current_endpoint_info", "current_endpoint_parameters", "=", "settings", ".", "swagger_current_endpoint_parameters", "current_endpoint_responses", "=", "settings", ".", "swagger_current_endpoint_responses", "endpoint", "=", "Sinatra", "::", "SwaggerExposer", "::", "Configuration", "::", "SwaggerEndpoint", ".", "new", "(", "type", ",", "path", ",", "current_endpoint_parameters", ".", "values", ",", "current_endpoint_responses", ".", "clone", ",", "current_endpoint_info", "[", ":summary", "]", ",", "current_endpoint_info", "[", ":description", "]", ",", "current_endpoint_info", "[", ":tags", "]", ",", "current_endpoint_info", "[", ":path", "]", ",", "current_endpoint_info", "[", ":produces", "]", ")", "settings", ".", "swagger_endpoints", "<<", "endpoint", "current_endpoint_info", ".", "clear", "current_endpoint_parameters", ".", "clear", "current_endpoint_responses", ".", "clear", "settings", ".", "swagger_processor_creator", ".", "create_request_processor", "(", "endpoint", ")", "end" ]
Call for each endpoint declaration @return [Sinatra::SwaggerExposer::Processing::SwaggerRequestProcessor]
[ "Call", "for", "each", "endpoint", "declaration" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L211-L230
1,046
archiloque/sinatra-swagger-exposer
lib/sinatra/swagger-exposer/swagger-exposer.rb
Sinatra.SwaggerExposer.check_if_not_duplicate
def check_if_not_duplicate(key, values, name) if values.key? key raise SwaggerInvalidException.new("#{name} already exist for #{key} with value [#{values[key]}]") end end
ruby
def check_if_not_duplicate(key, values, name) if values.key? key raise SwaggerInvalidException.new("#{name} already exist for #{key} with value [#{values[key]}]") end end
[ "def", "check_if_not_duplicate", "(", "key", ",", "values", ",", "name", ")", "if", "values", ".", "key?", "key", "raise", "SwaggerInvalidException", ".", "new", "(", "\"#{name} already exist for #{key} with value [#{values[key]}]\"", ")", "end", "end" ]
Check if a value does not exist in a hash and throw an Exception @param key the key to validate @param values [Hash] the existing keys @param name [String] the valud name for the error message
[ "Check", "if", "a", "value", "does", "not", "exist", "in", "a", "hash", "and", "throw", "an", "Exception" ]
375fcb432e901815562d94b64208753faaed7cdb
https://github.com/archiloque/sinatra-swagger-exposer/blob/375fcb432e901815562d94b64208753faaed7cdb/lib/sinatra/swagger-exposer/swagger-exposer.rb#L250-L254
1,047
kyrylo/pry-theme
lib/pry-theme/hex.rb
PryTheme.HEX.validate_value
def validate_value(value) unless value.is_a?(String) raise TypeError, "can't convert #{ value.class } into PryTheme::HEX" end if value !~ PryTheme::HEX::PATTERN fail ArgumentError, %|invalid value for PryTheme::HEX#new(): "#{value}"| end true end
ruby
def validate_value(value) unless value.is_a?(String) raise TypeError, "can't convert #{ value.class } into PryTheme::HEX" end if value !~ PryTheme::HEX::PATTERN fail ArgumentError, %|invalid value for PryTheme::HEX#new(): "#{value}"| end true end
[ "def", "validate_value", "(", "value", ")", "unless", "value", ".", "is_a?", "(", "String", ")", "raise", "TypeError", ",", "\"can't convert #{ value.class } into PryTheme::HEX\"", "end", "if", "value", "!~", "PryTheme", "::", "HEX", "::", "PATTERN", "fail", "ArgumentError", ",", "%|invalid value for PryTheme::HEX#new(): \"#{value}\"|", "end", "true", "end" ]
Validates whether +value+ is a valid hex colour value. @param [String] value @raise [TypeError] if +value+ isn't String @raise [ArgumentError] if +value+ is malformed @return [void]
[ "Validates", "whether", "+", "value", "+", "is", "a", "valid", "hex", "colour", "value", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/hex.rb#L65-L73
1,048
kyrylo/pry-theme
lib/pry-theme/when_started_hook.rb
PryTheme.WhenStartedHook.recreate_user_themes_from_default_ones
def recreate_user_themes_from_default_ones FileUtils.mkdir_p(USER_THEMES_DIR) unless File.exist?(USER_THEMES_DIR) default_themes = Dir.entries(DEF_THEMES_DIR) - %w(. ..) default_themes.each do |theme| user_theme_path = File.join(USER_THEMES_DIR, theme) next if File.exist?(user_theme_path) def_theme_path = File.join(DEF_THEMES_DIR, theme) FileUtils.cp(def_theme_path, USER_THEMES_DIR) end end
ruby
def recreate_user_themes_from_default_ones FileUtils.mkdir_p(USER_THEMES_DIR) unless File.exist?(USER_THEMES_DIR) default_themes = Dir.entries(DEF_THEMES_DIR) - %w(. ..) default_themes.each do |theme| user_theme_path = File.join(USER_THEMES_DIR, theme) next if File.exist?(user_theme_path) def_theme_path = File.join(DEF_THEMES_DIR, theme) FileUtils.cp(def_theme_path, USER_THEMES_DIR) end end
[ "def", "recreate_user_themes_from_default_ones", "FileUtils", ".", "mkdir_p", "(", "USER_THEMES_DIR", ")", "unless", "File", ".", "exist?", "(", "USER_THEMES_DIR", ")", "default_themes", "=", "Dir", ".", "entries", "(", "DEF_THEMES_DIR", ")", "-", "%w(", ".", "..", ")", "default_themes", ".", "each", "do", "|", "theme", "|", "user_theme_path", "=", "File", ".", "join", "(", "USER_THEMES_DIR", ",", "theme", ")", "next", "if", "File", ".", "exist?", "(", "user_theme_path", ")", "def_theme_path", "=", "File", ".", "join", "(", "DEF_THEMES_DIR", ",", "theme", ")", "FileUtils", ".", "cp", "(", "def_theme_path", ",", "USER_THEMES_DIR", ")", "end", "end" ]
Copy a default theme to theme directory, but only if it isn't there yet.
[ "Copy", "a", "default", "theme", "to", "theme", "directory", "but", "only", "if", "it", "isn", "t", "there", "yet", "." ]
db99825ff4438b04ce8b808b0303200350fe551b
https://github.com/kyrylo/pry-theme/blob/db99825ff4438b04ce8b808b0303200350fe551b/lib/pry-theme/when_started_hook.rb#L27-L37
1,049
cldwalker/bond
lib/bond/rc.rb
Bond.Rc.files
def files(input) (::Readline::FILENAME_COMPLETION_PROC.call(input) || []).map {|f| f =~ /^~/ ? File.expand_path(f) : f } end
ruby
def files(input) (::Readline::FILENAME_COMPLETION_PROC.call(input) || []).map {|f| f =~ /^~/ ? File.expand_path(f) : f } end
[ "def", "files", "(", "input", ")", "(", "::", "Readline", "::", "FILENAME_COMPLETION_PROC", ".", "call", "(", "input", ")", "||", "[", "]", ")", ".", "map", "{", "|", "f", "|", "f", "=~", "/", "/", "?", "File", ".", "expand_path", "(", "f", ")", ":", "f", "}", "end" ]
Action method with search which returns array of files that match current input.
[ "Action", "method", "with", "search", "which", "returns", "array", "of", "files", "that", "match", "current", "input", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/rc.rb#L27-L31
1,050
cldwalker/bond
lib/bond/rc.rb
Bond.Rc.objects_of
def objects_of(klass) object = [] ObjectSpace.each_object(klass) {|e| object.push(e) } object end
ruby
def objects_of(klass) object = [] ObjectSpace.each_object(klass) {|e| object.push(e) } object end
[ "def", "objects_of", "(", "klass", ")", "object", "=", "[", "]", "ObjectSpace", ".", "each_object", "(", "klass", ")", "{", "|", "e", "|", "object", ".", "push", "(", "e", ")", "}", "object", "end" ]
Helper method which returns objects of a given class.
[ "Helper", "method", "which", "returns", "objects", "of", "a", "given", "class", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/rc.rb#L34-L38
1,051
cldwalker/bond
lib/bond/mission.rb
Bond.Mission.call_search
def call_search(search, input, list) Rc.send("#{search}_search", input || '', list) rescue message = $!.is_a?(NoMethodError) && !Rc.respond_to?("#{search}_search") ? "Completion search '#{search}' doesn't exist." : "Failed during completion search with '#{$!.message}'." raise FailedMissionError.new(self), message end
ruby
def call_search(search, input, list) Rc.send("#{search}_search", input || '', list) rescue message = $!.is_a?(NoMethodError) && !Rc.respond_to?("#{search}_search") ? "Completion search '#{search}' doesn't exist." : "Failed during completion search with '#{$!.message}'." raise FailedMissionError.new(self), message end
[ "def", "call_search", "(", "search", ",", "input", ",", "list", ")", "Rc", ".", "send", "(", "\"#{search}_search\"", ",", "input", "||", "''", ",", "list", ")", "rescue", "message", "=", "$!", ".", "is_a?", "(", "NoMethodError", ")", "&&", "!", "Rc", ".", "respond_to?", "(", "\"#{search}_search\"", ")", "?", "\"Completion search '#{search}' doesn't exist.\"", ":", "\"Failed during completion search with '#{$!.message}'.\"", "raise", "FailedMissionError", ".", "new", "(", "self", ")", ",", "message", "end" ]
Searches possible completions from the action which match the input.
[ "Searches", "possible", "completions", "from", "the", "action", "which", "match", "the", "input", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/mission.rb#L85-L92
1,052
cldwalker/bond
lib/bond/mission.rb
Bond.Mission.call_action
def call_action(input) @action.respond_to?(:call) ? @action.call(input) : Rc.send(@action, input) rescue StandardError, SyntaxError message = $!.is_a?(NoMethodError) && [email protected]_to?(:call) && !Rc.respond_to?(@action) ? "Completion action '#{@action}' doesn't exist." : "Failed during completion action '#{name}' with '#{$!.message}'." raise FailedMissionError.new(self), message end
ruby
def call_action(input) @action.respond_to?(:call) ? @action.call(input) : Rc.send(@action, input) rescue StandardError, SyntaxError message = $!.is_a?(NoMethodError) && [email protected]_to?(:call) && !Rc.respond_to?(@action) ? "Completion action '#{@action}' doesn't exist." : "Failed during completion action '#{name}' with '#{$!.message}'." raise FailedMissionError.new(self), message end
[ "def", "call_action", "(", "input", ")", "@action", ".", "respond_to?", "(", ":call", ")", "?", "@action", ".", "call", "(", "input", ")", ":", "Rc", ".", "send", "(", "@action", ",", "input", ")", "rescue", "StandardError", ",", "SyntaxError", "message", "=", "$!", ".", "is_a?", "(", "NoMethodError", ")", "&&", "!", "@action", ".", "respond_to?", "(", ":call", ")", "&&", "!", "Rc", ".", "respond_to?", "(", "@action", ")", "?", "\"Completion action '#{@action}' doesn't exist.\"", ":", "\"Failed during completion action '#{name}' with '#{$!.message}'.\"", "raise", "FailedMissionError", ".", "new", "(", "self", ")", ",", "message", "end" ]
Calls the action to generate an array of possible completions.
[ "Calls", "the", "action", "to", "generate", "an", "array", "of", "possible", "completions", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/mission.rb#L95-L102
1,053
zverok/magic_cloud
lib/magic_cloud/spriter.rb
MagicCloud.Spriter.ensure_position
def ensure_position(rect) # no place in current row -> go to next row if cur_x + rect.width > canvas.width @cur_x = 0 @cur_y += row_height @row_height = 0 end # no place in current canvas -> restart canvas restart_canvas! if cur_y + rect.height > canvas.height end
ruby
def ensure_position(rect) # no place in current row -> go to next row if cur_x + rect.width > canvas.width @cur_x = 0 @cur_y += row_height @row_height = 0 end # no place in current canvas -> restart canvas restart_canvas! if cur_y + rect.height > canvas.height end
[ "def", "ensure_position", "(", "rect", ")", "# no place in current row -> go to next row", "if", "cur_x", "+", "rect", ".", "width", ">", "canvas", ".", "width", "@cur_x", "=", "0", "@cur_y", "+=", "row_height", "@row_height", "=", "0", "end", "# no place in current canvas -> restart canvas", "restart_canvas!", "if", "cur_y", "+", "rect", ".", "height", ">", "canvas", ".", "height", "end" ]
ensure this rect can be drawn at current position or shift position of it can't
[ "ensure", "this", "rect", "can", "be", "drawn", "at", "current", "position", "or", "shift", "position", "of", "it", "can", "t" ]
3c5d2dd19306c0fd557ba46556dc750931b3966f
https://github.com/zverok/magic_cloud/blob/3c5d2dd19306c0fd557ba46556dc750931b3966f/lib/magic_cloud/spriter.rb#L64-L74
1,054
oasic/nbayes
lib/nbayes.rb
NBayes.Data.remove_token_from_category
def remove_token_from_category(category, token) cat_data(category)[:tokens][token] -= 1 delete_token_from_category(category, token) if cat_data(category)[:tokens][token] < 1 cat_data(category)[:total_tokens] -= 1 delete_category(category) if cat_data(category)[:total_tokens] < 1 end
ruby
def remove_token_from_category(category, token) cat_data(category)[:tokens][token] -= 1 delete_token_from_category(category, token) if cat_data(category)[:tokens][token] < 1 cat_data(category)[:total_tokens] -= 1 delete_category(category) if cat_data(category)[:total_tokens] < 1 end
[ "def", "remove_token_from_category", "(", "category", ",", "token", ")", "cat_data", "(", "category", ")", "[", ":tokens", "]", "[", "token", "]", "-=", "1", "delete_token_from_category", "(", "category", ",", "token", ")", "if", "cat_data", "(", "category", ")", "[", ":tokens", "]", "[", "token", "]", "<", "1", "cat_data", "(", "category", ")", "[", ":total_tokens", "]", "-=", "1", "delete_category", "(", "category", ")", "if", "cat_data", "(", "category", ")", "[", ":total_tokens", "]", "<", "1", "end" ]
Decrement the token counter in a category If the counter is 0, delete the token. If the total number of tokens is 0, delete the category.
[ "Decrement", "the", "token", "counter", "in", "a", "category", "If", "the", "counter", "is", "0", "delete", "the", "token", ".", "If", "the", "total", "number", "of", "tokens", "is", "0", "delete", "the", "category", "." ]
3dd46bd2c8a2258ccdb69ee9ceff7d2fb5d62ed5
https://github.com/oasic/nbayes/blob/3dd46bd2c8a2258ccdb69ee9ceff7d2fb5d62ed5/lib/nbayes.rb#L126-L131
1,055
oasic/nbayes
lib/nbayes.rb
NBayes.Base.load
def load(yml) if yml.nil? nbayes = NBayes::Base.new elsif yml[0..2] == "---" nbayes = self.class.from_yml(yml) else nbayes = self.class.from(yml) end nbayes end
ruby
def load(yml) if yml.nil? nbayes = NBayes::Base.new elsif yml[0..2] == "---" nbayes = self.class.from_yml(yml) else nbayes = self.class.from(yml) end nbayes end
[ "def", "load", "(", "yml", ")", "if", "yml", ".", "nil?", "nbayes", "=", "NBayes", "::", "Base", ".", "new", "elsif", "yml", "[", "0", "..", "2", "]", "==", "\"---\"", "nbayes", "=", "self", ".", "class", ".", "from_yml", "(", "yml", ")", "else", "nbayes", "=", "self", ".", "class", ".", "from", "(", "yml", ")", "end", "nbayes", "end" ]
Load class instance
[ "Load", "class", "instance" ]
3dd46bd2c8a2258ccdb69ee9ceff7d2fb5d62ed5
https://github.com/oasic/nbayes/blob/3dd46bd2c8a2258ccdb69ee9ceff7d2fb5d62ed5/lib/nbayes.rb#L328-L337
1,056
cldwalker/bond
lib/bond/agent.rb
Bond.Agent.complete
def complete(options={}, &block) if (mission = create_mission(options, &block)).is_a?(Mission) mission.place.is_a?(Integer) ? @missions.insert(mission.place - 1, mission).compact! : @missions << mission sort_last_missions end mission end
ruby
def complete(options={}, &block) if (mission = create_mission(options, &block)).is_a?(Mission) mission.place.is_a?(Integer) ? @missions.insert(mission.place - 1, mission).compact! : @missions << mission sort_last_missions end mission end
[ "def", "complete", "(", "options", "=", "{", "}", ",", "&", "block", ")", "if", "(", "mission", "=", "create_mission", "(", "options", ",", "block", ")", ")", ".", "is_a?", "(", "Mission", ")", "mission", ".", "place", ".", "is_a?", "(", "Integer", ")", "?", "@missions", ".", "insert", "(", "mission", ".", "place", "-", "1", ",", "mission", ")", ".", "compact!", ":", "@missions", "<<", "mission", "sort_last_missions", "end", "mission", "end" ]
Creates a mission.
[ "Creates", "a", "mission", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/agent.rb#L20-L26
1,057
cldwalker/bond
lib/bond/agent.rb
Bond.Agent.recomplete
def recomplete(options={}, &block) if (mission = create_mission(options, &block)).is_a?(Mission) if (existing_mission = @missions.find {|e| e.name == mission.name }) @missions[@missions.index(existing_mission)] = mission sort_last_missions else return "No existing mission found to recomplete." end end mission end
ruby
def recomplete(options={}, &block) if (mission = create_mission(options, &block)).is_a?(Mission) if (existing_mission = @missions.find {|e| e.name == mission.name }) @missions[@missions.index(existing_mission)] = mission sort_last_missions else return "No existing mission found to recomplete." end end mission end
[ "def", "recomplete", "(", "options", "=", "{", "}", ",", "&", "block", ")", "if", "(", "mission", "=", "create_mission", "(", "options", ",", "block", ")", ")", ".", "is_a?", "(", "Mission", ")", "if", "(", "existing_mission", "=", "@missions", ".", "find", "{", "|", "e", "|", "e", ".", "name", "==", "mission", ".", "name", "}", ")", "@missions", "[", "@missions", ".", "index", "(", "existing_mission", ")", "]", "=", "mission", "sort_last_missions", "else", "return", "\"No existing mission found to recomplete.\"", "end", "end", "mission", "end" ]
Creates a mission and replaces the mission it matches if possible.
[ "Creates", "a", "mission", "and", "replaces", "the", "mission", "it", "matches", "if", "possible", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/agent.rb#L29-L39
1,058
cldwalker/bond
lib/bond/agent.rb
Bond.Agent.spy
def spy(input) if (mission = find_mission(input)) puts mission.match_message, "Possible completions: #{mission.execute.inspect}", "Matches for #{mission.condition.inspect} are #{mission.matched.to_a.inspect}" else puts "Doesn't match a completion." end rescue FailedMissionError => e puts e.mission.match_message, e.message, "Matches for #{e.mission.condition.inspect} are #{e.mission.matched.to_a.inspect}" end
ruby
def spy(input) if (mission = find_mission(input)) puts mission.match_message, "Possible completions: #{mission.execute.inspect}", "Matches for #{mission.condition.inspect} are #{mission.matched.to_a.inspect}" else puts "Doesn't match a completion." end rescue FailedMissionError => e puts e.mission.match_message, e.message, "Matches for #{e.mission.condition.inspect} are #{e.mission.matched.to_a.inspect}" end
[ "def", "spy", "(", "input", ")", "if", "(", "mission", "=", "find_mission", "(", "input", ")", ")", "puts", "mission", ".", "match_message", ",", "\"Possible completions: #{mission.execute.inspect}\"", ",", "\"Matches for #{mission.condition.inspect} are #{mission.matched.to_a.inspect}\"", "else", "puts", "\"Doesn't match a completion.\"", "end", "rescue", "FailedMissionError", "=>", "e", "puts", "e", ".", "mission", ".", "match_message", ",", "e", ".", "message", ",", "\"Matches for #{e.mission.condition.inspect} are #{e.mission.matched.to_a.inspect}\"", "end" ]
Given a hypothetical user input, reports back what mission it would have found and executed.
[ "Given", "a", "hypothetical", "user", "input", "reports", "back", "what", "mission", "it", "would", "have", "found", "and", "executed", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/agent.rb#L56-L66
1,059
cldwalker/bond
lib/bond/m.rb
Bond.M.debrief
def debrief(options={}) config.merge! options config[:readline] ||= default_readline if !config[:readline].is_a?(Module) && Bond.const_defined?(config[:readline].to_s.capitalize) config[:readline] = Bond.const_get(config[:readline].to_s.capitalize) end unless %w{setup line_buffer}.all? {|e| config[:readline].respond_to?(e) } $stderr.puts "Bond Error: Invalid readline plugin '#{config[:readline]}'." end end
ruby
def debrief(options={}) config.merge! options config[:readline] ||= default_readline if !config[:readline].is_a?(Module) && Bond.const_defined?(config[:readline].to_s.capitalize) config[:readline] = Bond.const_get(config[:readline].to_s.capitalize) end unless %w{setup line_buffer}.all? {|e| config[:readline].respond_to?(e) } $stderr.puts "Bond Error: Invalid readline plugin '#{config[:readline]}'." end end
[ "def", "debrief", "(", "options", "=", "{", "}", ")", "config", ".", "merge!", "options", "config", "[", ":readline", "]", "||=", "default_readline", "if", "!", "config", "[", ":readline", "]", ".", "is_a?", "(", "Module", ")", "&&", "Bond", ".", "const_defined?", "(", "config", "[", ":readline", "]", ".", "to_s", ".", "capitalize", ")", "config", "[", ":readline", "]", "=", "Bond", ".", "const_get", "(", "config", "[", ":readline", "]", ".", "to_s", ".", "capitalize", ")", "end", "unless", "%w{", "setup", "line_buffer", "}", ".", "all?", "{", "|", "e", "|", "config", "[", ":readline", "]", ".", "respond_to?", "(", "e", ")", "}", "$stderr", ".", "puts", "\"Bond Error: Invalid readline plugin '#{config[:readline]}'.\"", "end", "end" ]
Validates and sets values in M.config.
[ "Validates", "and", "sets", "values", "in", "M", ".", "config", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/m.rb#L49-L59
1,060
cldwalker/bond
lib/bond/m.rb
Bond.M.find_gem_file
def find_gem_file(rubygem, file) begin gem(rubygem); rescue Exception; end (dir = $:.find {|e| File.exist?(File.join(e, file)) }) && File.join(dir, file) end
ruby
def find_gem_file(rubygem, file) begin gem(rubygem); rescue Exception; end (dir = $:.find {|e| File.exist?(File.join(e, file)) }) && File.join(dir, file) end
[ "def", "find_gem_file", "(", "rubygem", ",", "file", ")", "begin", "gem", "(", "rubygem", ")", ";", "rescue", "Exception", ";", "end", "(", "dir", "=", "$:", ".", "find", "{", "|", "e", "|", "File", ".", "exist?", "(", "File", ".", "join", "(", "e", ",", "file", ")", ")", "}", ")", "&&", "File", ".", "join", "(", "dir", ",", "file", ")", "end" ]
Finds the full path to a gem's file relative it's load path directory. Returns nil if not found.
[ "Finds", "the", "full", "path", "to", "a", "gem", "s", "file", "relative", "it", "s", "load", "path", "directory", ".", "Returns", "nil", "if", "not", "found", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/m.rb#L83-L86
1,061
cldwalker/bond
lib/bond/m.rb
Bond.M.load_file
def load_file(file) Rc.module_eval File.read(file) rescue Exception => e $stderr.puts "Bond Error: Completion file '#{file}' failed to load with:", e.message end
ruby
def load_file(file) Rc.module_eval File.read(file) rescue Exception => e $stderr.puts "Bond Error: Completion file '#{file}' failed to load with:", e.message end
[ "def", "load_file", "(", "file", ")", "Rc", ".", "module_eval", "File", ".", "read", "(", "file", ")", "rescue", "Exception", "=>", "e", "$stderr", ".", "puts", "\"Bond Error: Completion file '#{file}' failed to load with:\"", ",", "e", ".", "message", "end" ]
Loads a completion file in Rc namespace.
[ "Loads", "a", "completion", "file", "in", "Rc", "namespace", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/m.rb#L89-L93
1,062
cldwalker/bond
lib/bond/m.rb
Bond.M.load_dir
def load_dir(base_dir) if File.exist?(dir = File.join(base_dir, 'completions')) Dir[dir + '/*.rb'].each {|file| load_file(file) } true end end
ruby
def load_dir(base_dir) if File.exist?(dir = File.join(base_dir, 'completions')) Dir[dir + '/*.rb'].each {|file| load_file(file) } true end end
[ "def", "load_dir", "(", "base_dir", ")", "if", "File", ".", "exist?", "(", "dir", "=", "File", ".", "join", "(", "base_dir", ",", "'completions'", ")", ")", "Dir", "[", "dir", "+", "'/*.rb'", "]", ".", "each", "{", "|", "file", "|", "load_file", "(", "file", ")", "}", "true", "end", "end" ]
Loads completion files in given directory.
[ "Loads", "completion", "files", "in", "given", "directory", "." ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/m.rb#L96-L101
1,063
cldwalker/bond
lib/bond/m.rb
Bond.M.home
def home ['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] } return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] File.expand_path("~") rescue File::ALT_SEPARATOR ? "C:/" : "/" end
ruby
def home ['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] } return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] File.expand_path("~") rescue File::ALT_SEPARATOR ? "C:/" : "/" end
[ "def", "home", "[", "'HOME'", ",", "'USERPROFILE'", "]", ".", "each", "{", "|", "e", "|", "return", "ENV", "[", "e", "]", "if", "ENV", "[", "e", "]", "}", "return", "\"#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}\"", "if", "ENV", "[", "'HOMEDRIVE'", "]", "&&", "ENV", "[", "'HOMEPATH'", "]", "File", ".", "expand_path", "(", "\"~\"", ")", "rescue", "File", "::", "ALT_SEPARATOR", "?", "\"C:/\"", ":", "\"/\"", "end" ]
Find a user's home in a cross-platform way
[ "Find", "a", "user", "s", "home", "in", "a", "cross", "-", "platform", "way" ]
19b0a9af11c59b1542f200f7288308315c47fda8
https://github.com/cldwalker/bond/blob/19b0a9af11c59b1542f200f7288308315c47fda8/lib/bond/m.rb#L109-L115
1,064
kost/nessus_rest-ruby
lib/nessus_rest.rb
NessusREST.Client.user_add
def user_add(username, password, permissions, type) payload = { :username => username, :password => password, :permissions => permissions, :type => type, :json => 1 } http_post(:uri=>"/users", :fields=>x_cookie, :data=>payload) end
ruby
def user_add(username, password, permissions, type) payload = { :username => username, :password => password, :permissions => permissions, :type => type, :json => 1 } http_post(:uri=>"/users", :fields=>x_cookie, :data=>payload) end
[ "def", "user_add", "(", "username", ",", "password", ",", "permissions", ",", "type", ")", "payload", "=", "{", ":username", "=>", "username", ",", ":password", "=>", "password", ",", ":permissions", "=>", "permissions", ",", ":type", "=>", "type", ",", ":json", "=>", "1", "}", "http_post", "(", ":uri", "=>", "\"/users\"", ",", ":fields", "=>", "x_cookie", ",", ":data", "=>", "payload", ")", "end" ]
Add user to server returns: JSON parsed object Usage: n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') pp n.user_add('user','password','16','local') Reference: https://localhost:8834/api#/resources/users/create
[ "Add", "user", "to", "server" ]
841c20eeea3bbd4154f74ef442ddd4d3e0224770
https://github.com/kost/nessus_rest-ruby/blob/841c20eeea3bbd4154f74ef442ddd4d3e0224770/lib/nessus_rest.rb#L203-L212
1,065
kost/nessus_rest-ruby
lib/nessus_rest.rb
NessusREST.Client.user_chpasswd
def user_chpasswd(user_id, password) payload = { :password => password, :json => 1 } res = http_put(:uri=>"/users/#{user_id}/chpasswd", :data=>payload, :fields=>x_cookie) return res.code end
ruby
def user_chpasswd(user_id, password) payload = { :password => password, :json => 1 } res = http_put(:uri=>"/users/#{user_id}/chpasswd", :data=>payload, :fields=>x_cookie) return res.code end
[ "def", "user_chpasswd", "(", "user_id", ",", "password", ")", "payload", "=", "{", ":password", "=>", "password", ",", ":json", "=>", "1", "}", "res", "=", "http_put", "(", ":uri", "=>", "\"/users/#{user_id}/chpasswd\"", ",", ":data", "=>", "payload", ",", ":fields", "=>", "x_cookie", ")", "return", "res", ".", "code", "end" ]
change password for user_id returns: result code Usage: n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') puts n.user_chpasswd(1,'newPassword')
[ "change", "password", "for", "user_id" ]
841c20eeea3bbd4154f74ef442ddd4d3e0224770
https://github.com/kost/nessus_rest-ruby/blob/841c20eeea3bbd4154f74ef442ddd4d3e0224770/lib/nessus_rest.rb#L235-L242
1,066
kost/nessus_rest-ruby
lib/nessus_rest.rb
NessusREST.Client.http_delete
def http_delete(opts={}) ret=http_delete_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_delete_low(opts) return ret else return ret end end
ruby
def http_delete(opts={}) ret=http_delete_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_delete_low(opts) return ret else return ret end end
[ "def", "http_delete", "(", "opts", "=", "{", "}", ")", "ret", "=", "http_delete_low", "(", "opts", ")", "if", "ret", ".", "is_a?", "(", "Hash", ")", "and", "ret", ".", "has_key?", "(", "'error'", ")", "and", "ret", "[", "'error'", "]", "==", "'Invalid Credentials'", "then", "authdefault", "ret", "=", "http_delete_low", "(", "opts", ")", "return", "ret", "else", "return", "ret", "end", "end" ]
Perform HTTP delete method with uri, data and fields returns: HTTP result object Usage: n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') res = n.http_delete(:uri=>"/session", :fields=>n.x_cookie) puts res.code
[ "Perform", "HTTP", "delete", "method", "with", "uri", "data", "and", "fields" ]
841c20eeea3bbd4154f74ef442ddd4d3e0224770
https://github.com/kost/nessus_rest-ruby/blob/841c20eeea3bbd4154f74ef442ddd4d3e0224770/lib/nessus_rest.rb#L658-L667
1,067
kost/nessus_rest-ruby
lib/nessus_rest.rb
NessusREST.Client.http_get
def http_get(opts={}) raw_content = opts[:raw_content] || false ret=http_get_low(opts) if !raw_content then if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_get_low(opts) return ret else return ret end else return ret end end
ruby
def http_get(opts={}) raw_content = opts[:raw_content] || false ret=http_get_low(opts) if !raw_content then if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_get_low(opts) return ret else return ret end else return ret end end
[ "def", "http_get", "(", "opts", "=", "{", "}", ")", "raw_content", "=", "opts", "[", ":raw_content", "]", "||", "false", "ret", "=", "http_get_low", "(", "opts", ")", "if", "!", "raw_content", "then", "if", "ret", ".", "is_a?", "(", "Hash", ")", "and", "ret", ".", "has_key?", "(", "'error'", ")", "and", "ret", "[", "'error'", "]", "==", "'Invalid Credentials'", "then", "authdefault", "ret", "=", "http_get_low", "(", "opts", ")", "return", "ret", "else", "return", "ret", "end", "else", "return", "ret", "end", "end" ]
Perform HTTP get method with uri and fields returns: JSON parsed object (if JSON parseable) Usage: n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') pp n.http_get(:uri=>"/users", :fields=>n.x_cookie)
[ "Perform", "HTTP", "get", "method", "with", "uri", "and", "fields" ]
841c20eeea3bbd4154f74ef442ddd4d3e0224770
https://github.com/kost/nessus_rest-ruby/blob/841c20eeea3bbd4154f74ef442ddd4d3e0224770/lib/nessus_rest.rb#L706-L720
1,068
kost/nessus_rest-ruby
lib/nessus_rest.rb
NessusREST.Client.http_post
def http_post(opts={}) if opts.has_key?(:authenticationmethod) then # i know authzmethod = opts.delete(:authorizationmethod) is short, but not readable authzmethod = opts[:authenticationmethod] opts.delete(:authenticationmethod) end ret=http_post_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then if not authzmethod authdefault ret=http_post_low(opts) return ret end else return ret end end
ruby
def http_post(opts={}) if opts.has_key?(:authenticationmethod) then # i know authzmethod = opts.delete(:authorizationmethod) is short, but not readable authzmethod = opts[:authenticationmethod] opts.delete(:authenticationmethod) end ret=http_post_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then if not authzmethod authdefault ret=http_post_low(opts) return ret end else return ret end end
[ "def", "http_post", "(", "opts", "=", "{", "}", ")", "if", "opts", ".", "has_key?", "(", ":authenticationmethod", ")", "then", "# i know authzmethod = opts.delete(:authorizationmethod) is short, but not readable", "authzmethod", "=", "opts", "[", ":authenticationmethod", "]", "opts", ".", "delete", "(", ":authenticationmethod", ")", "end", "ret", "=", "http_post_low", "(", "opts", ")", "if", "ret", ".", "is_a?", "(", "Hash", ")", "and", "ret", ".", "has_key?", "(", "'error'", ")", "and", "ret", "[", "'error'", "]", "==", "'Invalid Credentials'", "then", "if", "not", "authzmethod", "authdefault", "ret", "=", "http_post_low", "(", "opts", ")", "return", "ret", "end", "else", "return", "ret", "end", "end" ]
Perform HTTP post method with uri, data, body and fields returns: JSON parsed object (if JSON parseable) Usage: n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') pp n.http_post(:uri=>"/scans/#{scan_id}/launch", :fields=>n.x_cookie)
[ "Perform", "HTTP", "post", "method", "with", "uri", "data", "body", "and", "fields" ]
841c20eeea3bbd4154f74ef442ddd4d3e0224770
https://github.com/kost/nessus_rest-ruby/blob/841c20eeea3bbd4154f74ef442ddd4d3e0224770/lib/nessus_rest.rb#L762-L778
1,069
kost/nessus_rest-ruby
lib/nessus_rest.rb
NessusREST.Client.parse_json
def parse_json(body) buf = {} begin buf = JSON.parse(body) rescue JSON::ParserError end buf end
ruby
def parse_json(body) buf = {} begin buf = JSON.parse(body) rescue JSON::ParserError end buf end
[ "def", "parse_json", "(", "body", ")", "buf", "=", "{", "}", "begin", "buf", "=", "JSON", ".", "parse", "(", "body", ")", "rescue", "JSON", "::", "ParserError", "end", "buf", "end" ]
Perform JSON parsing of body returns: JSON parsed object (if JSON parseable)
[ "Perform", "JSON", "parsing", "of", "body" ]
841c20eeea3bbd4154f74ef442ddd4d3e0224770
https://github.com/kost/nessus_rest-ruby/blob/841c20eeea3bbd4154f74ef442ddd4d3e0224770/lib/nessus_rest.rb#L818-L827
1,070
tiabas/oauth2-client
lib/oauth2-client/helper.rb
OAuth2Client.UrlHelper.build_url
def build_url(uri, opts={}) path = opts[:path] || '' query = opts[:params] || {} fragment = opts[:fragment] || {} url = Addressable::URI.parse uri url.path = path url.query_values = query unless query.empty? url.fragment = Addressable::URI.form_encode(fragment) unless fragment.empty? url.to_s end
ruby
def build_url(uri, opts={}) path = opts[:path] || '' query = opts[:params] || {} fragment = opts[:fragment] || {} url = Addressable::URI.parse uri url.path = path url.query_values = query unless query.empty? url.fragment = Addressable::URI.form_encode(fragment) unless fragment.empty? url.to_s end
[ "def", "build_url", "(", "uri", ",", "opts", "=", "{", "}", ")", "path", "=", "opts", "[", ":path", "]", "||", "''", "query", "=", "opts", "[", ":params", "]", "||", "{", "}", "fragment", "=", "opts", "[", ":fragment", "]", "||", "{", "}", "url", "=", "Addressable", "::", "URI", ".", "parse", "uri", "url", ".", "path", "=", "path", "url", ".", "query_values", "=", "query", "unless", "query", ".", "empty?", "url", ".", "fragment", "=", "Addressable", "::", "URI", ".", "form_encode", "(", "fragment", ")", "unless", "fragment", ".", "empty?", "url", ".", "to_s", "end" ]
convenience method to build response URI
[ "convenience", "method", "to", "build", "response", "URI" ]
1fbc5851427ab9290769a080c61a53d94f552def
https://github.com/tiabas/oauth2-client/blob/1fbc5851427ab9290769a080c61a53d94f552def/lib/oauth2-client/helper.rb#L7-L16
1,071
tiabas/oauth2-client
lib/oauth2-client/helper.rb
OAuth2Client.UrlHelper.generate_urlsafe_key
def generate_urlsafe_key(size=48) seed = Time.now.to_i size = size - seed.to_s.length Base64.encode64("#{ OpenSSL::Random.random_bytes(size) }#{ seed }").gsub(/\W/, '') end
ruby
def generate_urlsafe_key(size=48) seed = Time.now.to_i size = size - seed.to_s.length Base64.encode64("#{ OpenSSL::Random.random_bytes(size) }#{ seed }").gsub(/\W/, '') end
[ "def", "generate_urlsafe_key", "(", "size", "=", "48", ")", "seed", "=", "Time", ".", "now", ".", "to_i", "size", "=", "size", "-", "seed", ".", "to_s", ".", "length", "Base64", ".", "encode64", "(", "\"#{ OpenSSL::Random.random_bytes(size) }#{ seed }\"", ")", ".", "gsub", "(", "/", "\\W", "/", ",", "''", ")", "end" ]
generates a random key of up to +size+ bytes. The value returned is Base64 encoded with non-word characters removed.
[ "generates", "a", "random", "key", "of", "up", "to", "+", "size", "+", "bytes", ".", "The", "value", "returned", "is", "Base64", "encoded", "with", "non", "-", "word", "characters", "removed", "." ]
1fbc5851427ab9290769a080c61a53d94f552def
https://github.com/tiabas/oauth2-client/blob/1fbc5851427ab9290769a080c61a53d94f552def/lib/oauth2-client/helper.rb#L20-L24
1,072
tiabas/oauth2-client
lib/oauth2-client/helper.rb
OAuth2Client.UrlHelper.to_query
def to_query(params) unless params.is_a?(Hash) raise "Expected Hash but got #{params.class.name}" end Addressable::URI.form_encode(params) end
ruby
def to_query(params) unless params.is_a?(Hash) raise "Expected Hash but got #{params.class.name}" end Addressable::URI.form_encode(params) end
[ "def", "to_query", "(", "params", ")", "unless", "params", ".", "is_a?", "(", "Hash", ")", "raise", "\"Expected Hash but got #{params.class.name}\"", "end", "Addressable", "::", "URI", ".", "form_encode", "(", "params", ")", "end" ]
converts a hash to a URI query string @params [Hash] params URI parameters
[ "converts", "a", "hash", "to", "a", "URI", "query", "string" ]
1fbc5851427ab9290769a080c61a53d94f552def
https://github.com/tiabas/oauth2-client/blob/1fbc5851427ab9290769a080c61a53d94f552def/lib/oauth2-client/helper.rb#L39-L44
1,073
ruby-odata/odata
lib/odata/entity.rb
OData.Entity.[]
def [](property_name) if get_property(property_name).is_a?(::OData::ComplexType) get_property(property_name) else get_property(property_name).value end rescue NoMethodError raise ArgumentError, "Unknown property: #{property_name}" end
ruby
def [](property_name) if get_property(property_name).is_a?(::OData::ComplexType) get_property(property_name) else get_property(property_name).value end rescue NoMethodError raise ArgumentError, "Unknown property: #{property_name}" end
[ "def", "[]", "(", "property_name", ")", "if", "get_property", "(", "property_name", ")", ".", "is_a?", "(", "::", "OData", "::", "ComplexType", ")", "get_property", "(", "property_name", ")", "else", "get_property", "(", "property_name", ")", ".", "value", "end", "rescue", "NoMethodError", "raise", "ArgumentError", ",", "\"Unknown property: #{property_name}\"", "end" ]
Get property value @param property_name [to_s] @return [*]
[ "Get", "property", "value" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/entity.rb#L40-L48
1,074
ruby-odata/odata
lib/odata/entity.rb
OData.Entity.[]=
def []=(property_name, value) properties[property_name.to_s].value = value rescue NoMethodError raise ArgumentError, "Unknown property: #{property_name}" end
ruby
def []=(property_name, value) properties[property_name.to_s].value = value rescue NoMethodError raise ArgumentError, "Unknown property: #{property_name}" end
[ "def", "[]=", "(", "property_name", ",", "value", ")", "properties", "[", "property_name", ".", "to_s", "]", ".", "value", "=", "value", "rescue", "NoMethodError", "raise", "ArgumentError", ",", "\"Unknown property: #{property_name}\"", "end" ]
Set property value @param property_name [to_s] @param value [*]
[ "Set", "property", "value" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/entity.rb#L53-L57
1,075
ruby-odata/odata
lib/odata/entity.rb
OData.Entity.to_xml
def to_xml builder = Nokogiri::XML::Builder.new do |xml| xml.entry('xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:data' => 'http://schemas.microsoft.com/ado/2007/08/dataservices', 'xmlns:metadata' => 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata', 'xmlns:georss' => 'http://www.georss.org/georss', 'xmlns:gml' => 'http://www.opengis.net/gml', 'xml:base' => 'http://services.odata.org/OData/OData.svc/') do xml.category(term: "#{namespace}.#{type}", scheme: 'http://schemas.microsoft.com/ado/2007/08/dataservices/scheme') xml.author { xml.name } xml.content(type: 'application/xml') do xml['metadata'].properties do properties.keys.each do |name| next if name == primary_key get_property(name).to_xml(xml) end end end end end builder.to_xml end
ruby
def to_xml builder = Nokogiri::XML::Builder.new do |xml| xml.entry('xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:data' => 'http://schemas.microsoft.com/ado/2007/08/dataservices', 'xmlns:metadata' => 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata', 'xmlns:georss' => 'http://www.georss.org/georss', 'xmlns:gml' => 'http://www.opengis.net/gml', 'xml:base' => 'http://services.odata.org/OData/OData.svc/') do xml.category(term: "#{namespace}.#{type}", scheme: 'http://schemas.microsoft.com/ado/2007/08/dataservices/scheme') xml.author { xml.name } xml.content(type: 'application/xml') do xml['metadata'].properties do properties.keys.each do |name| next if name == primary_key get_property(name).to_xml(xml) end end end end end builder.to_xml end
[ "def", "to_xml", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "entry", "(", "'xmlns'", "=>", "'http://www.w3.org/2005/Atom'", ",", "'xmlns:data'", "=>", "'http://schemas.microsoft.com/ado/2007/08/dataservices'", ",", "'xmlns:metadata'", "=>", "'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata'", ",", "'xmlns:georss'", "=>", "'http://www.georss.org/georss'", ",", "'xmlns:gml'", "=>", "'http://www.opengis.net/gml'", ",", "'xml:base'", "=>", "'http://services.odata.org/OData/OData.svc/'", ")", "do", "xml", ".", "category", "(", "term", ":", "\"#{namespace}.#{type}\"", ",", "scheme", ":", "'http://schemas.microsoft.com/ado/2007/08/dataservices/scheme'", ")", "xml", ".", "author", "{", "xml", ".", "name", "}", "xml", ".", "content", "(", "type", ":", "'application/xml'", ")", "do", "xml", "[", "'metadata'", "]", ".", "properties", "do", "properties", ".", "keys", ".", "each", "do", "|", "name", "|", "next", "if", "name", "==", "primary_key", "get_property", "(", "name", ")", ".", "to_xml", "(", "xml", ")", "end", "end", "end", "end", "end", "builder", ".", "to_xml", "end" ]
Converts Entity to its XML representation. @return [String]
[ "Converts", "Entity", "to", "its", "XML", "representation", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/entity.rb#L112-L135
1,076
ruby-odata/odata
lib/odata/service_registry.rb
OData.ServiceRegistry.add
def add(service) initialize_instance_variables @services << service if service.is_a?(OData::Service) && [email protected]?(service) @services_by_name[service.name] = @services.find_index(service) @services_by_url[service.service_url] = @services.find_index(service) end
ruby
def add(service) initialize_instance_variables @services << service if service.is_a?(OData::Service) && [email protected]?(service) @services_by_name[service.name] = @services.find_index(service) @services_by_url[service.service_url] = @services.find_index(service) end
[ "def", "add", "(", "service", ")", "initialize_instance_variables", "@services", "<<", "service", "if", "service", ".", "is_a?", "(", "OData", "::", "Service", ")", "&&", "!", "@services", ".", "include?", "(", "service", ")", "@services_by_name", "[", "service", ".", "name", "]", "=", "@services", ".", "find_index", "(", "service", ")", "@services_by_url", "[", "service", ".", "service_url", "]", "=", "@services", ".", "find_index", "(", "service", ")", "end" ]
Add a service to the Registry @param service [OData::Service] service to add to the registry
[ "Add", "a", "service", "to", "the", "Registry" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service_registry.rb#L11-L16
1,077
ruby-odata/odata
lib/odata/service.rb
OData.Service.entity_sets
def entity_sets @entity_sets ||= Hash[metadata.xpath('//EntityContainer/EntitySet').collect {|entity| [ entity.attributes['EntityType'].value.gsub("#{namespace}.", ''), entity.attributes['Name'].value ] }] end
ruby
def entity_sets @entity_sets ||= Hash[metadata.xpath('//EntityContainer/EntitySet').collect {|entity| [ entity.attributes['EntityType'].value.gsub("#{namespace}.", ''), entity.attributes['Name'].value ] }] end
[ "def", "entity_sets", "@entity_sets", "||=", "Hash", "[", "metadata", ".", "xpath", "(", "'//EntityContainer/EntitySet'", ")", ".", "collect", "{", "|", "entity", "|", "[", "entity", ".", "attributes", "[", "'EntityType'", "]", ".", "value", ".", "gsub", "(", "\"#{namespace}.\"", ",", "''", ")", ",", "entity", ".", "attributes", "[", "'Name'", "]", ".", "value", "]", "}", "]", "end" ]
Returns a hash of EntitySet names keyed to their respective EntityType name
[ "Returns", "a", "hash", "of", "EntitySet", "names", "keyed", "to", "their", "respective", "EntityType", "name" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L49-L56
1,078
ruby-odata/odata
lib/odata/service.rb
OData.Service.associations
def associations @associations ||= Hash[metadata.xpath('//Association').collect do |association_definition| [ association_definition.attributes['Name'].value, build_association(association_definition) ] end] end
ruby
def associations @associations ||= Hash[metadata.xpath('//Association').collect do |association_definition| [ association_definition.attributes['Name'].value, build_association(association_definition) ] end] end
[ "def", "associations", "@associations", "||=", "Hash", "[", "metadata", ".", "xpath", "(", "'//Association'", ")", ".", "collect", "do", "|", "association_definition", "|", "[", "association_definition", ".", "attributes", "[", "'Name'", "]", ".", "value", ",", "build_association", "(", "association_definition", ")", "]", "end", "]", "end" ]
Returns the associations defined by the service @return [Hash<OData::Association>]
[ "Returns", "the", "associations", "defined", "by", "the", "service" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L65-L72
1,079
ruby-odata/odata
lib/odata/service.rb
OData.Service.execute
def execute(url_chunk, additional_options = {}) request = ::Typhoeus::Request.new( URI.escape("#{service_url}/#{url_chunk}"), options[:typhoeus].merge({ method: :get }) .merge(additional_options) ) request.run response = request.response validate_response(response) response end
ruby
def execute(url_chunk, additional_options = {}) request = ::Typhoeus::Request.new( URI.escape("#{service_url}/#{url_chunk}"), options[:typhoeus].merge({ method: :get }) .merge(additional_options) ) request.run response = request.response validate_response(response) response end
[ "def", "execute", "(", "url_chunk", ",", "additional_options", "=", "{", "}", ")", "request", "=", "::", "Typhoeus", "::", "Request", ".", "new", "(", "URI", ".", "escape", "(", "\"#{service_url}/#{url_chunk}\"", ")", ",", "options", "[", ":typhoeus", "]", ".", "merge", "(", "{", "method", ":", ":get", "}", ")", ".", "merge", "(", "additional_options", ")", ")", "request", ".", "run", "response", "=", "request", ".", "response", "validate_response", "(", "response", ")", "response", "end" ]
Execute a request against the service @param url_chunk [to_s] string to append to service url @param additional_options [Hash] options to pass to Typhoeus @return [Typhoeus::Response]
[ "Execute", "a", "request", "against", "the", "service" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L126-L137
1,080
ruby-odata/odata
lib/odata/service.rb
OData.Service.find_node
def find_node(results, node_name) document = ::Nokogiri::XML(results.body) document.remove_namespaces! document.xpath("//#{node_name}").first end
ruby
def find_node(results, node_name) document = ::Nokogiri::XML(results.body) document.remove_namespaces! document.xpath("//#{node_name}").first end
[ "def", "find_node", "(", "results", ",", "node_name", ")", "document", "=", "::", "Nokogiri", "::", "XML", "(", "results", ".", "body", ")", "document", ".", "remove_namespaces!", "document", ".", "xpath", "(", "\"//#{node_name}\"", ")", ".", "first", "end" ]
Find a specific node in the given result set @param results [Typhoeus::Response] @return [Nokogiri::XML::Element]
[ "Find", "a", "specific", "node", "in", "the", "given", "result", "set" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L143-L147
1,081
ruby-odata/odata
lib/odata/service.rb
OData.Service.find_entities
def find_entities(results) document = ::Nokogiri::XML(results.body) document.remove_namespaces! document.xpath('//entry') end
ruby
def find_entities(results) document = ::Nokogiri::XML(results.body) document.remove_namespaces! document.xpath('//entry') end
[ "def", "find_entities", "(", "results", ")", "document", "=", "::", "Nokogiri", "::", "XML", "(", "results", ".", "body", ")", "document", ".", "remove_namespaces!", "document", ".", "xpath", "(", "'//entry'", ")", "end" ]
Find entity entries in a result set @param results [Typhoeus::Response] @return [Nokogiri::XML::NodeSet]
[ "Find", "entity", "entries", "in", "a", "result", "set" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L153-L157
1,082
ruby-odata/odata
lib/odata/service.rb
OData.Service.get_title_property_name
def get_title_property_name(entity_name) node = metadata.xpath("//EntityType[@Name='#{entity_name}']/Property[@FC_TargetPath='SyndicationTitle']").first node.nil? ? nil : node.attributes['Name'].value end
ruby
def get_title_property_name(entity_name) node = metadata.xpath("//EntityType[@Name='#{entity_name}']/Property[@FC_TargetPath='SyndicationTitle']").first node.nil? ? nil : node.attributes['Name'].value end
[ "def", "get_title_property_name", "(", "entity_name", ")", "node", "=", "metadata", ".", "xpath", "(", "\"//EntityType[@Name='#{entity_name}']/Property[@FC_TargetPath='SyndicationTitle']\"", ")", ".", "first", "node", ".", "nil?", "?", "nil", ":", "node", ".", "attributes", "[", "'Name'", "]", ".", "value", "end" ]
Get the property used as the title for an entity from metadata. @param entity_name [to_s] the name of the relevant entity @return [String] the name of the property used as the entity title
[ "Get", "the", "property", "used", "as", "the", "title", "for", "an", "entity", "from", "metadata", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L172-L175
1,083
ruby-odata/odata
lib/odata/service.rb
OData.Service.properties_for_entity
def properties_for_entity(entity_name) type_definition = metadata.xpath("//EntityType[@Name='#{entity_name}']").first raise ArgumentError, "Unknown EntityType: #{entity_name}" if type_definition.nil? properties_to_return = {} type_definition.xpath('./Property').each do |property_xml| property_name, property = process_property_from_xml(property_xml) properties_to_return[property_name] = property end properties_to_return end
ruby
def properties_for_entity(entity_name) type_definition = metadata.xpath("//EntityType[@Name='#{entity_name}']").first raise ArgumentError, "Unknown EntityType: #{entity_name}" if type_definition.nil? properties_to_return = {} type_definition.xpath('./Property').each do |property_xml| property_name, property = process_property_from_xml(property_xml) properties_to_return[property_name] = property end properties_to_return end
[ "def", "properties_for_entity", "(", "entity_name", ")", "type_definition", "=", "metadata", ".", "xpath", "(", "\"//EntityType[@Name='#{entity_name}']\"", ")", ".", "first", "raise", "ArgumentError", ",", "\"Unknown EntityType: #{entity_name}\"", "if", "type_definition", ".", "nil?", "properties_to_return", "=", "{", "}", "type_definition", ".", "xpath", "(", "'./Property'", ")", ".", "each", "do", "|", "property_xml", "|", "property_name", ",", "property", "=", "process_property_from_xml", "(", "property_xml", ")", "properties_to_return", "[", "property_name", "]", "=", "property", "end", "properties_to_return", "end" ]
Get the list of properties and their various options for the supplied Entity name. @param entity_name [to_s] @return [Hash] @api private
[ "Get", "the", "list", "of", "properties", "and", "their", "various", "options", "for", "the", "supplied", "Entity", "name", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L200-L209
1,084
ruby-odata/odata
lib/odata/service.rb
OData.Service.properties_for_complex_type
def properties_for_complex_type(type_name) type_definition = metadata.xpath("//ComplexType[@Name='#{type_name}']").first raise ArgumentError, "Unknown ComplexType: #{type_name}" if type_definition.nil? properties_to_return = {} type_definition.xpath('./Property').each do |property_xml| property_name, property = process_property_from_xml(property_xml) properties_to_return[property_name] = property end properties_to_return end
ruby
def properties_for_complex_type(type_name) type_definition = metadata.xpath("//ComplexType[@Name='#{type_name}']").first raise ArgumentError, "Unknown ComplexType: #{type_name}" if type_definition.nil? properties_to_return = {} type_definition.xpath('./Property').each do |property_xml| property_name, property = process_property_from_xml(property_xml) properties_to_return[property_name] = property end properties_to_return end
[ "def", "properties_for_complex_type", "(", "type_name", ")", "type_definition", "=", "metadata", ".", "xpath", "(", "\"//ComplexType[@Name='#{type_name}']\"", ")", ".", "first", "raise", "ArgumentError", ",", "\"Unknown ComplexType: #{type_name}\"", "if", "type_definition", ".", "nil?", "properties_to_return", "=", "{", "}", "type_definition", ".", "xpath", "(", "'./Property'", ")", ".", "each", "do", "|", "property_xml", "|", "property_name", ",", "property", "=", "process_property_from_xml", "(", "property_xml", ")", "properties_to_return", "[", "property_name", "]", "=", "property", "end", "properties_to_return", "end" ]
Get list of properties and their various options for the supplied ComplexType name. @param type_name [to_s] @return [Hash] @api private
[ "Get", "list", "of", "properties", "and", "their", "various", "options", "for", "the", "supplied", "ComplexType", "name", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/service.rb#L216-L225
1,085
ruby-odata/odata
lib/odata/entity_set.rb
OData.EntitySet.each
def each(&block) per_page = @each_batch_size page = 0 loop do entities = get_paginated_entities(per_page, page) break if entities.empty? entities.each do |entity| block_given? ? block.call(entity) : yield(entity) end page += 1 end end
ruby
def each(&block) per_page = @each_batch_size page = 0 loop do entities = get_paginated_entities(per_page, page) break if entities.empty? entities.each do |entity| block_given? ? block.call(entity) : yield(entity) end page += 1 end end
[ "def", "each", "(", "&", "block", ")", "per_page", "=", "@each_batch_size", "page", "=", "0", "loop", "do", "entities", "=", "get_paginated_entities", "(", "per_page", ",", "page", ")", "break", "if", "entities", ".", "empty?", "entities", ".", "each", "do", "|", "entity", "|", "block_given?", "?", "block", ".", "call", "(", "entity", ")", ":", "yield", "(", "entity", ")", "end", "page", "+=", "1", "end", "end" ]
Sets up the EntitySet to permit querying for the resources in the set. @param options [Hash] the options to setup the EntitySet @return [OData::EntitySet] an instance of the EntitySet Provided for Enumerable functionality @param block [block] a block to evaluate @return [OData::Entity] each entity in turn from this set
[ "Sets", "up", "the", "EntitySet", "to", "permit", "querying", "for", "the", "resources", "in", "the", "set", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/entity_set.rb#L43-L57
1,086
ruby-odata/odata
lib/odata/entity_set.rb
OData.EntitySet.first
def first(count = 1) query = OData::Query.new(self).limit(count) result = service.execute(query) entities = service.find_entities(result) res = count == 1 ? single_entity_from_xml(entities) : multiple_entities_from_xml(entities) res end
ruby
def first(count = 1) query = OData::Query.new(self).limit(count) result = service.execute(query) entities = service.find_entities(result) res = count == 1 ? single_entity_from_xml(entities) : multiple_entities_from_xml(entities) res end
[ "def", "first", "(", "count", "=", "1", ")", "query", "=", "OData", "::", "Query", ".", "new", "(", "self", ")", ".", "limit", "(", "count", ")", "result", "=", "service", ".", "execute", "(", "query", ")", "entities", "=", "service", ".", "find_entities", "(", "result", ")", "res", "=", "count", "==", "1", "?", "single_entity_from_xml", "(", "entities", ")", ":", "multiple_entities_from_xml", "(", "entities", ")", "res", "end" ]
Return the first n Entities for the set. If count is 1 it returns the single entity, otherwise its an array of entities @return [OData::EntitySet]
[ "Return", "the", "first", "n", "Entities", "for", "the", "set", ".", "If", "count", "is", "1", "it", "returns", "the", "single", "entity", "otherwise", "its", "an", "array", "of", "entities" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/entity_set.rb#L62-L68
1,087
ruby-odata/odata
lib/odata/entity_set.rb
OData.EntitySet.[]
def [](key) entity = new_entity key_property = entity.get_property(entity.primary_key) key_property.value = key result = service.execute("#{name}(#{key_property.url_value})") entities = service.find_entities(result) single_entity_from_xml(entities) end
ruby
def [](key) entity = new_entity key_property = entity.get_property(entity.primary_key) key_property.value = key result = service.execute("#{name}(#{key_property.url_value})") entities = service.find_entities(result) single_entity_from_xml(entities) end
[ "def", "[]", "(", "key", ")", "entity", "=", "new_entity", "key_property", "=", "entity", ".", "get_property", "(", "entity", ".", "primary_key", ")", "key_property", ".", "value", "=", "key", "result", "=", "service", ".", "execute", "(", "\"#{name}(#{key_property.url_value})\"", ")", "entities", "=", "service", ".", "find_entities", "(", "result", ")", "single_entity_from_xml", "(", "entities", ")", "end" ]
Find the Entity with the supplied key value. @param key [to_s] primary key to lookup @return [OData::Entity,nil]
[ "Find", "the", "Entity", "with", "the", "supplied", "key", "value", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/entity_set.rb#L93-L101
1,088
markburns/numbers_in_words
lib/numbers_in_words/number_group.rb
NumbersInWords.NumberGroup.groups
def groups size #1234567 => %w(765 432 1) @array = in_groups_of(@number.to_s.reverse.split(""), size) #%w(765 432 1) => %w(1 432 765) @array.reverse! #%w(1 432 765) => [1, 234, 567] @array.map! {|group| group.reverse.join("").to_i} @array.reverse! # put in ascending order of power of ten power = 0 #[1, 234, 567] => {6 => 1, 3 => 234, 0 => 567} @array.inject({}) do |o, digits| o[power] = digits power += size o end end
ruby
def groups size #1234567 => %w(765 432 1) @array = in_groups_of(@number.to_s.reverse.split(""), size) #%w(765 432 1) => %w(1 432 765) @array.reverse! #%w(1 432 765) => [1, 234, 567] @array.map! {|group| group.reverse.join("").to_i} @array.reverse! # put in ascending order of power of ten power = 0 #[1, 234, 567] => {6 => 1, 3 => 234, 0 => 567} @array.inject({}) do |o, digits| o[power] = digits power += size o end end
[ "def", "groups", "size", "#1234567 => %w(765 432 1)", "@array", "=", "in_groups_of", "(", "@number", ".", "to_s", ".", "reverse", ".", "split", "(", "\"\"", ")", ",", "size", ")", "#%w(765 432 1) => %w(1 432 765)", "@array", ".", "reverse!", "#%w(1 432 765) => [1, 234, 567]", "@array", ".", "map!", "{", "|", "group", "|", "group", ".", "reverse", ".", "join", "(", "\"\"", ")", ".", "to_i", "}", "@array", ".", "reverse!", "# put in ascending order of power of ten", "power", "=", "0", "#[1, 234, 567] => {6 => 1, 3 => 234, 0 => 567}", "@array", ".", "inject", "(", "{", "}", ")", "do", "|", "o", ",", "digits", "|", "o", "[", "power", "]", "=", "digits", "power", "+=", "size", "o", "end", "end" ]
split into groups this gives us 1234567 => 123 456 7 so we need to reverse first in stages
[ "split", "into", "groups", "this", "gives", "us", "1234567", "=", ">", "123", "456", "7", "so", "we", "need", "to", "reverse", "first", "in", "stages" ]
dc0ce29fb82b31c877afdc149111fa6ed3d1ed72
https://github.com/markburns/numbers_in_words/blob/dc0ce29fb82b31c877afdc149111fa6ed3d1ed72/lib/numbers_in_words/number_group.rb#L17-L35
1,089
ruby-odata/odata
lib/odata/query.rb
OData.Query.[]
def [](property) property_instance = @entity_set.new_entity.get_property(property) property_instance = property if property_instance.nil? OData::Query::Criteria.new(property: property_instance) end
ruby
def [](property) property_instance = @entity_set.new_entity.get_property(property) property_instance = property if property_instance.nil? OData::Query::Criteria.new(property: property_instance) end
[ "def", "[]", "(", "property", ")", "property_instance", "=", "@entity_set", ".", "new_entity", ".", "get_property", "(", "property", ")", "property_instance", "=", "property", "if", "property_instance", ".", "nil?", "OData", "::", "Query", "::", "Criteria", ".", "new", "(", "property", ":", "property_instance", ")", "end" ]
Create a new Query for the provided EntitySet @param entity_set [OData::EntitySet] Instantiates an OData::Query::Criteria for the named property. @param property [to_s]
[ "Create", "a", "new", "Query", "for", "the", "provided", "EntitySet" ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/query.rb#L16-L20
1,090
ruby-odata/odata
lib/odata/query.rb
OData.Query.execute
def execute response = entity_set.service.execute(self.to_s) OData::Query::Result.new(self, response) end
ruby
def execute response = entity_set.service.execute(self.to_s) OData::Query::Result.new(self, response) end
[ "def", "execute", "response", "=", "entity_set", ".", "service", ".", "execute", "(", "self", ".", "to_s", ")", "OData", "::", "Query", "::", "Result", ".", "new", "(", "self", ",", "response", ")", "end" ]
Execute the query. @return [OData::Query::Result]
[ "Execute", "the", "query", "." ]
be4626bebea595dab2250ae4442e59e94b5fd4c6
https://github.com/ruby-odata/odata/blob/be4626bebea595dab2250ae4442e59e94b5fd4c6/lib/odata/query.rb#L110-L113
1,091
nwops/puppet-retrospec
lib/retrospec/plugins/v1/plugin/generators/provider_generator.rb
Retrospec::Puppet::Generators.ProviderGenerator.template_dir
def template_dir external_templates = File.expand_path(File.join(config_data[:template_dir], 'providers', 'provider_template.rb.retrospec.erb')) if File.exist?(external_templates) File.join(config_data[:template_dir], 'providers') else File.expand_path(File.join(File.dirname(File.dirname(__FILE__)), 'templates', 'providers')) end end
ruby
def template_dir external_templates = File.expand_path(File.join(config_data[:template_dir], 'providers', 'provider_template.rb.retrospec.erb')) if File.exist?(external_templates) File.join(config_data[:template_dir], 'providers') else File.expand_path(File.join(File.dirname(File.dirname(__FILE__)), 'templates', 'providers')) end end
[ "def", "template_dir", "external_templates", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "config_data", "[", ":template_dir", "]", ",", "'providers'", ",", "'provider_template.rb.retrospec.erb'", ")", ")", "if", "File", ".", "exist?", "(", "external_templates", ")", "File", ".", "join", "(", "config_data", "[", ":template_dir", "]", ",", "'providers'", ")", "else", "File", ".", "expand_path", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "File", ".", "dirname", "(", "__FILE__", ")", ")", ",", "'templates'", ",", "'providers'", ")", ")", "end", "end" ]
retrospec will initaialize this class so its up to you to set any additional variables you need in the context in feed the templates. returns the path to the templates first looks inside the external templates directory for specific file then looks inside the gem path templates directory, which is really only useful when developing new templates.
[ "retrospec", "will", "initaialize", "this", "class", "so", "its", "up", "to", "you", "to", "set", "any", "additional", "variables", "you", "need", "in", "the", "context", "in", "feed", "the", "templates", ".", "returns", "the", "path", "to", "the", "templates", "first", "looks", "inside", "the", "external", "templates", "directory", "for", "specific", "file", "then", "looks", "inside", "the", "gem", "path", "templates", "directory", "which", "is", "really", "only", "useful", "when", "developing", "new", "templates", "." ]
89289ec0e86df39dc283a3cb4c392239e5166ec4
https://github.com/nwops/puppet-retrospec/blob/89289ec0e86df39dc283a3cb4c392239e5166ec4/lib/retrospec/plugins/v1/plugin/generators/provider_generator.rb#L26-L33
1,092
nwops/puppet-retrospec
lib/retrospec/plugins/v1/plugin/generators/provider_generator.rb
Retrospec::Puppet::Generators.ProviderGenerator.type_file
def type_file(p_type = provider_type) if TypeGenerator::CORE_TYPES.include?(p_type) type_file = "puppet/type/#{p_type}.rb" else type_file = File.join(type_dir, "#{p_type}.rb") end type_file end
ruby
def type_file(p_type = provider_type) if TypeGenerator::CORE_TYPES.include?(p_type) type_file = "puppet/type/#{p_type}.rb" else type_file = File.join(type_dir, "#{p_type}.rb") end type_file end
[ "def", "type_file", "(", "p_type", "=", "provider_type", ")", "if", "TypeGenerator", "::", "CORE_TYPES", ".", "include?", "(", "p_type", ")", "type_file", "=", "\"puppet/type/#{p_type}.rb\"", "else", "type_file", "=", "File", ".", "join", "(", "type_dir", ",", "\"#{p_type}.rb\"", ")", "end", "type_file", "end" ]
returns the type file that the provider uses if the type file does not exist it assumes a core puppet type because we could potentially dealing with multiple
[ "returns", "the", "type", "file", "that", "the", "provider", "uses", "if", "the", "type", "file", "does", "not", "exist", "it", "assumes", "a", "core", "puppet", "type", "because", "we", "could", "potentially", "dealing", "with", "multiple" ]
89289ec0e86df39dc283a3cb4c392239e5166ec4
https://github.com/nwops/puppet-retrospec/blob/89289ec0e86df39dc283a3cb4c392239e5166ec4/lib/retrospec/plugins/v1/plugin/generators/provider_generator.rb#L68-L75
1,093
nwops/puppet-retrospec
lib/retrospec/plugins/v1/plugin/puppet_module.rb
Utilities.PuppetModule.create_tmp_module_path
def create_tmp_module_path(module_path) fail 'ModulePathNotFound' unless module_path path = File.join(tmp_modules_dir, module_dir_name) unless File.exist?(path) # only create if it doesn't already exist # create a link where source is the current repo and dest is /tmp/modules/module_name FileUtils.ln_s(module_path, path) end path end
ruby
def create_tmp_module_path(module_path) fail 'ModulePathNotFound' unless module_path path = File.join(tmp_modules_dir, module_dir_name) unless File.exist?(path) # only create if it doesn't already exist # create a link where source is the current repo and dest is /tmp/modules/module_name FileUtils.ln_s(module_path, path) end path end
[ "def", "create_tmp_module_path", "(", "module_path", ")", "fail", "'ModulePathNotFound'", "unless", "module_path", "path", "=", "File", ".", "join", "(", "tmp_modules_dir", ",", "module_dir_name", ")", "unless", "File", ".", "exist?", "(", "path", ")", "# only create if it doesn't already exist", "# create a link where source is the current repo and dest is /tmp/modules/module_name", "FileUtils", ".", "ln_s", "(", "module_path", ",", "path", ")", "end", "path", "end" ]
puts a symlink in that module directory that points back to the user supplied module path
[ "puts", "a", "symlink", "in", "that", "module", "directory", "that", "points", "back", "to", "the", "user", "supplied", "module", "path" ]
89289ec0e86df39dc283a3cb4c392239e5166ec4
https://github.com/nwops/puppet-retrospec/blob/89289ec0e86df39dc283a3cb4c392239e5166ec4/lib/retrospec/plugins/v1/plugin/puppet_module.rb#L103-L111
1,094
nwops/puppet-retrospec
lib/retrospec/plugins/v1/plugin/puppet_module.rb
Utilities.PuppetModule.tmp_modules_dir
def tmp_modules_dir if @tmp_modules_dir.nil? || !File.exist?(@tmp_modules_dir) tmp_path = File.expand_path(File.join(temporary_environment_path, 'modules')) FileUtils.mkdir_p(tmp_path) @tmp_modules_dir = tmp_path end @tmp_modules_dir end
ruby
def tmp_modules_dir if @tmp_modules_dir.nil? || !File.exist?(@tmp_modules_dir) tmp_path = File.expand_path(File.join(temporary_environment_path, 'modules')) FileUtils.mkdir_p(tmp_path) @tmp_modules_dir = tmp_path end @tmp_modules_dir end
[ "def", "tmp_modules_dir", "if", "@tmp_modules_dir", ".", "nil?", "||", "!", "File", ".", "exist?", "(", "@tmp_modules_dir", ")", "tmp_path", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "temporary_environment_path", ",", "'modules'", ")", ")", "FileUtils", ".", "mkdir_p", "(", "tmp_path", ")", "@tmp_modules_dir", "=", "tmp_path", "end", "@tmp_modules_dir", "end" ]
creates a tmp module directory so puppet can work correctly
[ "creates", "a", "tmp", "module", "directory", "so", "puppet", "can", "work", "correctly" ]
89289ec0e86df39dc283a3cb4c392239e5166ec4
https://github.com/nwops/puppet-retrospec/blob/89289ec0e86df39dc283a3cb4c392239e5166ec4/lib/retrospec/plugins/v1/plugin/puppet_module.rb#L148-L155
1,095
nwops/puppet-retrospec
lib/retrospec/plugins/v1/plugin/puppet_module.rb
Utilities.PuppetModule.request
def request(key, method) instance = ::Puppet::Indirector::Indirection.instance(:resource_type) indirection_name = 'test' @request = ::Puppet::Indirector::Request.new(indirection_name, method, key, instance) @request.environment = puppet_environment @request end
ruby
def request(key, method) instance = ::Puppet::Indirector::Indirection.instance(:resource_type) indirection_name = 'test' @request = ::Puppet::Indirector::Request.new(indirection_name, method, key, instance) @request.environment = puppet_environment @request end
[ "def", "request", "(", "key", ",", "method", ")", "instance", "=", "::", "Puppet", "::", "Indirector", "::", "Indirection", ".", "instance", "(", ":resource_type", ")", "indirection_name", "=", "'test'", "@request", "=", "::", "Puppet", "::", "Indirector", "::", "Request", ".", "new", "(", "indirection_name", ",", "method", ",", "key", ",", "instance", ")", "@request", ".", "environment", "=", "puppet_environment", "@request", "end" ]
creates a puppet resource request to be used indirectly
[ "creates", "a", "puppet", "resource", "request", "to", "be", "used", "indirectly" ]
89289ec0e86df39dc283a3cb4c392239e5166ec4
https://github.com/nwops/puppet-retrospec/blob/89289ec0e86df39dc283a3cb4c392239e5166ec4/lib/retrospec/plugins/v1/plugin/puppet_module.rb#L178-L184
1,096
airbnb/stemcell
lib/stemcell/launcher.rb
Stemcell.Launcher.render_template
def render_template(opts={}) template_file_path = File.expand_path(TEMPLATE_PATH, __FILE__) template_file = File.read(template_file_path) erb_template = ERB.new(template_file) last_bootstrap_line = LAST_BOOTSTRAP_LINE generated_template = erb_template.result(binding) @log.debug "genereated template is #{generated_template}" return generated_template end
ruby
def render_template(opts={}) template_file_path = File.expand_path(TEMPLATE_PATH, __FILE__) template_file = File.read(template_file_path) erb_template = ERB.new(template_file) last_bootstrap_line = LAST_BOOTSTRAP_LINE generated_template = erb_template.result(binding) @log.debug "genereated template is #{generated_template}" return generated_template end
[ "def", "render_template", "(", "opts", "=", "{", "}", ")", "template_file_path", "=", "File", ".", "expand_path", "(", "TEMPLATE_PATH", ",", "__FILE__", ")", "template_file", "=", "File", ".", "read", "(", "template_file_path", ")", "erb_template", "=", "ERB", ".", "new", "(", "template_file", ")", "last_bootstrap_line", "=", "LAST_BOOTSTRAP_LINE", "generated_template", "=", "erb_template", ".", "result", "(", "binding", ")", "@log", ".", "debug", "\"genereated template is #{generated_template}\"", "return", "generated_template", "end" ]
this is made public for ec2admin usage
[ "this", "is", "made", "public", "for", "ec2admin", "usage" ]
8427f6a1aad80c85393c0fb7d3f52ac8400b8207
https://github.com/airbnb/stemcell/blob/8427f6a1aad80c85393c0fb7d3f52ac8400b8207/lib/stemcell/launcher.rb#L245-L253
1,097
airbnb/stemcell
lib/stemcell/launcher.rb
Stemcell.Launcher.get_vpc_security_group_ids
def get_vpc_security_group_ids(vpc_id, group_names) group_map = {} @log.info "resolving security groups #{group_names} in #{vpc_id}" vpc = AWS::EC2::VPC.new(vpc_id, :ec2_endpoint => "ec2.#{@region}.amazonaws.com") vpc.security_groups.each do |sg| next if sg.vpc_id != vpc_id group_map[sg.name] = sg.group_id end group_ids = [] group_names.each do |sg_name| raise "Couldn't find security group #{sg_name} in #{vpc_id}" unless group_map.has_key?(sg_name) group_ids << group_map[sg_name] end group_ids end
ruby
def get_vpc_security_group_ids(vpc_id, group_names) group_map = {} @log.info "resolving security groups #{group_names} in #{vpc_id}" vpc = AWS::EC2::VPC.new(vpc_id, :ec2_endpoint => "ec2.#{@region}.amazonaws.com") vpc.security_groups.each do |sg| next if sg.vpc_id != vpc_id group_map[sg.name] = sg.group_id end group_ids = [] group_names.each do |sg_name| raise "Couldn't find security group #{sg_name} in #{vpc_id}" unless group_map.has_key?(sg_name) group_ids << group_map[sg_name] end group_ids end
[ "def", "get_vpc_security_group_ids", "(", "vpc_id", ",", "group_names", ")", "group_map", "=", "{", "}", "@log", ".", "info", "\"resolving security groups #{group_names} in #{vpc_id}\"", "vpc", "=", "AWS", "::", "EC2", "::", "VPC", ".", "new", "(", "vpc_id", ",", ":ec2_endpoint", "=>", "\"ec2.#{@region}.amazonaws.com\"", ")", "vpc", ".", "security_groups", ".", "each", "do", "|", "sg", "|", "next", "if", "sg", ".", "vpc_id", "!=", "vpc_id", "group_map", "[", "sg", ".", "name", "]", "=", "sg", ".", "group_id", "end", "group_ids", "=", "[", "]", "group_names", ".", "each", "do", "|", "sg_name", "|", "raise", "\"Couldn't find security group #{sg_name} in #{vpc_id}\"", "unless", "group_map", ".", "has_key?", "(", "sg_name", ")", "group_ids", "<<", "group_map", "[", "sg_name", "]", "end", "group_ids", "end" ]
Resolve security group names to their ids in the given VPC
[ "Resolve", "security", "group", "names", "to", "their", "ids", "in", "the", "given", "VPC" ]
8427f6a1aad80c85393c0fb7d3f52ac8400b8207
https://github.com/airbnb/stemcell/blob/8427f6a1aad80c85393c0fb7d3f52ac8400b8207/lib/stemcell/launcher.rb#L315-L329
1,098
logicminds/rubyipmi
lib/rubyipmi/commands/basecommand.rb
Rubyipmi.BaseCommand.runcmd
def runcmd @success = false @success = run logger.debug(@lastcall.inspect) unless @lastcall.nil? if logger logger.debug(@result) unless @result.nil? if logger @success end
ruby
def runcmd @success = false @success = run logger.debug(@lastcall.inspect) unless @lastcall.nil? if logger logger.debug(@result) unless @result.nil? if logger @success end
[ "def", "runcmd", "@success", "=", "false", "@success", "=", "run", "logger", ".", "debug", "(", "@lastcall", ".", "inspect", ")", "unless", "@lastcall", ".", "nil?", "if", "logger", "logger", ".", "debug", "(", "@result", ")", "unless", "@result", ".", "nil?", "if", "logger", "@success", "end" ]
Use this function to run the command line tool, it will inherently use the options hash for all options That need to be specified on the command line
[ "Use", "this", "function", "to", "run", "the", "command", "line", "tool", "it", "will", "inherently", "use", "the", "options", "hash", "for", "all", "options", "That", "need", "to", "be", "specified", "on", "the", "command", "line" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/commands/basecommand.rb#L50-L56
1,099
logicminds/rubyipmi
lib/rubyipmi/commands/basecommand.rb
Rubyipmi.BaseCommand.find_fix
def find_fix(result) return unless result # The errorcode code hash contains the fix begin fix = ErrorCodes.search(result) @options.merge_notify!(fix) rescue Rubyipmi.logger.debug("Could not find fix for error code: \n#{result}") if logger raise "Could not find fix for error code: \n#{result}" end end
ruby
def find_fix(result) return unless result # The errorcode code hash contains the fix begin fix = ErrorCodes.search(result) @options.merge_notify!(fix) rescue Rubyipmi.logger.debug("Could not find fix for error code: \n#{result}") if logger raise "Could not find fix for error code: \n#{result}" end end
[ "def", "find_fix", "(", "result", ")", "return", "unless", "result", "# The errorcode code hash contains the fix", "begin", "fix", "=", "ErrorCodes", ".", "search", "(", "result", ")", "@options", ".", "merge_notify!", "(", "fix", ")", "rescue", "Rubyipmi", ".", "logger", ".", "debug", "(", "\"Could not find fix for error code: \\n#{result}\"", ")", "if", "logger", "raise", "\"Could not find fix for error code: \\n#{result}\"", "end", "end" ]
The findfix method acts like a recursive method and applies fixes defined in the errorcodes If a fix is found it is applied to the options hash, and then the last run command is retried until all the fixes are exhausted or a error not defined in the errorcodes is found this must be overrided in the subclass, as there are no generic errors that fit both providers
[ "The", "findfix", "method", "acts", "like", "a", "recursive", "method", "and", "applies", "fixes", "defined", "in", "the", "errorcodes", "If", "a", "fix", "is", "found", "it", "is", "applied", "to", "the", "options", "hash", "and", "then", "the", "last", "run", "command", "is", "retried", "until", "all", "the", "fixes", "are", "exhausted", "or", "a", "error", "not", "defined", "in", "the", "errorcodes", "is", "found", "this", "must", "be", "overrided", "in", "the", "subclass", "as", "there", "are", "no", "generic", "errors", "that", "fit", "both", "providers" ]
516dfb0d5f8aa126159a5f5c25d60ab5c98f862f
https://github.com/logicminds/rubyipmi/blob/516dfb0d5f8aa126159a5f5c25d60ab5c98f862f/lib/rubyipmi/commands/basecommand.rb#L93-L103