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
300
epuber-io/epuber
lib/epuber/book.rb
Epuber.Book.targets
def targets(*names, &block) if names.empty? UI.warning('Book#targets to get all targets is deprecated, use #all_targets instead', location: caller_locations.first) return all_targets end names.map { |name| target(name, &block) } end
ruby
def targets(*names, &block) if names.empty? UI.warning('Book#targets to get all targets is deprecated, use #all_targets instead', location: caller_locations.first) return all_targets end names.map { |name| target(name, &block) } end
[ "def", "targets", "(", "*", "names", ",", "&", "block", ")", "if", "names", ".", "empty?", "UI", ".", "warning", "(", "'Book#targets to get all targets is deprecated, use #all_targets instead'", ",", "location", ":", "caller_locations", ".", "first", ")", "return", "all_targets", "end", "names", ".", "map", "{", "|", "name", "|", "target", "(", "name", ",", "block", ")", "}", "end" ]
Defines several new targets with same configuration @param [Array<String, Symbol>] names @return [Array<Target>] result target
[ "Defines", "several", "new", "targets", "with", "same", "configuration" ]
4d736deb3f18c034fc93fcb95cfb9bf03b63c252
https://github.com/epuber-io/epuber/blob/4d736deb3f18c034fc93fcb95cfb9bf03b63c252/lib/epuber/book.rb#L127-L134
301
zanker/ruby-smugmug
lib/smugmug/http.rb
SmugMug.HTTP.request
def request(api, args) uri = api == :uploading ? UPLOAD_URI : API_URI args[:method] = "smugmug.#{api}" unless api == :uploading http = ::Net::HTTP.new(uri.host, uri.port, @http_proxy_host, @http_proxy_port, @http_proxy_user, @http_proxy_pass) http.set_debug_output(@config[:debug_output]) if @config[:debug_output] # Configure HTTPS if needed if uri.scheme == "https" http.use_ssl = true if @config[:http] and @config[:http][:verify_mode] http.verify_mode = @config[:http][:verify_mode] http.ca_file = @config[:http][:ca_file] http.ca_path = @config[:http][:ca_path] else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end # Upload request, which requires special handling if api == :uploading postdata = args.delete(:content) headers = @headers.merge("Content-Length" => postdata.length.to_s, "Content-MD5" => Digest::MD5.hexdigest(postdata), "X-Smug-Version" => "1.3.0", "X-Smug-ResponseType" => "JSON") UPLOAD_HEADERS.each do |key| next unless args[key] and args[key] != "" headers["X-Smug-#{key}"] = args[key].to_s end oauth = self.sign_request("POST", uri, nil) headers["Authorization"] = "OAuth oauth_consumer_key=\"#{oauth["oauth_consumer_key"]}\", oauth_nonce=\"#{oauth["oauth_nonce"]}\", oauth_signature_method=\"#{oauth["oauth_signature_method"]}\", oauth_signature=\"#{oauth["oauth_signature"]}\", oauth_timestamp=\"#{oauth["oauth_timestamp"]}\", oauth_version=\"#{oauth["oauth_version"]}\", oauth_token=\"#{oauth["oauth_token"]}\"" # Normal API method else postdata = self.sign_request("POST", uri, args) headers = @headers end response = http.request_post(uri.request_uri, postdata, headers) if response.code == "204" return nil elsif response.code != "200" raise SmugMug::HTTPError.new("HTTP #{response.code}, #{response.message}", response.code, response.message) end # Check for GZIP encoding if response.header["content-encoding"] == "gzip" begin body = Zlib::GzipReader.new(StringIO.new(response.body)).read rescue Zlib::GzipFile::Error raise end else body = response.body end return nil if body == "" data = JSON.parse(body) if data["stat"] == "fail" # Special casing for SmugMug being in Read only mode if data["code"] == 99 raise SmugMug::ReadonlyModeError.new("SmugMug is currently in read only mode, try again later") end klass = OAUTH_ERRORS[data["code"]] ? SmugMug::OAuthError : SmugMug::RequestError raise klass.new("Error ##{data["code"]}, #{data["message"]}", data["code"], data["message"]) end data.delete("stat") data.delete("method") # smugmug.albums.changeSettings at the least doesn't return any data return nil if data.length == 0 # It seems all smugmug APIs only return one hash of data, so this should be fine and not cause issues data.each do |_, value| return value end end
ruby
def request(api, args) uri = api == :uploading ? UPLOAD_URI : API_URI args[:method] = "smugmug.#{api}" unless api == :uploading http = ::Net::HTTP.new(uri.host, uri.port, @http_proxy_host, @http_proxy_port, @http_proxy_user, @http_proxy_pass) http.set_debug_output(@config[:debug_output]) if @config[:debug_output] # Configure HTTPS if needed if uri.scheme == "https" http.use_ssl = true if @config[:http] and @config[:http][:verify_mode] http.verify_mode = @config[:http][:verify_mode] http.ca_file = @config[:http][:ca_file] http.ca_path = @config[:http][:ca_path] else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end # Upload request, which requires special handling if api == :uploading postdata = args.delete(:content) headers = @headers.merge("Content-Length" => postdata.length.to_s, "Content-MD5" => Digest::MD5.hexdigest(postdata), "X-Smug-Version" => "1.3.0", "X-Smug-ResponseType" => "JSON") UPLOAD_HEADERS.each do |key| next unless args[key] and args[key] != "" headers["X-Smug-#{key}"] = args[key].to_s end oauth = self.sign_request("POST", uri, nil) headers["Authorization"] = "OAuth oauth_consumer_key=\"#{oauth["oauth_consumer_key"]}\", oauth_nonce=\"#{oauth["oauth_nonce"]}\", oauth_signature_method=\"#{oauth["oauth_signature_method"]}\", oauth_signature=\"#{oauth["oauth_signature"]}\", oauth_timestamp=\"#{oauth["oauth_timestamp"]}\", oauth_version=\"#{oauth["oauth_version"]}\", oauth_token=\"#{oauth["oauth_token"]}\"" # Normal API method else postdata = self.sign_request("POST", uri, args) headers = @headers end response = http.request_post(uri.request_uri, postdata, headers) if response.code == "204" return nil elsif response.code != "200" raise SmugMug::HTTPError.new("HTTP #{response.code}, #{response.message}", response.code, response.message) end # Check for GZIP encoding if response.header["content-encoding"] == "gzip" begin body = Zlib::GzipReader.new(StringIO.new(response.body)).read rescue Zlib::GzipFile::Error raise end else body = response.body end return nil if body == "" data = JSON.parse(body) if data["stat"] == "fail" # Special casing for SmugMug being in Read only mode if data["code"] == 99 raise SmugMug::ReadonlyModeError.new("SmugMug is currently in read only mode, try again later") end klass = OAUTH_ERRORS[data["code"]] ? SmugMug::OAuthError : SmugMug::RequestError raise klass.new("Error ##{data["code"]}, #{data["message"]}", data["code"], data["message"]) end data.delete("stat") data.delete("method") # smugmug.albums.changeSettings at the least doesn't return any data return nil if data.length == 0 # It seems all smugmug APIs only return one hash of data, so this should be fine and not cause issues data.each do |_, value| return value end end
[ "def", "request", "(", "api", ",", "args", ")", "uri", "=", "api", "==", ":uploading", "?", "UPLOAD_URI", ":", "API_URI", "args", "[", ":method", "]", "=", "\"smugmug.#{api}\"", "unless", "api", "==", ":uploading", "http", "=", "::", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ",", "@http_proxy_host", ",", "@http_proxy_port", ",", "@http_proxy_user", ",", "@http_proxy_pass", ")", "http", ".", "set_debug_output", "(", "@config", "[", ":debug_output", "]", ")", "if", "@config", "[", ":debug_output", "]", "# Configure HTTPS if needed", "if", "uri", ".", "scheme", "==", "\"https\"", "http", ".", "use_ssl", "=", "true", "if", "@config", "[", ":http", "]", "and", "@config", "[", ":http", "]", "[", ":verify_mode", "]", "http", ".", "verify_mode", "=", "@config", "[", ":http", "]", "[", ":verify_mode", "]", "http", ".", "ca_file", "=", "@config", "[", ":http", "]", "[", ":ca_file", "]", "http", ".", "ca_path", "=", "@config", "[", ":http", "]", "[", ":ca_path", "]", "else", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "end", "# Upload request, which requires special handling", "if", "api", "==", ":uploading", "postdata", "=", "args", ".", "delete", "(", ":content", ")", "headers", "=", "@headers", ".", "merge", "(", "\"Content-Length\"", "=>", "postdata", ".", "length", ".", "to_s", ",", "\"Content-MD5\"", "=>", "Digest", "::", "MD5", ".", "hexdigest", "(", "postdata", ")", ",", "\"X-Smug-Version\"", "=>", "\"1.3.0\"", ",", "\"X-Smug-ResponseType\"", "=>", "\"JSON\"", ")", "UPLOAD_HEADERS", ".", "each", "do", "|", "key", "|", "next", "unless", "args", "[", "key", "]", "and", "args", "[", "key", "]", "!=", "\"\"", "headers", "[", "\"X-Smug-#{key}\"", "]", "=", "args", "[", "key", "]", ".", "to_s", "end", "oauth", "=", "self", ".", "sign_request", "(", "\"POST\"", ",", "uri", ",", "nil", ")", "headers", "[", "\"Authorization\"", "]", "=", "\"OAuth oauth_consumer_key=\\\"#{oauth[\"oauth_consumer_key\"]}\\\", oauth_nonce=\\\"#{oauth[\"oauth_nonce\"]}\\\", oauth_signature_method=\\\"#{oauth[\"oauth_signature_method\"]}\\\", oauth_signature=\\\"#{oauth[\"oauth_signature\"]}\\\", oauth_timestamp=\\\"#{oauth[\"oauth_timestamp\"]}\\\", oauth_version=\\\"#{oauth[\"oauth_version\"]}\\\", oauth_token=\\\"#{oauth[\"oauth_token\"]}\\\"\"", "# Normal API method", "else", "postdata", "=", "self", ".", "sign_request", "(", "\"POST\"", ",", "uri", ",", "args", ")", "headers", "=", "@headers", "end", "response", "=", "http", ".", "request_post", "(", "uri", ".", "request_uri", ",", "postdata", ",", "headers", ")", "if", "response", ".", "code", "==", "\"204\"", "return", "nil", "elsif", "response", ".", "code", "!=", "\"200\"", "raise", "SmugMug", "::", "HTTPError", ".", "new", "(", "\"HTTP #{response.code}, #{response.message}\"", ",", "response", ".", "code", ",", "response", ".", "message", ")", "end", "# Check for GZIP encoding", "if", "response", ".", "header", "[", "\"content-encoding\"", "]", "==", "\"gzip\"", "begin", "body", "=", "Zlib", "::", "GzipReader", ".", "new", "(", "StringIO", ".", "new", "(", "response", ".", "body", ")", ")", ".", "read", "rescue", "Zlib", "::", "GzipFile", "::", "Error", "raise", "end", "else", "body", "=", "response", ".", "body", "end", "return", "nil", "if", "body", "==", "\"\"", "data", "=", "JSON", ".", "parse", "(", "body", ")", "if", "data", "[", "\"stat\"", "]", "==", "\"fail\"", "# Special casing for SmugMug being in Read only mode", "if", "data", "[", "\"code\"", "]", "==", "99", "raise", "SmugMug", "::", "ReadonlyModeError", ".", "new", "(", "\"SmugMug is currently in read only mode, try again later\"", ")", "end", "klass", "=", "OAUTH_ERRORS", "[", "data", "[", "\"code\"", "]", "]", "?", "SmugMug", "::", "OAuthError", ":", "SmugMug", "::", "RequestError", "raise", "klass", ".", "new", "(", "\"Error ##{data[\"code\"]}, #{data[\"message\"]}\"", ",", "data", "[", "\"code\"", "]", ",", "data", "[", "\"message\"", "]", ")", "end", "data", ".", "delete", "(", "\"stat\"", ")", "data", ".", "delete", "(", "\"method\"", ")", "# smugmug.albums.changeSettings at the least doesn't return any data", "return", "nil", "if", "data", ".", "length", "==", "0", "# It seems all smugmug APIs only return one hash of data, so this should be fine and not cause issues", "data", ".", "each", "do", "|", "_", ",", "value", "|", "return", "value", "end", "end" ]
Creates a new HTTP wrapper to handle the network portions of the API requests @param [Hash] args Same as [SmugMug::HTTP]
[ "Creates", "a", "new", "HTTP", "wrapper", "to", "handle", "the", "network", "portions", "of", "the", "API", "requests" ]
97d38e3143ae89efa22bcb81676968da5c6afef5
https://github.com/zanker/ruby-smugmug/blob/97d38e3143ae89efa22bcb81676968da5c6afef5/lib/smugmug/http.rb#L35-L116
302
zanker/ruby-smugmug
lib/smugmug/http.rb
SmugMug.HTTP.sign_request
def sign_request(method, uri, form_args) # Convert non-string keys to strings so the sort works args = {} if form_args form_args.each do |key, value| next unless value and value != "" key = key.to_s unless key.is_a?(String) args[key] = value end end # Add the necessary OAuth args args["oauth_version"] = "1.0" args["oauth_consumer_key"] = @config[:api_key] args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}") args["oauth_signature_method"] = "HMAC-SHA1" args["oauth_timestamp"] = Time.now.utc.to_i args["oauth_token"] = @config[:user][:token] # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says: # # Thus, only alphanumerics, the special characters "$-_.+!*'(),", and # reserved characters used for their reserved purposes may be used # unencoded within a URL. # # However, if we don't escape apostrophes and parentheses the SmugMug API fails # with an invalid signature error: # # Error #35, invalid signature (SmugMug::OAuthError) # # To overcome this, define a new unreserved character list and use this in URI::escape unreserved = "\\-_.!~*a-zA-Z\\d" unsafe = Regexp.new("[^#{unreserved}]", false, 'N') # Sort the params sorted_args = [] args.sort.each do |key, value| sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}") end postdata = sorted_args.join("&") # Final string to hash sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}" signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base) signature = URI::escape(Base64.encode64(signature).chomp, unsafe) if uri == API_URI "#{postdata}&oauth_signature=#{signature}" else args["oauth_signature"] = signature args end end
ruby
def sign_request(method, uri, form_args) # Convert non-string keys to strings so the sort works args = {} if form_args form_args.each do |key, value| next unless value and value != "" key = key.to_s unless key.is_a?(String) args[key] = value end end # Add the necessary OAuth args args["oauth_version"] = "1.0" args["oauth_consumer_key"] = @config[:api_key] args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}") args["oauth_signature_method"] = "HMAC-SHA1" args["oauth_timestamp"] = Time.now.utc.to_i args["oauth_token"] = @config[:user][:token] # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says: # # Thus, only alphanumerics, the special characters "$-_.+!*'(),", and # reserved characters used for their reserved purposes may be used # unencoded within a URL. # # However, if we don't escape apostrophes and parentheses the SmugMug API fails # with an invalid signature error: # # Error #35, invalid signature (SmugMug::OAuthError) # # To overcome this, define a new unreserved character list and use this in URI::escape unreserved = "\\-_.!~*a-zA-Z\\d" unsafe = Regexp.new("[^#{unreserved}]", false, 'N') # Sort the params sorted_args = [] args.sort.each do |key, value| sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}") end postdata = sorted_args.join("&") # Final string to hash sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}" signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base) signature = URI::escape(Base64.encode64(signature).chomp, unsafe) if uri == API_URI "#{postdata}&oauth_signature=#{signature}" else args["oauth_signature"] = signature args end end
[ "def", "sign_request", "(", "method", ",", "uri", ",", "form_args", ")", "# Convert non-string keys to strings so the sort works", "args", "=", "{", "}", "if", "form_args", "form_args", ".", "each", "do", "|", "key", ",", "value", "|", "next", "unless", "value", "and", "value", "!=", "\"\"", "key", "=", "key", ".", "to_s", "unless", "key", ".", "is_a?", "(", "String", ")", "args", "[", "key", "]", "=", "value", "end", "end", "# Add the necessary OAuth args", "args", "[", "\"oauth_version\"", "]", "=", "\"1.0\"", "args", "[", "\"oauth_consumer_key\"", "]", "=", "@config", "[", ":api_key", "]", "args", "[", "\"oauth_nonce\"", "]", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{Time.now.to_f}#{rand(10 ** 30)}\"", ")", "args", "[", "\"oauth_signature_method\"", "]", "=", "\"HMAC-SHA1\"", "args", "[", "\"oauth_timestamp\"", "]", "=", "Time", ".", "now", ".", "utc", ".", "to_i", "args", "[", "\"oauth_token\"", "]", "=", "@config", "[", ":user", "]", "[", ":token", "]", "# RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says:", "#", "# Thus, only alphanumerics, the special characters \"$-_.+!*'(),\", and", "# reserved characters used for their reserved purposes may be used", "# unencoded within a URL.", "#", "# However, if we don't escape apostrophes and parentheses the SmugMug API fails", "# with an invalid signature error:", "#", "# Error #35, invalid signature (SmugMug::OAuthError)", "#", "# To overcome this, define a new unreserved character list and use this in URI::escape", "unreserved", "=", "\"\\\\-_.!~*a-zA-Z\\\\d\"", "unsafe", "=", "Regexp", ".", "new", "(", "\"[^#{unreserved}]\"", ",", "false", ",", "'N'", ")", "# Sort the params", "sorted_args", "=", "[", "]", "args", ".", "sort", ".", "each", "do", "|", "key", ",", "value", "|", "sorted_args", ".", "push", "(", "\"#{key.to_s}=#{URI::escape(value.to_s, unsafe)}\"", ")", "end", "postdata", "=", "sorted_args", ".", "join", "(", "\"&\"", ")", "# Final string to hash", "sig_base", "=", "\"#{method}&#{URI::escape(\"#{uri.scheme}://#{uri.host}#{uri.path}\", unsafe)}&#{URI::escape(postdata, unsafe)}\"", "signature", "=", "OpenSSL", "::", "HMAC", ".", "digest", "(", "@digest", ",", "\"#{@config[:oauth_secret]}&#{@config[:user][:secret]}\"", ",", "sig_base", ")", "signature", "=", "URI", "::", "escape", "(", "Base64", ".", "encode64", "(", "signature", ")", ".", "chomp", ",", "unsafe", ")", "if", "uri", "==", "API_URI", "\"#{postdata}&oauth_signature=#{signature}\"", "else", "args", "[", "\"oauth_signature\"", "]", "=", "signature", "args", "end", "end" ]
Generates an OAuth signature and updates the args with the required fields @param [String] method HTTP method that the request is sent as @param [String] uri Full URL of the request @param [Hash] form_args Args to be passed to the server
[ "Generates", "an", "OAuth", "signature", "and", "updates", "the", "args", "with", "the", "required", "fields" ]
97d38e3143ae89efa22bcb81676968da5c6afef5
https://github.com/zanker/ruby-smugmug/blob/97d38e3143ae89efa22bcb81676968da5c6afef5/lib/smugmug/http.rb#L123-L178
303
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.get_user_by_id
def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
ruby
def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
[ "def", "get_user_by_id", "(", "id", ")", "resp", "=", "request", "(", "'getUserByID'", ",", "userID", ":", "id", ")", "[", "'user'", "]", "resp", "[", "'user_id'", "]", ".", "nil?", "?", "nil", ":", "User", ".", "new", "(", "self", ",", "resp", ")", "end" ]
Find user by ID
[ "Find", "user", "by", "ID" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L26-L29
304
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.get_user_by_username
def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
ruby
def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
[ "def", "get_user_by_username", "(", "name", ")", "resp", "=", "request", "(", "'getUserByUsername'", ",", "username", ":", "name", ")", "[", "'user'", "]", "resp", "[", "'user_id'", "]", ".", "nil?", "?", "nil", ":", "User", ".", "new", "(", "self", ",", "resp", ")", "end" ]
Find user by username
[ "Find", "user", "by", "username" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L32-L35
305
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.popular_songs
def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end
ruby
def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end
[ "def", "popular_songs", "(", "type", "=", "'daily'", ")", "fail", "ArgumentError", ",", "'Invalid type'", "unless", "%w(", "daily", "monthly", ")", ".", "include?", "(", "type", ")", "request", "(", "'popularGetSongs'", ",", "type", ":", "type", ")", "[", "'songs'", "]", ".", "map", "{", "|", "s", "|", "Song", ".", "new", "(", "s", ")", "}", "end" ]
Get popular songs type => daily, monthly
[ "Get", "popular", "songs", "type", "=", ">", "daily", "monthly" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L47-L50
306
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.top_broadcasts
def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end
ruby
def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end
[ "def", "top_broadcasts", "(", "count", "=", "10", ")", "top_broadcasts", "=", "[", "]", "request", "(", "'getTopBroadcastsCombined'", ")", ".", "each", "do", "|", "key", ",", "_val", "|", "broadcast_id", "=", "key", ".", "split", "(", "':'", ")", "[", "1", "]", "top_broadcasts", ".", "push", "(", "Broadcast", ".", "new", "(", "self", ",", "broadcast_id", ")", ")", "count", "-=", "1", "break", "if", "count", "==", "0", "end", "top_broadcasts", "end" ]
Get top broadcasts count => specifies how many broadcasts to get
[ "Get", "top", "broadcasts", "count", "=", ">", "specifies", "how", "many", "broadcasts", "to", "get" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L54-L64
307
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.search
def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') results end
ruby
def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') results end
[ "def", "search", "(", "type", ",", "query", ")", "results", "=", "[", "]", "search", "=", "request", "(", "'getResultsFromSearch'", ",", "type", ":", "type", ",", "query", ":", "query", ")", "results", "=", "search", "[", "'result'", "]", ".", "map", "do", "|", "data", "|", "next", "Song", ".", "new", "data", "if", "type", "==", "'Songs'", "next", "Playlist", ".", "new", "(", "self", ",", "data", ")", "if", "type", "==", "'Playlists'", "data", "end", "if", "search", ".", "key?", "(", "'result'", ")", "results", "end" ]
Perform search request for query
[ "Perform", "search", "request", "for", "query" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L67-L76
308
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.get_stream_auth_by_songid
def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result == [] fail GeneralError, 'No data for this song. ' \ 'Maybe Grooveshark banned your IP.' end result end
ruby
def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result == [] fail GeneralError, 'No data for this song. ' \ 'Maybe Grooveshark banned your IP.' end result end
[ "def", "get_stream_auth_by_songid", "(", "song_id", ")", "result", "=", "request", "(", "'getStreamKeyFromSongIDEx'", ",", "'type'", "=>", "0", ",", "'prefetch'", "=>", "false", ",", "'songID'", "=>", "song_id", ",", "'country'", "=>", "@country", ",", "'mobile'", "=>", "false", ")", "if", "result", "==", "[", "]", "fail", "GeneralError", ",", "'No data for this song. '", "'Maybe Grooveshark banned your IP.'", "end", "result", "end" ]
Get stream authentication by song ID
[ "Get", "stream", "authentication", "by", "song", "ID" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L89-L101
309
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.request
def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' => 'application/json') rescue StandardError => ex raise GeneralError, ex.message end data = JSON.parse(data) data = data.normalize if data.is_a?(Hash) if data.key?('fault') fail ApiError, data['fault'] else data['result'] end end
ruby
def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' => 'application/json') rescue StandardError => ex raise GeneralError, ex.message end data = JSON.parse(data) data = data.normalize if data.is_a?(Hash) if data.key?('fault') fail ApiError, data['fault'] else data['result'] end end
[ "def", "request", "(", "method", ",", "params", "=", "{", "}", ",", "secure", "=", "false", ")", "refresh_token", "if", "@comm_token", "url", "=", "\"#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}\"", "begin", "data", "=", "RestClient", ".", "post", "(", "url", ",", "body", "(", "method", ",", "params", ")", ".", "to_json", ",", "'Content-Type'", "=>", "'application/json'", ")", "rescue", "StandardError", "=>", "ex", "raise", "GeneralError", ",", "ex", ".", "message", "end", "data", "=", "JSON", ".", "parse", "(", "data", ")", "data", "=", "data", ".", "normalize", "if", "data", ".", "is_a?", "(", "Hash", ")", "if", "data", ".", "key?", "(", "'fault'", ")", "fail", "ApiError", ",", "data", "[", "'fault'", "]", "else", "data", "[", "'result'", "]", "end", "end" ]
Perform API request
[ "Perform", "API", "request" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L171-L191
310
floriank/oeffi
lib/oeffi.rb
Oeffi.Configuration.provider=
def provider=(sym) klass = "#{sym.to_s.capitalize}Provider" begin java_import "de.schildbach.pte.#{klass}" @provider = Oeffi::const_get(klass).new rescue Exception => e raise "Unknown Provider name: #{klass}" end end
ruby
def provider=(sym) klass = "#{sym.to_s.capitalize}Provider" begin java_import "de.schildbach.pte.#{klass}" @provider = Oeffi::const_get(klass).new rescue Exception => e raise "Unknown Provider name: #{klass}" end end
[ "def", "provider", "=", "(", "sym", ")", "klass", "=", "\"#{sym.to_s.capitalize}Provider\"", "begin", "java_import", "\"de.schildbach.pte.#{klass}\"", "@provider", "=", "Oeffi", "::", "const_get", "(", "klass", ")", ".", "new", "rescue", "Exception", "=>", "e", "raise", "\"Unknown Provider name: #{klass}\"", "end", "end" ]
Configure a provider for the oeffi module Possible providers: :atc, :avv, :bahn, :bayern, :bsag, :bsvag, :bvb, :bvg, :ding, :dsb, :dub, :eireann, :gvh, :invg, :ivb, :kvv, :linz, :location, :lu, :maribor, :met, :mvg, :mvv, :naldo, :nasa, :nri, :ns, :nvbw, :nvv, :oebb, :pl, :rt, :sad, :sbb, :se, :septa, :sf, :sh, :sncb, :stockholm, :stv, :svv, :sydney, :tfi, :tfl, :tlem, :tlsw, :tlwm, :vagfr, :vbb, :vbl, :vbn, :vgn, :vgs, :vmobil, :vms, :vmv, :vor, :vrn, :vrr, :vrt, :vvm, :vvo, :vvs, :vvt, :vvv, :wien, :zvv
[ "Configure", "a", "provider", "for", "the", "oeffi", "module" ]
d129eb8be20ef5a7d4ebe24fc746b62b67de259b
https://github.com/floriank/oeffi/blob/d129eb8be20ef5a7d4ebe24fc746b62b67de259b/lib/oeffi.rb#L42-L50
311
4rlm/crm_formatter
lib/crm_formatter/address.rb
CrmFormatter.Address.check_addr_status
def check_addr_status(hsh) full_addr = hsh[:full_addr] full_addr_f = hsh[:full_addr_f] status = nil if full_addr && full_addr_f status = full_addr != full_addr_f ? 'formatted' : 'unchanged' end hsh[:address_status] = status hsh end
ruby
def check_addr_status(hsh) full_addr = hsh[:full_addr] full_addr_f = hsh[:full_addr_f] status = nil if full_addr && full_addr_f status = full_addr != full_addr_f ? 'formatted' : 'unchanged' end hsh[:address_status] = status hsh end
[ "def", "check_addr_status", "(", "hsh", ")", "full_addr", "=", "hsh", "[", ":full_addr", "]", "full_addr_f", "=", "hsh", "[", ":full_addr_f", "]", "status", "=", "nil", "if", "full_addr", "&&", "full_addr_f", "status", "=", "full_addr", "!=", "full_addr_f", "?", "'formatted'", ":", "'unchanged'", "end", "hsh", "[", ":address_status", "]", "=", "status", "hsh", "end" ]
COMPARE ORIGINAL AND FORMATTED ADR
[ "COMPARE", "ORIGINAL", "AND", "FORMATTED", "ADR" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/address.rb#L20-L31
312
4rlm/crm_formatter
lib/crm_formatter/address.rb
CrmFormatter.Address.make_full_address_original
def make_full_address_original(hsh) full_adr = [hsh[:street], hsh[:city], hsh[:state], hsh[:zip]].compact.join(', ') full_adr end
ruby
def make_full_address_original(hsh) full_adr = [hsh[:street], hsh[:city], hsh[:state], hsh[:zip]].compact.join(', ') full_adr end
[ "def", "make_full_address_original", "(", "hsh", ")", "full_adr", "=", "[", "hsh", "[", ":street", "]", ",", "hsh", "[", ":city", "]", ",", "hsh", "[", ":state", "]", ",", "hsh", "[", ":zip", "]", "]", ".", "compact", ".", "join", "(", "', '", ")", "full_adr", "end" ]
FORMAT FULL ADDRESS
[ "FORMAT", "FULL", "ADDRESS" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/address.rb#L34-L40
313
neopoly/redmine-more_view_hooks
lib/more_view_hooks/hook_collection.rb
MoreViewHooks.HookCollection.add
def add(name, options) fail ArgumentError, "A view hook '#{name}' already exists" if @hooks[name] context = options.delete(:context) hook = @hooks[name] = Hook.new(name, context, options) hook.apply! if @applied end
ruby
def add(name, options) fail ArgumentError, "A view hook '#{name}' already exists" if @hooks[name] context = options.delete(:context) hook = @hooks[name] = Hook.new(name, context, options) hook.apply! if @applied end
[ "def", "add", "(", "name", ",", "options", ")", "fail", "ArgumentError", ",", "\"A view hook '#{name}' already exists\"", "if", "@hooks", "[", "name", "]", "context", "=", "options", ".", "delete", "(", ":context", ")", "hook", "=", "@hooks", "[", "name", "]", "=", "Hook", ".", "new", "(", "name", ",", "context", ",", "options", ")", "hook", ".", "apply!", "if", "@applied", "end" ]
Registers a new view hook @param name [String] @param options [Hash] for Defaced
[ "Registers", "a", "new", "view", "hook" ]
816fff22ede91289cc47b4b80ac2f38873b6c839
https://github.com/neopoly/redmine-more_view_hooks/blob/816fff22ede91289cc47b4b80ac2f38873b6c839/lib/more_view_hooks/hook_collection.rb#L18-L23
314
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.add_node
def add_node(namespace_inc_global, body, opts = {}) data, _status_code, _headers = add_node_with_http_info(namespace_inc_global, body, opts) return data end
ruby
def add_node(namespace_inc_global, body, opts = {}) data, _status_code, _headers = add_node_with_http_info(namespace_inc_global, body, opts) return data end
[ "def", "add_node", "(", "namespace_inc_global", ",", "body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "add_node_with_http_info", "(", "namespace_inc_global", ",", "body", ",", "opts", ")", "return", "data", "end" ]
Add a node @param namespace_inc_global identifier namespacing the blueprint. `global` is a special namespace which references data from all blueprints in the call. @param body node @param [Hash] opts the optional parameters @return [NodeBody]
[ "Add", "a", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L29-L32
315
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.delete_node
def delete_node(namespace, id, type, opts = {}) delete_node_with_http_info(namespace, id, type, opts) return nil end
ruby
def delete_node(namespace, id, type, opts = {}) delete_node_with_http_info(namespace, id, type, opts) return nil end
[ "def", "delete_node", "(", "namespace", ",", "id", ",", "type", ",", "opts", "=", "{", "}", ")", "delete_node_with_http_info", "(", "namespace", ",", "id", ",", "type", ",", "opts", ")", "return", "nil", "end" ]
Delete a node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @return [nil]
[ "Delete", "a", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L169-L172
316
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.get_node
def get_node(namespace, id, type, opts = {}) data, _status_code, _headers = get_node_with_http_info(namespace, id, type, opts) return data end
ruby
def get_node(namespace, id, type, opts = {}) data, _status_code, _headers = get_node_with_http_info(namespace, id, type, opts) return data end
[ "def", "get_node", "(", "namespace", ",", "id", ",", "type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_node_with_http_info", "(", "namespace", ",", "id", ",", "type", ",", "opts", ")", "return", "data", "end" ]
Get details of a given node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @option opts [Array<String>] :include comma separated list of elements to hydrate. Can include children, parents, nodes, and/or assets @return [NodeBody]
[ "Get", "details", "of", "a", "given", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L691-L694
317
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.replace_node
def replace_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = replace_node_with_http_info(namespace, id, body, type, opts) return data end
ruby
def replace_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = replace_node_with_http_info(namespace, id, body, type, opts) return data end
[ "def", "replace_node", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "replace_node_with_http_info", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", ")", "return", "data", "end" ]
Replaces the node with the data sent in the body @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param body node @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @return [NodeBody]
[ "Replaces", "the", "node", "with", "the", "data", "sent", "in", "the", "body" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L888-L891
318
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.update_node
def update_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = update_node_with_http_info(namespace, id, body, type, opts) return data end
ruby
def update_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = update_node_with_http_info(namespace, id, body, type, opts) return data end
[ "def", "update_node", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_node_with_http_info", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", ")", "return", "data", "end" ]
Perform a partial update of a node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param body node @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @return [NodeBody]
[ "Perform", "a", "partial", "update", "of", "a", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L1219-L1222
319
berkshelf/berkshelf-hg
lib/berkshelf/locations/hg.rb
Berkshelf.HgLocation.install
def install if cached? # Update and checkout the correct ref Dir.chdir(cache_path) do hg %|pull| end else # Ensure the cache directory is present before doing anything FileUtils.mkdir_p(cache_path) Dir.chdir(cache_path) do hg %|clone #{uri} .| end end Dir.chdir(cache_path) do hg %|update --clean --rev #{revision || ref}| @revision ||= hg %|id -i| end # Gab the path where we should copy from (since it might be relative to # the root). copy_path = rel ? cache_path.join(rel) : cache_path begin # Validate the thing we are copying is a Chef cookbook validate_cached!(copy_path) # Remove the current cookbook at this location (this is required or else # FileUtils will copy into a subdirectory in the next step) FileUtils.rm_rf(install_path) # Create the containing parent directory FileUtils.mkdir_p(install_path.parent) # Copy whatever is in the current cache over to the store FileUtils.cp_r(copy_path, install_path) ensure # Remove the .hg directory to save storage space # TODO this can have huge performance implications, # make it a config option? if (hg_path = install_path.join('.hg')).exist? FileUtils.rm_r(hg_path) end FileUtils.rm_rf (copy_path) end end
ruby
def install if cached? # Update and checkout the correct ref Dir.chdir(cache_path) do hg %|pull| end else # Ensure the cache directory is present before doing anything FileUtils.mkdir_p(cache_path) Dir.chdir(cache_path) do hg %|clone #{uri} .| end end Dir.chdir(cache_path) do hg %|update --clean --rev #{revision || ref}| @revision ||= hg %|id -i| end # Gab the path where we should copy from (since it might be relative to # the root). copy_path = rel ? cache_path.join(rel) : cache_path begin # Validate the thing we are copying is a Chef cookbook validate_cached!(copy_path) # Remove the current cookbook at this location (this is required or else # FileUtils will copy into a subdirectory in the next step) FileUtils.rm_rf(install_path) # Create the containing parent directory FileUtils.mkdir_p(install_path.parent) # Copy whatever is in the current cache over to the store FileUtils.cp_r(copy_path, install_path) ensure # Remove the .hg directory to save storage space # TODO this can have huge performance implications, # make it a config option? if (hg_path = install_path.join('.hg')).exist? FileUtils.rm_r(hg_path) end FileUtils.rm_rf (copy_path) end end
[ "def", "install", "if", "cached?", "# Update and checkout the correct ref", "Dir", ".", "chdir", "(", "cache_path", ")", "do", "hg", "%|pull|", "end", "else", "# Ensure the cache directory is present before doing anything", "FileUtils", ".", "mkdir_p", "(", "cache_path", ")", "Dir", ".", "chdir", "(", "cache_path", ")", "do", "hg", "%|clone #{uri} .|", "end", "end", "Dir", ".", "chdir", "(", "cache_path", ")", "do", "hg", "%|update --clean --rev #{revision || ref}|", "@revision", "||=", "hg", "%|id -i|", "end", "# Gab the path where we should copy from (since it might be relative to", "# the root).", "copy_path", "=", "rel", "?", "cache_path", ".", "join", "(", "rel", ")", ":", "cache_path", "begin", "# Validate the thing we are copying is a Chef cookbook", "validate_cached!", "(", "copy_path", ")", "# Remove the current cookbook at this location (this is required or else", "# FileUtils will copy into a subdirectory in the next step)", "FileUtils", ".", "rm_rf", "(", "install_path", ")", "# Create the containing parent directory", "FileUtils", ".", "mkdir_p", "(", "install_path", ".", "parent", ")", "# Copy whatever is in the current cache over to the store", "FileUtils", ".", "cp_r", "(", "copy_path", ",", "install_path", ")", "ensure", "# Remove the .hg directory to save storage space", "# TODO this can have huge performance implications, ", "# make it a config option?", "if", "(", "hg_path", "=", "install_path", ".", "join", "(", "'.hg'", ")", ")", ".", "exist?", "FileUtils", ".", "rm_r", "(", "hg_path", ")", "end", "FileUtils", ".", "rm_rf", "(", "copy_path", ")", "end", "end" ]
Download the cookbook from the remote hg repository @return void
[ "Download", "the", "cookbook", "from", "the", "remote", "hg", "repository" ]
b60a022d34051533f20903fe8cbe102ac3f8b6b9
https://github.com/berkshelf/berkshelf-hg/blob/b60a022d34051533f20903fe8cbe102ac3f8b6b9/lib/berkshelf/locations/hg.rb#L58-L107
320
berkshelf/berkshelf-hg
lib/berkshelf/locations/hg.rb
Berkshelf.HgLocation.hg
def hg(command, error = true) unless Berkshelf.which('hg') || Berkshelf.which('hg.exe') raise HgNotInstalled.new end Berkshelf.log.debug("Running:hg #{command}") response = shell_out(%|hg #{command}|) Berkshelf.log.debug("response:hg #{response.stdout}") if response.error? raise HgCommandError.new(command, response, cache_path) end response.stdout.strip end
ruby
def hg(command, error = true) unless Berkshelf.which('hg') || Berkshelf.which('hg.exe') raise HgNotInstalled.new end Berkshelf.log.debug("Running:hg #{command}") response = shell_out(%|hg #{command}|) Berkshelf.log.debug("response:hg #{response.stdout}") if response.error? raise HgCommandError.new(command, response, cache_path) end response.stdout.strip end
[ "def", "hg", "(", "command", ",", "error", "=", "true", ")", "unless", "Berkshelf", ".", "which", "(", "'hg'", ")", "||", "Berkshelf", ".", "which", "(", "'hg.exe'", ")", "raise", "HgNotInstalled", ".", "new", "end", "Berkshelf", ".", "log", ".", "debug", "(", "\"Running:hg #{command}\"", ")", "response", "=", "shell_out", "(", "%|hg #{command}|", ")", "Berkshelf", ".", "log", ".", "debug", "(", "\"response:hg #{response.stdout}\"", ")", "if", "response", ".", "error?", "raise", "HgCommandError", ".", "new", "(", "command", ",", "response", ",", "cache_path", ")", "end", "response", ".", "stdout", ".", "strip", "end" ]
Perform a mercurial command. @param [String] command the command to run @param [Boolean] error whether to raise error if the command fails @raise [String] the +$stdout+ from the command
[ "Perform", "a", "mercurial", "command", "." ]
b60a022d34051533f20903fe8cbe102ac3f8b6b9
https://github.com/berkshelf/berkshelf-hg/blob/b60a022d34051533f20903fe8cbe102ac3f8b6b9/lib/berkshelf/locations/hg.rb#L159-L173
321
berkshelf/berkshelf-hg
lib/berkshelf/locations/hg.rb
Berkshelf.HgLocation.cache_path
def cache_path Pathname.new(Berkshelf.berkshelf_path) .join('.cache', 'hg', Digest::SHA1.hexdigest(uri)) end
ruby
def cache_path Pathname.new(Berkshelf.berkshelf_path) .join('.cache', 'hg', Digest::SHA1.hexdigest(uri)) end
[ "def", "cache_path", "Pathname", ".", "new", "(", "Berkshelf", ".", "berkshelf_path", ")", ".", "join", "(", "'.cache'", ",", "'hg'", ",", "Digest", "::", "SHA1", ".", "hexdigest", "(", "uri", ")", ")", "end" ]
The path where this hg repository is cached. @return [Pathname]
[ "The", "path", "where", "this", "hg", "repository", "is", "cached", "." ]
b60a022d34051533f20903fe8cbe102ac3f8b6b9
https://github.com/berkshelf/berkshelf-hg/blob/b60a022d34051533f20903fe8cbe102ac3f8b6b9/lib/berkshelf/locations/hg.rb#L194-L197
322
AgilTec/cadenero
app/controllers/cadenero/v1/account/sessions_controller.rb
Cadenero::V1.Account::SessionsController.create
def create if env['warden'].authenticate(:password, :scope => :user) #return the user JSON on success render json: current_user, status: :created else #return error mesage in a JSON on error render json: {errors: {user:["Invalid email or password"]}}, status: :unprocessable_entity end end
ruby
def create if env['warden'].authenticate(:password, :scope => :user) #return the user JSON on success render json: current_user, status: :created else #return error mesage in a JSON on error render json: {errors: {user:["Invalid email or password"]}}, status: :unprocessable_entity end end
[ "def", "create", "if", "env", "[", "'warden'", "]", ".", "authenticate", "(", ":password", ",", ":scope", "=>", ":user", ")", "#return the user JSON on success", "render", "json", ":", "current_user", ",", "status", ":", ":created", "else", "#return error mesage in a JSON on error", "render", "json", ":", "{", "errors", ":", "{", "user", ":", "[", "\"Invalid email or password\"", "]", "}", "}", ",", "status", ":", ":unprocessable_entity", "end", "end" ]
create the session for the user using the password strategy and returning the user JSON
[ "create", "the", "session", "for", "the", "user", "using", "the", "password", "strategy", "and", "returning", "the", "user", "JSON" ]
62449f160c48cce51cd8e97e5acad19f4a62be6c
https://github.com/AgilTec/cadenero/blob/62449f160c48cce51cd8e97e5acad19f4a62be6c/app/controllers/cadenero/v1/account/sessions_controller.rb#L7-L15
323
AgilTec/cadenero
app/controllers/cadenero/v1/account/sessions_controller.rb
Cadenero::V1.Account::SessionsController.delete
def delete user = Cadenero::User.find_by_id(params[:id]) if user_signed_in? env['warden'].logout(:user) render json: {message: "Successful logout"}, status: :ok else render json: {message: "Unsuccessful logout user with id"}, status: :forbidden end end
ruby
def delete user = Cadenero::User.find_by_id(params[:id]) if user_signed_in? env['warden'].logout(:user) render json: {message: "Successful logout"}, status: :ok else render json: {message: "Unsuccessful logout user with id"}, status: :forbidden end end
[ "def", "delete", "user", "=", "Cadenero", "::", "User", ".", "find_by_id", "(", "params", "[", ":id", "]", ")", "if", "user_signed_in?", "env", "[", "'warden'", "]", ".", "logout", "(", ":user", ")", "render", "json", ":", "{", "message", ":", "\"Successful logout\"", "}", ",", "status", ":", ":ok", "else", "render", "json", ":", "{", "message", ":", "\"Unsuccessful logout user with id\"", "}", ",", "status", ":", ":forbidden", "end", "end" ]
destroy the session for the user using params id
[ "destroy", "the", "session", "for", "the", "user", "using", "params", "id" ]
62449f160c48cce51cd8e97e5acad19f4a62be6c
https://github.com/AgilTec/cadenero/blob/62449f160c48cce51cd8e97e5acad19f4a62be6c/app/controllers/cadenero/v1/account/sessions_controller.rb#L18-L26
324
bunto/bunto-sitemap
lib/bunto/bunto-sitemap.rb
Bunto.BuntoSitemap.file_exists?
def file_exists?(file_path) if @site.respond_to?(:in_source_dir) File.exist? @site.in_source_dir(file_path) else File.exist? Bunto.sanitized_path(@site.source, file_path) end end
ruby
def file_exists?(file_path) if @site.respond_to?(:in_source_dir) File.exist? @site.in_source_dir(file_path) else File.exist? Bunto.sanitized_path(@site.source, file_path) end end
[ "def", "file_exists?", "(", "file_path", ")", "if", "@site", ".", "respond_to?", "(", ":in_source_dir", ")", "File", ".", "exist?", "@site", ".", "in_source_dir", "(", "file_path", ")", "else", "File", ".", "exist?", "Bunto", ".", "sanitized_path", "(", "@site", ".", "source", ",", "file_path", ")", "end", "end" ]
Checks if a file already exists in the site source
[ "Checks", "if", "a", "file", "already", "exists", "in", "the", "site", "source" ]
0ffa2fb5a1a8fe44815865e4e976d12957565fef
https://github.com/bunto/bunto-sitemap/blob/0ffa2fb5a1a8fe44815865e4e976d12957565fef/lib/bunto/bunto-sitemap.rb#L62-L68
325
riddler/riddler_admin
app/controllers/riddler_admin/steps_controller.rb
RiddlerAdmin.StepsController.internal_preview
def internal_preview @preview_context = ::RiddlerAdmin::PreviewContext.find_by_id params["pctx_id"] if @preview_context.nil? render(status: 400, json: {message: "Invalid pctx_id"}) and return end @use_case = ::Riddler::UseCases::AdminPreviewStep.new @step.definition_hash, preview_context_data: @preview_context.data @preview_hash = @use_case.process end
ruby
def internal_preview @preview_context = ::RiddlerAdmin::PreviewContext.find_by_id params["pctx_id"] if @preview_context.nil? render(status: 400, json: {message: "Invalid pctx_id"}) and return end @use_case = ::Riddler::UseCases::AdminPreviewStep.new @step.definition_hash, preview_context_data: @preview_context.data @preview_hash = @use_case.process end
[ "def", "internal_preview", "@preview_context", "=", "::", "RiddlerAdmin", "::", "PreviewContext", ".", "find_by_id", "params", "[", "\"pctx_id\"", "]", "if", "@preview_context", ".", "nil?", "render", "(", "status", ":", "400", ",", "json", ":", "{", "message", ":", "\"Invalid pctx_id\"", "}", ")", "and", "return", "end", "@use_case", "=", "::", "Riddler", "::", "UseCases", "::", "AdminPreviewStep", ".", "new", "@step", ".", "definition_hash", ",", "preview_context_data", ":", "@preview_context", ".", "data", "@preview_hash", "=", "@use_case", ".", "process", "end" ]
Should always comes from the admin tool
[ "Should", "always", "comes", "from", "the", "admin", "tool" ]
33eda9721e9df44ff0a0b2f2af4b755a2f49048d
https://github.com/riddler/riddler_admin/blob/33eda9721e9df44ff0a0b2f2af4b755a2f49048d/app/controllers/riddler_admin/steps_controller.rb#L35-L45
326
wurmlab/genevalidatorapp
lib/genevalidatorapp/config.rb
GeneValidatorApp.Config.write_config_file
def write_config_file return unless config_file File.open(config_file, 'w') do |f| f.puts(data.delete_if { |_, v| v.nil? }.to_yaml) end end
ruby
def write_config_file return unless config_file File.open(config_file, 'w') do |f| f.puts(data.delete_if { |_, v| v.nil? }.to_yaml) end end
[ "def", "write_config_file", "return", "unless", "config_file", "File", ".", "open", "(", "config_file", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "puts", "(", "data", ".", "delete_if", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", ".", "to_yaml", ")", "end", "end" ]
Write config data to config file.
[ "Write", "config", "data", "to", "config", "file", "." ]
78c3415a1f7c417b36ebecda753442b6ba6a2417
https://github.com/wurmlab/genevalidatorapp/blob/78c3415a1f7c417b36ebecda753442b6ba6a2417/lib/genevalidatorapp/config.rb#L37-L43
327
wurmlab/genevalidatorapp
lib/genevalidatorapp/config.rb
GeneValidatorApp.Config.symbolise
def symbolise(data) return {} unless data # Symbolize keys. Hash[data.map { |k, v| [k.to_sym, v] }] end
ruby
def symbolise(data) return {} unless data # Symbolize keys. Hash[data.map { |k, v| [k.to_sym, v] }] end
[ "def", "symbolise", "(", "data", ")", "return", "{", "}", "unless", "data", "# Symbolize keys.", "Hash", "[", "data", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_sym", ",", "v", "]", "}", "]", "end" ]
Symbolizes keys. Changes `database` key to `database_dir`.
[ "Symbolizes", "keys", ".", "Changes", "database", "key", "to", "database_dir", "." ]
78c3415a1f7c417b36ebecda753442b6ba6a2417
https://github.com/wurmlab/genevalidatorapp/blob/78c3415a1f7c417b36ebecda753442b6ba6a2417/lib/genevalidatorapp/config.rb#L48-L52
328
wurmlab/genevalidatorapp
lib/genevalidatorapp/config.rb
GeneValidatorApp.Config.defaults
def defaults { num_threads: 1, mafft_threads: 1, port: 5678, ssl: false, host: '0.0.0.0', serve_public_dir: File.join(Dir.home, '.genevalidatorapp/'), max_characters: 'undefined' } end
ruby
def defaults { num_threads: 1, mafft_threads: 1, port: 5678, ssl: false, host: '0.0.0.0', serve_public_dir: File.join(Dir.home, '.genevalidatorapp/'), max_characters: 'undefined' } end
[ "def", "defaults", "{", "num_threads", ":", "1", ",", "mafft_threads", ":", "1", ",", "port", ":", "5678", ",", "ssl", ":", "false", ",", "host", ":", "'0.0.0.0'", ",", "serve_public_dir", ":", "File", ".", "join", "(", "Dir", ".", "home", ",", "'.genevalidatorapp/'", ")", ",", "max_characters", ":", "'undefined'", "}", "end" ]
Default configuration data.
[ "Default", "configuration", "data", "." ]
78c3415a1f7c417b36ebecda753442b6ba6a2417
https://github.com/wurmlab/genevalidatorapp/blob/78c3415a1f7c417b36ebecda753442b6ba6a2417/lib/genevalidatorapp/config.rb#L73-L83
329
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Account.trustlines
def trustlines data = RippleRest .get("v1/accounts/#{@address}/trustlines")["trustlines"] .map(&Trustline.method(:new)) obj = Trustlines.new data obj.account = self obj end
ruby
def trustlines data = RippleRest .get("v1/accounts/#{@address}/trustlines")["trustlines"] .map(&Trustline.method(:new)) obj = Trustlines.new data obj.account = self obj end
[ "def", "trustlines", "data", "=", "RippleRest", ".", "get", "(", "\"v1/accounts/#{@address}/trustlines\"", ")", "[", "\"trustlines\"", "]", ".", "map", "(", "Trustline", ".", "method", "(", ":new", ")", ")", "obj", "=", "Trustlines", ".", "new", "data", "obj", ".", "account", "=", "self", "obj", "end" ]
Returns a Trustlines object for this account. @return [Trustlines] @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down
[ "Returns", "a", "Trustlines", "object", "for", "this", "account", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L31-L38
330
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Account.settings
def settings data = RippleRest.get("v1/accounts/#{@address}/settings")["settings"] obj = AccountSettings.new data obj.account = self obj end
ruby
def settings data = RippleRest.get("v1/accounts/#{@address}/settings")["settings"] obj = AccountSettings.new data obj.account = self obj end
[ "def", "settings", "data", "=", "RippleRest", ".", "get", "(", "\"v1/accounts/#{@address}/settings\"", ")", "[", "\"settings\"", "]", "obj", "=", "AccountSettings", ".", "new", "data", "obj", ".", "account", "=", "self", "obj", "end" ]
Returns a AccountSettings object for this account. @return [AccountSettings] @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down
[ "Returns", "a", "AccountSettings", "object", "for", "this", "account", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L44-L49
331
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Account.payments
def payments payments ||= lambda { obj = Payments.new obj.account = self obj }.call end
ruby
def payments payments ||= lambda { obj = Payments.new obj.account = self obj }.call end
[ "def", "payments", "payments", "||=", "lambda", "{", "obj", "=", "Payments", ".", "new", "obj", ".", "account", "=", "self", "obj", "}", ".", "call", "end" ]
Returns a Payments object for this account. @return [Payments]
[ "Returns", "a", "Payments", "object", "for", "this", "account", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L63-L69
332
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Payments.find_path
def find_path destination_account, destination_amount, source_currencies = nil uri = "v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}" if source_currencies cur = source_currencies.join(",") uri += "?source_currencies=#{cur}" end RippleRest.get(uri)["payments"].map(&Payment.method(:new)).each do |i| i.account = account end end
ruby
def find_path destination_account, destination_amount, source_currencies = nil uri = "v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}" if source_currencies cur = source_currencies.join(",") uri += "?source_currencies=#{cur}" end RippleRest.get(uri)["payments"].map(&Payment.method(:new)).each do |i| i.account = account end end
[ "def", "find_path", "destination_account", ",", "destination_amount", ",", "source_currencies", "=", "nil", "uri", "=", "\"v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}\"", "if", "source_currencies", "cur", "=", "source_currencies", ".", "join", "(", "\",\"", ")", "uri", "+=", "\"?source_currencies=#{cur}\"", "end", "RippleRest", ".", "get", "(", "uri", ")", "[", "\"payments\"", "]", ".", "map", "(", "Payment", ".", "method", "(", ":new", ")", ")", ".", "each", "do", "|", "i", "|", "i", ".", "account", "=", "account", "end", "end" ]
Query `rippled` for possible payment "paths" through the Ripple Network to deliver the given amount to the specified `destination_account`. If the `destination_amount` issuer is not specified, paths will be returned for all of the issuers from whom the `destination_account` accepts the given currency. @param destination_account [String, Account] destination account @param destination_amount [String, Amount] destination amount @param source_currencies [Array<String>] an array of source currencies that can be used to constrain the results returned (e.g. `["XRP", "USD+r...", "BTC+r..."]`) Currencies can be denoted by their currency code (e.g. USD) or by their currency code and issuer (e.g. `USD+r...`). If no issuer is specified for a currency other than XRP, the results will be limited to the specified currencies but any issuer for that currency will do. @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down @return [Array<Payment>]
[ "Query", "rippled", "for", "possible", "payment", "paths", "through", "the", "Ripple", "Network", "to", "deliver", "the", "given", "amount", "to", "the", "specified", "destination_account", ".", "If", "the", "destination_amount", "issuer", "is", "not", "specified", "paths", "will", "be", "returned", "for", "all", "of", "the", "issuers", "from", "whom", "the", "destination_account", "accepts", "the", "given", "currency", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L124-L135
333
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Payments.create
def create destination_account, destination_amount payment = Payment.new payment.account = account payment.destination_account = destination_account.to_s payment.destination_amount = Amount.from_string(destination_amount) payment end
ruby
def create destination_account, destination_amount payment = Payment.new payment.account = account payment.destination_account = destination_account.to_s payment.destination_amount = Amount.from_string(destination_amount) payment end
[ "def", "create", "destination_account", ",", "destination_amount", "payment", "=", "Payment", ".", "new", "payment", ".", "account", "=", "account", "payment", ".", "destination_account", "=", "destination_account", ".", "to_s", "payment", ".", "destination_amount", "=", "Amount", ".", "from_string", "(", "destination_amount", ")", "payment", "end" ]
Create a Payment object with some field filled. @return [Payment]
[ "Create", "a", "Payment", "object", "with", "some", "field", "filled", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L139-L145
334
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Payments.query
def query options = {} qs = "" if options && options.size > 0 qs = "?" + options.map { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&') end uri = "v1/accounts/#{account.address}/payments#{qs}" RippleRest.get(uri)["payments"].map do |i| payment = Payment.new(i["payment"]) payment.client_resource_id = i["client_resource_id"] payment end end
ruby
def query options = {} qs = "" if options && options.size > 0 qs = "?" + options.map { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&') end uri = "v1/accounts/#{account.address}/payments#{qs}" RippleRest.get(uri)["payments"].map do |i| payment = Payment.new(i["payment"]) payment.client_resource_id = i["client_resource_id"] payment end end
[ "def", "query", "options", "=", "{", "}", "qs", "=", "\"\"", "if", "options", "&&", "options", ".", "size", ">", "0", "qs", "=", "\"?\"", "+", "options", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{CGI::escape(v.to_s)}\"", "}", ".", "join", "(", "'&'", ")", "end", "uri", "=", "\"v1/accounts/#{account.address}/payments#{qs}\"", "RippleRest", ".", "get", "(", "uri", ")", "[", "\"payments\"", "]", ".", "map", "do", "|", "i", "|", "payment", "=", "Payment", ".", "new", "(", "i", "[", "\"payment\"", "]", ")", "payment", ".", "client_resource_id", "=", "i", "[", "\"client_resource_id\"", "]", "payment", "end", "end" ]
Browse historical payments in bulk. @option options [String, Account] :source_account If specified, limit the results to payments initiated by a particular account @option options [String, Account] :destination_account If specified, limit the results to payments made to a particular account @option options [Boolean] :exclude_failed if set to true, this will return only payment that were successfully validated and written into the Ripple Ledger @option options [String] :start_ledger If earliest_first is set to true this will be the index number of the earliest ledger queried, or the most recent one if earliest_first is set to false. Defaults to the first ledger the rippled has in its complete ledger. An error will be returned if this value is outside the rippled's complete ledger set @option options [String] :end_ledger If earliest_first is set to true this will be the index number of the most recent ledger queried, or the earliest one if earliest_first is set to false. Defaults to the last ledger the rippled has in its complete ledger. An error will be returned if this value is outside the rippled's complete ledger set @option options [Boolean] :earliest_first Determines the order in which the results should be displayed. Defaults to true @option options [Fixnum] :results_per_page Limits the number of resources displayed per page. Defaults to 20 @option options [Fixnum] :page The page to be displayed. If there are fewer than the results_per_page number displayed, this indicates that this is the last page @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down @return [Array<Payment>]
[ "Browse", "historical", "payments", "in", "bulk", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L159-L172
335
aaronroyer/qunited
lib/qunited/application.rb
QUnited.Application.handle_options
def handle_options drivers = ::QUnited::Driver.constants.reject { |d| d == :Base } valid_drivers_string = "Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}" args_empty = ARGV.empty? # This is a bit of a hack, but OptionParser removes the -- that separates the source # and test files and we need to put it back in the right place. Save the distance from # the end to do this later. double_dash_neg_index = ARGV.find_index('--') && (ARGV.find_index('--') - ARGV.size) optparse = OptionParser.new do |opts| opts.banner = <<-HELP_TEXT Usage: qunited [OPTIONS] [JS_SOURCE_FILES...] -- [JS_TEST_FILES..] Runs JavaScript unit tests with QUnit. JS_SOURCE_FILES are the JavaScript files that you want to test. They will all be loaded for running each test. JS_TEST_FILES are files that contain the QUnit tests to run. Options: HELP_TEXT opts.on('-d', '--driver [NAME]', 'Specify the driver to use in running the tests', valid_drivers_string) do |name| raise UsageError, 'Must specify a driver name with -d or --driver option' unless name names_and_drivers = Hash[drivers.map { |d| d.to_s.downcase }.zip(drivers)] driver = names_and_drivers[name.downcase] raise UsageError, "Invalid driver specified: #{name}\n#{valid_drivers_string}" unless driver options[:driver] = driver end opts.on('--fixtures [FILES]', 'Specify some files to include as html before running the tests') do |files| options[:fixture_files] = files.split(',') end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('--version', 'Print the QUnited version') do puts ::QUnited::VERSION exit end if args_empty puts opts exit 1 end end.parse! # Put the -- back in if we had one initially and it was removed if double_dash_neg_index && !ARGV.include?('--') ARGV.insert(double_dash_neg_index, '--') end end
ruby
def handle_options drivers = ::QUnited::Driver.constants.reject { |d| d == :Base } valid_drivers_string = "Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}" args_empty = ARGV.empty? # This is a bit of a hack, but OptionParser removes the -- that separates the source # and test files and we need to put it back in the right place. Save the distance from # the end to do this later. double_dash_neg_index = ARGV.find_index('--') && (ARGV.find_index('--') - ARGV.size) optparse = OptionParser.new do |opts| opts.banner = <<-HELP_TEXT Usage: qunited [OPTIONS] [JS_SOURCE_FILES...] -- [JS_TEST_FILES..] Runs JavaScript unit tests with QUnit. JS_SOURCE_FILES are the JavaScript files that you want to test. They will all be loaded for running each test. JS_TEST_FILES are files that contain the QUnit tests to run. Options: HELP_TEXT opts.on('-d', '--driver [NAME]', 'Specify the driver to use in running the tests', valid_drivers_string) do |name| raise UsageError, 'Must specify a driver name with -d or --driver option' unless name names_and_drivers = Hash[drivers.map { |d| d.to_s.downcase }.zip(drivers)] driver = names_and_drivers[name.downcase] raise UsageError, "Invalid driver specified: #{name}\n#{valid_drivers_string}" unless driver options[:driver] = driver end opts.on('--fixtures [FILES]', 'Specify some files to include as html before running the tests') do |files| options[:fixture_files] = files.split(',') end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('--version', 'Print the QUnited version') do puts ::QUnited::VERSION exit end if args_empty puts opts exit 1 end end.parse! # Put the -- back in if we had one initially and it was removed if double_dash_neg_index && !ARGV.include?('--') ARGV.insert(double_dash_neg_index, '--') end end
[ "def", "handle_options", "drivers", "=", "::", "QUnited", "::", "Driver", ".", "constants", ".", "reject", "{", "|", "d", "|", "d", "==", ":Base", "}", "valid_drivers_string", "=", "\"Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}\"", "args_empty", "=", "ARGV", ".", "empty?", "# This is a bit of a hack, but OptionParser removes the -- that separates the source", "# and test files and we need to put it back in the right place. Save the distance from", "# the end to do this later.", "double_dash_neg_index", "=", "ARGV", ".", "find_index", "(", "'--'", ")", "&&", "(", "ARGV", ".", "find_index", "(", "'--'", ")", "-", "ARGV", ".", "size", ")", "optparse", "=", "OptionParser", ".", "new", "do", "|", "opts", "|", "opts", ".", "banner", "=", "<<-HELP_TEXT", "HELP_TEXT", "opts", ".", "on", "(", "'-d'", ",", "'--driver [NAME]'", ",", "'Specify the driver to use in running the tests'", ",", "valid_drivers_string", ")", "do", "|", "name", "|", "raise", "UsageError", ",", "'Must specify a driver name with -d or --driver option'", "unless", "name", "names_and_drivers", "=", "Hash", "[", "drivers", ".", "map", "{", "|", "d", "|", "d", ".", "to_s", ".", "downcase", "}", ".", "zip", "(", "drivers", ")", "]", "driver", "=", "names_and_drivers", "[", "name", ".", "downcase", "]", "raise", "UsageError", ",", "\"Invalid driver specified: #{name}\\n#{valid_drivers_string}\"", "unless", "driver", "options", "[", ":driver", "]", "=", "driver", "end", "opts", ".", "on", "(", "'--fixtures [FILES]'", ",", "'Specify some files to include as html before running the tests'", ")", "do", "|", "files", "|", "options", "[", ":fixture_files", "]", "=", "files", ".", "split", "(", "','", ")", "end", "opts", ".", "on_tail", "(", "'-h'", ",", "'--help'", ",", "'Show this message'", ")", "do", "puts", "opts", "exit", "end", "opts", ".", "on_tail", "(", "'--version'", ",", "'Print the QUnited version'", ")", "do", "puts", "::", "QUnited", "::", "VERSION", "exit", "end", "if", "args_empty", "puts", "opts", "exit", "1", "end", "end", ".", "parse!", "# Put the -- back in if we had one initially and it was removed", "if", "double_dash_neg_index", "&&", "!", "ARGV", ".", "include?", "(", "'--'", ")", "ARGV", ".", "insert", "(", "double_dash_neg_index", ",", "'--'", ")", "end", "end" ]
Parse and handle command line options
[ "Parse", "and", "handle", "command", "line", "options" ]
2a47680a13a49bf8cc0aad2de12e6939e16c1495
https://github.com/aaronroyer/qunited/blob/2a47680a13a49bf8cc0aad2de12e6939e16c1495/lib/qunited/application.rb#L24-L81
336
ample/ample_assets
lib/ample_assets/view_helper.rb
AmpleAssets.ViewHelper.image_asset
def image_asset(object, args={}) # Gracefully handle nil return if object.try(:file).nil? && args[:object].nil? # Define default opts and merge with parameter args opts = { :alt => '', :video_dimensions => '500x350', :encode => :png }.merge(args) # Override alt text with object title if it exists opts[:alt] = escape_javascript(object.title) if object.respond_to?('title') # See if optional file object actually contains a dfly instance if opts[:object] attachment = opts[:object].attachment attachment_gravity = opts[:object].attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(opts[:object].alt_text) if opts[:object].respond_to?('alt_text') && !opts[:object].send(:alt_text).blank? else attachment = object.file.attachment attachment_gravity = object.file.attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(object.file.alt_text) if object.file.respond_to?('alt_text') && !object.file.send(:alt_text).blank? end # If this is a crop, try to add gravity if opts.try(:[], :dimensions) && opts[:dimensions].include?('#') # Strip out image geometry opts[:size] = /[0-9]{1,}x[0-9]{1,}/.match(opts[:dimensions]).try(:[], 0) width, height = opts[:size].split('x') image = attachment.process(:resize_and_crop, :width => width, :height => height, :gravity => attachment_gravity).encode(opts[:encode]) else image = opts.try(:[], :dimensions) ? attachment.process(:thumb, opts[:dimensions]).encode(opts[:encode]) : attachment.encode(opts[:encode]) end # Determine which opts ultimately get passed to image_tag valid_opts = [:alt, :class, :style, :title] valid_opts.push(:size) unless args[:size] == false # Create image tag img_tag = image_tag(image.url, opts.slice(*valid_opts)) # If this is a video link if opts[:video] link_to img_tag, opts[:link], :rel => 'facebox', :rev => "iframe|#{opts[:video_dimensions]}" else link_to_if opts[:link], img_tag, opts[:link] end end
ruby
def image_asset(object, args={}) # Gracefully handle nil return if object.try(:file).nil? && args[:object].nil? # Define default opts and merge with parameter args opts = { :alt => '', :video_dimensions => '500x350', :encode => :png }.merge(args) # Override alt text with object title if it exists opts[:alt] = escape_javascript(object.title) if object.respond_to?('title') # See if optional file object actually contains a dfly instance if opts[:object] attachment = opts[:object].attachment attachment_gravity = opts[:object].attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(opts[:object].alt_text) if opts[:object].respond_to?('alt_text') && !opts[:object].send(:alt_text).blank? else attachment = object.file.attachment attachment_gravity = object.file.attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(object.file.alt_text) if object.file.respond_to?('alt_text') && !object.file.send(:alt_text).blank? end # If this is a crop, try to add gravity if opts.try(:[], :dimensions) && opts[:dimensions].include?('#') # Strip out image geometry opts[:size] = /[0-9]{1,}x[0-9]{1,}/.match(opts[:dimensions]).try(:[], 0) width, height = opts[:size].split('x') image = attachment.process(:resize_and_crop, :width => width, :height => height, :gravity => attachment_gravity).encode(opts[:encode]) else image = opts.try(:[], :dimensions) ? attachment.process(:thumb, opts[:dimensions]).encode(opts[:encode]) : attachment.encode(opts[:encode]) end # Determine which opts ultimately get passed to image_tag valid_opts = [:alt, :class, :style, :title] valid_opts.push(:size) unless args[:size] == false # Create image tag img_tag = image_tag(image.url, opts.slice(*valid_opts)) # If this is a video link if opts[:video] link_to img_tag, opts[:link], :rel => 'facebox', :rev => "iframe|#{opts[:video_dimensions]}" else link_to_if opts[:link], img_tag, opts[:link] end end
[ "def", "image_asset", "(", "object", ",", "args", "=", "{", "}", ")", "# Gracefully handle nil", "return", "if", "object", ".", "try", "(", ":file", ")", ".", "nil?", "&&", "args", "[", ":object", "]", ".", "nil?", "# Define default opts and merge with parameter args", "opts", "=", "{", ":alt", "=>", "''", ",", ":video_dimensions", "=>", "'500x350'", ",", ":encode", "=>", ":png", "}", ".", "merge", "(", "args", ")", "# Override alt text with object title if it exists", "opts", "[", ":alt", "]", "=", "escape_javascript", "(", "object", ".", "title", ")", "if", "object", ".", "respond_to?", "(", "'title'", ")", "# See if optional file object actually contains a dfly instance", "if", "opts", "[", ":object", "]", "attachment", "=", "opts", "[", ":object", "]", ".", "attachment", "attachment_gravity", "=", "opts", "[", ":object", "]", ".", "attachment_gravity", "# Override alt text with attachment alt_text if it exists", "opts", "[", ":alt", "]", "=", "escape_javascript", "(", "opts", "[", ":object", "]", ".", "alt_text", ")", "if", "opts", "[", ":object", "]", ".", "respond_to?", "(", "'alt_text'", ")", "&&", "!", "opts", "[", ":object", "]", ".", "send", "(", ":alt_text", ")", ".", "blank?", "else", "attachment", "=", "object", ".", "file", ".", "attachment", "attachment_gravity", "=", "object", ".", "file", ".", "attachment_gravity", "# Override alt text with attachment alt_text if it exists", "opts", "[", ":alt", "]", "=", "escape_javascript", "(", "object", ".", "file", ".", "alt_text", ")", "if", "object", ".", "file", ".", "respond_to?", "(", "'alt_text'", ")", "&&", "!", "object", ".", "file", ".", "send", "(", ":alt_text", ")", ".", "blank?", "end", "# If this is a crop, try to add gravity", "if", "opts", ".", "try", "(", ":[]", ",", ":dimensions", ")", "&&", "opts", "[", ":dimensions", "]", ".", "include?", "(", "'#'", ")", "# Strip out image geometry", "opts", "[", ":size", "]", "=", "/", "/", ".", "match", "(", "opts", "[", ":dimensions", "]", ")", ".", "try", "(", ":[]", ",", "0", ")", "width", ",", "height", "=", "opts", "[", ":size", "]", ".", "split", "(", "'x'", ")", "image", "=", "attachment", ".", "process", "(", ":resize_and_crop", ",", ":width", "=>", "width", ",", ":height", "=>", "height", ",", ":gravity", "=>", "attachment_gravity", ")", ".", "encode", "(", "opts", "[", ":encode", "]", ")", "else", "image", "=", "opts", ".", "try", "(", ":[]", ",", ":dimensions", ")", "?", "attachment", ".", "process", "(", ":thumb", ",", "opts", "[", ":dimensions", "]", ")", ".", "encode", "(", "opts", "[", ":encode", "]", ")", ":", "attachment", ".", "encode", "(", "opts", "[", ":encode", "]", ")", "end", "# Determine which opts ultimately get passed to image_tag", "valid_opts", "=", "[", ":alt", ",", ":class", ",", ":style", ",", ":title", "]", "valid_opts", ".", "push", "(", ":size", ")", "unless", "args", "[", ":size", "]", "==", "false", "# Create image tag", "img_tag", "=", "image_tag", "(", "image", ".", "url", ",", "opts", ".", "slice", "(", "valid_opts", ")", ")", "# If this is a video link", "if", "opts", "[", ":video", "]", "link_to", "img_tag", ",", "opts", "[", ":link", "]", ",", ":rel", "=>", "'facebox'", ",", ":rev", "=>", "\"iframe|#{opts[:video_dimensions]}\"", "else", "link_to_if", "opts", "[", ":link", "]", ",", "img_tag", ",", "opts", "[", ":link", "]", "end", "end" ]
Returns image tag for an object's attachment, with optional link element wrapped around it. @param Object - Required @param String :alt - Defaults to object.title @param String :title @param String :class @param String :style @param String :dimensions - Dragonfly-esque dimensions... @see http://markevans.github.com/dragonfly/file.Processing.html @param String :link - Destination for link_to tag @param Symbol :encode - :gif, :jpg, :png, etc. Defaults to :png @param Object :object - Dragonfly object, defaults to object.file @param Boolean :video - Link to an iframe lightbox? @param String :video_dimensions - (width)x(height), defaults to 500x350
[ "Returns", "image", "tag", "for", "an", "object", "s", "attachment", "with", "optional", "link", "element", "wrapped", "around", "it", "." ]
54264a70f0b1920908d431ec67e73cf9a07844e2
https://github.com/ample/ample_assets/blob/54264a70f0b1920908d431ec67e73cf9a07844e2/lib/ample_assets/view_helper.rb#L26-L79
337
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_configs_api.rb
BlueprintClient.AssetTypeConfigsApi.get
def get(namespace, asset_type, opts = {}) data, _status_code, _headers = get_with_http_info(namespace, asset_type, opts) return data end
ruby
def get(namespace, asset_type, opts = {}) data, _status_code, _headers = get_with_http_info(namespace, asset_type, opts) return data end
[ "def", "get", "(", "namespace", ",", "asset_type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_with_http_info", "(", "namespace", ",", "asset_type", ",", "opts", ")", "return", "data", "end" ]
get a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param [Hash] opts the optional parameters @return [TemplateBody]
[ "get", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_configs_api.rb#L29-L32
338
bmulvihill/agglomerative_clustering
lib/agglomerative_clustering/silhouette_coefficient.rb
AgglomerativeClustering.SilhouetteCoefficient.measure
def measure clusters silhouettes = [] average_distances = [] main_cluster.points.each do |point1| a1 = calculate_a1(point1) (clusters - [main_cluster]).each do |cluster| distances = [] cluster.points.each do |point2| distances << euclidean_distance(point1, point2).round(2) end average_distances << distances.inject(:+)/distances.size end b1 = average_distances.min || 0 s1 = (b1 - a1)/[a1,b1].max silhouettes << s1 end (silhouettes.inject(:+) / silhouettes.size).round(2) end
ruby
def measure clusters silhouettes = [] average_distances = [] main_cluster.points.each do |point1| a1 = calculate_a1(point1) (clusters - [main_cluster]).each do |cluster| distances = [] cluster.points.each do |point2| distances << euclidean_distance(point1, point2).round(2) end average_distances << distances.inject(:+)/distances.size end b1 = average_distances.min || 0 s1 = (b1 - a1)/[a1,b1].max silhouettes << s1 end (silhouettes.inject(:+) / silhouettes.size).round(2) end
[ "def", "measure", "clusters", "silhouettes", "=", "[", "]", "average_distances", "=", "[", "]", "main_cluster", ".", "points", ".", "each", "do", "|", "point1", "|", "a1", "=", "calculate_a1", "(", "point1", ")", "(", "clusters", "-", "[", "main_cluster", "]", ")", ".", "each", "do", "|", "cluster", "|", "distances", "=", "[", "]", "cluster", ".", "points", ".", "each", "do", "|", "point2", "|", "distances", "<<", "euclidean_distance", "(", "point1", ",", "point2", ")", ".", "round", "(", "2", ")", "end", "average_distances", "<<", "distances", ".", "inject", "(", ":+", ")", "/", "distances", ".", "size", "end", "b1", "=", "average_distances", ".", "min", "||", "0", "s1", "=", "(", "b1", "-", "a1", ")", "/", "[", "a1", ",", "b1", "]", ".", "max", "silhouettes", "<<", "s1", "end", "(", "silhouettes", ".", "inject", "(", ":+", ")", "/", "silhouettes", ".", "size", ")", ".", "round", "(", "2", ")", "end" ]
Measures the silhouette coefficient of a cluster compared to all other clusters Returns the average silhouette coefficient of a cluster
[ "Measures", "the", "silhouette", "coefficient", "of", "a", "cluster", "compared", "to", "all", "other", "clusters", "Returns", "the", "average", "silhouette", "coefficient", "of", "a", "cluster" ]
bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77
https://github.com/bmulvihill/agglomerative_clustering/blob/bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77/lib/agglomerative_clustering/silhouette_coefficient.rb#L12-L29
339
bmulvihill/agglomerative_clustering
lib/agglomerative_clustering/silhouette_coefficient.rb
AgglomerativeClustering.SilhouetteCoefficient.calculate_a1
def calculate_a1 point distances = [] main_cluster.points.each do |point1| distances << euclidean_distance(point, point1).round(2) end return 0 if distances.size == 1 (distances.inject(:+)/(distances.size - 1)).round(2) end
ruby
def calculate_a1 point distances = [] main_cluster.points.each do |point1| distances << euclidean_distance(point, point1).round(2) end return 0 if distances.size == 1 (distances.inject(:+)/(distances.size - 1)).round(2) end
[ "def", "calculate_a1", "point", "distances", "=", "[", "]", "main_cluster", ".", "points", ".", "each", "do", "|", "point1", "|", "distances", "<<", "euclidean_distance", "(", "point", ",", "point1", ")", ".", "round", "(", "2", ")", "end", "return", "0", "if", "distances", ".", "size", "==", "1", "(", "distances", ".", "inject", "(", ":+", ")", "/", "(", "distances", ".", "size", "-", "1", ")", ")", ".", "round", "(", "2", ")", "end" ]
Calculates the a1 value of a cluster
[ "Calculates", "the", "a1", "value", "of", "a", "cluster" ]
bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77
https://github.com/bmulvihill/agglomerative_clustering/blob/bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77/lib/agglomerative_clustering/silhouette_coefficient.rb#L32-L39
340
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/common_methods.rb
ActsAsSolr.CommonMethods.get_solr_field_type
def get_solr_field_type(field_type) if field_type.is_a?(Symbol) t = TypeMapping[field_type] raise "Unknown field_type symbol: #{field_type}" if t.nil? t elsif field_type.is_a?(String) return field_type else raise "Unknown field_type class: #{field_type.class}: #{field_type}" end end
ruby
def get_solr_field_type(field_type) if field_type.is_a?(Symbol) t = TypeMapping[field_type] raise "Unknown field_type symbol: #{field_type}" if t.nil? t elsif field_type.is_a?(String) return field_type else raise "Unknown field_type class: #{field_type.class}: #{field_type}" end end
[ "def", "get_solr_field_type", "(", "field_type", ")", "if", "field_type", ".", "is_a?", "(", "Symbol", ")", "t", "=", "TypeMapping", "[", "field_type", "]", "raise", "\"Unknown field_type symbol: #{field_type}\"", "if", "t", ".", "nil?", "t", "elsif", "field_type", ".", "is_a?", "(", "String", ")", "return", "field_type", "else", "raise", "\"Unknown field_type class: #{field_type.class}: #{field_type}\"", "end", "end" ]
Converts field types into Solr types
[ "Converts", "field", "types", "into", "Solr", "types" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/common_methods.rb#L20-L30
341
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/common_methods.rb
ActsAsSolr.CommonMethods.solr_add
def solr_add(add_xml) ActsAsSolr::Post.execute(Solr::Request::AddDocument.new(add_xml)) end
ruby
def solr_add(add_xml) ActsAsSolr::Post.execute(Solr::Request::AddDocument.new(add_xml)) end
[ "def", "solr_add", "(", "add_xml", ")", "ActsAsSolr", "::", "Post", ".", "execute", "(", "Solr", "::", "Request", "::", "AddDocument", ".", "new", "(", "add_xml", ")", ")", "end" ]
Sends an add command to Solr
[ "Sends", "an", "add", "command", "to", "Solr" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/common_methods.rb#L44-L46
342
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/common_methods.rb
ActsAsSolr.CommonMethods.solr_delete
def solr_delete(solr_ids) ActsAsSolr::Post.execute(Solr::Request::Delete.new(:id => solr_ids)) end
ruby
def solr_delete(solr_ids) ActsAsSolr::Post.execute(Solr::Request::Delete.new(:id => solr_ids)) end
[ "def", "solr_delete", "(", "solr_ids", ")", "ActsAsSolr", "::", "Post", ".", "execute", "(", "Solr", "::", "Request", "::", "Delete", ".", "new", "(", ":id", "=>", "solr_ids", ")", ")", "end" ]
Sends the delete command to Solr
[ "Sends", "the", "delete", "command", "to", "Solr" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/common_methods.rb#L49-L51
343
redding/dk
lib/dk/remote.rb
Dk::Remote.BaseCmd.build_ssh_cmd_str
def build_ssh_cmd_str(cmd_str, host, args, host_args) Dk::Remote.ssh_cmd_str(cmd_str, host, args, host_args) end
ruby
def build_ssh_cmd_str(cmd_str, host, args, host_args) Dk::Remote.ssh_cmd_str(cmd_str, host, args, host_args) end
[ "def", "build_ssh_cmd_str", "(", "cmd_str", ",", "host", ",", "args", ",", "host_args", ")", "Dk", "::", "Remote", ".", "ssh_cmd_str", "(", "cmd_str", ",", "host", ",", "args", ",", "host_args", ")", "end" ]
escape everything properly; run in sh to ensure full profile is loaded
[ "escape", "everything", "properly", ";", "run", "in", "sh", "to", "ensure", "full", "profile", "is", "loaded" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/remote.rb#L82-L84
344
aaronroyer/qunited
lib/qunited/rake_task.rb
QUnited.RakeTask.files_array
def files_array(files) return [] unless files files.is_a?(Array) ? files : pattern_to_filelist(files.to_s) end
ruby
def files_array(files) return [] unless files files.is_a?(Array) ? files : pattern_to_filelist(files.to_s) end
[ "def", "files_array", "(", "files", ")", "return", "[", "]", "unless", "files", "files", ".", "is_a?", "(", "Array", ")", "?", "files", ":", "pattern_to_filelist", "(", "files", ".", "to_s", ")", "end" ]
Force convert to array of files if glob pattern
[ "Force", "convert", "to", "array", "of", "files", "if", "glob", "pattern" ]
2a47680a13a49bf8cc0aad2de12e6939e16c1495
https://github.com/aaronroyer/qunited/blob/2a47680a13a49bf8cc0aad2de12e6939e16c1495/lib/qunited/rake_task.rb#L151-L154
345
openplacos/openplacos
components/LibComponent.rb
LibComponent.Pin.introspect
def introspect iface = Hash.new pin = Hash.new meth = Array.new if self.respond_to?(:read) meth << "read" end if self.respond_to?(:write) meth << "write" end iface[@interface] = meth pin[@name] = iface return pin end
ruby
def introspect iface = Hash.new pin = Hash.new meth = Array.new if self.respond_to?(:read) meth << "read" end if self.respond_to?(:write) meth << "write" end iface[@interface] = meth pin[@name] = iface return pin end
[ "def", "introspect", "iface", "=", "Hash", ".", "new", "pin", "=", "Hash", ".", "new", "meth", "=", "Array", ".", "new", "if", "self", ".", "respond_to?", "(", ":read", ")", "meth", "<<", "\"read\"", "end", "if", "self", ".", "respond_to?", "(", ":write", ")", "meth", "<<", "\"write\"", "end", "iface", "[", "@interface", "]", "=", "meth", "pin", "[", "@name", "]", "=", "iface", "return", "pin", "end" ]
Return introspect object that can be delivered to openplacos server
[ "Return", "introspect", "object", "that", "can", "be", "delivered", "to", "openplacos", "server" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L27-L41
346
openplacos/openplacos
components/LibComponent.rb
LibComponent.Component.<<
def <<(pin_) if pin_.kind_of?(Input) @inputs << pin_ elsif pin_.kind_of?(Output) @outputs << pin_ elsif pin_.kind_of?(Array) # push an array of pin pin_.each { |p| self << p } end pin_.set_component(self) end
ruby
def <<(pin_) if pin_.kind_of?(Input) @inputs << pin_ elsif pin_.kind_of?(Output) @outputs << pin_ elsif pin_.kind_of?(Array) # push an array of pin pin_.each { |p| self << p } end pin_.set_component(self) end
[ "def", "<<", "(", "pin_", ")", "if", "pin_", ".", "kind_of?", "(", "Input", ")", "@inputs", "<<", "pin_", "elsif", "pin_", ".", "kind_of?", "(", "Output", ")", "@outputs", "<<", "pin_", "elsif", "pin_", ".", "kind_of?", "(", "Array", ")", "# push an array of pin", "pin_", ".", "each", "{", "|", "p", "|", "self", "<<", "p", "}", "end", "pin_", ".", "set_component", "(", "self", ")", "end" ]
Push pin to component
[ "Push", "pin", "to", "component" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L292-L304
347
openplacos/openplacos
components/LibComponent.rb
LibComponent.Component.run
def run # execute startup methods @inputs.each do |inp| inp.start if inp.respond_to?(:start) end @outputs.each do |outp| outp.start if outp.respond_to?(:start) end intro = introspect if @options[:introspect] print intro.to_yaml else @bus = create_bus #create dbus input pins dbusinputs = LibComponent::DbusInput.create_dbusinputs_from_introspect(intro["input"]["pin"],self) name = "org.openplacos.components.#{@name.downcase}" if (@bus.proxy.ListNames[0].member?(name)) quit_server(255, "#{name} already exists") end @service = @bus.request_service(name) dbusinputs.each { |pin| @service.export(pin) } #create and connect output pins if options[:debug] @dbusoutputs = LibComponent::DebugOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self) else @dbusoutputs = LibComponent::DbusOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self) @servicesignal = Servicesignal.new(@bus, self) # listen for service signal from server end Signal.trap('INT') do self.quit_callback end @main = DBus::Main.new @main << @bus @main.run end end
ruby
def run # execute startup methods @inputs.each do |inp| inp.start if inp.respond_to?(:start) end @outputs.each do |outp| outp.start if outp.respond_to?(:start) end intro = introspect if @options[:introspect] print intro.to_yaml else @bus = create_bus #create dbus input pins dbusinputs = LibComponent::DbusInput.create_dbusinputs_from_introspect(intro["input"]["pin"],self) name = "org.openplacos.components.#{@name.downcase}" if (@bus.proxy.ListNames[0].member?(name)) quit_server(255, "#{name} already exists") end @service = @bus.request_service(name) dbusinputs.each { |pin| @service.export(pin) } #create and connect output pins if options[:debug] @dbusoutputs = LibComponent::DebugOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self) else @dbusoutputs = LibComponent::DbusOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self) @servicesignal = Servicesignal.new(@bus, self) # listen for service signal from server end Signal.trap('INT') do self.quit_callback end @main = DBus::Main.new @main << @bus @main.run end end
[ "def", "run", "# execute startup methods", "@inputs", ".", "each", "do", "|", "inp", "|", "inp", ".", "start", "if", "inp", ".", "respond_to?", "(", ":start", ")", "end", "@outputs", ".", "each", "do", "|", "outp", "|", "outp", ".", "start", "if", "outp", ".", "respond_to?", "(", ":start", ")", "end", "intro", "=", "introspect", "if", "@options", "[", ":introspect", "]", "print", "intro", ".", "to_yaml", "else", "@bus", "=", "create_bus", "#create dbus input pins", "dbusinputs", "=", "LibComponent", "::", "DbusInput", ".", "create_dbusinputs_from_introspect", "(", "intro", "[", "\"input\"", "]", "[", "\"pin\"", "]", ",", "self", ")", "name", "=", "\"org.openplacos.components.#{@name.downcase}\"", "if", "(", "@bus", ".", "proxy", ".", "ListNames", "[", "0", "]", ".", "member?", "(", "name", ")", ")", "quit_server", "(", "255", ",", "\"#{name} already exists\"", ")", "end", "@service", "=", "@bus", ".", "request_service", "(", "name", ")", "dbusinputs", ".", "each", "{", "|", "pin", "|", "@service", ".", "export", "(", "pin", ")", "}", "#create and connect output pins", "if", "options", "[", ":debug", "]", "@dbusoutputs", "=", "LibComponent", "::", "DebugOutput", ".", "create_dbusoutputs_from_introspect", "(", "intro", "[", "\"output\"", "]", "[", "\"pin\"", "]", ",", "self", ")", "else", "@dbusoutputs", "=", "LibComponent", "::", "DbusOutput", ".", "create_dbusoutputs_from_introspect", "(", "intro", "[", "\"output\"", "]", "[", "\"pin\"", "]", ",", "self", ")", "@servicesignal", "=", "Servicesignal", ".", "new", "(", "@bus", ",", "self", ")", "# listen for service signal from server", "end", "Signal", ".", "trap", "(", "'INT'", ")", "do", "self", ".", "quit_callback", "end", "@main", "=", "DBus", "::", "Main", ".", "new", "@main", "<<", "@bus", "@main", ".", "run", "end", "end" ]
Let's rock! Run the component
[ "Let", "s", "rock!", "Run", "the", "component" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L315-L357
348
openplacos/openplacos
components/LibComponent.rb
LibComponent.Component.introspect
def introspect inputs_h = Hash.new outputs_h = Hash.new #call all inputs introspect and merge values @inputs.each { |input| inputs_h.merge!(input.introspect) { |key, old, new| old.merge(new) } } #call all outputs introspect and merge values @outputs.each { |output| outputs_h.merge!(output.introspect) { |key, old, new| old.merge(new) } } res = Hash.new res["input"] = {"pin" => inputs_h} res["output"] = {"pin" => outputs_h} # component options opt = @options.dup opt.delete(:introspect) opt.delete(:debug) optmod = Hash.new opt.each_pair do |key,value| optmod[key.to_s] = value end res["component"] ={"options" => optmod} # component description res["component"]["description"] = @description res["component"]["category"] = @category res["component"]["ttl"] = @ttl return res end
ruby
def introspect inputs_h = Hash.new outputs_h = Hash.new #call all inputs introspect and merge values @inputs.each { |input| inputs_h.merge!(input.introspect) { |key, old, new| old.merge(new) } } #call all outputs introspect and merge values @outputs.each { |output| outputs_h.merge!(output.introspect) { |key, old, new| old.merge(new) } } res = Hash.new res["input"] = {"pin" => inputs_h} res["output"] = {"pin" => outputs_h} # component options opt = @options.dup opt.delete(:introspect) opt.delete(:debug) optmod = Hash.new opt.each_pair do |key,value| optmod[key.to_s] = value end res["component"] ={"options" => optmod} # component description res["component"]["description"] = @description res["component"]["category"] = @category res["component"]["ttl"] = @ttl return res end
[ "def", "introspect", "inputs_h", "=", "Hash", ".", "new", "outputs_h", "=", "Hash", ".", "new", "#call all inputs introspect and merge values", "@inputs", ".", "each", "{", "|", "input", "|", "inputs_h", ".", "merge!", "(", "input", ".", "introspect", ")", "{", "|", "key", ",", "old", ",", "new", "|", "old", ".", "merge", "(", "new", ")", "}", "}", "#call all outputs introspect and merge values", "@outputs", ".", "each", "{", "|", "output", "|", "outputs_h", ".", "merge!", "(", "output", ".", "introspect", ")", "{", "|", "key", ",", "old", ",", "new", "|", "old", ".", "merge", "(", "new", ")", "}", "}", "res", "=", "Hash", ".", "new", "res", "[", "\"input\"", "]", "=", "{", "\"pin\"", "=>", "inputs_h", "}", "res", "[", "\"output\"", "]", "=", "{", "\"pin\"", "=>", "outputs_h", "}", "# component options", "opt", "=", "@options", ".", "dup", "opt", ".", "delete", "(", ":introspect", ")", "opt", ".", "delete", "(", ":debug", ")", "optmod", "=", "Hash", ".", "new", "opt", ".", "each_pair", "do", "|", "key", ",", "value", "|", "optmod", "[", "key", ".", "to_s", "]", "=", "value", "end", "res", "[", "\"component\"", "]", "=", "{", "\"options\"", "=>", "optmod", "}", "# component description", "res", "[", "\"component\"", "]", "[", "\"description\"", "]", "=", "@description", "res", "[", "\"component\"", "]", "[", "\"category\"", "]", "=", "@category", "res", "[", "\"component\"", "]", "[", "\"ttl\"", "]", "=", "@ttl", "return", "res", "end" ]
Parse inputs and outputs to communicate with server
[ "Parse", "inputs", "and", "outputs", "to", "communicate", "with", "server" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L367-L399
349
openplacos/openplacos
components/LibComponent.rb
LibComponent.Component.quit_server
def quit_server(status_, str_) $stderr.puts str_ if ([email protected]?) && !@options[:debug] bus = DBus::ASessionBus.new server = bus.service("org.openplacos.server.internal") opos = server.object("/plugins") opos.introspect opos.default_iface = "org.openplacos.plugins" opos.exit(status_, str_) else Process.exit 1 end end
ruby
def quit_server(status_, str_) $stderr.puts str_ if ([email protected]?) && !@options[:debug] bus = DBus::ASessionBus.new server = bus.service("org.openplacos.server.internal") opos = server.object("/plugins") opos.introspect opos.default_iface = "org.openplacos.plugins" opos.exit(status_, str_) else Process.exit 1 end end
[ "def", "quit_server", "(", "status_", ",", "str_", ")", "$stderr", ".", "puts", "str_", "if", "(", "!", "@options", ".", "nil?", ")", "&&", "!", "@options", "[", ":debug", "]", "bus", "=", "DBus", "::", "ASessionBus", ".", "new", "server", "=", "bus", ".", "service", "(", "\"org.openplacos.server.internal\"", ")", "opos", "=", "server", ".", "object", "(", "\"/plugins\"", ")", "opos", ".", "introspect", "opos", ".", "default_iface", "=", "\"org.openplacos.plugins\"", "opos", ".", "exit", "(", "status_", ",", "str_", ")", "else", "Process", ".", "exit", "1", "end", "end" ]
Print an error message and make the server quit
[ "Print", "an", "error", "message", "and", "make", "the", "server", "quit" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L437-L450
350
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/face_graph.rb
Zadt.FaceGraph.make_original_face
def make_original_face(num_edges) num_edges_check(num_edges) # Make the vertices vert_ref = Array.new(num_edges) {Vertex.new} edge_ref = [] # Connect each vertex to the one before it (including the first one :) (num_edges).times do |vert_id| edge_ref << make_connection(vert_ref[vert_id - 1], vert_ref[vert_id]) end # Make the face and store it face = add_face(edge_ref) # Store the new vertices @vertices += vert_ref # Store the new edges @edges += edge_ref face end
ruby
def make_original_face(num_edges) num_edges_check(num_edges) # Make the vertices vert_ref = Array.new(num_edges) {Vertex.new} edge_ref = [] # Connect each vertex to the one before it (including the first one :) (num_edges).times do |vert_id| edge_ref << make_connection(vert_ref[vert_id - 1], vert_ref[vert_id]) end # Make the face and store it face = add_face(edge_ref) # Store the new vertices @vertices += vert_ref # Store the new edges @edges += edge_ref face end
[ "def", "make_original_face", "(", "num_edges", ")", "num_edges_check", "(", "num_edges", ")", "# Make the vertices", "vert_ref", "=", "Array", ".", "new", "(", "num_edges", ")", "{", "Vertex", ".", "new", "}", "edge_ref", "=", "[", "]", "# Connect each vertex to the one before it (including the first one :)", "(", "num_edges", ")", ".", "times", "do", "|", "vert_id", "|", "edge_ref", "<<", "make_connection", "(", "vert_ref", "[", "vert_id", "-", "1", "]", ",", "vert_ref", "[", "vert_id", "]", ")", "end", "# Make the face and store it", "face", "=", "add_face", "(", "edge_ref", ")", "# Store the new vertices", "@vertices", "+=", "vert_ref", "# Store the new edges", "@edges", "+=", "edge_ref", "face", "end" ]
Makes a face with num_edges edges, which will be attached to nothing.
[ "Makes", "a", "face", "with", "num_edges", "edges", "which", "will", "be", "attached", "to", "nothing", "." ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L27-L46
351
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/face_graph.rb
Zadt.FaceGraph.add_attached_face
def add_attached_face(vertex_array, num_edges) vertex_array_check(vertex_array) num_edges_check(num_edges) # Make the vertices into a line vertex_line = confirm_vertex_line(vertex_array) # This finds the "ends" of the vertex line end_vertices = [vertex_line.first, vertex_line.last] # Find the neighbors that will be added later new_neighbors = find_neighbors(vertex_array) # How many vertices and edges to be made vertices_to_make = num_edges - vertex_array.length edges_to_make = vertices_to_make + 1 # Make new vertices vert_ref = Array.new(vertices_to_make) {Vertex.new} edge_ref = [] # Connect new vertices in a line (edges_to_make - 2).times do |vert_id| # Connect each vertex to the one after it edge_ref << make_connection(vert_ref[vert_id], vert_ref[vert_id + 1]) end # Connect "ends" of new vertices to "ends" of vertex line (making a circuit) # Connect "first" of new vertices to "last end" of old ones edge_ref << make_connection(vert_ref.first, end_vertices.last) # Connect "last" of new vertices to "first end" of old ones edge_ref << make_connection(vert_ref.last, end_vertices.first) # Add edges from vertex_line to edge_ref (vertex_line.length - 1).times do |vert_id| edge_ref << find_connection(vertex_line[vert_id], vertex_line[vert_id + 1]) end face_border = edge_ref # Make a face out of the new circuit, and store it face = add_face(face_border) # Store the new vertices @vertices += vert_ref # Store the new edges @edges += edge_ref face end
ruby
def add_attached_face(vertex_array, num_edges) vertex_array_check(vertex_array) num_edges_check(num_edges) # Make the vertices into a line vertex_line = confirm_vertex_line(vertex_array) # This finds the "ends" of the vertex line end_vertices = [vertex_line.first, vertex_line.last] # Find the neighbors that will be added later new_neighbors = find_neighbors(vertex_array) # How many vertices and edges to be made vertices_to_make = num_edges - vertex_array.length edges_to_make = vertices_to_make + 1 # Make new vertices vert_ref = Array.new(vertices_to_make) {Vertex.new} edge_ref = [] # Connect new vertices in a line (edges_to_make - 2).times do |vert_id| # Connect each vertex to the one after it edge_ref << make_connection(vert_ref[vert_id], vert_ref[vert_id + 1]) end # Connect "ends" of new vertices to "ends" of vertex line (making a circuit) # Connect "first" of new vertices to "last end" of old ones edge_ref << make_connection(vert_ref.first, end_vertices.last) # Connect "last" of new vertices to "first end" of old ones edge_ref << make_connection(vert_ref.last, end_vertices.first) # Add edges from vertex_line to edge_ref (vertex_line.length - 1).times do |vert_id| edge_ref << find_connection(vertex_line[vert_id], vertex_line[vert_id + 1]) end face_border = edge_ref # Make a face out of the new circuit, and store it face = add_face(face_border) # Store the new vertices @vertices += vert_ref # Store the new edges @edges += edge_ref face end
[ "def", "add_attached_face", "(", "vertex_array", ",", "num_edges", ")", "vertex_array_check", "(", "vertex_array", ")", "num_edges_check", "(", "num_edges", ")", "# Make the vertices into a line", "vertex_line", "=", "confirm_vertex_line", "(", "vertex_array", ")", "# This finds the \"ends\" of the vertex line", "end_vertices", "=", "[", "vertex_line", ".", "first", ",", "vertex_line", ".", "last", "]", "# Find the neighbors that will be added later", "new_neighbors", "=", "find_neighbors", "(", "vertex_array", ")", "# How many vertices and edges to be made", "vertices_to_make", "=", "num_edges", "-", "vertex_array", ".", "length", "edges_to_make", "=", "vertices_to_make", "+", "1", "# Make new vertices", "vert_ref", "=", "Array", ".", "new", "(", "vertices_to_make", ")", "{", "Vertex", ".", "new", "}", "edge_ref", "=", "[", "]", "# Connect new vertices in a line", "(", "edges_to_make", "-", "2", ")", ".", "times", "do", "|", "vert_id", "|", "# Connect each vertex to the one after it", "edge_ref", "<<", "make_connection", "(", "vert_ref", "[", "vert_id", "]", ",", "vert_ref", "[", "vert_id", "+", "1", "]", ")", "end", "# Connect \"ends\" of new vertices to \"ends\" of vertex line (making a circuit)", "# Connect \"first\" of new vertices to \"last end\" of old ones", "edge_ref", "<<", "make_connection", "(", "vert_ref", ".", "first", ",", "end_vertices", ".", "last", ")", "# Connect \"last\" of new vertices to \"first end\" of old ones", "edge_ref", "<<", "make_connection", "(", "vert_ref", ".", "last", ",", "end_vertices", ".", "first", ")", "# Add edges from vertex_line to edge_ref", "(", "vertex_line", ".", "length", "-", "1", ")", ".", "times", "do", "|", "vert_id", "|", "edge_ref", "<<", "find_connection", "(", "vertex_line", "[", "vert_id", "]", ",", "vertex_line", "[", "vert_id", "+", "1", "]", ")", "end", "face_border", "=", "edge_ref", "# Make a face out of the new circuit, and store it", "face", "=", "add_face", "(", "face_border", ")", "# Store the new vertices", "@vertices", "+=", "vert_ref", "# Store the new edges", "@edges", "+=", "edge_ref", "face", "end" ]
This adds a face that will be attached to the given vertices Make sure the vertices are connected, or it will raise an error All new vertices and edges will be created This will automatically make_neighbors with any faces that share a vertex with the new face
[ "This", "adds", "a", "face", "that", "will", "be", "attached", "to", "the", "given", "vertices", "Make", "sure", "the", "vertices", "are", "connected", "or", "it", "will", "raise", "an", "error", "All", "new", "vertices", "and", "edges", "will", "be", "created", "This", "will", "automatically", "make_neighbors", "with", "any", "faces", "that", "share", "a", "vertex", "with", "the", "new", "face" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L53-L95
352
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/face_graph.rb
Zadt.FaceGraph.find_neighbors
def find_neighbors(vertex_array) vertex_array_check(vertex_array) neighbors = [] vertex_array.each do |vertex| @faces.each do |face| neighbors << face if face.vertices.include?(vertex) end end neighbors.uniq end
ruby
def find_neighbors(vertex_array) vertex_array_check(vertex_array) neighbors = [] vertex_array.each do |vertex| @faces.each do |face| neighbors << face if face.vertices.include?(vertex) end end neighbors.uniq end
[ "def", "find_neighbors", "(", "vertex_array", ")", "vertex_array_check", "(", "vertex_array", ")", "neighbors", "=", "[", "]", "vertex_array", ".", "each", "do", "|", "vertex", "|", "@faces", ".", "each", "do", "|", "face", "|", "neighbors", "<<", "face", "if", "face", ".", "vertices", ".", "include?", "(", "vertex", ")", "end", "end", "neighbors", ".", "uniq", "end" ]
Return all faces containing the given vertices
[ "Return", "all", "faces", "containing", "the", "given", "vertices" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L98-L107
353
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/face_graph.rb
Zadt.FaceGraph.find_face_neighbors
def find_face_neighbors(face) raise "not a face" unless face.is_a?(Face) neighbors = find_neighbors(face.vertices) neighbors - [face] end
ruby
def find_face_neighbors(face) raise "not a face" unless face.is_a?(Face) neighbors = find_neighbors(face.vertices) neighbors - [face] end
[ "def", "find_face_neighbors", "(", "face", ")", "raise", "\"not a face\"", "unless", "face", ".", "is_a?", "(", "Face", ")", "neighbors", "=", "find_neighbors", "(", "face", ".", "vertices", ")", "neighbors", "-", "[", "face", "]", "end" ]
Return all neighbors of the given faces Neighbor is defined as sharing a vertex, not necessarily sharing an edge.
[ "Return", "all", "neighbors", "of", "the", "given", "faces", "Neighbor", "is", "defined", "as", "sharing", "a", "vertex", "not", "necessarily", "sharing", "an", "edge", "." ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L112-L116
354
4rlm/crm_formatter
lib/crm_formatter/proper.rb
CrmFormatter.Proper.check_proper_status
def check_proper_status(hsh) proper = hsh[:proper] proper_f = hsh[:proper_f] status = 'invalid' status = proper != proper_f ? 'formatted' : 'unchanged' if proper && proper_f hsh[:proper_status] = status if status.present? hsh end
ruby
def check_proper_status(hsh) proper = hsh[:proper] proper_f = hsh[:proper_f] status = 'invalid' status = proper != proper_f ? 'formatted' : 'unchanged' if proper && proper_f hsh[:proper_status] = status if status.present? hsh end
[ "def", "check_proper_status", "(", "hsh", ")", "proper", "=", "hsh", "[", ":proper", "]", "proper_f", "=", "hsh", "[", ":proper_f", "]", "status", "=", "'invalid'", "status", "=", "proper", "!=", "proper_f", "?", "'formatted'", ":", "'unchanged'", "if", "proper", "&&", "proper_f", "hsh", "[", ":proper_status", "]", "=", "status", "if", "status", ".", "present?", "hsh", "end" ]
COMPARE ORIGINAL AND FORMATTED PROPER
[ "COMPARE", "ORIGINAL", "AND", "FORMATTED", "PROPER" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/proper.rb#L13-L20
355
blambeau/finitio-rb
lib/finitio/type/union_type.rb
Finitio.UnionType.dress
def dress(value, handler = DressHelper.new) error = nil # Do nothing on TypeError as the next candidate could be the good one! candidates.each do |c| success, uped = handler.just_try do c.dress(value, handler) end return uped if success error ||= uped end # No one succeed, just fail handler.failed!(self, value, error) end
ruby
def dress(value, handler = DressHelper.new) error = nil # Do nothing on TypeError as the next candidate could be the good one! candidates.each do |c| success, uped = handler.just_try do c.dress(value, handler) end return uped if success error ||= uped end # No one succeed, just fail handler.failed!(self, value, error) end
[ "def", "dress", "(", "value", ",", "handler", "=", "DressHelper", ".", "new", ")", "error", "=", "nil", "# Do nothing on TypeError as the next candidate could be the good one!", "candidates", ".", "each", "do", "|", "c", "|", "success", ",", "uped", "=", "handler", ".", "just_try", "do", "c", ".", "dress", "(", "value", ",", "handler", ")", "end", "return", "uped", "if", "success", "error", "||=", "uped", "end", "# No one succeed, just fail", "handler", ".", "failed!", "(", "self", ",", "value", ",", "error", ")", "end" ]
Invoke `dress` on each candidate type in turn. Return the value returned by the first one that does not fail. Fail with an TypeError if no candidate succeeds at tranforming `value`.
[ "Invoke", "dress", "on", "each", "candidate", "type", "in", "turn", ".", "Return", "the", "value", "returned", "by", "the", "first", "one", "that", "does", "not", "fail", ".", "Fail", "with", "an", "TypeError", "if", "no", "candidate", "succeeds", "at", "tranforming", "value", "." ]
c07a3887a6af26b2ed1eb3c50b101e210d3d8b40
https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/type/union_type.rb#L53-L67
356
arrac/eluka
lib/eluka/feature_vector.rb
Eluka.FeatureVectors.define_features
def define_features @fvs.each do |vector, label| vector.each do |term, value| @features.add(term) end end end
ruby
def define_features @fvs.each do |vector, label| vector.each do |term, value| @features.add(term) end end end
[ "def", "define_features", "@fvs", ".", "each", "do", "|", "vector", ",", "label", "|", "vector", ".", "each", "do", "|", "term", ",", "value", "|", "@features", ".", "add", "(", "term", ")", "end", "end", "end" ]
For training data points we make sure all the features are added to the feature list
[ "For", "training", "data", "points", "we", "make", "sure", "all", "the", "features", "are", "added", "to", "the", "feature", "list" ]
1293f0cc6f9810a1a289ad74c8fab234db786212
https://github.com/arrac/eluka/blob/1293f0cc6f9810a1a289ad74c8fab234db786212/lib/eluka/feature_vector.rb#L41-L47
357
talis/blueprint_rb
lib/blueprint_ruby_client/api/integrations_api.rb
BlueprintClient.IntegrationsApi.add_integration
def add_integration(namespace, body, opts = {}) data, _status_code, _headers = add_integration_with_http_info(namespace, body, opts) return data end
ruby
def add_integration(namespace, body, opts = {}) data, _status_code, _headers = add_integration_with_http_info(namespace, body, opts) return data end
[ "def", "add_integration", "(", "namespace", ",", "body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "add_integration_with_http_info", "(", "namespace", ",", "body", ",", "opts", ")", "return", "data", "end" ]
Add an integration @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param body integration @param [Hash] opts the optional parameters @return [IntegrationBody]
[ "Add", "an", "integration" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L29-L32
358
talis/blueprint_rb
lib/blueprint_ruby_client/api/integrations_api.rb
BlueprintClient.IntegrationsApi.delete_integration
def delete_integration(namespace, integration_id, integration_type, opts = {}) delete_integration_with_http_info(namespace, integration_id, integration_type, opts) return nil end
ruby
def delete_integration(namespace, integration_id, integration_type, opts = {}) delete_integration_with_http_info(namespace, integration_id, integration_type, opts) return nil end
[ "def", "delete_integration", "(", "namespace", ",", "integration_id", ",", "integration_type", ",", "opts", "=", "{", "}", ")", "delete_integration_with_http_info", "(", "namespace", ",", "integration_id", ",", "integration_type", ",", "opts", ")", "return", "nil", "end" ]
Delete an integration @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param integration_id id of an integration @param integration_type Type of external integration, e.g. &#39;lti1&#39; @param [Hash] opts the optional parameters @return [nil]
[ "Delete", "an", "integration" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L105-L108
359
talis/blueprint_rb
lib/blueprint_ruby_client/api/integrations_api.rb
BlueprintClient.IntegrationsApi.get_integration
def get_integration(namespace, integration_type, integration_id, opts = {}) data, _status_code, _headers = get_integration_with_http_info(namespace, integration_type, integration_id, opts) return data end
ruby
def get_integration(namespace, integration_type, integration_id, opts = {}) data, _status_code, _headers = get_integration_with_http_info(namespace, integration_type, integration_id, opts) return data end
[ "def", "get_integration", "(", "namespace", ",", "integration_type", ",", "integration_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_integration_with_http_info", "(", "namespace", ",", "integration_type", ",", "integration_id", ",", "opts", ")", "return", "data", "end" ]
Get details of a given integration @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param integration_type Type of external integration, e.g. &#39;lti1&#39; @param integration_id id of an integration @param [Hash] opts the optional parameters @return [IntegrationBody]
[ "Get", "details", "of", "a", "given", "integration" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L189-L192
360
talis/blueprint_rb
lib/blueprint_ruby_client/api/integrations_api.rb
BlueprintClient.IntegrationsApi.replace_integration
def replace_integration(namespace, integration_id, integration_type, body, opts = {}) data, _status_code, _headers = replace_integration_with_http_info(namespace, integration_id, integration_type, body, opts) return data end
ruby
def replace_integration(namespace, integration_id, integration_type, body, opts = {}) data, _status_code, _headers = replace_integration_with_http_info(namespace, integration_id, integration_type, body, opts) return data end
[ "def", "replace_integration", "(", "namespace", ",", "integration_id", ",", "integration_type", ",", "body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "replace_integration_with_http_info", "(", "namespace", ",", "integration_id", ",", "integration_type", ",", "body", ",", "opts", ")", "return", "data", "end" ]
Replace an integration @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param integration_id id of an integration @param integration_type Type of external integration, e.g. &#39;lti1&#39; @param body integration @param [Hash] opts the optional parameters @return [IntegrationBody]
[ "Replace", "an", "integration" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L528-L531
361
JonnieCache/tinyci
lib/tinyci/git_utils.rb
TinyCI.GitUtils.repo_root
def repo_root return git_directory_path if inside_bare_repo? if inside_git_directory? File.expand_path('..', git_directory_path) elsif inside_work_tree? execute(git_cmd('rev-parse', '--show-toplevel')) else raise 'not in git directory or work tree!?' end end
ruby
def repo_root return git_directory_path if inside_bare_repo? if inside_git_directory? File.expand_path('..', git_directory_path) elsif inside_work_tree? execute(git_cmd('rev-parse', '--show-toplevel')) else raise 'not in git directory or work tree!?' end end
[ "def", "repo_root", "return", "git_directory_path", "if", "inside_bare_repo?", "if", "inside_git_directory?", "File", ".", "expand_path", "(", "'..'", ",", "git_directory_path", ")", "elsif", "inside_work_tree?", "execute", "(", "git_cmd", "(", "'rev-parse'", ",", "'--show-toplevel'", ")", ")", "else", "raise", "'not in git directory or work tree!?'", "end", "end" ]
Returns the absolute path to the root of the current git directory @return [String] the path
[ "Returns", "the", "absolute", "path", "to", "the", "root", "of", "the", "current", "git", "directory" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/git_utils.rb#L11-L21
362
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/parser_methods.rb
ActsAsSolr.ParserMethods.parse_results
def parse_results(solr_data, options = {}) results = { :docs => [], :total => 0 } configuration = { :format => :objects } results.update(:spellcheck => solr_data.data['spellcheck']) unless solr_data.nil? results.update(:facets => {'facet_fields' => []}) if options[:facets] unless solr_data.nil? or solr_data.header['params'].nil? header = solr_data.header results.update :rows => header['params']['rows'] results.update :start => header['params']['start'] end return SearchResults.new(results) if (solr_data.nil? || solr_data.total_hits == 0) configuration.update(options) if options.is_a?(Hash) ids = solr_data.hits.collect {|doc| doc["#{solr_configuration[:primary_key_field]}"]}.flatten result = find_objects(ids, options, configuration) add_scores(result, solr_data) if configuration[:format] == :objects && options[:scores] highlighted = {} solr_data.highlighting.map do |x,y| e={} y1=y.map{|x1,y1| e[x1.gsub(/_[^_]*/,"")]=y1} unless y.nil? highlighted[x.gsub(/[^:]*:/,"").to_i]=e end unless solr_data.highlighting.nil? results.update(:facets => solr_data.data['facet_counts']) if options[:facets] results.update({:docs => result, :total => solr_data.total_hits, :max_score => solr_data.max_score, :query_time => solr_data.data['responseHeader']['QTime']}) results.update({:highlights=>highlighted}) SearchResults.new(results) end
ruby
def parse_results(solr_data, options = {}) results = { :docs => [], :total => 0 } configuration = { :format => :objects } results.update(:spellcheck => solr_data.data['spellcheck']) unless solr_data.nil? results.update(:facets => {'facet_fields' => []}) if options[:facets] unless solr_data.nil? or solr_data.header['params'].nil? header = solr_data.header results.update :rows => header['params']['rows'] results.update :start => header['params']['start'] end return SearchResults.new(results) if (solr_data.nil? || solr_data.total_hits == 0) configuration.update(options) if options.is_a?(Hash) ids = solr_data.hits.collect {|doc| doc["#{solr_configuration[:primary_key_field]}"]}.flatten result = find_objects(ids, options, configuration) add_scores(result, solr_data) if configuration[:format] == :objects && options[:scores] highlighted = {} solr_data.highlighting.map do |x,y| e={} y1=y.map{|x1,y1| e[x1.gsub(/_[^_]*/,"")]=y1} unless y.nil? highlighted[x.gsub(/[^:]*:/,"").to_i]=e end unless solr_data.highlighting.nil? results.update(:facets => solr_data.data['facet_counts']) if options[:facets] results.update({:docs => result, :total => solr_data.total_hits, :max_score => solr_data.max_score, :query_time => solr_data.data['responseHeader']['QTime']}) results.update({:highlights=>highlighted}) SearchResults.new(results) end
[ "def", "parse_results", "(", "solr_data", ",", "options", "=", "{", "}", ")", "results", "=", "{", ":docs", "=>", "[", "]", ",", ":total", "=>", "0", "}", "configuration", "=", "{", ":format", "=>", ":objects", "}", "results", ".", "update", "(", ":spellcheck", "=>", "solr_data", ".", "data", "[", "'spellcheck'", "]", ")", "unless", "solr_data", ".", "nil?", "results", ".", "update", "(", ":facets", "=>", "{", "'facet_fields'", "=>", "[", "]", "}", ")", "if", "options", "[", ":facets", "]", "unless", "solr_data", ".", "nil?", "or", "solr_data", ".", "header", "[", "'params'", "]", ".", "nil?", "header", "=", "solr_data", ".", "header", "results", ".", "update", ":rows", "=>", "header", "[", "'params'", "]", "[", "'rows'", "]", "results", ".", "update", ":start", "=>", "header", "[", "'params'", "]", "[", "'start'", "]", "end", "return", "SearchResults", ".", "new", "(", "results", ")", "if", "(", "solr_data", ".", "nil?", "||", "solr_data", ".", "total_hits", "==", "0", ")", "configuration", ".", "update", "(", "options", ")", "if", "options", ".", "is_a?", "(", "Hash", ")", "ids", "=", "solr_data", ".", "hits", ".", "collect", "{", "|", "doc", "|", "doc", "[", "\"#{solr_configuration[:primary_key_field]}\"", "]", "}", ".", "flatten", "result", "=", "find_objects", "(", "ids", ",", "options", ",", "configuration", ")", "add_scores", "(", "result", ",", "solr_data", ")", "if", "configuration", "[", ":format", "]", "==", ":objects", "&&", "options", "[", ":scores", "]", "highlighted", "=", "{", "}", "solr_data", ".", "highlighting", ".", "map", "do", "|", "x", ",", "y", "|", "e", "=", "{", "}", "y1", "=", "y", ".", "map", "{", "|", "x1", ",", "y1", "|", "e", "[", "x1", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", "]", "=", "y1", "}", "unless", "y", ".", "nil?", "highlighted", "[", "x", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "to_i", "]", "=", "e", "end", "unless", "solr_data", ".", "highlighting", ".", "nil?", "results", ".", "update", "(", ":facets", "=>", "solr_data", ".", "data", "[", "'facet_counts'", "]", ")", "if", "options", "[", ":facets", "]", "results", ".", "update", "(", "{", ":docs", "=>", "result", ",", ":total", "=>", "solr_data", ".", "total_hits", ",", ":max_score", "=>", "solr_data", ".", "max_score", ",", ":query_time", "=>", "solr_data", ".", "data", "[", "'responseHeader'", "]", "[", "'QTime'", "]", "}", ")", "results", ".", "update", "(", "{", ":highlights", "=>", "highlighted", "}", ")", "SearchResults", ".", "new", "(", "results", ")", "end" ]
Parses the data returned from Solr
[ "Parses", "the", "data", "returned", "from", "Solr" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/parser_methods.rb#L134-L171
363
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/parser_methods.rb
ActsAsSolr.ParserMethods.reorder
def reorder(things, ids) ordered_things = [] ids.each do |id| thing = things.find{ |t| t.id.to_s == id.to_s } ordered_things |= [thing] if thing end ordered_things end
ruby
def reorder(things, ids) ordered_things = [] ids.each do |id| thing = things.find{ |t| t.id.to_s == id.to_s } ordered_things |= [thing] if thing end ordered_things end
[ "def", "reorder", "(", "things", ",", "ids", ")", "ordered_things", "=", "[", "]", "ids", ".", "each", "do", "|", "id", "|", "thing", "=", "things", ".", "find", "{", "|", "t", "|", "t", ".", "id", ".", "to_s", "==", "id", ".", "to_s", "}", "ordered_things", "|=", "[", "thing", "]", "if", "thing", "end", "ordered_things", "end" ]
Reorders the instances keeping the order returned from Solr
[ "Reorders", "the", "instances", "keeping", "the", "order", "returned", "from", "Solr" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/parser_methods.rb#L191-L198
364
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/parser_methods.rb
ActsAsSolr.ParserMethods.add_scores
def add_scores(results, solr_data) with_score = [] solr_data.hits.each do |doc| with_score.push([doc["score"], results.find {|record| scorable_record?(record, doc) }]) end with_score.each do |score, object| class << object; attr_accessor :solr_score; end object.solr_score = score end end
ruby
def add_scores(results, solr_data) with_score = [] solr_data.hits.each do |doc| with_score.push([doc["score"], results.find {|record| scorable_record?(record, doc) }]) end with_score.each do |score, object| class << object; attr_accessor :solr_score; end object.solr_score = score end end
[ "def", "add_scores", "(", "results", ",", "solr_data", ")", "with_score", "=", "[", "]", "solr_data", ".", "hits", ".", "each", "do", "|", "doc", "|", "with_score", ".", "push", "(", "[", "doc", "[", "\"score\"", "]", ",", "results", ".", "find", "{", "|", "record", "|", "scorable_record?", "(", "record", ",", "doc", ")", "}", "]", ")", "end", "with_score", ".", "each", "do", "|", "score", ",", "object", "|", "class", "<<", "object", ";", "attr_accessor", ":solr_score", ";", "end", "object", ".", "solr_score", "=", "score", "end", "end" ]
Adds the score to each one of the instances found
[ "Adds", "the", "score", "to", "each", "one", "of", "the", "instances", "found" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/parser_methods.rb#L223-L233
365
4rlm/crm_formatter
lib/crm_formatter/web.rb
CrmFormatter.Web.check_web_status
def check_web_status(hsh) status = 'invalid' if hsh[:web_neg]&.include?('error') if hsh[:url] && hsh[:url_f] && status.nil? status = hsh[:url] != hsh[:url_f] ? 'formatted' : 'unchanged' end hsh[:web_status] = status if status.present? hsh end
ruby
def check_web_status(hsh) status = 'invalid' if hsh[:web_neg]&.include?('error') if hsh[:url] && hsh[:url_f] && status.nil? status = hsh[:url] != hsh[:url_f] ? 'formatted' : 'unchanged' end hsh[:web_status] = status if status.present? hsh end
[ "def", "check_web_status", "(", "hsh", ")", "status", "=", "'invalid'", "if", "hsh", "[", ":web_neg", "]", "&.", "include?", "(", "'error'", ")", "if", "hsh", "[", ":url", "]", "&&", "hsh", "[", ":url_f", "]", "&&", "status", ".", "nil?", "status", "=", "hsh", "[", ":url", "]", "!=", "hsh", "[", ":url_f", "]", "?", "'formatted'", ":", "'unchanged'", "end", "hsh", "[", ":web_status", "]", "=", "status", "if", "status", ".", "present?", "hsh", "end" ]
COMPARE ORIGINAL AND FORMATTED URL
[ "COMPARE", "ORIGINAL", "AND", "FORMATTED", "URL" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/web.rb#L31-L40
366
4rlm/crm_formatter
lib/crm_formatter/web.rb
CrmFormatter.Web.extract_path
def extract_path(url_hash) path_parts = url_hash[:url_f].split('//').last.split('/')[1..-1] path = "/#{path_parts.join('/')}" if path&.length > 2 url_hash[:url_path] = path url_hash[:url_f] = url_hash[:url_f].gsub(url_hash[:url_path], '') end url_hash end
ruby
def extract_path(url_hash) path_parts = url_hash[:url_f].split('//').last.split('/')[1..-1] path = "/#{path_parts.join('/')}" if path&.length > 2 url_hash[:url_path] = path url_hash[:url_f] = url_hash[:url_f].gsub(url_hash[:url_path], '') end url_hash end
[ "def", "extract_path", "(", "url_hash", ")", "path_parts", "=", "url_hash", "[", ":url_f", "]", ".", "split", "(", "'//'", ")", ".", "last", ".", "split", "(", "'/'", ")", "[", "1", "..", "-", "1", "]", "path", "=", "\"/#{path_parts.join('/')}\"", "if", "path", "&.", "length", ">", "2", "url_hash", "[", ":url_path", "]", "=", "path", "url_hash", "[", ":url_f", "]", "=", "url_hash", "[", ":url_f", "]", ".", "gsub", "(", "url_hash", "[", ":url_path", "]", ",", "''", ")", "end", "url_hash", "end" ]
Supporting Methods Below
[ "Supporting", "Methods", "Below" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/web.rb#L143-L151
367
justintanner/column_pack
lib/column_pack/view_helpers.rb
ColumnPack.ViewHelpers.pack_element
def pack_element(height, content = nil, &block) return if @column_packer.nil? if block_given? @column_packer.add(height.to_i, capture(&block)) else @column_packer.add(height.to_i, content) end end
ruby
def pack_element(height, content = nil, &block) return if @column_packer.nil? if block_given? @column_packer.add(height.to_i, capture(&block)) else @column_packer.add(height.to_i, content) end end
[ "def", "pack_element", "(", "height", ",", "content", "=", "nil", ",", "&", "block", ")", "return", "if", "@column_packer", ".", "nil?", "if", "block_given?", "@column_packer", ".", "add", "(", "height", ".", "to_i", ",", "capture", "(", "block", ")", ")", "else", "@column_packer", ".", "add", "(", "height", ".", "to_i", ",", "content", ")", "end", "end" ]
Packs a single element with a given height into a column. pack_element should be called withing pack_in_columns's block: pack_in_columns(3) do pack_element(100) do "A" end end Accepts parameter strings or block content (ERB, strings, etc).
[ "Packs", "a", "single", "element", "with", "a", "given", "height", "into", "a", "column", "." ]
bffe22f74063718fdcf7b9c5dce1001ceabe8046
https://github.com/justintanner/column_pack/blob/bffe22f74063718fdcf7b9c5dce1001ceabe8046/lib/column_pack/view_helpers.rb#L40-L48
368
LAS-IT/ps_utilities
lib/ps_utilities/pre_built_post.rb
PsUtilities.PreBuiltPost.u_students_extension
def u_students_extension(data) db_extensions = { "name"=>"u_students_extension", "recordFound"=>false, "_field"=> [] } data.each do |key, value| db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"} end db_extensions end
ruby
def u_students_extension(data) db_extensions = { "name"=>"u_students_extension", "recordFound"=>false, "_field"=> [] } data.each do |key, value| db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"} end db_extensions end
[ "def", "u_students_extension", "(", "data", ")", "db_extensions", "=", "{", "\"name\"", "=>", "\"u_students_extension\"", ",", "\"recordFound\"", "=>", "false", ",", "\"_field\"", "=>", "[", "]", "}", "data", ".", "each", "do", "|", "key", ",", "value", "|", "db_extensions", "[", "\"_field\"", "]", "<<", "{", "\"name\"", "=>", "\"#{key}\"", ",", "\"type\"", "=>", "\"String\"", ",", "\"value\"", "=>", "\"#{value}\"", "}", "end", "db_extensions", "end" ]
prepare data to update student database extensions @param data [Hash] - with the format: {u_students_extension: {field1: data1, field2: data2}} @return [Hash] - with data like below: { "name"=>"u_students_extension", "recordFound"=>false, "_field"=> [ {"name"=>"preferredname", "type"=>"String", "value"=>"Joe"}, {"name"=>"student_email", "type"=>"String", "value"=>"[email protected]"}, ] }
[ "prepare", "data", "to", "update", "student", "database", "extensions" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_post.rb#L124-L131
369
LAS-IT/ps_utilities
lib/ps_utilities/pre_built_post.rb
PsUtilities.PreBuiltPost.u_studentsuserfields
def u_studentsuserfields(data) db_extensions = { "name"=>"u_studentsuserfields", "recordFound"=>false, "_field"=> [] } data.each do |key, value| db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"} end db_extensions end
ruby
def u_studentsuserfields(data) db_extensions = { "name"=>"u_studentsuserfields", "recordFound"=>false, "_field"=> [] } data.each do |key, value| db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"} end db_extensions end
[ "def", "u_studentsuserfields", "(", "data", ")", "db_extensions", "=", "{", "\"name\"", "=>", "\"u_studentsuserfields\"", ",", "\"recordFound\"", "=>", "false", ",", "\"_field\"", "=>", "[", "]", "}", "data", ".", "each", "do", "|", "key", ",", "value", "|", "db_extensions", "[", "\"_field\"", "]", "<<", "{", "\"name\"", "=>", "\"#{key}\"", ",", "\"type\"", "=>", "\"String\"", ",", "\"value\"", "=>", "\"#{value}\"", "}", "end", "db_extensions", "end" ]
prepare data to built-in database extensions @param data [Hash] - with the format: {u_studentsuserfields: {field1: data1, field2: data2}} @return [Hash] - with data like below: { "name"=>"u_students_extension", "recordFound"=>false, "_field"=> [ {"name"=>"transcriptaddrzip", "type"=>"String", "value"=>75230}, {"name"=>"transcriptaddrcountry", "type"=>"String", "value"=>"United States"}, {"name"=>"transcriptaddrcity", "type"=>"String", "value"=>"dallas"}, {"name"=>"transcriptaddrstate", "type"=>"String", "value"=>"Texas"}, {"name"=>"transcriptaddrline1", "type"=>"String", "value"=>"6138 meadow rd"} ] }
[ "prepare", "data", "to", "built", "-", "in", "database", "extensions" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_post.rb#L146-L153
370
trampoline/rews
lib/rews/util.rb
Rews.Util.strip_bang
def strip_bang(k) if k.is_a? Symbol k.to_s[0...-1].to_sym else k.to_s[0...-1] end end
ruby
def strip_bang(k) if k.is_a? Symbol k.to_s[0...-1].to_sym else k.to_s[0...-1] end end
[ "def", "strip_bang", "(", "k", ")", "if", "k", ".", "is_a?", "Symbol", "k", ".", "to_s", "[", "0", "...", "-", "1", "]", ".", "to_sym", "else", "k", ".", "to_s", "[", "0", "...", "-", "1", "]", "end", "end" ]
strip a ! from the end of a +String+ or +Symbol+
[ "strip", "a", "!", "from", "the", "end", "of", "a", "+", "String", "+", "or", "+", "Symbol", "+" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L48-L54
371
trampoline/rews
lib/rews/util.rb
Rews.Util.camelize
def camelize(s) if s.is_a?(Symbol) s.to_s.split('_').map(&:capitalize).join.to_sym else s.split('_').map(&:capitalize).join end end
ruby
def camelize(s) if s.is_a?(Symbol) s.to_s.split('_').map(&:capitalize).join.to_sym else s.split('_').map(&:capitalize).join end end
[ "def", "camelize", "(", "s", ")", "if", "s", ".", "is_a?", "(", "Symbol", ")", "s", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize", ")", ".", "join", ".", "to_sym", "else", "s", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize", ")", ".", "join", "end", "end" ]
camel-case a +String+
[ "camel", "-", "case", "a", "+", "String", "+" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L57-L63
372
trampoline/rews
lib/rews/util.rb
Rews.Util.camel_keys
def camel_keys(h) Hash[h.map{|k,v| [camelize(k.to_s), v]}] end
ruby
def camel_keys(h) Hash[h.map{|k,v| [camelize(k.to_s), v]}] end
[ "def", "camel_keys", "(", "h", ")", "Hash", "[", "h", ".", "map", "{", "|", "k", ",", "v", "|", "[", "camelize", "(", "k", ".", "to_s", ")", ",", "v", "]", "}", "]", "end" ]
camel-case the keys of a +Hash+
[ "camel", "-", "case", "the", "keys", "of", "a", "+", "Hash", "+" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L66-L68
373
trampoline/rews
lib/rews/util.rb
Rews.Util.apply_namespace
def apply_namespace(qname, apply_prefix, apply_uri) local_part, prefix, uri = qname if !prefix prefix = apply_prefix uri = apply_uri end [local_part, prefix, uri].compact end
ruby
def apply_namespace(qname, apply_prefix, apply_uri) local_part, prefix, uri = qname if !prefix prefix = apply_prefix uri = apply_uri end [local_part, prefix, uri].compact end
[ "def", "apply_namespace", "(", "qname", ",", "apply_prefix", ",", "apply_uri", ")", "local_part", ",", "prefix", ",", "uri", "=", "qname", "if", "!", "prefix", "prefix", "=", "apply_prefix", "uri", "=", "apply_uri", "end", "[", "local_part", ",", "prefix", ",", "uri", "]", ".", "compact", "end" ]
given an exploded qname, apply a given namespace and uri if the qname has no namespace already
[ "given", "an", "exploded", "qname", "apply", "a", "given", "namespace", "and", "uri", "if", "the", "qname", "has", "no", "namespace", "already" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L72-L81
374
trampoline/rews
lib/rews/util.rb
Rews.Util.camelize_qname
def camelize_qname(qname) local_part, prefix, uri = qname [camelize(local_part), prefix, uri].compact end
ruby
def camelize_qname(qname) local_part, prefix, uri = qname [camelize(local_part), prefix, uri].compact end
[ "def", "camelize_qname", "(", "qname", ")", "local_part", ",", "prefix", ",", "uri", "=", "qname", "[", "camelize", "(", "local_part", ")", ",", "prefix", ",", "uri", "]", ".", "compact", "end" ]
given an exploded qname, camelize the local_part
[ "given", "an", "exploded", "qname", "camelize", "the", "local_part" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L84-L87
375
trampoline/rews
lib/rews/util.rb
Rews.Util.with_error_check
def with_error_check(client, *response_msg_keys) raise "no block" if !block_given? begin response = yield hash_response = response.to_hash statuses = hash_response.fetch_in(*response_msg_keys) if statuses.is_a?(Array) all_statuses = statuses else all_statuses = [statuses] end errors = all_statuses.map{|s| single_error_check(client, s)}.compact rescue Exception=>e Rews.log{|logger| logger.warn(e)} tag_exception(e, :savon_response=>response) raise e end raise Error.new(errors.join("\n")) if !errors.empty? statuses end
ruby
def with_error_check(client, *response_msg_keys) raise "no block" if !block_given? begin response = yield hash_response = response.to_hash statuses = hash_response.fetch_in(*response_msg_keys) if statuses.is_a?(Array) all_statuses = statuses else all_statuses = [statuses] end errors = all_statuses.map{|s| single_error_check(client, s)}.compact rescue Exception=>e Rews.log{|logger| logger.warn(e)} tag_exception(e, :savon_response=>response) raise e end raise Error.new(errors.join("\n")) if !errors.empty? statuses end
[ "def", "with_error_check", "(", "client", ",", "*", "response_msg_keys", ")", "raise", "\"no block\"", "if", "!", "block_given?", "begin", "response", "=", "yield", "hash_response", "=", "response", ".", "to_hash", "statuses", "=", "hash_response", ".", "fetch_in", "(", "response_msg_keys", ")", "if", "statuses", ".", "is_a?", "(", "Array", ")", "all_statuses", "=", "statuses", "else", "all_statuses", "=", "[", "statuses", "]", "end", "errors", "=", "all_statuses", ".", "map", "{", "|", "s", "|", "single_error_check", "(", "client", ",", "s", ")", "}", ".", "compact", "rescue", "Exception", "=>", "e", "Rews", ".", "log", "{", "|", "logger", "|", "logger", ".", "warn", "(", "e", ")", "}", "tag_exception", "(", "e", ",", ":savon_response", "=>", "response", ")", "raise", "e", "end", "raise", "Error", ".", "new", "(", "errors", ".", "join", "(", "\"\\n\"", ")", ")", "if", "!", "errors", ".", "empty?", "statuses", "end" ]
check the response codes of an Exchange Web Services request. the supplied block makes a SOAP request, and the response is parsed out and checked
[ "check", "the", "response", "codes", "of", "an", "Exchange", "Web", "Services", "request", ".", "the", "supplied", "block", "makes", "a", "SOAP", "request", "and", "the", "response", "is", "parsed", "out", "and", "checked" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L107-L130
376
trampoline/rews
lib/rews/util.rb
Rews.Util.single_error_check
def single_error_check(client, status) begin response_class = status[:response_class] rescue raise "no response_class found: #{status.inspect}" if !response_class end if status[:response_class] == "Error" return "#{status[:response_code]} - #{status[:message_text]}" elsif status[:response_class] == "Warning" Rews.log{|logger| logger.warn("#{status[:response_code]} - #{status[:message_text]}")} end end
ruby
def single_error_check(client, status) begin response_class = status[:response_class] rescue raise "no response_class found: #{status.inspect}" if !response_class end if status[:response_class] == "Error" return "#{status[:response_code]} - #{status[:message_text]}" elsif status[:response_class] == "Warning" Rews.log{|logger| logger.warn("#{status[:response_code]} - #{status[:message_text]}")} end end
[ "def", "single_error_check", "(", "client", ",", "status", ")", "begin", "response_class", "=", "status", "[", ":response_class", "]", "rescue", "raise", "\"no response_class found: #{status.inspect}\"", "if", "!", "response_class", "end", "if", "status", "[", ":response_class", "]", "==", "\"Error\"", "return", "\"#{status[:response_code]} - #{status[:message_text]}\"", "elsif", "status", "[", ":response_class", "]", "==", "\"Warning\"", "Rews", ".", "log", "{", "|", "logger", "|", "logger", ".", "warn", "(", "\"#{status[:response_code]} - #{status[:message_text]}\"", ")", "}", "end", "end" ]
check the status of the response of a single part of a multi-part request
[ "check", "the", "status", "of", "the", "response", "of", "a", "single", "part", "of", "a", "multi", "-", "part", "request" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L133-L145
377
blambeau/finitio-rb
lib/finitio/support/attribute.rb
Finitio.Attribute.fetch_on
def fetch_on(arg, &bl) unless arg.respond_to?(:fetch) raise ArgumentError, "Object responding to `fetch` expected" end arg.fetch(name) do arg.fetch(name.to_s, &bl) end end
ruby
def fetch_on(arg, &bl) unless arg.respond_to?(:fetch) raise ArgumentError, "Object responding to `fetch` expected" end arg.fetch(name) do arg.fetch(name.to_s, &bl) end end
[ "def", "fetch_on", "(", "arg", ",", "&", "bl", ")", "unless", "arg", ".", "respond_to?", "(", ":fetch", ")", "raise", "ArgumentError", ",", "\"Object responding to `fetch` expected\"", "end", "arg", ".", "fetch", "(", "name", ")", "do", "arg", ".", "fetch", "(", "name", ".", "to_s", ",", "bl", ")", "end", "end" ]
Fetch the attribute on `arg`, which is expected to be a Hash object. This method allows working with ruby hashes having either Symbols or Strings as keys. It ensures that no Symbol is created by the rest of the code, since this would provide a DoS attack vector under MRI.
[ "Fetch", "the", "attribute", "on", "arg", "which", "is", "expected", "to", "be", "a", "Hash", "object", "." ]
c07a3887a6af26b2ed1eb3c50b101e210d3d8b40
https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/support/attribute.rb#L35-L42
378
tanalab2/ya_lorem_ja
lib/ya_lorem_ja/word_resource.rb
YaLoremJa.WordResource.sentences
def sentences(total) list = [] total.times do word_count = rand(word_count_range_in_a_sentence) sentence_len = word_count.times.inject(0){ |sum| sum + rand(char_count_range_in_a_word) } sentence_key = bsearch(sentence_map_keys, sentence_len) unless sentence_key sentence_key = sentence_map.keys.min end list << sentence_map[sentence_key].sample end return list.join(@line_break) end
ruby
def sentences(total) list = [] total.times do word_count = rand(word_count_range_in_a_sentence) sentence_len = word_count.times.inject(0){ |sum| sum + rand(char_count_range_in_a_word) } sentence_key = bsearch(sentence_map_keys, sentence_len) unless sentence_key sentence_key = sentence_map.keys.min end list << sentence_map[sentence_key].sample end return list.join(@line_break) end
[ "def", "sentences", "(", "total", ")", "list", "=", "[", "]", "total", ".", "times", "do", "word_count", "=", "rand", "(", "word_count_range_in_a_sentence", ")", "sentence_len", "=", "word_count", ".", "times", ".", "inject", "(", "0", ")", "{", "|", "sum", "|", "sum", "+", "rand", "(", "char_count_range_in_a_word", ")", "}", "sentence_key", "=", "bsearch", "(", "sentence_map_keys", ",", "sentence_len", ")", "unless", "sentence_key", "sentence_key", "=", "sentence_map", ".", "keys", ".", "min", "end", "list", "<<", "sentence_map", "[", "sentence_key", "]", ".", "sample", "end", "return", "list", ".", "join", "(", "@line_break", ")", "end" ]
return rondom sentences from word resource @param [Fixnum] total count of sentence @return [String] words
[ "return", "rondom", "sentences", "from", "word", "resource" ]
9f2e36ab3f0543492d0bb9918431105b73e90c8e
https://github.com/tanalab2/ya_lorem_ja/blob/9f2e36ab3f0543492d0bb9918431105b73e90c8e/lib/ya_lorem_ja/word_resource.rb#L113-L125
379
Antti/skyper
lib/skyper/skype_object.rb
Skyper.SkypeObject.set_property
def set_property(property, value) cmd = ["SET",self.class.object_name, id, property, value].compact.join(" ") Skyper::Skype.send_command(cmd) end
ruby
def set_property(property, value) cmd = ["SET",self.class.object_name, id, property, value].compact.join(" ") Skyper::Skype.send_command(cmd) end
[ "def", "set_property", "(", "property", ",", "value", ")", "cmd", "=", "[", "\"SET\"", ",", "self", ".", "class", ".", "object_name", ",", "id", ",", "property", ",", "value", "]", ".", "compact", ".", "join", "(", "\" \"", ")", "Skyper", "::", "Skype", ".", "send_command", "(", "cmd", ")", "end" ]
Invokes SET command for a given object with id, property and value @param[String] property Property to be set @param[String] value Property value
[ "Invokes", "SET", "command", "for", "a", "given", "object", "with", "id", "property", "and", "value" ]
16c1c19a485be24376acfa0b7e0a7775ec16b30c
https://github.com/Antti/skyper/blob/16c1c19a485be24376acfa0b7e0a7775ec16b30c/lib/skyper/skype_object.rb#L26-L29
380
blambeau/finitio-rb
lib/finitio/support/type_factory.rb
Finitio.TypeFactory.subtype
def subtype(super_type, constraints = nil, name = nil, metadata = nil, &bl) super_type = type(super_type) constraints = constraints(constraints, &bl) name = name(name) meta = metadata(metadata) SubType.new(super_type, constraints, name, metadata) end
ruby
def subtype(super_type, constraints = nil, name = nil, metadata = nil, &bl) super_type = type(super_type) constraints = constraints(constraints, &bl) name = name(name) meta = metadata(metadata) SubType.new(super_type, constraints, name, metadata) end
[ "def", "subtype", "(", "super_type", ",", "constraints", "=", "nil", ",", "name", "=", "nil", ",", "metadata", "=", "nil", ",", "&", "bl", ")", "super_type", "=", "type", "(", "super_type", ")", "constraints", "=", "constraints", "(", "constraints", ",", "bl", ")", "name", "=", "name", "(", "name", ")", "meta", "=", "metadata", "(", "metadata", ")", "SubType", ".", "new", "(", "super_type", ",", "constraints", ",", "name", ",", "metadata", ")", "end" ]
Sub and union
[ "Sub", "and", "union" ]
c07a3887a6af26b2ed1eb3c50b101e210d3d8b40
https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/support/type_factory.rb#L192-L199
381
blambeau/finitio-rb
lib/finitio/support/type_factory.rb
Finitio.TypeFactory.tuple
def tuple(heading, name = nil, metadata = nil) heading = heading(heading) name = name(name) meta = metadata(metadata) TupleType.new(heading, name, meta) end
ruby
def tuple(heading, name = nil, metadata = nil) heading = heading(heading) name = name(name) meta = metadata(metadata) TupleType.new(heading, name, meta) end
[ "def", "tuple", "(", "heading", ",", "name", "=", "nil", ",", "metadata", "=", "nil", ")", "heading", "=", "heading", "(", "heading", ")", "name", "=", "name", "(", "name", ")", "meta", "=", "metadata", "(", "metadata", ")", "TupleType", ".", "new", "(", "heading", ",", "name", ",", "meta", ")", "end" ]
Tuples and relations
[ "Tuples", "and", "relations" ]
c07a3887a6af26b2ed1eb3c50b101e210d3d8b40
https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/support/type_factory.rb#L243-L249
382
tanalab2/ya_lorem_ja
lib/ya_lorem_ja.rb
YaLoremJa.Lorem.image
def image(size, options={}) domain = options[:domain] || 'http://placehold.it' src = "#{domain}/#{size}" hex = %w(a b c d e f 0 1 2 3 4 5 6 7 8 9) background_color = options[:background_color] color = options[:color] if options[:random_color] background_color = hex.shuffle[0...6].join color = hex.shuffle[0...6].join end src << "/#{background_color.sub(/^#/, '')}" if background_color src << '/ccc' if background_color.nil? && color src << "/#{color.sub(/^#/, '')}" if color src << "&text=#{Rack::Utils.escape(options[:text])}" if options[:text] src end
ruby
def image(size, options={}) domain = options[:domain] || 'http://placehold.it' src = "#{domain}/#{size}" hex = %w(a b c d e f 0 1 2 3 4 5 6 7 8 9) background_color = options[:background_color] color = options[:color] if options[:random_color] background_color = hex.shuffle[0...6].join color = hex.shuffle[0...6].join end src << "/#{background_color.sub(/^#/, '')}" if background_color src << '/ccc' if background_color.nil? && color src << "/#{color.sub(/^#/, '')}" if color src << "&text=#{Rack::Utils.escape(options[:text])}" if options[:text] src end
[ "def", "image", "(", "size", ",", "options", "=", "{", "}", ")", "domain", "=", "options", "[", ":domain", "]", "||", "'http://placehold.it'", "src", "=", "\"#{domain}/#{size}\"", "hex", "=", "%w(", "a", "b", "c", "d", "e", "f", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ")", "background_color", "=", "options", "[", ":background_color", "]", "color", "=", "options", "[", ":color", "]", "if", "options", "[", ":random_color", "]", "background_color", "=", "hex", ".", "shuffle", "[", "0", "...", "6", "]", ".", "join", "color", "=", "hex", ".", "shuffle", "[", "0", "...", "6", "]", ".", "join", "end", "src", "<<", "\"/#{background_color.sub(/^#/, '')}\"", "if", "background_color", "src", "<<", "'/ccc'", "if", "background_color", ".", "nil?", "&&", "color", "src", "<<", "\"/#{color.sub(/^#/, '')}\"", "if", "color", "src", "<<", "\"&text=#{Rack::Utils.escape(options[:text])}\"", "if", "options", "[", ":text", "]", "src", "end" ]
Get a placeholder image, using placehold.it by default @param [String] size @param [Hash] options @return [String]
[ "Get", "a", "placeholder", "image", "using", "placehold", ".", "it", "by", "default" ]
9f2e36ab3f0543492d0bb9918431105b73e90c8e
https://github.com/tanalab2/ya_lorem_ja/blob/9f2e36ab3f0543492d0bb9918431105b73e90c8e/lib/ya_lorem_ja.rb#L142-L160
383
orzFly/ruby-ripple-rest
lib/ripple-rest/schemas.rb
RippleRest.AccountSettings.save
def save raise ArgumentError.new("Account is missing.") unless account account.require_secret hash = {} hash["settings"] = to_hash hash["secret"] = account.secret RippleRest.post "v1/accounts/#{account.address}/settings", hash end
ruby
def save raise ArgumentError.new("Account is missing.") unless account account.require_secret hash = {} hash["settings"] = to_hash hash["secret"] = account.secret RippleRest.post "v1/accounts/#{account.address}/settings", hash end
[ "def", "save", "raise", "ArgumentError", ".", "new", "(", "\"Account is missing.\"", ")", "unless", "account", "account", ".", "require_secret", "hash", "=", "{", "}", "hash", "[", "\"settings\"", "]", "=", "to_hash", "hash", "[", "\"secret\"", "]", "=", "account", ".", "secret", "RippleRest", ".", "post", "\"v1/accounts/#{account.address}/settings\"", ",", "hash", "end" ]
Save the account settings @raise [ArgumentError] if secret is missing from the Account object @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down @return [void]
[ "Save", "the", "account", "settings" ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/schemas.rb#L11-L21
384
orzFly/ruby-ripple-rest
lib/ripple-rest/schemas.rb
RippleRest.Payment.submit
def submit @account.require_secret hash = {} hash["payment"] = self.to_hash hash["secret"] = @account.secret hash["client_resource_id"] = client_resource_id = RippleRest.next_uuid source_account = self.to_hash[:source_account] RippleRest.post("v1/accounts/#{source_account}/payments", hash)["client_resource_id"] end
ruby
def submit @account.require_secret hash = {} hash["payment"] = self.to_hash hash["secret"] = @account.secret hash["client_resource_id"] = client_resource_id = RippleRest.next_uuid source_account = self.to_hash[:source_account] RippleRest.post("v1/accounts/#{source_account}/payments", hash)["client_resource_id"] end
[ "def", "submit", "@account", ".", "require_secret", "hash", "=", "{", "}", "hash", "[", "\"payment\"", "]", "=", "self", ".", "to_hash", "hash", "[", "\"secret\"", "]", "=", "@account", ".", "secret", "hash", "[", "\"client_resource_id\"", "]", "=", "client_resource_id", "=", "RippleRest", ".", "next_uuid", "source_account", "=", "self", ".", "to_hash", "[", ":source_account", "]", "RippleRest", ".", "post", "(", "\"v1/accounts/#{source_account}/payments\"", ",", "hash", ")", "[", "\"client_resource_id\"", "]", "end" ]
Submits a payment @return [String] Client resource ID @raise [ArgumentError] if secret is missing from the Account object @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down
[ "Submits", "a", "payment" ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/schemas.rb#L69-L79
385
trampoline/rews
lib/rews/item.rb
Rews.Item.read_items
def read_items(client, items) return [] if !items items.map do |item_class,items_of_class| items_of_class = [items_of_class] if !items_of_class.is_a?(Array) items_of_class.map do |item| Item.new(client, item_class, item) end end.flatten end
ruby
def read_items(client, items) return [] if !items items.map do |item_class,items_of_class| items_of_class = [items_of_class] if !items_of_class.is_a?(Array) items_of_class.map do |item| Item.new(client, item_class, item) end end.flatten end
[ "def", "read_items", "(", "client", ",", "items", ")", "return", "[", "]", "if", "!", "items", "items", ".", "map", "do", "|", "item_class", ",", "items_of_class", "|", "items_of_class", "=", "[", "items_of_class", "]", "if", "!", "items_of_class", ".", "is_a?", "(", "Array", ")", "items_of_class", ".", "map", "do", "|", "item", "|", "Item", ".", "new", "(", "client", ",", "item_class", ",", "item", ")", "end", "end", ".", "flatten", "end" ]
return a list of Item objects given a hash formed from an Items element
[ "return", "a", "list", "of", "Item", "objects", "given", "a", "hash", "formed", "from", "an", "Items", "element" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/item.rb#L6-L14
386
trampoline/rews
lib/rews/item.rb
Rews.Item.read_get_item_response_messages
def read_get_item_response_messages(client, get_item_response_messages) get_item_response_messages = [get_item_response_messages] if !get_item_response_messages.is_a?(Array) items = get_item_response_messages.map do |girm| read_items(client, girm[:items]) end.flatten end
ruby
def read_get_item_response_messages(client, get_item_response_messages) get_item_response_messages = [get_item_response_messages] if !get_item_response_messages.is_a?(Array) items = get_item_response_messages.map do |girm| read_items(client, girm[:items]) end.flatten end
[ "def", "read_get_item_response_messages", "(", "client", ",", "get_item_response_messages", ")", "get_item_response_messages", "=", "[", "get_item_response_messages", "]", "if", "!", "get_item_response_messages", ".", "is_a?", "(", "Array", ")", "items", "=", "get_item_response_messages", ".", "map", "do", "|", "girm", "|", "read_items", "(", "client", ",", "girm", "[", ":items", "]", ")", "end", ".", "flatten", "end" ]
return a list of Item objects from a list of GetItemResponseMessages
[ "return", "a", "list", "of", "Item", "objects", "from", "a", "list", "of", "GetItemResponseMessages" ]
3f18671a25750b9045714af587c1989679f84de8
https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/item.rb#L17-L22
387
dpla/KriKri
lib/krikri/enrichments/dcmi_type_map.rb
Krikri::Enrichments.DcmiTypeMap.most_similar
def most_similar(value, threshold = 0.5) @white ||= Text::WhiteSimilarity.new result = @map.max_by { |str, _| @white.similarity(value, str) } return result[1] if @white.similarity(value, result.first) > threshold nil end
ruby
def most_similar(value, threshold = 0.5) @white ||= Text::WhiteSimilarity.new result = @map.max_by { |str, _| @white.similarity(value, str) } return result[1] if @white.similarity(value, result.first) > threshold nil end
[ "def", "most_similar", "(", "value", ",", "threshold", "=", "0.5", ")", "@white", "||=", "Text", "::", "WhiteSimilarity", ".", "new", "result", "=", "@map", ".", "max_by", "{", "|", "str", ",", "_", "|", "@white", ".", "similarity", "(", "value", ",", "str", ")", "}", "return", "result", "[", "1", "]", "if", "@white", ".", "similarity", "(", "value", ",", "result", ".", "first", ")", ">", "threshold", "nil", "end" ]
Performs White Similarity comparison against the keys, and gives the value of the closest match. @param value [String] a string value to compare to the hash map keys. @param threshold [Float] the value at which a string is considered to be a match @return [RDF::Vocabulary::Term, nil] the closest DCMI type match, or `nil` if none is sufficiently close @see Text::WhiteSimilarity @see http://www.catalysoft.com/articles/strikeamatch.html article defining the White Similarity algorithm @todo consider text similarity algorithms/strategies and move text matching to a utility and behind a Facade interface.
[ "Performs", "White", "Similarity", "comparison", "against", "the", "keys", "and", "gives", "the", "value", "of", "the", "closest", "match", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/dcmi_type_map.rb#L121-L127
388
mariochavez/restful
lib/restful/actions.rb
Restful.Actions.index
def index(options = {}, &block) respond_with(collection, options, &block) if stale?(collection, last_modified: collection.maximum(:updated_at)) end
ruby
def index(options = {}, &block) respond_with(collection, options, &block) if stale?(collection, last_modified: collection.maximum(:updated_at)) end
[ "def", "index", "(", "options", "=", "{", "}", ",", "&", "block", ")", "respond_with", "(", "collection", ",", "options", ",", "block", ")", "if", "stale?", "(", "collection", ",", "last_modified", ":", "collection", ".", "maximum", "(", ":updated_at", ")", ")", "end" ]
index action, this set a collection of objects to an instance variable which can be accessed from the view using the collection helper method. The instance variable name is a pluralization of the model name defined in the restful macro.
[ "index", "action", "this", "set", "a", "collection", "of", "objects", "to", "an", "instance", "variable", "which", "can", "be", "accessed", "from", "the", "view", "using", "the", "collection", "helper", "method", ".", "The", "instance", "variable", "name", "is", "a", "pluralization", "of", "the", "model", "name", "defined", "in", "the", "restful", "macro", "." ]
4b421ef6b448a8dfbd72dac183561fe829095aef
https://github.com/mariochavez/restful/blob/4b421ef6b448a8dfbd72dac183561fe829095aef/lib/restful/actions.rb#L72-L74
389
mariochavez/restful
lib/restful/actions.rb
Restful.Actions.create
def create(options = {}, &block) object = get_resource_ivar || create_resource options[:location] = collection_path if object.errors.empty? respond_with_dual(object, options, &block) end
ruby
def create(options = {}, &block) object = get_resource_ivar || create_resource options[:location] = collection_path if object.errors.empty? respond_with_dual(object, options, &block) end
[ "def", "create", "(", "options", "=", "{", "}", ",", "&", "block", ")", "object", "=", "get_resource_ivar", "||", "create_resource", "options", "[", ":location", "]", "=", "collection_path", "if", "object", ".", "errors", ".", "empty?", "respond_with_dual", "(", "object", ",", "options", ",", "block", ")", "end" ]
create action, creates a new object off the received params and sets an instance variable if record is saved then a redirect to index action is made. If record fail to be saved, the new form is renderd and the instance variable can be accessed from the view using the resource helper method. The instance variable is named after the model name defined in the restful macro.
[ "create", "action", "creates", "a", "new", "object", "off", "the", "received", "params", "and", "sets", "an", "instance", "variable", "if", "record", "is", "saved", "then", "a", "redirect", "to", "index", "action", "is", "made", "." ]
4b421ef6b448a8dfbd72dac183561fe829095aef
https://github.com/mariochavez/restful/blob/4b421ef6b448a8dfbd72dac183561fe829095aef/lib/restful/actions.rb#L95-L101
390
dpla/KriKri
lib/krikri/harvesters/primo_harvester.rb
Krikri::Harvesters.PrimoHarvester.enumerate_records
def enumerate_records(xml) doc = Nokogiri::XML(xml) doc.root.add_namespace_definition('nmbib', PRIMO_NS) doc.xpath('//sear:DOC').lazy.map do |record| identifier = record.xpath('./nmbib:PrimoNMBib/nmbib:record/' \ 'nmbib:control/nmbib:recordid') .first.text record = record.dup record.add_namespace_definition('sear', SEAR_NS) @record_class.build(mint_id(identifier), record.to_xml) end end
ruby
def enumerate_records(xml) doc = Nokogiri::XML(xml) doc.root.add_namespace_definition('nmbib', PRIMO_NS) doc.xpath('//sear:DOC').lazy.map do |record| identifier = record.xpath('./nmbib:PrimoNMBib/nmbib:record/' \ 'nmbib:control/nmbib:recordid') .first.text record = record.dup record.add_namespace_definition('sear', SEAR_NS) @record_class.build(mint_id(identifier), record.to_xml) end end
[ "def", "enumerate_records", "(", "xml", ")", "doc", "=", "Nokogiri", "::", "XML", "(", "xml", ")", "doc", ".", "root", ".", "add_namespace_definition", "(", "'nmbib'", ",", "PRIMO_NS", ")", "doc", ".", "xpath", "(", "'//sear:DOC'", ")", ".", "lazy", ".", "map", "do", "|", "record", "|", "identifier", "=", "record", ".", "xpath", "(", "'./nmbib:PrimoNMBib/nmbib:record/'", "'nmbib:control/nmbib:recordid'", ")", ".", "first", ".", "text", "record", "=", "record", ".", "dup", "record", ".", "add_namespace_definition", "(", "'sear'", ",", "SEAR_NS", ")", "@record_class", ".", "build", "(", "mint_id", "(", "identifier", ")", ",", "record", ".", "to_xml", ")", "end", "end" ]
Extract a page's worth of records from a Primo XML search result. @param xml [String] an XML document returned from a Primo search @return [Array] an array of @record_class instances
[ "Extract", "a", "page", "s", "worth", "of", "records", "from", "a", "Primo", "XML", "search", "result", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/primo_harvester.rb#L91-L104
391
lambda2/rice_cooker
lib/rice_cooker/base/helpers.rb
RiceCooker.Helpers.sortable_fields_for
def sortable_fields_for(model) if model.respond_to?(:sortable_fields) model.sortable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) else [] end end
ruby
def sortable_fields_for(model) if model.respond_to?(:sortable_fields) model.sortable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) else [] end end
[ "def", "sortable_fields_for", "(", "model", ")", "if", "model", ".", "respond_to?", "(", ":sortable_fields", ")", "model", ".", "sortable_fields", ".", "map", "(", ":to_sym", ")", "elsif", "model", ".", "respond_to?", "(", ":column_names", ")", "model", ".", "column_names", ".", "map", "(", ":to_sym", ")", "else", "[", "]", "end", "end" ]
Overridable method for available sortable fields
[ "Overridable", "method", "for", "available", "sortable", "fields" ]
b7ce285d3bd76ae979111f0374c5a43815473332
https://github.com/lambda2/rice_cooker/blob/b7ce285d3bd76ae979111f0374c5a43815473332/lib/rice_cooker/base/helpers.rb#L30-L38
392
lambda2/rice_cooker
lib/rice_cooker/base/helpers.rb
RiceCooker.Helpers.filterable_fields_for
def filterable_fields_for(model) if model.respond_to?(:filterable_fields) model.filterable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) else [] end end
ruby
def filterable_fields_for(model) if model.respond_to?(:filterable_fields) model.filterable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) else [] end end
[ "def", "filterable_fields_for", "(", "model", ")", "if", "model", ".", "respond_to?", "(", ":filterable_fields", ")", "model", ".", "filterable_fields", ".", "map", "(", ":to_sym", ")", "elsif", "model", ".", "respond_to?", "(", ":column_names", ")", "model", ".", "column_names", ".", "map", "(", ":to_sym", ")", "else", "[", "]", "end", "end" ]
Overridable method for available filterable fields
[ "Overridable", "method", "for", "available", "filterable", "fields" ]
b7ce285d3bd76ae979111f0374c5a43815473332
https://github.com/lambda2/rice_cooker/blob/b7ce285d3bd76ae979111f0374c5a43815473332/lib/rice_cooker/base/helpers.rb#L41-L49
393
schrodingersbox/status_cat
app/helpers/status_cat/status_helper.rb
StatusCat.StatusHelper.status_report
def status_report(checkers) format, format_length = status_report_format(checkers) header = status_report_header(format) length = [format_length, header.length].max separator = ('-' * length) + "\n" result = separator + header + separator checkers.each { |checker| result << checker.to_s(format) } result << separator return result end
ruby
def status_report(checkers) format, format_length = status_report_format(checkers) header = status_report_header(format) length = [format_length, header.length].max separator = ('-' * length) + "\n" result = separator + header + separator checkers.each { |checker| result << checker.to_s(format) } result << separator return result end
[ "def", "status_report", "(", "checkers", ")", "format", ",", "format_length", "=", "status_report_format", "(", "checkers", ")", "header", "=", "status_report_header", "(", "format", ")", "length", "=", "[", "format_length", ",", "header", ".", "length", "]", ".", "max", "separator", "=", "(", "'-'", "*", "length", ")", "+", "\"\\n\"", "result", "=", "separator", "+", "header", "+", "separator", "checkers", ".", "each", "{", "|", "checker", "|", "result", "<<", "checker", ".", "to_s", "(", "format", ")", "}", "result", "<<", "separator", "return", "result", "end" ]
Constructs a text status report
[ "Constructs", "a", "text", "status", "report" ]
af56e3e79999d4a608ab6fe682e0a7c76becd6ca
https://github.com/schrodingersbox/status_cat/blob/af56e3e79999d4a608ab6fe682e0a7c76becd6ca/app/helpers/status_cat/status_helper.rb#L56-L67
394
schrodingersbox/status_cat
app/helpers/status_cat/status_helper.rb
StatusCat.StatusHelper.status_report_format
def status_report_format(checkers) name_max = status_report_format_max_length(checkers, :name) value_max = status_report_format_max_length(checkers, :value) status_max = status_report_format_max_length(checkers, :status) format = "%#{name_max}s | %#{value_max}s | %#{status_max}s\n" length = name_max + 3 + value_max + 3 + status_max return format, length end
ruby
def status_report_format(checkers) name_max = status_report_format_max_length(checkers, :name) value_max = status_report_format_max_length(checkers, :value) status_max = status_report_format_max_length(checkers, :status) format = "%#{name_max}s | %#{value_max}s | %#{status_max}s\n" length = name_max + 3 + value_max + 3 + status_max return format, length end
[ "def", "status_report_format", "(", "checkers", ")", "name_max", "=", "status_report_format_max_length", "(", "checkers", ",", ":name", ")", "value_max", "=", "status_report_format_max_length", "(", "checkers", ",", ":value", ")", "status_max", "=", "status_report_format_max_length", "(", "checkers", ",", ":status", ")", "format", "=", "\"%#{name_max}s | %#{value_max}s | %#{status_max}s\\n\"", "length", "=", "name_max", "+", "3", "+", "value_max", "+", "3", "+", "status_max", "return", "format", ",", "length", "end" ]
Generate a format string to justify all values
[ "Generate", "a", "format", "string", "to", "justify", "all", "values" ]
af56e3e79999d4a608ab6fe682e0a7c76becd6ca
https://github.com/schrodingersbox/status_cat/blob/af56e3e79999d4a608ab6fe682e0a7c76becd6ca/app/helpers/status_cat/status_helper.rb#L71-L80
395
schrodingersbox/status_cat
app/helpers/status_cat/status_helper.rb
StatusCat.StatusHelper.status_report_header
def status_report_header(format = StatusCat::Checkers::Base::FORMAT) name = I18n.t(:name, scope: :status_cat) value = I18n.t(:value, scope: :status_cat) status = I18n.t(:status, scope: :status_cat) return format(format, name, value, status) end
ruby
def status_report_header(format = StatusCat::Checkers::Base::FORMAT) name = I18n.t(:name, scope: :status_cat) value = I18n.t(:value, scope: :status_cat) status = I18n.t(:status, scope: :status_cat) return format(format, name, value, status) end
[ "def", "status_report_header", "(", "format", "=", "StatusCat", "::", "Checkers", "::", "Base", "::", "FORMAT", ")", "name", "=", "I18n", ".", "t", "(", ":name", ",", "scope", ":", ":status_cat", ")", "value", "=", "I18n", ".", "t", "(", ":value", ",", "scope", ":", ":status_cat", ")", "status", "=", "I18n", ".", "t", "(", ":status", ",", "scope", ":", ":status_cat", ")", "return", "format", "(", "format", ",", "name", ",", "value", ",", "status", ")", "end" ]
Generate a header string
[ "Generate", "a", "header", "string" ]
af56e3e79999d4a608ab6fe682e0a7c76becd6ca
https://github.com/schrodingersbox/status_cat/blob/af56e3e79999d4a608ab6fe682e0a7c76becd6ca/app/helpers/status_cat/status_helper.rb#L88-L93
396
tlux/vnstat-ruby
lib/vnstat/parser.rb
Vnstat.Parser.extract_month_from_xml_element
def extract_month_from_xml_element(element) month = element.xpath('date/month').text.to_i year = element.xpath('date/year').text.to_i [year, month] end
ruby
def extract_month_from_xml_element(element) month = element.xpath('date/month').text.to_i year = element.xpath('date/year').text.to_i [year, month] end
[ "def", "extract_month_from_xml_element", "(", "element", ")", "month", "=", "element", ".", "xpath", "(", "'date/month'", ")", ".", "text", ".", "to_i", "year", "=", "element", ".", "xpath", "(", "'date/year'", ")", ".", "text", ".", "to_i", "[", "year", ",", "month", "]", "end" ]
Extracts the year and month from the given XML element. @param [Nokogiri::XML::Element] element The XML element. @return [Array<Integer, Integer>] An Array consisting of year and month.
[ "Extracts", "the", "year", "and", "month", "from", "the", "given", "XML", "element", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L15-L19
397
tlux/vnstat-ruby
lib/vnstat/parser.rb
Vnstat.Parser.extract_date_from_xml_element
def extract_date_from_xml_element(element) day = element.xpath('date/day').text.to_i year, month = extract_month_from_xml_element(element) Date.new(year, month, day) end
ruby
def extract_date_from_xml_element(element) day = element.xpath('date/day').text.to_i year, month = extract_month_from_xml_element(element) Date.new(year, month, day) end
[ "def", "extract_date_from_xml_element", "(", "element", ")", "day", "=", "element", ".", "xpath", "(", "'date/day'", ")", ".", "text", ".", "to_i", "year", ",", "month", "=", "extract_month_from_xml_element", "(", "element", ")", "Date", ".", "new", "(", "year", ",", "month", ",", "day", ")", "end" ]
Extracts the date from the given XML element. @param [Nokogiri::XML::Element] element The XML element. @return [Date]
[ "Extracts", "the", "date", "from", "the", "given", "XML", "element", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L26-L30
398
tlux/vnstat-ruby
lib/vnstat/parser.rb
Vnstat.Parser.extract_datetime_from_xml_element
def extract_datetime_from_xml_element(element) date = extract_date_from_xml_element(element) hour = element.xpath('time/hour').text.to_i minute = element.xpath('time/minute').text.to_i offset = Time.now.strftime('%:z') Time.new(date.year, date.month, date.day, hour, minute, 0, offset) end
ruby
def extract_datetime_from_xml_element(element) date = extract_date_from_xml_element(element) hour = element.xpath('time/hour').text.to_i minute = element.xpath('time/minute').text.to_i offset = Time.now.strftime('%:z') Time.new(date.year, date.month, date.day, hour, minute, 0, offset) end
[ "def", "extract_datetime_from_xml_element", "(", "element", ")", "date", "=", "extract_date_from_xml_element", "(", "element", ")", "hour", "=", "element", ".", "xpath", "(", "'time/hour'", ")", ".", "text", ".", "to_i", "minute", "=", "element", ".", "xpath", "(", "'time/minute'", ")", ".", "text", ".", "to_i", "offset", "=", "Time", ".", "now", ".", "strftime", "(", "'%:z'", ")", "Time", ".", "new", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ",", "hour", ",", "minute", ",", "0", ",", "offset", ")", "end" ]
Extracts the date and time from the given XML element. @param [Nokogiri::XML::Element] element The XML element. @return [DateTime]
[ "Extracts", "the", "date", "and", "time", "from", "the", "given", "XML", "element", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L37-L43
399
tlux/vnstat-ruby
lib/vnstat/parser.rb
Vnstat.Parser.extract_transmitted_bytes_from_xml_element
def extract_transmitted_bytes_from_xml_element(element) bytes_received = element.xpath('rx').text.to_i * 1024 bytes_sent = element.xpath('tx').text.to_i * 1024 [bytes_received, bytes_sent] end
ruby
def extract_transmitted_bytes_from_xml_element(element) bytes_received = element.xpath('rx').text.to_i * 1024 bytes_sent = element.xpath('tx').text.to_i * 1024 [bytes_received, bytes_sent] end
[ "def", "extract_transmitted_bytes_from_xml_element", "(", "element", ")", "bytes_received", "=", "element", ".", "xpath", "(", "'rx'", ")", ".", "text", ".", "to_i", "*", "1024", "bytes_sent", "=", "element", ".", "xpath", "(", "'tx'", ")", ".", "text", ".", "to_i", "*", "1024", "[", "bytes_received", ",", "bytes_sent", "]", "end" ]
Extracts the bytes received and sent from the given XML element. @param [Nokogiri::XML::Element] element The XML element. @return [Array<Integer, Integer>] An Array consisting of bytes received and bytes sent.
[ "Extracts", "the", "bytes", "received", "and", "sent", "from", "the", "given", "XML", "element", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L51-L55