id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
9,700
OSHPark/ruby-api-client
lib/oshpark/client.rb
Oshpark.Client.add_order_item
def add_order_item id, project_id, quantity post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}} end
ruby
def add_order_item id, project_id, quantity post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}} end
[ "def", "add_order_item", "id", ",", "project_id", ",", "quantity", "post_request", "\"orders/#{id}/add_item\"", ",", "{", "order", ":", "{", "project_id", ":", "project_id", ",", "quantity", ":", "quantity", "}", "}", "end" ]
Add a Project to an Order @param id @param project_id @param quantity
[ "Add", "a", "Project", "to", "an", "Order" ]
629c633c6c2189e2634b4b8721e6f0711209703b
https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L117-L119
9,701
butchmarshall/ruby-jive-signed_request
lib/jive/signed_request.rb
Jive.SignedRequest.sign
def sign(string, secret, algorithm = nil) plain = ::Base64.decode64(secret.gsub(/\.s$/,'')) # if no override algorithm passed try and extract from string if algorithm.nil? paramMap = ::CGI.parse string if !paramMap.has_key?("algorithm") raise ArgumentError, "missing algorithm" end algorithm = paramMap["algorithm"].first.gsub(/^hmac/i,'') end hmac = ::OpenSSL::HMAC.digest(algorithm, plain, string) Base64::encode64(hmac).gsub(/\n$/,'') end
ruby
def sign(string, secret, algorithm = nil) plain = ::Base64.decode64(secret.gsub(/\.s$/,'')) # if no override algorithm passed try and extract from string if algorithm.nil? paramMap = ::CGI.parse string if !paramMap.has_key?("algorithm") raise ArgumentError, "missing algorithm" end algorithm = paramMap["algorithm"].first.gsub(/^hmac/i,'') end hmac = ::OpenSSL::HMAC.digest(algorithm, plain, string) Base64::encode64(hmac).gsub(/\n$/,'') end
[ "def", "sign", "(", "string", ",", "secret", ",", "algorithm", "=", "nil", ")", "plain", "=", "::", "Base64", ".", "decode64", "(", "secret", ".", "gsub", "(", "/", "\\.", "/", ",", "''", ")", ")", "# if no override algorithm passed try and extract from string", "if", "algorithm", ".", "nil?", "paramMap", "=", "::", "CGI", ".", "parse", "string", "if", "!", "paramMap", ".", "has_key?", "(", "\"algorithm\"", ")", "raise", "ArgumentError", ",", "\"missing algorithm\"", "end", "algorithm", "=", "paramMap", "[", "\"algorithm\"", "]", ".", "first", ".", "gsub", "(", "/", "/i", ",", "''", ")", "end", "hmac", "=", "::", "OpenSSL", "::", "HMAC", ".", "digest", "(", "algorithm", ",", "plain", ",", "string", ")", "Base64", "::", "encode64", "(", "hmac", ")", ".", "gsub", "(", "/", "\\n", "/", ",", "''", ")", "end" ]
Sign a string with a secret Sign a string with a secret and get the signature * *Args* : - +string+ -> the string to sign - +secret+ -> the secret to use * *Returns* : - the signature * *Raises* : - +ArgumentError+ -> if no algorithm passed and algorithm could not be derived from the string
[ "Sign", "a", "string", "with", "a", "secret" ]
98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9
https://github.com/butchmarshall/ruby-jive-signed_request/blob/98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9/lib/jive/signed_request.rb#L23-L39
9,702
butchmarshall/ruby-jive-signed_request
lib/jive/signed_request.rb
Jive.SignedRequest.authenticate
def authenticate(authorization_header, client_secret) # Validate JiveEXTN part of header if !authorization_header.match(/^JiveEXTN/) raise ArgumentError, "Jive authorization header is not properly formatted, must start with JiveEXTN" end paramMap = ::CGI.parse authorization_header.gsub(/^JiveEXTN\s/,'') # Validate all parameters are passed from header if !paramMap.has_key?("algorithm") || !paramMap.has_key?("client_id") || !paramMap.has_key?("jive_url") || !paramMap.has_key?("tenant_id") || !paramMap.has_key?("timestamp") || !paramMap.has_key?("signature") raise ArgumentError, "Jive authorization header is partial" end # Validate timestamp is still valid timestamp = Time.at(paramMap["timestamp"].first.to_i/1000) secondsPassed = Time.now - timestamp if secondsPassed < 0 || secondsPassed > (5*60) raise ArgumentError, "Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)" end self.sign(authorization_header.gsub(/^JiveEXTN\s/,'').gsub(/\&signature[^$]+/,''), client_secret) === paramMap["signature"].first end
ruby
def authenticate(authorization_header, client_secret) # Validate JiveEXTN part of header if !authorization_header.match(/^JiveEXTN/) raise ArgumentError, "Jive authorization header is not properly formatted, must start with JiveEXTN" end paramMap = ::CGI.parse authorization_header.gsub(/^JiveEXTN\s/,'') # Validate all parameters are passed from header if !paramMap.has_key?("algorithm") || !paramMap.has_key?("client_id") || !paramMap.has_key?("jive_url") || !paramMap.has_key?("tenant_id") || !paramMap.has_key?("timestamp") || !paramMap.has_key?("signature") raise ArgumentError, "Jive authorization header is partial" end # Validate timestamp is still valid timestamp = Time.at(paramMap["timestamp"].first.to_i/1000) secondsPassed = Time.now - timestamp if secondsPassed < 0 || secondsPassed > (5*60) raise ArgumentError, "Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)" end self.sign(authorization_header.gsub(/^JiveEXTN\s/,'').gsub(/\&signature[^$]+/,''), client_secret) === paramMap["signature"].first end
[ "def", "authenticate", "(", "authorization_header", ",", "client_secret", ")", "# Validate JiveEXTN part of header", "if", "!", "authorization_header", ".", "match", "(", "/", "/", ")", "raise", "ArgumentError", ",", "\"Jive authorization header is not properly formatted, must start with JiveEXTN\"", "end", "paramMap", "=", "::", "CGI", ".", "parse", "authorization_header", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", "# Validate all parameters are passed from header", "if", "!", "paramMap", ".", "has_key?", "(", "\"algorithm\"", ")", "||", "!", "paramMap", ".", "has_key?", "(", "\"client_id\"", ")", "||", "!", "paramMap", ".", "has_key?", "(", "\"jive_url\"", ")", "||", "!", "paramMap", ".", "has_key?", "(", "\"tenant_id\"", ")", "||", "!", "paramMap", ".", "has_key?", "(", "\"timestamp\"", ")", "||", "!", "paramMap", ".", "has_key?", "(", "\"signature\"", ")", "raise", "ArgumentError", ",", "\"Jive authorization header is partial\"", "end", "# Validate timestamp is still valid", "timestamp", "=", "Time", ".", "at", "(", "paramMap", "[", "\"timestamp\"", "]", ".", "first", ".", "to_i", "/", "1000", ")", "secondsPassed", "=", "Time", ".", "now", "-", "timestamp", "if", "secondsPassed", "<", "0", "||", "secondsPassed", ">", "(", "5", "*", "60", ")", "raise", "ArgumentError", ",", "\"Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)\"", "end", "self", ".", "sign", "(", "authorization_header", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", ".", "gsub", "(", "/", "\\&", "/", ",", "''", ")", ",", "client_secret", ")", "===", "paramMap", "[", "\"signature\"", "]", ".", "first", "end" ]
Authenticate an authorization header Authenticates that an authorization header sent by Jive is valid given an apps secret * *Args* : - +authorization_header+ -> the entire Authorization header sent by Jive - +client_secret+ -> the client secret to authenticate the header with * *Returns* : - the signature * *Raises* : - +ArgumentError+ -> if the authorization_header does not contain JiveEXTN - +ArgumentError+ -> if the heauthorization_header does not contain all the required parameters - +ArgumentError+ -> if the heauthorization_header has expired (more than 5 minutes old)
[ "Authenticate", "an", "authorization", "header" ]
98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9
https://github.com/butchmarshall/ruby-jive-signed_request/blob/98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9/lib/jive/signed_request.rb#L55-L82
9,703
butchmarshall/ruby-jive-signed_request
lib/jive/signed_request.rb
Jive.SignedRequest.validate_registration
def validate_registration(validationBlock, *args) options = ((args.last.is_a?(Hash)) ? args.pop : {}) require "open-uri" require "net/http" require "openssl" jive_signature_url = validationBlock[:jiveSignatureURL] jive_signature = validationBlock[:jiveSignature] validationBlock.delete(:jiveSignature) if !validationBlock[:clientSecret].nil? validationBlock[:clientSecret] = Digest::SHA256.hexdigest(validationBlock[:clientSecret]) end uri = URI.parse(jive_signature_url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl? && !options[:verify_ssl] buffer = '' validationBlock = validationBlock.sort (validationBlock.respond_to?(:to_h) ? validationBlock.to_h : Hash[validationBlock] ).each_pair { |k,v| buffer = "#{buffer}#{k}:#{v}\n" } request = Net::HTTP::Post.new(uri.request_uri) request.body = buffer request["X-Jive-MAC"] = jive_signature request["Content-Type"] = "application/json" response = http.request(request) (response.code.to_i === 204) end
ruby
def validate_registration(validationBlock, *args) options = ((args.last.is_a?(Hash)) ? args.pop : {}) require "open-uri" require "net/http" require "openssl" jive_signature_url = validationBlock[:jiveSignatureURL] jive_signature = validationBlock[:jiveSignature] validationBlock.delete(:jiveSignature) if !validationBlock[:clientSecret].nil? validationBlock[:clientSecret] = Digest::SHA256.hexdigest(validationBlock[:clientSecret]) end uri = URI.parse(jive_signature_url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl? && !options[:verify_ssl] buffer = '' validationBlock = validationBlock.sort (validationBlock.respond_to?(:to_h) ? validationBlock.to_h : Hash[validationBlock] ).each_pair { |k,v| buffer = "#{buffer}#{k}:#{v}\n" } request = Net::HTTP::Post.new(uri.request_uri) request.body = buffer request["X-Jive-MAC"] = jive_signature request["Content-Type"] = "application/json" response = http.request(request) (response.code.to_i === 204) end
[ "def", "validate_registration", "(", "validationBlock", ",", "*", "args", ")", "options", "=", "(", "(", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", ")", "?", "args", ".", "pop", ":", "{", "}", ")", "require", "\"open-uri\"", "require", "\"net/http\"", "require", "\"openssl\"", "jive_signature_url", "=", "validationBlock", "[", ":jiveSignatureURL", "]", "jive_signature", "=", "validationBlock", "[", ":jiveSignature", "]", "validationBlock", ".", "delete", "(", ":jiveSignature", ")", "if", "!", "validationBlock", "[", ":clientSecret", "]", ".", "nil?", "validationBlock", "[", ":clientSecret", "]", "=", "Digest", "::", "SHA256", ".", "hexdigest", "(", "validationBlock", "[", ":clientSecret", "]", ")", "end", "uri", "=", "URI", ".", "parse", "(", "jive_signature_url", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "if", "http", ".", "use_ssl?", "&&", "!", "options", "[", ":verify_ssl", "]", "buffer", "=", "''", "validationBlock", "=", "validationBlock", ".", "sort", "(", "validationBlock", ".", "respond_to?", "(", ":to_h", ")", "?", "validationBlock", ".", "to_h", ":", "Hash", "[", "validationBlock", "]", ")", ".", "each_pair", "{", "|", "k", ",", "v", "|", "buffer", "=", "\"#{buffer}#{k}:#{v}\\n\"", "}", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ")", "request", ".", "body", "=", "buffer", "request", "[", "\"X-Jive-MAC\"", "]", "=", "jive_signature", "request", "[", "\"Content-Type\"", "]", "=", "\"application/json\"", "response", "=", "http", ".", "request", "(", "request", ")", "(", "response", ".", "code", ".", "to_i", "===", "204", ")", "end" ]
Validates an app registration Validates an app registration came from where it claims via jiveSignatureURL * *Args* : - +validationBlock+ -> the request body of the registration - +args+ -> additional arguments * *Returns* : - boolean
[ "Validates", "an", "app", "registration" ]
98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9
https://github.com/butchmarshall/ruby-jive-signed_request/blob/98dbbcdfbba7a212cfad6dbeeca620f6a634a3a9/lib/jive/signed_request.rb#L94-L131
9,704
sj26/rubygems-keychain
lib/rubygems/keychain.rb
Gem::Keychain.ConfigFileExtensions.load_api_keys
def load_api_keys fallback = load_file(credentials_path) if File.exists?(credentials_path) @api_keys = Gem::Keychain::ApiKeys.new(fallback: fallback) end
ruby
def load_api_keys fallback = load_file(credentials_path) if File.exists?(credentials_path) @api_keys = Gem::Keychain::ApiKeys.new(fallback: fallback) end
[ "def", "load_api_keys", "fallback", "=", "load_file", "(", "credentials_path", ")", "if", "File", ".", "exists?", "(", "credentials_path", ")", "@api_keys", "=", "Gem", "::", "Keychain", "::", "ApiKeys", ".", "new", "(", "fallback", ":", "fallback", ")", "end" ]
Override api key methods with proxy object
[ "Override", "api", "key", "methods", "with", "proxy", "object" ]
9599383c207ef53972b8193e8d9908f3211cc3b6
https://github.com/sj26/rubygems-keychain/blob/9599383c207ef53972b8193e8d9908f3211cc3b6/lib/rubygems/keychain.rb#L110-L114
9,705
cbrumelle/blueprintr
lib/blueprint-css/lib/blueprint/custom_layout.rb
Blueprint.CustomLayout.generate_grid_css
def generate_grid_css # loads up erb template to evaluate custom widths css = ERB::new(File.path_to_string(CustomLayout::CSS_ERB_FILE)) # bind it to this instance css.result(binding) end
ruby
def generate_grid_css # loads up erb template to evaluate custom widths css = ERB::new(File.path_to_string(CustomLayout::CSS_ERB_FILE)) # bind it to this instance css.result(binding) end
[ "def", "generate_grid_css", "# loads up erb template to evaluate custom widths", "css", "=", "ERB", "::", "new", "(", "File", ".", "path_to_string", "(", "CustomLayout", "::", "CSS_ERB_FILE", ")", ")", "# bind it to this instance", "css", ".", "result", "(", "binding", ")", "end" ]
Loads grid.css.erb file, binds it to current instance, and returns output
[ "Loads", "grid", ".", "css", ".", "erb", "file", "binds", "it", "to", "current", "instance", "and", "returns", "output" ]
b414436f614a8d97d77b47b588ddcf3f5e61b6bd
https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/custom_layout.rb#L63-L69
9,706
geminisbs/common_view_helpers
lib/common_view_helpers/common_view_helpers.rb
CommonViewHelpers.ViewHelpers.info_pair
def info_pair(label, value) value = content_tag(:span, "None", :class => "blank") if value.blank? label = content_tag(:span, "#{label}:", :class => "label") content_tag(:span, [label, value].join(" "), :class => "info_pair") end
ruby
def info_pair(label, value) value = content_tag(:span, "None", :class => "blank") if value.blank? label = content_tag(:span, "#{label}:", :class => "label") content_tag(:span, [label, value].join(" "), :class => "info_pair") end
[ "def", "info_pair", "(", "label", ",", "value", ")", "value", "=", "content_tag", "(", ":span", ",", "\"None\"", ",", ":class", "=>", "\"blank\"", ")", "if", "value", ".", "blank?", "label", "=", "content_tag", "(", ":span", ",", "\"#{label}:\"", ",", ":class", "=>", "\"label\"", ")", "content_tag", "(", ":span", ",", "[", "label", ",", "value", "]", ".", "join", "(", "\" \"", ")", ",", ":class", "=>", "\"info_pair\"", ")", "end" ]
Output an easily styleable key-value pair
[ "Output", "an", "easily", "styleable", "key", "-", "value", "pair" ]
a5b16957f61f201a27bda632db553991c7d42af4
https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L17-L21
9,707
geminisbs/common_view_helpers
lib/common_view_helpers/common_view_helpers.rb
CommonViewHelpers.ViewHelpers.generate_table
def generate_table(collection, headers=nil, options={}) return if collection.blank? thead = content_tag(:thead) do content_tag(:tr) do headers.map {|header| content_tag(:th, header)} end end unless headers.nil? tbody = content_tag(:tbody) do collection.map do |values| content_tag(:tr) do values.map {|value| content_tag(:td, value)} end end end content_tag(:table, [thead, tbody].compact.join("\n"), options) end
ruby
def generate_table(collection, headers=nil, options={}) return if collection.blank? thead = content_tag(:thead) do content_tag(:tr) do headers.map {|header| content_tag(:th, header)} end end unless headers.nil? tbody = content_tag(:tbody) do collection.map do |values| content_tag(:tr) do values.map {|value| content_tag(:td, value)} end end end content_tag(:table, [thead, tbody].compact.join("\n"), options) end
[ "def", "generate_table", "(", "collection", ",", "headers", "=", "nil", ",", "options", "=", "{", "}", ")", "return", "if", "collection", ".", "blank?", "thead", "=", "content_tag", "(", ":thead", ")", "do", "content_tag", "(", ":tr", ")", "do", "headers", ".", "map", "{", "|", "header", "|", "content_tag", "(", ":th", ",", "header", ")", "}", "end", "end", "unless", "headers", ".", "nil?", "tbody", "=", "content_tag", "(", ":tbody", ")", "do", "collection", ".", "map", "do", "|", "values", "|", "content_tag", "(", ":tr", ")", "do", "values", ".", "map", "{", "|", "value", "|", "content_tag", "(", ":td", ",", "value", ")", "}", "end", "end", "end", "content_tag", "(", ":table", ",", "[", "thead", ",", "tbody", "]", ".", "compact", ".", "join", "(", "\"\\n\"", ")", ",", "options", ")", "end" ]
Build an HTML table For collection, pass an array of arrays For headers, pass an array of label strings for the top of the table All other options will be passed along to the table content_tag
[ "Build", "an", "HTML", "table", "For", "collection", "pass", "an", "array", "of", "arrays", "For", "headers", "pass", "an", "array", "of", "label", "strings", "for", "the", "top", "of", "the", "table", "All", "other", "options", "will", "be", "passed", "along", "to", "the", "table", "content_tag" ]
a5b16957f61f201a27bda632db553991c7d42af4
https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L46-L61
9,708
geminisbs/common_view_helpers
lib/common_view_helpers/common_view_helpers.rb
CommonViewHelpers.ViewHelpers.options_td
def options_td(record_or_name_or_array, hide_destroy = false) items = [] items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array)) items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_destroy list = content_tag(:ul, convert_to_list_items(items)) content_tag(:td, list, :class => "options") end
ruby
def options_td(record_or_name_or_array, hide_destroy = false) items = [] items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array)) items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_destroy list = content_tag(:ul, convert_to_list_items(items)) content_tag(:td, list, :class => "options") end
[ "def", "options_td", "(", "record_or_name_or_array", ",", "hide_destroy", "=", "false", ")", "items", "=", "[", "]", "items", "<<", "link_to", "(", "'Edit'", ",", "edit_polymorphic_path", "(", "record_or_name_or_array", ")", ")", "items", "<<", "link_to", "(", "'Delete'", ",", "polymorphic_path", "(", "record_or_name_or_array", ")", ",", ":confirm", "=>", "'Are you sure?'", ",", ":method", "=>", ":delete", ",", ":class", "=>", "\"destructive\"", ")", "unless", "hide_destroy", "list", "=", "content_tag", "(", ":ul", ",", "convert_to_list_items", "(", "items", ")", ")", "content_tag", "(", ":td", ",", "list", ",", ":class", "=>", "\"options\"", ")", "end" ]
Pass in an ActiveRecord object, get back edit and delete links inside a TD tag
[ "Pass", "in", "an", "ActiveRecord", "object", "get", "back", "edit", "and", "delete", "links", "inside", "a", "TD", "tag" ]
a5b16957f61f201a27bda632db553991c7d42af4
https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L64-L70
9,709
geminisbs/common_view_helpers
lib/common_view_helpers/common_view_helpers.rb
CommonViewHelpers.ViewHelpers.link
def link(name, options={}, html_options={}) link_to_unless_current(name, options, html_options) do html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ") link_to(name, options, html_options) end end
ruby
def link(name, options={}, html_options={}) link_to_unless_current(name, options, html_options) do html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ") link_to(name, options, html_options) end end
[ "def", "link", "(", "name", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ")", "link_to_unless_current", "(", "name", ",", "options", ",", "html_options", ")", "do", "html_options", "[", ":class", "]", "=", "(", "html_options", "[", ":class", "]", "||", "\"\"", ")", ".", "split", "(", "\" \"", ")", ".", "push", "(", "\"active\"", ")", ".", "join", "(", "\" \"", ")", "link_to", "(", "name", ",", "options", ",", "html_options", ")", "end", "end" ]
This works just like link_to, but with one difference.. If the link is to the current page, a class of 'active' is added
[ "This", "works", "just", "like", "link_to", "but", "with", "one", "difference", "..", "If", "the", "link", "is", "to", "the", "current", "page", "a", "class", "of", "active", "is", "added" ]
a5b16957f61f201a27bda632db553991c7d42af4
https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L74-L79
9,710
geminisbs/common_view_helpers
lib/common_view_helpers/common_view_helpers.rb
CommonViewHelpers.ViewHelpers.list_model_columns
def list_model_columns(obj) items = obj.class.columns.map{ |col| info_pair(col.name, obj[col.name]) } content_tag(:ul, convert_to_list_items(items), :class => "model_columns") end
ruby
def list_model_columns(obj) items = obj.class.columns.map{ |col| info_pair(col.name, obj[col.name]) } content_tag(:ul, convert_to_list_items(items), :class => "model_columns") end
[ "def", "list_model_columns", "(", "obj", ")", "items", "=", "obj", ".", "class", ".", "columns", ".", "map", "{", "|", "col", "|", "info_pair", "(", "col", ".", "name", ",", "obj", "[", "col", ".", "name", "]", ")", "}", "content_tag", "(", ":ul", ",", "convert_to_list_items", "(", "items", ")", ",", ":class", "=>", "\"model_columns\"", ")", "end" ]
Generate a list of column name-value pairs for an AR object
[ "Generate", "a", "list", "of", "column", "name", "-", "value", "pairs", "for", "an", "AR", "object" ]
a5b16957f61f201a27bda632db553991c7d42af4
https://github.com/geminisbs/common_view_helpers/blob/a5b16957f61f201a27bda632db553991c7d42af4/lib/common_view_helpers/common_view_helpers.rb#L92-L95
9,711
ktonon/code_node
spec/fixtures/activerecord/src/active_record/migration.rb
ActiveRecord.Migrator.ddl_transaction
def ddl_transaction(&block) if Base.connection.supports_ddl_transactions? Base.transaction { block.call } else block.call end end
ruby
def ddl_transaction(&block) if Base.connection.supports_ddl_transactions? Base.transaction { block.call } else block.call end end
[ "def", "ddl_transaction", "(", "&", "block", ")", "if", "Base", ".", "connection", ".", "supports_ddl_transactions?", "Base", ".", "transaction", "{", "block", ".", "call", "}", "else", "block", ".", "call", "end", "end" ]
Wrap the migration in a transaction only if supported by the adapter.
[ "Wrap", "the", "migration", "in", "a", "transaction", "only", "if", "supported", "by", "the", "adapter", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/migration.rb#L773-L779
9,712
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.add_vertical
def add_vertical(str, value) node = nil str.each_char { |c| if (node == nil) node = self.add_horizontal_char(c) elsif (node.down != nil) node = node.down.add_horizontal_char(c) else node.down = Node.new(c, node) node = node.down end } node.value = value end
ruby
def add_vertical(str, value) node = nil str.each_char { |c| if (node == nil) node = self.add_horizontal_char(c) elsif (node.down != nil) node = node.down.add_horizontal_char(c) else node.down = Node.new(c, node) node = node.down end } node.value = value end
[ "def", "add_vertical", "(", "str", ",", "value", ")", "node", "=", "nil", "str", ".", "each_char", "{", "|", "c", "|", "if", "(", "node", "==", "nil", ")", "node", "=", "self", ".", "add_horizontal_char", "(", "c", ")", "elsif", "(", "node", ".", "down", "!=", "nil", ")", "node", "=", "node", ".", "down", ".", "add_horizontal_char", "(", "c", ")", "else", "node", ".", "down", "=", "Node", ".", "new", "(", "c", ",", "node", ")", "node", "=", "node", ".", "down", "end", "}", "node", ".", "value", "=", "value", "end" ]
Add the given String str and value vertically to this node, by adding or finding each character horizontally, then stepping down and repeating with the next character and so on, writing the value to the last node.
[ "Add", "the", "given", "String", "str", "and", "value", "vertically", "to", "this", "node", "by", "adding", "or", "finding", "each", "character", "horizontally", "then", "stepping", "down", "and", "repeating", "with", "the", "next", "character", "and", "so", "on", "writing", "the", "value", "to", "the", "last", "node", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L78-L91
9,713
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.find_vertical
def find_vertical(str, offset = 0, length = str.length-offset) node = nil i = offset while (i<offset+length) c = str[i] if (node == nil) node = self.find_horizontal(c) elsif (node.down != nil) node = node.down.find_horizontal(c) else return nil end return nil if (node == nil) i += 1 end node end
ruby
def find_vertical(str, offset = 0, length = str.length-offset) node = nil i = offset while (i<offset+length) c = str[i] if (node == nil) node = self.find_horizontal(c) elsif (node.down != nil) node = node.down.find_horizontal(c) else return nil end return nil if (node == nil) i += 1 end node end
[ "def", "find_vertical", "(", "str", ",", "offset", "=", "0", ",", "length", "=", "str", ".", "length", "-", "offset", ")", "node", "=", "nil", "i", "=", "offset", "while", "(", "i", "<", "offset", "+", "length", ")", "c", "=", "str", "[", "i", "]", "if", "(", "node", "==", "nil", ")", "node", "=", "self", ".", "find_horizontal", "(", "c", ")", "elsif", "(", "node", ".", "down", "!=", "nil", ")", "node", "=", "node", ".", "down", ".", "find_horizontal", "(", "c", ")", "else", "return", "nil", "end", "return", "nil", "if", "(", "node", "==", "nil", ")", "i", "+=", "1", "end", "node", "end" ]
Find the given String str vertically by finding each character horizontally, then stepping down and repeating with the next character and so on. Return the last node if found, or nil if any horizontal search fails. Optionally, set the offset into the string and its length
[ "Find", "the", "given", "String", "str", "vertically", "by", "finding", "each", "character", "horizontally", "then", "stepping", "down", "and", "repeating", "with", "the", "next", "character", "and", "so", "on", ".", "Return", "the", "last", "node", "if", "found", "or", "nil", "if", "any", "horizontal", "search", "fails", ".", "Optionally", "set", "the", "offset", "into", "the", "string", "and", "its", "length" ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L97-L114
9,714
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.balance
def balance node = self i = (node.count(:right) - node.count(:left))/2 while (i!=0) if (i>0) mvnode = node.right node.right = nil mvnode.add_horizontal node i -= 1 else mvnode = node.left node.left = nil mvnode.add_horizontal node i += 1 end node = mvnode end if (node.left != nil) node.left = node.left.balance end if (node.right != nil) node.right = node.right.balance end if (node.down != nil) node.down = node.down.balance end node end
ruby
def balance node = self i = (node.count(:right) - node.count(:left))/2 while (i!=0) if (i>0) mvnode = node.right node.right = nil mvnode.add_horizontal node i -= 1 else mvnode = node.left node.left = nil mvnode.add_horizontal node i += 1 end node = mvnode end if (node.left != nil) node.left = node.left.balance end if (node.right != nil) node.right = node.right.balance end if (node.down != nil) node.down = node.down.balance end node end
[ "def", "balance", "node", "=", "self", "i", "=", "(", "node", ".", "count", "(", ":right", ")", "-", "node", ".", "count", "(", ":left", ")", ")", "/", "2", "while", "(", "i!", "=", "0", ")", "if", "(", "i", ">", "0", ")", "mvnode", "=", "node", ".", "right", "node", ".", "right", "=", "nil", "mvnode", ".", "add_horizontal", "node", "i", "-=", "1", "else", "mvnode", "=", "node", ".", "left", "node", ".", "left", "=", "nil", "mvnode", ".", "add_horizontal", "node", "i", "+=", "1", "end", "node", "=", "mvnode", "end", "if", "(", "node", ".", "left", "!=", "nil", ")", "node", ".", "left", "=", "node", ".", "left", ".", "balance", "end", "if", "(", "node", ".", "right", "!=", "nil", ")", "node", ".", "right", "=", "node", ".", "right", ".", "balance", "end", "if", "(", "node", ".", "down", "!=", "nil", ")", "node", ".", "down", "=", "node", ".", "down", ".", "balance", "end", "node", "end" ]
Recursively balance this node in its own tree, and every node in all four directions, and return the new root node.
[ "Recursively", "balance", "this", "node", "in", "its", "own", "tree", "and", "every", "node", "in", "all", "four", "directions", "and", "return", "the", "new", "root", "node", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L152-L179
9,715
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.walk
def walk(str="", &block) @down.walk(str+char, &block) if @down != nil @left.walk(str, &block) if @left != nil yield str+@char, @value if @value != nil @right.walk(str, &block) if @right != nil end
ruby
def walk(str="", &block) @down.walk(str+char, &block) if @down != nil @left.walk(str, &block) if @left != nil yield str+@char, @value if @value != nil @right.walk(str, &block) if @right != nil end
[ "def", "walk", "(", "str", "=", "\"\"", ",", "&", "block", ")", "@down", ".", "walk", "(", "str", "+", "char", ",", "block", ")", "if", "@down", "!=", "nil", "@left", ".", "walk", "(", "str", ",", "block", ")", "if", "@left", "!=", "nil", "yield", "str", "+", "@char", ",", "@value", "if", "@value", "!=", "nil", "@right", ".", "walk", "(", "str", ",", "block", ")", "if", "@right", "!=", "nil", "end" ]
Walk the tree from this node, yielding all strings and values where the value is not nil. Optionally, use the given prefix String str.
[ "Walk", "the", "tree", "from", "this", "node", "yielding", "all", "strings", "and", "values", "where", "the", "value", "is", "not", "nil", ".", "Optionally", "use", "the", "given", "prefix", "String", "str", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L183-L188
9,716
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.to_s
def to_s st = @char node = self while node != nil node = node.up break if node==nil st = node.char+st end st end
ruby
def to_s st = @char node = self while node != nil node = node.up break if node==nil st = node.char+st end st end
[ "def", "to_s", "st", "=", "@char", "node", "=", "self", "while", "node", "!=", "nil", "node", "=", "node", ".", "up", "break", "if", "node", "==", "nil", "st", "=", "node", ".", "char", "+", "st", "end", "st", "end" ]
Return the complete string from the tree root up to and including this node i.e. The total string key for this node from root.
[ "Return", "the", "complete", "string", "from", "the", "tree", "root", "up", "to", "and", "including", "this", "node", "i", ".", "e", ".", "The", "total", "string", "key", "for", "this", "node", "from", "root", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L192-L201
9,717
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.all_partials
def all_partials(str = "") list = [] @down.walk(str) { |str| list << str } unless @down.nil? list end
ruby
def all_partials(str = "") list = [] @down.walk(str) { |str| list << str } unless @down.nil? list end
[ "def", "all_partials", "(", "str", "=", "\"\"", ")", "list", "=", "[", "]", "@down", ".", "walk", "(", "str", ")", "{", "|", "str", "|", "list", "<<", "str", "}", "unless", "@down", ".", "nil?", "list", "end" ]
Return an Array of Strings of all possible partial string from this node. Optionally, use the given prefix String str.
[ "Return", "an", "Array", "of", "Strings", "of", "all", "possible", "partial", "string", "from", "this", "node", ".", "Optionally", "use", "the", "given", "prefix", "String", "str", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L210-L214
9,718
tomdionysus/stringtree-ruby
lib/stringtree/node.rb
StringTree.Node.prune
def prune return true if !@down.nil? && down.prune return true if !@left.nil? && left.prune return true if !@right.nil? && right.prune return true unless @value.nil? up.down = nil if !up.nil? && left.nil? && right.nil? false end
ruby
def prune return true if !@down.nil? && down.prune return true if !@left.nil? && left.prune return true if !@right.nil? && right.prune return true unless @value.nil? up.down = nil if !up.nil? && left.nil? && right.nil? false end
[ "def", "prune", "return", "true", "if", "!", "@down", ".", "nil?", "&&", "down", ".", "prune", "return", "true", "if", "!", "@left", ".", "nil?", "&&", "left", ".", "prune", "return", "true", "if", "!", "@right", ".", "nil?", "&&", "right", ".", "prune", "return", "true", "unless", "@value", ".", "nil?", "up", ".", "down", "=", "nil", "if", "!", "up", ".", "nil?", "&&", "left", ".", "nil?", "&&", "right", ".", "nil?", "false", "end" ]
Prune the tree back from this node onward so that all leaves have values.
[ "Prune", "the", "tree", "back", "from", "this", "node", "onward", "so", "that", "all", "leaves", "have", "values", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/node.rb#L217-L224
9,719
humpyard/humpyard
app/controllers/humpyard/pages_controller.rb
Humpyard.PagesController.index
def index authorize! :manage, Humpyard::Page @root_page = Humpyard::Page.root @page = Humpyard::Page.find_by_id(params[:actual_page_id]) unless @page.nil? @page = @page.content_data end render :partial => 'index' end
ruby
def index authorize! :manage, Humpyard::Page @root_page = Humpyard::Page.root @page = Humpyard::Page.find_by_id(params[:actual_page_id]) unless @page.nil? @page = @page.content_data end render :partial => 'index' end
[ "def", "index", "authorize!", ":manage", ",", "Humpyard", "::", "Page", "@root_page", "=", "Humpyard", "::", "Page", ".", "root", "@page", "=", "Humpyard", "::", "Page", ".", "find_by_id", "(", "params", "[", ":actual_page_id", "]", ")", "unless", "@page", ".", "nil?", "@page", "=", "@page", ".", "content_data", "end", "render", ":partial", "=>", "'index'", "end" ]
Probably unneccassary - may be removed later
[ "Probably", "unneccassary", "-", "may", "be", "removed", "later" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L8-L18
9,720
humpyard/humpyard
app/controllers/humpyard/pages_controller.rb
Humpyard.PagesController.new
def new @page = Humpyard::config.page_types[params[:type]].new unless can? :create, @page.page render :json => { :status => :failed }, :status => 403 return end @page_type = params[:type] @prev = Humpyard::Page.find_by_id(params[:prev_id]) @next = Humpyard::Page.find_by_id(params[:next_id]) render :partial => 'edit' end
ruby
def new @page = Humpyard::config.page_types[params[:type]].new unless can? :create, @page.page render :json => { :status => :failed }, :status => 403 return end @page_type = params[:type] @prev = Humpyard::Page.find_by_id(params[:prev_id]) @next = Humpyard::Page.find_by_id(params[:next_id]) render :partial => 'edit' end
[ "def", "new", "@page", "=", "Humpyard", "::", "config", ".", "page_types", "[", "params", "[", ":type", "]", "]", ".", "new", "unless", "can?", ":create", ",", "@page", ".", "page", "render", ":json", "=>", "{", ":status", "=>", ":failed", "}", ",", ":status", "=>", "403", "return", "end", "@page_type", "=", "params", "[", ":type", "]", "@prev", "=", "Humpyard", "::", "Page", ".", "find_by_id", "(", "params", "[", ":prev_id", "]", ")", "@next", "=", "Humpyard", "::", "Page", ".", "find_by_id", "(", "params", "[", ":next_id", "]", ")", "render", ":partial", "=>", "'edit'", "end" ]
Dialog content for a new page
[ "Dialog", "content", "for", "a", "new", "page" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L21-L36
9,721
humpyard/humpyard
app/controllers/humpyard/pages_controller.rb
Humpyard.PagesController.update
def update @page = Humpyard::Page.find(params[:id]).content_data if @page unless can? :update, @page.page render :json => { :status => :failed }, :status => 403 return end if @page.update_attributes params[:page] @page.title_for_url = @page.page.suggested_title_for_url @page.save render :json => { :status => :ok, # :dialog => :close, :replace => [ { :element => "hy-page-treeview-text-#{@page.id}", :content => @page.title } ], :flash => { :level => 'info', :content => I18n.t('humpyard_form.flashes.update_success', :model => Humpyard::Page.model_name.human) } } else render :json => { :status => :failed, :errors => @page.errors, :flash => { :level => 'error', :content => I18n.t('humpyard_form.flashes.update_fail', :model => Humpyard::Page.model_name.human) } } end else render :json => { :status => :failed }, :status => 404 end end
ruby
def update @page = Humpyard::Page.find(params[:id]).content_data if @page unless can? :update, @page.page render :json => { :status => :failed }, :status => 403 return end if @page.update_attributes params[:page] @page.title_for_url = @page.page.suggested_title_for_url @page.save render :json => { :status => :ok, # :dialog => :close, :replace => [ { :element => "hy-page-treeview-text-#{@page.id}", :content => @page.title } ], :flash => { :level => 'info', :content => I18n.t('humpyard_form.flashes.update_success', :model => Humpyard::Page.model_name.human) } } else render :json => { :status => :failed, :errors => @page.errors, :flash => { :level => 'error', :content => I18n.t('humpyard_form.flashes.update_fail', :model => Humpyard::Page.model_name.human) } } end else render :json => { :status => :failed }, :status => 404 end end
[ "def", "update", "@page", "=", "Humpyard", "::", "Page", ".", "find", "(", "params", "[", ":id", "]", ")", ".", "content_data", "if", "@page", "unless", "can?", ":update", ",", "@page", ".", "page", "render", ":json", "=>", "{", ":status", "=>", ":failed", "}", ",", ":status", "=>", "403", "return", "end", "if", "@page", ".", "update_attributes", "params", "[", ":page", "]", "@page", ".", "title_for_url", "=", "@page", ".", "page", ".", "suggested_title_for_url", "@page", ".", "save", "render", ":json", "=>", "{", ":status", "=>", ":ok", ",", "# :dialog => :close,", ":replace", "=>", "[", "{", ":element", "=>", "\"hy-page-treeview-text-#{@page.id}\"", ",", ":content", "=>", "@page", ".", "title", "}", "]", ",", ":flash", "=>", "{", ":level", "=>", "'info'", ",", ":content", "=>", "I18n", ".", "t", "(", "'humpyard_form.flashes.update_success'", ",", ":model", "=>", "Humpyard", "::", "Page", ".", "model_name", ".", "human", ")", "}", "}", "else", "render", ":json", "=>", "{", ":status", "=>", ":failed", ",", ":errors", "=>", "@page", ".", "errors", ",", ":flash", "=>", "{", ":level", "=>", "'error'", ",", ":content", "=>", "I18n", ".", "t", "(", "'humpyard_form.flashes.update_fail'", ",", ":model", "=>", "Humpyard", "::", "Page", ".", "model_name", ".", "human", ")", "}", "}", "end", "else", "render", ":json", "=>", "{", ":status", "=>", ":failed", "}", ",", ":status", "=>", "404", "end", "end" ]
Update an existing page
[ "Update", "an", "existing", "page" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L99-L143
9,722
humpyard/humpyard
app/controllers/humpyard/pages_controller.rb
Humpyard.PagesController.move
def move @page = Humpyard::Page.find(params[:id]) if @page unless can? :update, @page render :json => { :status => :failed }, :status => 403 return end parent = Humpyard::Page.find_by_id(params[:parent_id]) # by default, make it possible to move page to root, uncomment to do otherwise: #unless parent # parent = Humpyard::Page.root_page #end @page.update_attribute :parent, parent @prev = Humpyard::Page.find_by_id(params[:prev_id]) @next = Humpyard::Page.find_by_id(params[:next_id]) do_move(@page, @prev, @next) replace_options = { :element => "hy-page-treeview", :content => render_to_string(:partial => "tree.html", :locals => {:page => @page}) } render :json => { :status => :ok, :replace => [replace_options] } else render :json => { :status => :failed }, :status => 404 end end
ruby
def move @page = Humpyard::Page.find(params[:id]) if @page unless can? :update, @page render :json => { :status => :failed }, :status => 403 return end parent = Humpyard::Page.find_by_id(params[:parent_id]) # by default, make it possible to move page to root, uncomment to do otherwise: #unless parent # parent = Humpyard::Page.root_page #end @page.update_attribute :parent, parent @prev = Humpyard::Page.find_by_id(params[:prev_id]) @next = Humpyard::Page.find_by_id(params[:next_id]) do_move(@page, @prev, @next) replace_options = { :element => "hy-page-treeview", :content => render_to_string(:partial => "tree.html", :locals => {:page => @page}) } render :json => { :status => :ok, :replace => [replace_options] } else render :json => { :status => :failed }, :status => 404 end end
[ "def", "move", "@page", "=", "Humpyard", "::", "Page", ".", "find", "(", "params", "[", ":id", "]", ")", "if", "@page", "unless", "can?", ":update", ",", "@page", "render", ":json", "=>", "{", ":status", "=>", ":failed", "}", ",", ":status", "=>", "403", "return", "end", "parent", "=", "Humpyard", "::", "Page", ".", "find_by_id", "(", "params", "[", ":parent_id", "]", ")", "# by default, make it possible to move page to root, uncomment to do otherwise:", "#unless parent", "# parent = Humpyard::Page.root_page", "#end", "@page", ".", "update_attribute", ":parent", ",", "parent", "@prev", "=", "Humpyard", "::", "Page", ".", "find_by_id", "(", "params", "[", ":prev_id", "]", ")", "@next", "=", "Humpyard", "::", "Page", ".", "find_by_id", "(", "params", "[", ":next_id", "]", ")", "do_move", "(", "@page", ",", "@prev", ",", "@next", ")", "replace_options", "=", "{", ":element", "=>", "\"hy-page-treeview\"", ",", ":content", "=>", "render_to_string", "(", ":partial", "=>", "\"tree.html\"", ",", ":locals", "=>", "{", ":page", "=>", "@page", "}", ")", "}", "render", ":json", "=>", "{", ":status", "=>", ":ok", ",", ":replace", "=>", "[", "replace_options", "]", "}", "else", "render", ":json", "=>", "{", ":status", "=>", ":failed", "}", ",", ":status", "=>", "404", "end", "end" ]
Move a page
[ "Move", "a", "page" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L146-L182
9,723
humpyard/humpyard
app/controllers/humpyard/pages_controller.rb
Humpyard.PagesController.show
def show # No page found at the beginning @page = nil if params[:locale] and Humpyard.config.locales.include? params[:locale].to_sym I18n.locale = params[:locale] elsif session[:humpyard_locale] I18n.locale = session[:humpyard_locale] else I18n.locale = Humpyard.config.locales.first end # Find page by name if not params[:webpath].blank? dyn_page_path = false parent_page = nil params[:webpath].split('/').each do |path_part| # Ignore multiple slashes in URLs unless(path_part.blank?) if(dyn_page_path) dyn_page_path << path_part else # Find page by name and parent; parent=nil means page on root level @page = Page.with_translated_attribute(:title_for_url, CGI::escape(path_part), I18n.locale).first # Raise 404 if no page was found for the URL or subpart raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4201) [#{path_part}]" if @page.nil? raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4202)" if not (@page.parent == parent_page or @page.parent == Humpyard::Page.root_page) parent_page = @page unless @page.is_root_page? dyn_page_path = [] if @page.content_data.is_humpyard_dynamic_page? end end end if @page.content_data.is_humpyard_dynamic_page? and dyn_page_path.size > 0 @sub_page = @page.parse_path(dyn_page_path) # Raise 404 if no page was found for the sub_page part raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (D4201)" if @sub_page.blank? @page_partial = "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}" if @sub_page[:partial] @local_vars = {:page => @page}.merge(@sub_page[:locals]) if @sub_page[:locals] and @sub_page[:locals].class == Hash # render partial only if request was an AJAX-call if request.xhr? respond_to do |format| format.html { render :partial => @page_partial, :locals => @local_vars } end return end end # Find page by id elsif not params[:id].blank? # Render page by id if not webpath was given but an id @page = Page.find(params[:id]) # Find root page else # Render index page if neither id or webpath was given @page = Page.root_page :force_reload => true unless @page @page = Page.new render '/humpyard/pages/welcome' return false end end # Raise 404 if no page was found raise ::ActionController::RoutingError, "No route matches \"#{request.path}\"" if @page.nil? or @page.content_data.is_humpyard_virtual_page? response.headers['X-Humpyard-Page'] = "#{@page.id}" response.headers['X-Humpyard-Modified'] = "#{@page.last_modified}" response.headers['X-Humpyard-ServerTime'] = "#{Time.now.utc}" @page_partial ||= "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show" @local_vars ||= {:page => @page} self.class.layout(@page.template_name) if Rails.application.config.action_controller.perform_caching and not @page.always_refresh fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}", :last_modified => @page.last_modified(:include_pages => true), :public => @humpyard_user.nil? end end
ruby
def show # No page found at the beginning @page = nil if params[:locale] and Humpyard.config.locales.include? params[:locale].to_sym I18n.locale = params[:locale] elsif session[:humpyard_locale] I18n.locale = session[:humpyard_locale] else I18n.locale = Humpyard.config.locales.first end # Find page by name if not params[:webpath].blank? dyn_page_path = false parent_page = nil params[:webpath].split('/').each do |path_part| # Ignore multiple slashes in URLs unless(path_part.blank?) if(dyn_page_path) dyn_page_path << path_part else # Find page by name and parent; parent=nil means page on root level @page = Page.with_translated_attribute(:title_for_url, CGI::escape(path_part), I18n.locale).first # Raise 404 if no page was found for the URL or subpart raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4201) [#{path_part}]" if @page.nil? raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (X4202)" if not (@page.parent == parent_page or @page.parent == Humpyard::Page.root_page) parent_page = @page unless @page.is_root_page? dyn_page_path = [] if @page.content_data.is_humpyard_dynamic_page? end end end if @page.content_data.is_humpyard_dynamic_page? and dyn_page_path.size > 0 @sub_page = @page.parse_path(dyn_page_path) # Raise 404 if no page was found for the sub_page part raise ::ActionController::RoutingError, "No route matches \"#{request.path}\" (D4201)" if @sub_page.blank? @page_partial = "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}" if @sub_page[:partial] @local_vars = {:page => @page}.merge(@sub_page[:locals]) if @sub_page[:locals] and @sub_page[:locals].class == Hash # render partial only if request was an AJAX-call if request.xhr? respond_to do |format| format.html { render :partial => @page_partial, :locals => @local_vars } end return end end # Find page by id elsif not params[:id].blank? # Render page by id if not webpath was given but an id @page = Page.find(params[:id]) # Find root page else # Render index page if neither id or webpath was given @page = Page.root_page :force_reload => true unless @page @page = Page.new render '/humpyard/pages/welcome' return false end end # Raise 404 if no page was found raise ::ActionController::RoutingError, "No route matches \"#{request.path}\"" if @page.nil? or @page.content_data.is_humpyard_virtual_page? response.headers['X-Humpyard-Page'] = "#{@page.id}" response.headers['X-Humpyard-Modified'] = "#{@page.last_modified}" response.headers['X-Humpyard-ServerTime'] = "#{Time.now.utc}" @page_partial ||= "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show" @local_vars ||= {:page => @page} self.class.layout(@page.template_name) if Rails.application.config.action_controller.perform_caching and not @page.always_refresh fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}", :last_modified => @page.last_modified(:include_pages => true), :public => @humpyard_user.nil? end end
[ "def", "show", "# No page found at the beginning", "@page", "=", "nil", "if", "params", "[", ":locale", "]", "and", "Humpyard", ".", "config", ".", "locales", ".", "include?", "params", "[", ":locale", "]", ".", "to_sym", "I18n", ".", "locale", "=", "params", "[", ":locale", "]", "elsif", "session", "[", ":humpyard_locale", "]", "I18n", ".", "locale", "=", "session", "[", ":humpyard_locale", "]", "else", "I18n", ".", "locale", "=", "Humpyard", ".", "config", ".", "locales", ".", "first", "end", "# Find page by name", "if", "not", "params", "[", ":webpath", "]", ".", "blank?", "dyn_page_path", "=", "false", "parent_page", "=", "nil", "params", "[", ":webpath", "]", ".", "split", "(", "'/'", ")", ".", "each", "do", "|", "path_part", "|", "# Ignore multiple slashes in URLs", "unless", "(", "path_part", ".", "blank?", ")", "if", "(", "dyn_page_path", ")", "dyn_page_path", "<<", "path_part", "else", "# Find page by name and parent; parent=nil means page on root level", "@page", "=", "Page", ".", "with_translated_attribute", "(", ":title_for_url", ",", "CGI", "::", "escape", "(", "path_part", ")", ",", "I18n", ".", "locale", ")", ".", "first", "# Raise 404 if no page was found for the URL or subpart", "raise", "::", "ActionController", "::", "RoutingError", ",", "\"No route matches \\\"#{request.path}\\\" (X4201) [#{path_part}]\"", "if", "@page", ".", "nil?", "raise", "::", "ActionController", "::", "RoutingError", ",", "\"No route matches \\\"#{request.path}\\\" (X4202)\"", "if", "not", "(", "@page", ".", "parent", "==", "parent_page", "or", "@page", ".", "parent", "==", "Humpyard", "::", "Page", ".", "root_page", ")", "parent_page", "=", "@page", "unless", "@page", ".", "is_root_page?", "dyn_page_path", "=", "[", "]", "if", "@page", ".", "content_data", ".", "is_humpyard_dynamic_page?", "end", "end", "end", "if", "@page", ".", "content_data", ".", "is_humpyard_dynamic_page?", "and", "dyn_page_path", ".", "size", ">", "0", "@sub_page", "=", "@page", ".", "parse_path", "(", "dyn_page_path", ")", "# Raise 404 if no page was found for the sub_page part", "raise", "::", "ActionController", "::", "RoutingError", ",", "\"No route matches \\\"#{request.path}\\\" (D4201)\"", "if", "@sub_page", ".", "blank?", "@page_partial", "=", "\"/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}\"", "if", "@sub_page", "[", ":partial", "]", "@local_vars", "=", "{", ":page", "=>", "@page", "}", ".", "merge", "(", "@sub_page", "[", ":locals", "]", ")", "if", "@sub_page", "[", ":locals", "]", "and", "@sub_page", "[", ":locals", "]", ".", "class", "==", "Hash", "# render partial only if request was an AJAX-call", "if", "request", ".", "xhr?", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "render", ":partial", "=>", "@page_partial", ",", ":locals", "=>", "@local_vars", "}", "end", "return", "end", "end", "# Find page by id", "elsif", "not", "params", "[", ":id", "]", ".", "blank?", "# Render page by id if not webpath was given but an id", "@page", "=", "Page", ".", "find", "(", "params", "[", ":id", "]", ")", "# Find root page", "else", "# Render index page if neither id or webpath was given", "@page", "=", "Page", ".", "root_page", ":force_reload", "=>", "true", "unless", "@page", "@page", "=", "Page", ".", "new", "render", "'/humpyard/pages/welcome'", "return", "false", "end", "end", "# Raise 404 if no page was found", "raise", "::", "ActionController", "::", "RoutingError", ",", "\"No route matches \\\"#{request.path}\\\"\"", "if", "@page", ".", "nil?", "or", "@page", ".", "content_data", ".", "is_humpyard_virtual_page?", "response", ".", "headers", "[", "'X-Humpyard-Page'", "]", "=", "\"#{@page.id}\"", "response", ".", "headers", "[", "'X-Humpyard-Modified'", "]", "=", "\"#{@page.last_modified}\"", "response", ".", "headers", "[", "'X-Humpyard-ServerTime'", "]", "=", "\"#{Time.now.utc}\"", "@page_partial", "||=", "\"/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show\"", "@local_vars", "||=", "{", ":page", "=>", "@page", "}", "self", ".", "class", ".", "layout", "(", "@page", ".", "template_name", ")", "if", "Rails", ".", "application", ".", "config", ".", "action_controller", ".", "perform_caching", "and", "not", "@page", ".", "always_refresh", "fresh_when", ":etag", "=>", "\"#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}\"", ",", ":last_modified", "=>", "@page", ".", "last_modified", "(", ":include_pages", "=>", "true", ")", ",", ":public", "=>", "@humpyard_user", ".", "nil?", "end", "end" ]
Render a given page When a "webpath" parameter is given it will render the page with that name. This is what happens when you call a page with it's pretty URL. When no "name" is given and an "id" parameter is given it will render the page with the given id. When no "name" nor "id" parameter is given it will render the root page.
[ "Render", "a", "given", "page" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L203-L287
9,724
humpyard/humpyard
app/controllers/humpyard/pages_controller.rb
Humpyard.PagesController.sitemap
def sitemap require 'builder' xml = ::Builder::XmlMarkup.new :indent => 2 xml.instruct! xml.tag! :urlset, { 'xmlns'=>"http://www.sitemaps.org/schemas/sitemap/0.9", 'xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance", 'xsi:schemaLocation'=>"http://www.sitemaps.org/schemas/sitemap/0.9\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" } do base_url = "#{request.protocol}#{request.host}#{request.port==80 ? '' : ":#{request.port}"}" if root_page = Page.root_page Humpyard.config.locales.each do |locale| add_to_sitemap xml, base_url, locale, [{ :index => true, :url => root_page.human_url(:locale => locale), :lastmod => root_page.last_modified, :children => [] }] + root_page.child_pages(:single_root => true).map{|p| p.content_data.site_map(locale)} end end end render :xml => xml.target! end
ruby
def sitemap require 'builder' xml = ::Builder::XmlMarkup.new :indent => 2 xml.instruct! xml.tag! :urlset, { 'xmlns'=>"http://www.sitemaps.org/schemas/sitemap/0.9", 'xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance", 'xsi:schemaLocation'=>"http://www.sitemaps.org/schemas/sitemap/0.9\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" } do base_url = "#{request.protocol}#{request.host}#{request.port==80 ? '' : ":#{request.port}"}" if root_page = Page.root_page Humpyard.config.locales.each do |locale| add_to_sitemap xml, base_url, locale, [{ :index => true, :url => root_page.human_url(:locale => locale), :lastmod => root_page.last_modified, :children => [] }] + root_page.child_pages(:single_root => true).map{|p| p.content_data.site_map(locale)} end end end render :xml => xml.target! end
[ "def", "sitemap", "require", "'builder'", "xml", "=", "::", "Builder", "::", "XmlMarkup", ".", "new", ":indent", "=>", "2", "xml", ".", "instruct!", "xml", ".", "tag!", ":urlset", ",", "{", "'xmlns'", "=>", "\"http://www.sitemaps.org/schemas/sitemap/0.9\"", ",", "'xmlns:xsi'", "=>", "\"http://www.w3.org/2001/XMLSchema-instance\"", ",", "'xsi:schemaLocation'", "=>", "\"http://www.sitemaps.org/schemas/sitemap/0.9\\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\"", "}", "do", "base_url", "=", "\"#{request.protocol}#{request.host}#{request.port==80 ? '' : \":#{request.port}\"}\"", "if", "root_page", "=", "Page", ".", "root_page", "Humpyard", ".", "config", ".", "locales", ".", "each", "do", "|", "locale", "|", "add_to_sitemap", "xml", ",", "base_url", ",", "locale", ",", "[", "{", ":index", "=>", "true", ",", ":url", "=>", "root_page", ".", "human_url", "(", ":locale", "=>", "locale", ")", ",", ":lastmod", "=>", "root_page", ".", "last_modified", ",", ":children", "=>", "[", "]", "}", "]", "+", "root_page", ".", "child_pages", "(", ":single_root", "=>", "true", ")", ".", "map", "{", "|", "p", "|", "p", ".", "content_data", ".", "site_map", "(", "locale", ")", "}", "end", "end", "end", "render", ":xml", "=>", "xml", ".", "target!", "end" ]
Render the sitemap.xml for robots
[ "Render", "the", "sitemap", ".", "xml", "for", "robots" ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/pages_controller.rb#L290-L315
9,725
ideonetwork/lato-blog
app/models/lato_blog/post_field.rb
LatoBlog.PostField.update_child_visibility
def update_child_visibility return if meta_visible == meta_visible_was post_fields.map { |pf| pf.update(meta_visible: meta_visible) } end
ruby
def update_child_visibility return if meta_visible == meta_visible_was post_fields.map { |pf| pf.update(meta_visible: meta_visible) } end
[ "def", "update_child_visibility", "return", "if", "meta_visible", "==", "meta_visible_was", "post_fields", ".", "map", "{", "|", "pf", "|", "pf", ".", "update", "(", "meta_visible", ":", "meta_visible", ")", "}", "end" ]
This functions update all post fields child visibility with the current post field visibility.
[ "This", "functions", "update", "all", "post", "fields", "child", "visibility", "with", "the", "current", "post", "field", "visibility", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post_field.rb#L43-L46
9,726
jeremyvdw/disqussion
lib/disqussion/client/posts.rb
Disqussion.Posts.vote
def vote(*args) options = args.last.is_a?(Hash) ? args.pop : {} if args.length == 2 options.merge!(:vote => args[0]) options.merge!(:post => args[1]) response = post('posts/vote', options) else puts "#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID" end end
ruby
def vote(*args) options = args.last.is_a?(Hash) ? args.pop : {} if args.length == 2 options.merge!(:vote => args[0]) options.merge!(:post => args[1]) response = post('posts/vote', options) else puts "#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID" end end
[ "def", "vote", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "if", "args", ".", "length", "==", "2", "options", ".", "merge!", "(", ":vote", "=>", "args", "[", "0", "]", ")", "options", ".", "merge!", "(", ":post", "=>", "args", "[", "1", "]", ")", "response", "=", "post", "(", "'posts/vote'", ",", "options", ")", "else", "puts", "\"#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID\"", "end", "end" ]
Register a vote for a post. @accessibility: public key, secret key @methods: POST @format: json, jsonp @authenticated: true @limited: false @param vote [Integer] Choices: -1, 0, 1 @param post [Integer] Looks up a post by ID. @return [Hashie::Rash] Details on the post. @example Vote for post ID 12345678 Disqussion::Client.posts.vote(1, 12345678) @see: http://disqus.com/api/3.0/posts/vote.json
[ "Register", "a", "vote", "for", "a", "post", "." ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/posts.rb#L275-L284
9,727
tmcarthur/DAF
lib/daf/datasources/yaml_data_source.rb
DAF.YAMLDataSource.action_options
def action_options # Attempt resolution to outputs of monitor return @action_options unless @monitor_class.outputs.length > 0 action_options = @action_options.clone @monitor_class.outputs.each do |output, _type| action_options.each do |option_key, option_value| action_options[option_key] = option_value.gsub("{{#{output}}}", @monitor.send(output).to_s) end end action_options end
ruby
def action_options # Attempt resolution to outputs of monitor return @action_options unless @monitor_class.outputs.length > 0 action_options = @action_options.clone @monitor_class.outputs.each do |output, _type| action_options.each do |option_key, option_value| action_options[option_key] = option_value.gsub("{{#{output}}}", @monitor.send(output).to_s) end end action_options end
[ "def", "action_options", "# Attempt resolution to outputs of monitor", "return", "@action_options", "unless", "@monitor_class", ".", "outputs", ".", "length", ">", "0", "action_options", "=", "@action_options", ".", "clone", "@monitor_class", ".", "outputs", ".", "each", "do", "|", "output", ",", "_type", "|", "action_options", ".", "each", "do", "|", "option_key", ",", "option_value", "|", "action_options", "[", "option_key", "]", "=", "option_value", ".", "gsub", "(", "\"{{#{output}}}\"", ",", "@monitor", ".", "send", "(", "output", ")", ".", "to_s", ")", "end", "end", "action_options", "end" ]
Accepts the path of the YAML file to be parsed into commands - will throw a CommandException should it have invalid parameters @param filePath [String] Path for YAML file
[ "Accepts", "the", "path", "of", "the", "YAML", "file", "to", "be", "parsed", "into", "commands", "-", "will", "throw", "a", "CommandException", "should", "it", "have", "invalid", "parameters" ]
e88d67ec123cc911131dbc74d33735378224703b
https://github.com/tmcarthur/DAF/blob/e88d67ec123cc911131dbc74d33735378224703b/lib/daf/datasources/yaml_data_source.rb#L24-L35
9,728
deepfryed/pony-express
lib/pony-express.rb
PonyExpress.Mail.remove
def remove keys keys = keys.map(&:to_sym) @options.reject! {|k, v| keys.include?(k) } end
ruby
def remove keys keys = keys.map(&:to_sym) @options.reject! {|k, v| keys.include?(k) } end
[ "def", "remove", "keys", "keys", "=", "keys", ".", "map", "(", ":to_sym", ")", "@options", ".", "reject!", "{", "|", "k", ",", "v", "|", "keys", ".", "include?", "(", "k", ")", "}", "end" ]
Remove an option. @example remove. require "pony-express" mail = PonyExpress::Mail.new mail.add to: "burns@plant.local", cc: "smithers@plant.local" mail.remove :cc
[ "Remove", "an", "option", "." ]
adedc87a6d47591a56dd2c4fc69339274a754754
https://github.com/deepfryed/pony-express/blob/adedc87a6d47591a56dd2c4fc69339274a754754/lib/pony-express.rb#L128-L131
9,729
rubiii/ambience
lib/ambience/config.rb
Ambience.Config.to_hash
def to_hash config = load_base_config config = config.deep_merge(load_env_config) config.deep_merge(load_jvm_config) end
ruby
def to_hash config = load_base_config config = config.deep_merge(load_env_config) config.deep_merge(load_jvm_config) end
[ "def", "to_hash", "config", "=", "load_base_config", "config", "=", "config", ".", "deep_merge", "(", "load_env_config", ")", "config", ".", "deep_merge", "(", "load_jvm_config", ")", "end" ]
Returns the Ambience config as a Hash.
[ "Returns", "the", "Ambience", "config", "as", "a", "Hash", "." ]
25f6e4a94cbed60c719307616fa37a23ecd0fbc2
https://github.com/rubiii/ambience/blob/25f6e4a94cbed60c719307616fa37a23ecd0fbc2/lib/ambience/config.rb#L38-L42
9,730
rubiii/ambience
lib/ambience/config.rb
Ambience.Config.hash_from_property
def hash_from_property(property, value) property.split(".").reverse.inject(value) { |value, item| { item => value } } end
ruby
def hash_from_property(property, value) property.split(".").reverse.inject(value) { |value, item| { item => value } } end
[ "def", "hash_from_property", "(", "property", ",", "value", ")", "property", ".", "split", "(", "\".\"", ")", ".", "reverse", ".", "inject", "(", "value", ")", "{", "|", "value", ",", "item", "|", "{", "item", "=>", "value", "}", "}", "end" ]
Returns a Hash generated from a JVM +property+ and its +value+. ==== Example: hash_from_property "webservice.auth.address", "http://auth.example.com" # => { "webservice" => { "auth" => { "address" => "http://auth.example.com" } } }
[ "Returns", "a", "Hash", "generated", "from", "a", "JVM", "+", "property", "+", "and", "its", "+", "value", "+", "." ]
25f6e4a94cbed60c719307616fa37a23ecd0fbc2
https://github.com/rubiii/ambience/blob/25f6e4a94cbed60c719307616fa37a23ecd0fbc2/lib/ambience/config.rb#L85-L87
9,731
acnalesso/anagram_solver
lib/anagram_solver/permutator.rb
AnagramSolver.Permutator.precompute_old
def precompute_old warn "This method should not be used, please use precompute instead." word_list.rewind.each do |line| word = line.chomp precomputed_list_old[word.split('').sort.join.freeze] += [word] end end
ruby
def precompute_old warn "This method should not be used, please use precompute instead." word_list.rewind.each do |line| word = line.chomp precomputed_list_old[word.split('').sort.join.freeze] += [word] end end
[ "def", "precompute_old", "warn", "\"This method should not be used, please use precompute instead.\"", "word_list", ".", "rewind", ".", "each", "do", "|", "line", "|", "word", "=", "line", ".", "chomp", "precomputed_list_old", "[", "word", ".", "split", "(", "''", ")", ".", "sort", ".", "join", ".", "freeze", "]", "+=", "[", "word", "]", "end", "end" ]
Initializes word_list instance variable, precomputed_list assigning it a hash whose default values is an empty array. Precomputes word_list in underneath the hood. (i.e A in-process thread that AsyncConsumer offers. ) Used for benchmarking
[ "Initializes", "word_list", "instance", "variable", "precomputed_list", "assigning", "it", "a", "hash", "whose", "default", "values", "is", "an", "empty", "array", "." ]
edb228d8472e898ff06360cfc098d80a43e7d0ea
https://github.com/acnalesso/anagram_solver/blob/edb228d8472e898ff06360cfc098d80a43e7d0ea/lib/anagram_solver/permutator.rb#L36-L42
9,732
cbrumelle/blueprintr
lib/blueprint-css/lib/blueprint/compressor.rb
Blueprint.Compressor.initialize_project_from_yaml
def initialize_project_from_yaml(project_name = nil) # ensures project_name is set and settings.yml is present return unless (project_name && File.exist?(@settings_file)) # loads yaml into hash projects = YAML::load(File.path_to_string(@settings_file)) if (project = projects[project_name]) # checks to see if project info is present self.namespace = project['namespace'] || "" self.destination_path = (self.destination_path == Blueprint::BLUEPRINT_ROOT_PATH ? project['path'] : self.destination_path) || Blueprint::BLUEPRINT_ROOT_PATH self.custom_css = project['custom_css'] || {} self.semantic_classes = project['semantic_classes'] || {} self.plugins = project['plugins'] || [] if (layout = project['custom_layout']) self.custom_layout = CustomLayout.new(:column_count => layout['column_count'], :column_width => layout['column_width'], :gutter_width => layout['gutter_width'], :input_padding => layout['input_padding'], :input_border => layout['input_border']) end @loaded_from_settings = true end end
ruby
def initialize_project_from_yaml(project_name = nil) # ensures project_name is set and settings.yml is present return unless (project_name && File.exist?(@settings_file)) # loads yaml into hash projects = YAML::load(File.path_to_string(@settings_file)) if (project = projects[project_name]) # checks to see if project info is present self.namespace = project['namespace'] || "" self.destination_path = (self.destination_path == Blueprint::BLUEPRINT_ROOT_PATH ? project['path'] : self.destination_path) || Blueprint::BLUEPRINT_ROOT_PATH self.custom_css = project['custom_css'] || {} self.semantic_classes = project['semantic_classes'] || {} self.plugins = project['plugins'] || [] if (layout = project['custom_layout']) self.custom_layout = CustomLayout.new(:column_count => layout['column_count'], :column_width => layout['column_width'], :gutter_width => layout['gutter_width'], :input_padding => layout['input_padding'], :input_border => layout['input_border']) end @loaded_from_settings = true end end
[ "def", "initialize_project_from_yaml", "(", "project_name", "=", "nil", ")", "# ensures project_name is set and settings.yml is present", "return", "unless", "(", "project_name", "&&", "File", ".", "exist?", "(", "@settings_file", ")", ")", "# loads yaml into hash", "projects", "=", "YAML", "::", "load", "(", "File", ".", "path_to_string", "(", "@settings_file", ")", ")", "if", "(", "project", "=", "projects", "[", "project_name", "]", ")", "# checks to see if project info is present", "self", ".", "namespace", "=", "project", "[", "'namespace'", "]", "||", "\"\"", "self", ".", "destination_path", "=", "(", "self", ".", "destination_path", "==", "Blueprint", "::", "BLUEPRINT_ROOT_PATH", "?", "project", "[", "'path'", "]", ":", "self", ".", "destination_path", ")", "||", "Blueprint", "::", "BLUEPRINT_ROOT_PATH", "self", ".", "custom_css", "=", "project", "[", "'custom_css'", "]", "||", "{", "}", "self", ".", "semantic_classes", "=", "project", "[", "'semantic_classes'", "]", "||", "{", "}", "self", ".", "plugins", "=", "project", "[", "'plugins'", "]", "||", "[", "]", "if", "(", "layout", "=", "project", "[", "'custom_layout'", "]", ")", "self", ".", "custom_layout", "=", "CustomLayout", ".", "new", "(", ":column_count", "=>", "layout", "[", "'column_count'", "]", ",", ":column_width", "=>", "layout", "[", "'column_width'", "]", ",", ":gutter_width", "=>", "layout", "[", "'gutter_width'", "]", ",", ":input_padding", "=>", "layout", "[", "'input_padding'", "]", ",", ":input_border", "=>", "layout", "[", "'input_border'", "]", ")", "end", "@loaded_from_settings", "=", "true", "end", "end" ]
attempts to load output settings from settings.yml
[ "attempts", "to", "load", "output", "settings", "from", "settings", ".", "yml" ]
b414436f614a8d97d77b47b588ddcf3f5e61b6bd
https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/compressor.rb#L77-L96
9,733
bradfeehan/derelict
lib/derelict/executer.rb
Derelict.Executer.execute
def execute(command, &block) logger.info "Executing command '#{command}'" reset pid, stdin, stdout_stream, stderr_stream = Open4::popen4(command) @pid = pid stdin.close rescue nil save_exit_status(pid) forward_signals_to(pid) do handle_streams stdout_stream, stderr_stream, &block end self ensure logger.debug "Closing stdout and stderr streams for process" stdout.close rescue nil stderr.close rescue nil end
ruby
def execute(command, &block) logger.info "Executing command '#{command}'" reset pid, stdin, stdout_stream, stderr_stream = Open4::popen4(command) @pid = pid stdin.close rescue nil save_exit_status(pid) forward_signals_to(pid) do handle_streams stdout_stream, stderr_stream, &block end self ensure logger.debug "Closing stdout and stderr streams for process" stdout.close rescue nil stderr.close rescue nil end
[ "def", "execute", "(", "command", ",", "&", "block", ")", "logger", ".", "info", "\"Executing command '#{command}'\"", "reset", "pid", ",", "stdin", ",", "stdout_stream", ",", "stderr_stream", "=", "Open4", "::", "popen4", "(", "command", ")", "@pid", "=", "pid", "stdin", ".", "close", "rescue", "nil", "save_exit_status", "(", "pid", ")", "forward_signals_to", "(", "pid", ")", "do", "handle_streams", "stdout_stream", ",", "stderr_stream", ",", "block", "end", "self", "ensure", "logger", ".", "debug", "\"Closing stdout and stderr streams for process\"", "stdout", ".", "close", "rescue", "nil", "stderr", ".", "close", "rescue", "nil", "end" ]
Initializes an Executer instance with particular options * options: A hash of options, with the following (symbol) keys: * :mode: Controls how the process' output is given to the block, one of :chars (pass each character one by one, retrieved with getc), or :lines (pass only whole lines, retrieved with gets). (optional, defaults to :lines) * :no_buffer: If true, the process' stdout and stderr won't be collected in the stdout and stderr properties, and will only be passed to the block (optional, defaults to false) Executes <tt>command</tt> and returns after execution * command: A string containing the command to run * block: Gets passed stdout and stderr every time the process outputs to each stream (first parameter is stdout, second parameter is stderr; only one will contain data, the other will be nil)
[ "Initializes", "an", "Executer", "instance", "with", "particular", "options" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L68-L85
9,734
bradfeehan/derelict
lib/derelict/executer.rb
Derelict.Executer.forward_signals_to
def forward_signals_to(pid, signals = %w[INT]) # Set up signal handlers logger.debug "Setting up signal handlers for #{signals.inspect}" signal_count = 0 signals.each do |signal| Signal.trap(signal) do Process.kill signal, pid rescue nil # If this is the second time we've received and forwarded # on the signal, make sure next time we just give up. reset_handlers_for signals if ++signal_count >= 2 end end # Run the block now that the signals are being forwarded yield ensure # Always good to make sure we clean up after ourselves reset_handlers_for signals end
ruby
def forward_signals_to(pid, signals = %w[INT]) # Set up signal handlers logger.debug "Setting up signal handlers for #{signals.inspect}" signal_count = 0 signals.each do |signal| Signal.trap(signal) do Process.kill signal, pid rescue nil # If this is the second time we've received and forwarded # on the signal, make sure next time we just give up. reset_handlers_for signals if ++signal_count >= 2 end end # Run the block now that the signals are being forwarded yield ensure # Always good to make sure we clean up after ourselves reset_handlers_for signals end
[ "def", "forward_signals_to", "(", "pid", ",", "signals", "=", "%w[", "INT", "]", ")", "# Set up signal handlers", "logger", ".", "debug", "\"Setting up signal handlers for #{signals.inspect}\"", "signal_count", "=", "0", "signals", ".", "each", "do", "|", "signal", "|", "Signal", ".", "trap", "(", "signal", ")", "do", "Process", ".", "kill", "signal", ",", "pid", "rescue", "nil", "# If this is the second time we've received and forwarded", "# on the signal, make sure next time we just give up.", "reset_handlers_for", "signals", "if", "+", "+", "signal_count", ">=", "2", "end", "end", "# Run the block now that the signals are being forwarded", "yield", "ensure", "# Always good to make sure we clean up after ourselves", "reset_handlers_for", "signals", "end" ]
Forward signals to a process while running the given block * pid: The process ID to forward signals to * signals: The names of the signals to handle (optional, defaults to SIGINT only)
[ "Forward", "signals", "to", "a", "process", "while", "running", "the", "given", "block" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L129-L148
9,735
bradfeehan/derelict
lib/derelict/executer.rb
Derelict.Executer.reset_handlers_for
def reset_handlers_for(signals) logger.debug "Resetting signal handlers for #{signals.inspect}" signals.each {|signal| Signal.trap signal, "DEFAULT" } end
ruby
def reset_handlers_for(signals) logger.debug "Resetting signal handlers for #{signals.inspect}" signals.each {|signal| Signal.trap signal, "DEFAULT" } end
[ "def", "reset_handlers_for", "(", "signals", ")", "logger", ".", "debug", "\"Resetting signal handlers for #{signals.inspect}\"", "signals", ".", "each", "{", "|", "signal", "|", "Signal", ".", "trap", "signal", ",", "\"DEFAULT\"", "}", "end" ]
Resets the handlers for particular signals to the default * signals: An array of signal names to reset the handlers for
[ "Resets", "the", "handlers", "for", "particular", "signals", "to", "the", "default" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L153-L156
9,736
bradfeehan/derelict
lib/derelict/executer.rb
Derelict.Executer.handle_streams
def handle_streams(stdout_stream, stderr_stream, &block) logger.debug "Monitoring stdout/stderr streams for output" streams = [stdout_stream, stderr_stream] until streams.empty? # Find which streams are ready for reading, timeout 0.1s selected, = select(streams, nil, nil, 0.1) # Try again if none were ready next if selected.nil? or selected.empty? selected.each do |stream| if stream.eof? logger.debug "Stream reached end-of-file" if @success.nil? logger.debug "Process hasn't finished, keeping stream" else logger.debug "Removing stream" streams.delete(stream) end next end while data = @reader.call(stream) data = ((@options[:mode] == :chars) ? data.chr : data) stream_name = (stream == stdout_stream) ? :stdout : :stderr output data, stream_name, &block unless block.nil? buffer data, stream_name unless @options[:no_buffer] end end end end
ruby
def handle_streams(stdout_stream, stderr_stream, &block) logger.debug "Monitoring stdout/stderr streams for output" streams = [stdout_stream, stderr_stream] until streams.empty? # Find which streams are ready for reading, timeout 0.1s selected, = select(streams, nil, nil, 0.1) # Try again if none were ready next if selected.nil? or selected.empty? selected.each do |stream| if stream.eof? logger.debug "Stream reached end-of-file" if @success.nil? logger.debug "Process hasn't finished, keeping stream" else logger.debug "Removing stream" streams.delete(stream) end next end while data = @reader.call(stream) data = ((@options[:mode] == :chars) ? data.chr : data) stream_name = (stream == stdout_stream) ? :stdout : :stderr output data, stream_name, &block unless block.nil? buffer data, stream_name unless @options[:no_buffer] end end end end
[ "def", "handle_streams", "(", "stdout_stream", ",", "stderr_stream", ",", "&", "block", ")", "logger", ".", "debug", "\"Monitoring stdout/stderr streams for output\"", "streams", "=", "[", "stdout_stream", ",", "stderr_stream", "]", "until", "streams", ".", "empty?", "# Find which streams are ready for reading, timeout 0.1s", "selected", ",", "=", "select", "(", "streams", ",", "nil", ",", "nil", ",", "0.1", ")", "# Try again if none were ready", "next", "if", "selected", ".", "nil?", "or", "selected", ".", "empty?", "selected", ".", "each", "do", "|", "stream", "|", "if", "stream", ".", "eof?", "logger", ".", "debug", "\"Stream reached end-of-file\"", "if", "@success", ".", "nil?", "logger", ".", "debug", "\"Process hasn't finished, keeping stream\"", "else", "logger", ".", "debug", "\"Removing stream\"", "streams", ".", "delete", "(", "stream", ")", "end", "next", "end", "while", "data", "=", "@reader", ".", "call", "(", "stream", ")", "data", "=", "(", "(", "@options", "[", ":mode", "]", "==", ":chars", ")", "?", "data", ".", "chr", ":", "data", ")", "stream_name", "=", "(", "stream", "==", "stdout_stream", ")", "?", ":stdout", ":", ":stderr", "output", "data", ",", "stream_name", ",", "block", "unless", "block", ".", "nil?", "buffer", "data", ",", "stream_name", "unless", "@options", "[", ":no_buffer", "]", "end", "end", "end", "end" ]
Manages reading from the stdout and stderr streams * stdout_stream: The process' stdout stream * stderr_stream: The process' stderr stream * block: The block to pass output to (optional)
[ "Manages", "reading", "from", "the", "stdout", "and", "stderr", "streams" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L163-L193
9,737
bradfeehan/derelict
lib/derelict/executer.rb
Derelict.Executer.output
def output(data, stream_name = :stdout, &block) # Pass the output to the block if block.arity == 2 args = [nil, nil] if stream_name == :stdout args[0] = data else args[1] = data end block.call(*args) else yield data if stream_name == :stdout end end
ruby
def output(data, stream_name = :stdout, &block) # Pass the output to the block if block.arity == 2 args = [nil, nil] if stream_name == :stdout args[0] = data else args[1] = data end block.call(*args) else yield data if stream_name == :stdout end end
[ "def", "output", "(", "data", ",", "stream_name", "=", ":stdout", ",", "&", "block", ")", "# Pass the output to the block", "if", "block", ".", "arity", "==", "2", "args", "=", "[", "nil", ",", "nil", "]", "if", "stream_name", "==", ":stdout", "args", "[", "0", "]", "=", "data", "else", "args", "[", "1", "]", "=", "data", "end", "block", ".", "call", "(", "args", ")", "else", "yield", "data", "if", "stream_name", "==", ":stdout", "end", "end" ]
Outputs data to the block * data: The data that needs to be passed to the block * stream_name: The stream data came from (:stdout or :stderr) * block: The block to pass the data to
[ "Outputs", "data", "to", "the", "block" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/executer.rb#L200-L213
9,738
tmcarthur/DAF
lib/daf/command.rb
DAF.Command.execute
def execute @thread = Thread.new do if Thread.current != Thread.main loop do @datasource.monitor.on_trigger do @datasource.action.activate(@datasource.action_options) end end end end end
ruby
def execute @thread = Thread.new do if Thread.current != Thread.main loop do @datasource.monitor.on_trigger do @datasource.action.activate(@datasource.action_options) end end end end end
[ "def", "execute", "@thread", "=", "Thread", ".", "new", "do", "if", "Thread", ".", "current", "!=", "Thread", ".", "main", "loop", "do", "@datasource", ".", "monitor", ".", "on_trigger", "do", "@datasource", ".", "action", ".", "activate", "(", "@datasource", ".", "action_options", ")", "end", "end", "end", "end", "end" ]
Create a new command object from a data source @param datasource [CommandDataSource] The data source to use to initialize command object Begins executing the command by starting the monitor specified in the data source - will return immediately
[ "Create", "a", "new", "command", "object", "from", "a", "data", "source" ]
e88d67ec123cc911131dbc74d33735378224703b
https://github.com/tmcarthur/DAF/blob/e88d67ec123cc911131dbc74d33735378224703b/lib/daf/command.rb#L21-L31
9,739
sugaryourcoffee/syclink
lib/syclink/link_checker.rb
SycLink.LinkChecker.response_of_uri
def response_of_uri(uri) begin Net::HTTP.start(uri.host, uri.port) do |http| http.head(uri.path.size > 0 ? uri.path : "/").code end rescue Exception => e "Error" end end
ruby
def response_of_uri(uri) begin Net::HTTP.start(uri.host, uri.port) do |http| http.head(uri.path.size > 0 ? uri.path : "/").code end rescue Exception => e "Error" end end
[ "def", "response_of_uri", "(", "uri", ")", "begin", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "do", "|", "http", "|", "http", ".", "head", "(", "uri", ".", "path", ".", "size", ">", "0", "?", "uri", ".", "path", ":", "\"/\"", ")", ".", "code", "end", "rescue", "Exception", "=>", "e", "\"Error\"", "end", "end" ]
Checks whether the uri is reachable. If so it returns '200' otherwise 'Error'. uri has to have a host, that is uri.host should not be nil
[ "Checks", "whether", "the", "uri", "is", "reachable", ".", "If", "so", "it", "returns", "200", "otherwise", "Error", ".", "uri", "has", "to", "have", "a", "host", "that", "is", "uri", ".", "host", "should", "not", "be", "nil" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/link_checker.rb#L20-L28
9,740
celldee/ffi-rxs
lib/ffi-rxs/poll.rb
XS.Poller.register
def register sock, events = XS::POLLIN | XS::POLLOUT, fd = 0 return false if (sock.nil? && fd.zero?) || events.zero? item = @items.get(@sockets.index(sock)) unless item @sockets << sock item = LibXS::PollItem.new if sock.kind_of?(XS::Socket) || sock.kind_of?(Socket) item[:socket] = sock.socket item[:fd] = 0 else item[:socket] = FFI::MemoryPointer.new(0) item[:fd] = fd end @raw_to_socket[item.socket.address] = sock @items << item end item[:events] |= events end
ruby
def register sock, events = XS::POLLIN | XS::POLLOUT, fd = 0 return false if (sock.nil? && fd.zero?) || events.zero? item = @items.get(@sockets.index(sock)) unless item @sockets << sock item = LibXS::PollItem.new if sock.kind_of?(XS::Socket) || sock.kind_of?(Socket) item[:socket] = sock.socket item[:fd] = 0 else item[:socket] = FFI::MemoryPointer.new(0) item[:fd] = fd end @raw_to_socket[item.socket.address] = sock @items << item end item[:events] |= events end
[ "def", "register", "sock", ",", "events", "=", "XS", "::", "POLLIN", "|", "XS", "::", "POLLOUT", ",", "fd", "=", "0", "return", "false", "if", "(", "sock", ".", "nil?", "&&", "fd", ".", "zero?", ")", "||", "events", ".", "zero?", "item", "=", "@items", ".", "get", "(", "@sockets", ".", "index", "(", "sock", ")", ")", "unless", "item", "@sockets", "<<", "sock", "item", "=", "LibXS", "::", "PollItem", ".", "new", "if", "sock", ".", "kind_of?", "(", "XS", "::", "Socket", ")", "||", "sock", ".", "kind_of?", "(", "Socket", ")", "item", "[", ":socket", "]", "=", "sock", ".", "socket", "item", "[", ":fd", "]", "=", "0", "else", "item", "[", ":socket", "]", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", "0", ")", "item", "[", ":fd", "]", "=", "fd", "end", "@raw_to_socket", "[", "item", ".", "socket", ".", "address", "]", "=", "sock", "@items", "<<", "item", "end", "item", "[", ":events", "]", "|=", "events", "end" ]
Register the +sock+ for +events+. This method is idempotent meaning it can be called multiple times with the same data and the socket will only get registered at most once. Calling multiple times with different values for +events+ will OR the event information together. @param socket @param events One of @XS::POLLIN@ and @XS::POLLOUT@ @return true if successful @return false if not
[ "Register", "the", "+", "sock", "+", "for", "+", "events", "+", ".", "This", "method", "is", "idempotent", "meaning", "it", "can", "be", "called", "multiple", "times", "with", "the", "same", "data", "and", "the", "socket", "will", "only", "get", "registered", "at", "most", "once", ".", "Calling", "multiple", "times", "with", "different", "values", "for", "+", "events", "+", "will", "OR", "the", "event", "information", "together", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L75-L96
9,741
celldee/ffi-rxs
lib/ffi-rxs/poll.rb
XS.Poller.deregister
def deregister sock, events, fd = 0 return unless sock || !fd.zero? item = @items.get(@sockets.index(sock)) if item && (item[:events] & events) > 0 # change the value in place item[:events] ^= events delete sock if item[:events].zero? true else false end end
ruby
def deregister sock, events, fd = 0 return unless sock || !fd.zero? item = @items.get(@sockets.index(sock)) if item && (item[:events] & events) > 0 # change the value in place item[:events] ^= events delete sock if item[:events].zero? true else false end end
[ "def", "deregister", "sock", ",", "events", ",", "fd", "=", "0", "return", "unless", "sock", "||", "!", "fd", ".", "zero?", "item", "=", "@items", ".", "get", "(", "@sockets", ".", "index", "(", "sock", ")", ")", "if", "item", "&&", "(", "item", "[", ":events", "]", "&", "events", ")", ">", "0", "# change the value in place", "item", "[", ":events", "]", "^=", "events", "delete", "sock", "if", "item", "[", ":events", "]", ".", "zero?", "true", "else", "false", "end", "end" ]
Deregister the +sock+ for +events+. When there are no events left, this also deletes the socket from the poll items. @param socket @param events One of @XS::POLLIN@ and @XS::POLLOUT@ @return true if successful @return false if not
[ "Deregister", "the", "+", "sock", "+", "for", "+", "events", "+", ".", "When", "there", "are", "no", "events", "left", "this", "also", "deletes", "the", "socket", "from", "the", "poll", "items", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L107-L121
9,742
celldee/ffi-rxs
lib/ffi-rxs/poll.rb
XS.Poller.delete
def delete sock unless (size = @sockets.size).zero? @sockets.delete_if { |socket| socket.socket.address == sock.socket.address } socket_deleted = size != @sockets.size item_deleted = @items.delete sock raw_deleted = @raw_to_socket.delete(sock.socket.address) socket_deleted && item_deleted && raw_deleted else false end end
ruby
def delete sock unless (size = @sockets.size).zero? @sockets.delete_if { |socket| socket.socket.address == sock.socket.address } socket_deleted = size != @sockets.size item_deleted = @items.delete sock raw_deleted = @raw_to_socket.delete(sock.socket.address) socket_deleted && item_deleted && raw_deleted else false end end
[ "def", "delete", "sock", "unless", "(", "size", "=", "@sockets", ".", "size", ")", ".", "zero?", "@sockets", ".", "delete_if", "{", "|", "socket", "|", "socket", ".", "socket", ".", "address", "==", "sock", ".", "socket", ".", "address", "}", "socket_deleted", "=", "size", "!=", "@sockets", ".", "size", "item_deleted", "=", "@items", ".", "delete", "sock", "raw_deleted", "=", "@raw_to_socket", ".", "delete", "(", "sock", ".", "socket", ".", "address", ")", "socket_deleted", "&&", "item_deleted", "&&", "raw_deleted", "else", "false", "end", "end" ]
Deletes the +sock+ for all subscribed events. Called internally when a socket has been deregistered and has no more events registered anywhere. Can also be called directly to remove the socket from the polling array. @param socket @return true if successful @return false if not
[ "Deletes", "the", "+", "sock", "+", "for", "all", "subscribed", "events", ".", "Called", "internally", "when", "a", "socket", "has", "been", "deregistered", "and", "has", "no", "more", "events", "registered", "anywhere", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L174-L188
9,743
celldee/ffi-rxs
lib/ffi-rxs/poll.rb
XS.Poller.update_selectables
def update_selectables @readables.clear @writables.clear @items.each do |poll_item| #FIXME: spec for sockets *and* file descriptors if poll_item.readable? @readables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address]) end if poll_item.writable? @writables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address]) end end end
ruby
def update_selectables @readables.clear @writables.clear @items.each do |poll_item| #FIXME: spec for sockets *and* file descriptors if poll_item.readable? @readables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address]) end if poll_item.writable? @writables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address]) end end end
[ "def", "update_selectables", "@readables", ".", "clear", "@writables", ".", "clear", "@items", ".", "each", "do", "|", "poll_item", "|", "#FIXME: spec for sockets *and* file descriptors", "if", "poll_item", ".", "readable?", "@readables", "<<", "(", "poll_item", ".", "socket", ".", "address", ".", "zero?", "?", "poll_item", ".", "fd", ":", "@raw_to_socket", "[", "poll_item", ".", "socket", ".", "address", "]", ")", "end", "if", "poll_item", ".", "writable?", "@writables", "<<", "(", "poll_item", ".", "socket", ".", "address", ".", "zero?", "?", "poll_item", ".", "fd", ":", "@raw_to_socket", "[", "poll_item", ".", "socket", ".", "address", "]", ")", "end", "end", "end" ]
Update readables and writeables
[ "Update", "readables", "and", "writeables" ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll.rb#L216-L230
9,744
hybridgroup/taskmapper-bugzilla
lib/provider/bugzilla.rb
TaskMapper::Provider.Bugzilla.authorize
def authorize(auth = {}) @authentication ||= TaskMapper::Authenticator.new(auth) auth = @authentication if (auth.username.nil? || auth.url.nil? || auth.password.nil?) raise "Please provide username, password and url" end url = auth.url.gsub(/\/$/,'') unless url.split('/').last == 'xmlrpc.cgi' auth.url = url+'/xmlrpc.cgi' end @bugzilla = Rubyzilla::Bugzilla.new(auth.url) begin @bugzilla.login(auth.username,auth.password) rescue warn 'Authentication was invalid' end end
ruby
def authorize(auth = {}) @authentication ||= TaskMapper::Authenticator.new(auth) auth = @authentication if (auth.username.nil? || auth.url.nil? || auth.password.nil?) raise "Please provide username, password and url" end url = auth.url.gsub(/\/$/,'') unless url.split('/').last == 'xmlrpc.cgi' auth.url = url+'/xmlrpc.cgi' end @bugzilla = Rubyzilla::Bugzilla.new(auth.url) begin @bugzilla.login(auth.username,auth.password) rescue warn 'Authentication was invalid' end end
[ "def", "authorize", "(", "auth", "=", "{", "}", ")", "@authentication", "||=", "TaskMapper", "::", "Authenticator", ".", "new", "(", "auth", ")", "auth", "=", "@authentication", "if", "(", "auth", ".", "username", ".", "nil?", "||", "auth", ".", "url", ".", "nil?", "||", "auth", ".", "password", ".", "nil?", ")", "raise", "\"Please provide username, password and url\"", "end", "url", "=", "auth", ".", "url", ".", "gsub", "(", "/", "\\/", "/", ",", "''", ")", "unless", "url", ".", "split", "(", "'/'", ")", ".", "last", "==", "'xmlrpc.cgi'", "auth", ".", "url", "=", "url", "+", "'/xmlrpc.cgi'", "end", "@bugzilla", "=", "Rubyzilla", "::", "Bugzilla", ".", "new", "(", "auth", ".", "url", ")", "begin", "@bugzilla", ".", "login", "(", "auth", ".", "username", ",", "auth", ".", "password", ")", "rescue", "warn", "'Authentication was invalid'", "end", "end" ]
declare needed overloaded methods here
[ "declare", "needed", "overloaded", "methods", "here" ]
2eb871742418206bbe9fe683e5bc20831e1eb236
https://github.com/hybridgroup/taskmapper-bugzilla/blob/2eb871742418206bbe9fe683e5bc20831e1eb236/lib/provider/bugzilla.rb#L15-L31
9,745
fuCtor/mswallet
lib/mswallet/pass.rb
Mswallet.Pass.file
def file(options = {}) options[:file_name] ||= 'pass.mswallet' temp_file = Tempfile.new(options[:file_name]) temp_file.write self.stream.string temp_file.close temp_file end
ruby
def file(options = {}) options[:file_name] ||= 'pass.mswallet' temp_file = Tempfile.new(options[:file_name]) temp_file.write self.stream.string temp_file.close temp_file end
[ "def", "file", "(", "options", "=", "{", "}", ")", "options", "[", ":file_name", "]", "||=", "'pass.mswallet'", "temp_file", "=", "Tempfile", ".", "new", "(", "options", "[", ":file_name", "]", ")", "temp_file", ".", "write", "self", ".", "stream", ".", "string", "temp_file", ".", "close", "temp_file", "end" ]
Return a Tempfile containing our ZipStream
[ "Return", "a", "Tempfile", "containing", "our", "ZipStream" ]
684475989c0936f2654e3f040d56aa58fa94e22a
https://github.com/fuCtor/mswallet/blob/684475989c0936f2654e3f040d56aa58fa94e22a/lib/mswallet/pass.rb#L39-L45
9,746
colstrom/ezmq
lib/ezmq/request.rb
EZMQ.Client.request
def request(message, **options) send message, options if block_given? yield receive options else receive options end end
ruby
def request(message, **options) send message, options if block_given? yield receive options else receive options end end
[ "def", "request", "(", "message", ",", "**", "options", ")", "send", "message", ",", "options", "if", "block_given?", "yield", "receive", "options", "else", "receive", "options", "end", "end" ]
Creates a new Client socket. @param [:bind, :connect] mode (:connect) a mode for the socket. @param [Hash] options optional parameters. @see EZMQ::Socket EZMQ::Socket for optional parameters. @return [Client] a new instance of Client. Sends a message and waits to receive a response. @param [String] message the message to send. @param [Hash] options optional parameters. @option options [lambda] encode how to encode the message. @option options [lambda] decode how to decode the message. @return [void] the decoded response message.
[ "Creates", "a", "new", "Client", "socket", "." ]
cd7f9f256d6c3f7a844871a3a77a89d7122d5836
https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/request.rb#L28-L35
9,747
jeremyd/virtualmonkey
lib/virtualmonkey/frontend.rb
VirtualMonkey.Frontend.get_lb_hostname_input
def get_lb_hostname_input lb_hostname_input = "text:" fe_servers.each do |fe| timeout = 30 loopcounter = 0 begin if fe.settings['private-dns-name'] == nil raise "FATAL: private DNS name is empty" if loopcounter > 10 sleep(timeout) loopcounter += 1 next end lb_hostname_input << fe.settings['private-dns-name'] + " " done = true end while !done end lb_hostname_input end
ruby
def get_lb_hostname_input lb_hostname_input = "text:" fe_servers.each do |fe| timeout = 30 loopcounter = 0 begin if fe.settings['private-dns-name'] == nil raise "FATAL: private DNS name is empty" if loopcounter > 10 sleep(timeout) loopcounter += 1 next end lb_hostname_input << fe.settings['private-dns-name'] + " " done = true end while !done end lb_hostname_input end
[ "def", "get_lb_hostname_input", "lb_hostname_input", "=", "\"text:\"", "fe_servers", ".", "each", "do", "|", "fe", "|", "timeout", "=", "30", "loopcounter", "=", "0", "begin", "if", "fe", ".", "settings", "[", "'private-dns-name'", "]", "==", "nil", "raise", "\"FATAL: private DNS name is empty\"", "if", "loopcounter", ">", "10", "sleep", "(", "timeout", ")", "loopcounter", "+=", "1", "next", "end", "lb_hostname_input", "<<", "fe", ".", "settings", "[", "'private-dns-name'", "]", "+", "\" \"", "done", "=", "true", "end", "while", "!", "done", "end", "lb_hostname_input", "end" ]
returns String with all the private dns of the Front End servers used for setting the LB_HOSTNAME input.
[ "returns", "String", "with", "all", "the", "private", "dns", "of", "the", "Front", "End", "servers", "used", "for", "setting", "the", "LB_HOSTNAME", "input", "." ]
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/frontend.rb#L15-L32
9,748
dmitrizagidulin/riagent
lib/riagent/configuration.rb
Riagent.Configuration.config_for
def config_for(environment=:development) if self.config.present? env_config = self.config[environment.to_s] else env_config = { 'host' => ENV['RIAK_HOST'], 'http_port' => ENV['RIAK_HTTP_PORT'], 'pb_port' => ENV['RIAK_PB_PORT'] } end env_config end
ruby
def config_for(environment=:development) if self.config.present? env_config = self.config[environment.to_s] else env_config = { 'host' => ENV['RIAK_HOST'], 'http_port' => ENV['RIAK_HTTP_PORT'], 'pb_port' => ENV['RIAK_PB_PORT'] } end env_config end
[ "def", "config_for", "(", "environment", "=", ":development", ")", "if", "self", ".", "config", ".", "present?", "env_config", "=", "self", ".", "config", "[", "environment", ".", "to_s", "]", "else", "env_config", "=", "{", "'host'", "=>", "ENV", "[", "'RIAK_HOST'", "]", ",", "'http_port'", "=>", "ENV", "[", "'RIAK_HTTP_PORT'", "]", ",", "'pb_port'", "=>", "ENV", "[", "'RIAK_PB_PORT'", "]", "}", "end", "env_config", "end" ]
Return a configuration hash for a given environment @param [Symbol] environment Environment for which to load the client configs @return [Hash]
[ "Return", "a", "configuration", "hash", "for", "a", "given", "environment" ]
074bbb9c354abc1ba2037d704b0706caa3f34f37
https://github.com/dmitrizagidulin/riagent/blob/074bbb9c354abc1ba2037d704b0706caa3f34f37/lib/riagent/configuration.rb#L38-L49
9,749
gr4y/streambot
lib/streambot/handler.rb
StreamBot.Handler.parse_response
def parse_response(object) LOG.debug("response is #{object}") case object when ::Net::HTTPUnauthorized ::File.delete(ACCESS_TOKEN) raise 'user revoked oauth connection' when ::Net::HTTPOK then object.body end end
ruby
def parse_response(object) LOG.debug("response is #{object}") case object when ::Net::HTTPUnauthorized ::File.delete(ACCESS_TOKEN) raise 'user revoked oauth connection' when ::Net::HTTPOK then object.body end end
[ "def", "parse_response", "(", "object", ")", "LOG", ".", "debug", "(", "\"response is #{object}\"", ")", "case", "object", "when", "::", "Net", "::", "HTTPUnauthorized", "::", "File", ".", "delete", "(", "ACCESS_TOKEN", ")", "raise", "'user revoked oauth connection'", "when", "::", "Net", "::", "HTTPOK", "then", "object", ".", "body", "end", "end" ]
parse an response
[ "parse", "an", "response" ]
3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375
https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/handler.rb#L5-L14
9,750
esmarkowski/schemata
lib/schemata/schema/addressable.rb
Schemata.Schema.addressable
def addressable apply_schema :street_address_1, String apply_schema :street_address_2, String apply_schema :city, String apply_schema :state, String apply_schema :zip_code, String apply_schema :country, String end
ruby
def addressable apply_schema :street_address_1, String apply_schema :street_address_2, String apply_schema :city, String apply_schema :state, String apply_schema :zip_code, String apply_schema :country, String end
[ "def", "addressable", "apply_schema", ":street_address_1", ",", "String", "apply_schema", ":street_address_2", ",", "String", "apply_schema", ":city", ",", "String", "apply_schema", ":state", ",", "String", "apply_schema", ":zip_code", ",", "String", "apply_schema", ":country", ",", "String", "end" ]
Provides a common set of address fields such as, street_address_1, street_address_2, city, state, zip_code and country as String fields.
[ "Provides", "a", "common", "set", "of", "address", "fields", "such", "as", "street_address_1", "street_address_2", "city", "state", "zip_code", "and", "country", "as", "String", "fields", "." ]
59689b60eefcf6d15babebea37ee58325e0f6042
https://github.com/esmarkowski/schemata/blob/59689b60eefcf6d15babebea37ee58325e0f6042/lib/schemata/schema/addressable.rb#L6-L13
9,751
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.merge_into_snapshot
def merge_into_snapshot(other) if @snapshot.nil? then raise ValidationError.new("Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.") end # the non-domain attribute => [target value, other value] difference hash delta = diff(other) # the difference attribute => other value hash, excluding nil other values dvh = delta.transform_value { |d| d.last } return if dvh.empty? logger.debug { "#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}" } logger.debug { "Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}..." } # update the snapshot from the other value to reflect the database state @snapshot.merge!(dvh) end
ruby
def merge_into_snapshot(other) if @snapshot.nil? then raise ValidationError.new("Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.") end # the non-domain attribute => [target value, other value] difference hash delta = diff(other) # the difference attribute => other value hash, excluding nil other values dvh = delta.transform_value { |d| d.last } return if dvh.empty? logger.debug { "#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}" } logger.debug { "Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}..." } # update the snapshot from the other value to reflect the database state @snapshot.merge!(dvh) end
[ "def", "merge_into_snapshot", "(", "other", ")", "if", "@snapshot", ".", "nil?", "then", "raise", "ValidationError", ".", "new", "(", "\"Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.\"", ")", "end", "# the non-domain attribute => [target value, other value] difference hash", "delta", "=", "diff", "(", "other", ")", "# the difference attribute => other value hash, excluding nil other values", "dvh", "=", "delta", ".", "transform_value", "{", "|", "d", "|", "d", ".", "last", "}", "return", "if", "dvh", ".", "empty?", "logger", ".", "debug", "{", "\"#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}\"", "}", "logger", ".", "debug", "{", "\"Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}...\"", "}", "# update the snapshot from the other value to reflect the database state", "@snapshot", ".", "merge!", "(", "dvh", ")", "end" ]
Merges the other domain object non-domain attribute values into this domain object's snapshot, An existing snapshot value is replaced by the corresponding other attribute value. @param [Jinx::Resource] other the source domain object @raise [ValidationError] if this domain object does not have a snapshot
[ "Merges", "the", "other", "domain", "object", "non", "-", "domain", "attribute", "values", "into", "this", "domain", "object", "s", "snapshot", "An", "existing", "snapshot", "value", "is", "replaced", "by", "the", "corresponding", "other", "attribute", "value", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L145-L158
9,752
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.add_lazy_loader
def add_lazy_loader(loader, attributes=nil) # guard against invalid call if identifier.nil? then raise ValidationError.new("Cannot add lazy loader to an unfetched domain object: #{self}") end # the attributes to lazy-load attributes ||= loadable_attributes return if attributes.empty? # define the reader and writer method overrides for the missing attributes pas = attributes.select { |pa| inject_lazy_loader(pa) } logger.debug { "Lazy loader added to #{qp} attributes #{pas.to_series}." } unless pas.empty? end
ruby
def add_lazy_loader(loader, attributes=nil) # guard against invalid call if identifier.nil? then raise ValidationError.new("Cannot add lazy loader to an unfetched domain object: #{self}") end # the attributes to lazy-load attributes ||= loadable_attributes return if attributes.empty? # define the reader and writer method overrides for the missing attributes pas = attributes.select { |pa| inject_lazy_loader(pa) } logger.debug { "Lazy loader added to #{qp} attributes #{pas.to_series}." } unless pas.empty? end
[ "def", "add_lazy_loader", "(", "loader", ",", "attributes", "=", "nil", ")", "# guard against invalid call", "if", "identifier", ".", "nil?", "then", "raise", "ValidationError", ".", "new", "(", "\"Cannot add lazy loader to an unfetched domain object: #{self}\"", ")", "end", "# the attributes to lazy-load", "attributes", "||=", "loadable_attributes", "return", "if", "attributes", ".", "empty?", "# define the reader and writer method overrides for the missing attributes", "pas", "=", "attributes", ".", "select", "{", "|", "pa", "|", "inject_lazy_loader", "(", "pa", ")", "}", "logger", ".", "debug", "{", "\"Lazy loader added to #{qp} attributes #{pas.to_series}.\"", "}", "unless", "pas", ".", "empty?", "end" ]
Lazy loads the attributes. If a block is given to this method, then the attributes are determined by calling the block with this Persistable as a parameter. Otherwise, the default attributes are the unfetched domain attributes. Each of the attributes which does not already hold a non-nil or non-empty value will be loaded from the database on demand. This method injects attribute value initialization into each loadable attribute reader. The initializer is given by either the loader Proc argument. The loader takes two arguments, the target object and the attribute to load. If this Persistable already has a lazy loader, then this method is a no-op. Lazy loading is disabled on an attribute after it is invoked on that attribute or when the attribute setter method is called. @param loader [LazyLoader] the lazy loader to add
[ "Lazy", "loads", "the", "attributes", ".", "If", "a", "block", "is", "given", "to", "this", "method", "then", "the", "attributes", "are", "determined", "by", "calling", "the", "block", "with", "this", "Persistable", "as", "a", "parameter", ".", "Otherwise", "the", "default", "attributes", "are", "the", "unfetched", "domain", "attributes", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L197-L206
9,753
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.remove_lazy_loader
def remove_lazy_loader(attribute=nil) if attribute.nil? then return self.class.domain_attributes.each { |pa| remove_lazy_loader(pa) } end # the modified accessor method reader, writer = self.class.property(attribute).accessors # remove the reader override disable_singleton_method(reader) # remove the writer override disable_singleton_method(writer) end
ruby
def remove_lazy_loader(attribute=nil) if attribute.nil? then return self.class.domain_attributes.each { |pa| remove_lazy_loader(pa) } end # the modified accessor method reader, writer = self.class.property(attribute).accessors # remove the reader override disable_singleton_method(reader) # remove the writer override disable_singleton_method(writer) end
[ "def", "remove_lazy_loader", "(", "attribute", "=", "nil", ")", "if", "attribute", ".", "nil?", "then", "return", "self", ".", "class", ".", "domain_attributes", ".", "each", "{", "|", "pa", "|", "remove_lazy_loader", "(", "pa", ")", "}", "end", "# the modified accessor method", "reader", ",", "writer", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", ".", "accessors", "# remove the reader override", "disable_singleton_method", "(", "reader", ")", "# remove the writer override", "disable_singleton_method", "(", "writer", ")", "end" ]
Disables lazy loading of the specified attribute. Lazy loaded is disabled for all attributes if no attribute is specified. This method is a no-op if this Persistable does not have a lazy loader. @param [Symbol] the attribute to remove from the load list, or nil if to remove all attributes
[ "Disables", "lazy", "loading", "of", "the", "specified", "attribute", ".", "Lazy", "loaded", "is", "disabled", "for", "all", "attributes", "if", "no", "attribute", "is", "specified", ".", "This", "method", "is", "a", "no", "-", "op", "if", "this", "Persistable", "does", "not", "have", "a", "lazy", "loader", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L231-L241
9,754
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.fetch_saved?
def fetch_saved? # only fetch a create, not an update (note that subclasses can override this condition) return false if identifier # Check for an attribute with a value that might need to be changed in order to # reflect the auto-generated database content. ag_attrs = self.class.autogenerated_attributes return false if ag_attrs.empty? ag_attrs.any? { |pa| not send(pa).nil_or_empty? } end
ruby
def fetch_saved? # only fetch a create, not an update (note that subclasses can override this condition) return false if identifier # Check for an attribute with a value that might need to be changed in order to # reflect the auto-generated database content. ag_attrs = self.class.autogenerated_attributes return false if ag_attrs.empty? ag_attrs.any? { |pa| not send(pa).nil_or_empty? } end
[ "def", "fetch_saved?", "# only fetch a create, not an update (note that subclasses can override this condition)", "return", "false", "if", "identifier", "# Check for an attribute with a value that might need to be changed in order to", "# reflect the auto-generated database content.", "ag_attrs", "=", "self", ".", "class", ".", "autogenerated_attributes", "return", "false", "if", "ag_attrs", ".", "empty?", "ag_attrs", ".", "any?", "{", "|", "pa", "|", "not", "send", "(", "pa", ")", ".", "nil_or_empty?", "}", "end" ]
Returns whether this domain object must be fetched to reflect the database state. This default implementation returns whether this domain object was created and there are any autogenerated attributes. Subclasses can override to relax or restrict the condition. @quirk caCORE The auto-generated criterion is a necessary but not sufficient condition to determine whether a save caCORE result reflects the database state. Example: * caTissue SCG event parameters are not auto-generated on SCG create if the SCG collection status is Pending, but are auto-generated on SCG update if the SCG status is changed to Complete. By contrast, the SCG specimens are auto-generated on SCG create, even if the status is +Pending+. The caBIG application can override this method in a Database subclass to fine-tune the fetch criteria. Adding a more restrictive {#fetch_saved?} condition will will improve performance but not change functionality. @quirk caCORE A saved attribute which is cascaded but not fetched must be fetched in order to reflect the database identifier in the saved object. TODO - this method is no longeer used. Should it be? If not, remove here and in catissue subclasses. @return [Boolean] whether this domain object must be fetched to reflect the database state
[ "Returns", "whether", "this", "domain", "object", "must", "be", "fetched", "to", "reflect", "the", "database", "state", ".", "This", "default", "implementation", "returns", "whether", "this", "domain", "object", "was", "created", "and", "there", "are", "any", "autogenerated", "attributes", ".", "Subclasses", "can", "override", "to", "relax", "or", "restrict", "the", "condition", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L378-L386
9,755
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.inject_lazy_loader
def inject_lazy_loader(attribute) # bail if there is already a value return false if attribute_loaded?(attribute) # the accessor methods to modify reader, writer = self.class.property(attribute).accessors # The singleton attribute reader method loads the reference once and thenceforth calls the # standard reader. instance_eval "def #{reader}; load_reference(:#{attribute}); end" # The singleton attribute writer method removes the lazy loader once and thenceforth calls # the standard writer. instance_eval "def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end" true end
ruby
def inject_lazy_loader(attribute) # bail if there is already a value return false if attribute_loaded?(attribute) # the accessor methods to modify reader, writer = self.class.property(attribute).accessors # The singleton attribute reader method loads the reference once and thenceforth calls the # standard reader. instance_eval "def #{reader}; load_reference(:#{attribute}); end" # The singleton attribute writer method removes the lazy loader once and thenceforth calls # the standard writer. instance_eval "def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end" true end
[ "def", "inject_lazy_loader", "(", "attribute", ")", "# bail if there is already a value", "return", "false", "if", "attribute_loaded?", "(", "attribute", ")", "# the accessor methods to modify", "reader", ",", "writer", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", ".", "accessors", "# The singleton attribute reader method loads the reference once and thenceforth calls the", "# standard reader.", "instance_eval", "\"def #{reader}; load_reference(:#{attribute}); end\"", "# The singleton attribute writer method removes the lazy loader once and thenceforth calls", "# the standard writer.", "instance_eval", "\"def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end\"", "true", "end" ]
Adds this Persistable lazy loader to the given attribute unless the attribute already holds a fetched reference. @param [Symbol] attribute the attribute to mod @return [Boolean] whether a loader was added to the attribute
[ "Adds", "this", "Persistable", "lazy", "loader", "to", "the", "given", "attribute", "unless", "the", "attribute", "already", "holds", "a", "fetched", "reference", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L471-L483
9,756
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.load_reference
def load_reference(attribute) ldr = database.lazy_loader # bypass the singleton method and call the class instance method if the lazy loader is disabled return transient_value(attribute) unless ldr.enabled? # First disable lazy loading for the attribute, since the reader method is called by the loader. remove_lazy_loader(attribute) # load the fetched value merged = ldr.load(self, attribute) # update dependent snapshots if necessary pa = self.class.property(attribute) if pa.dependent? then # the owner attribute oattr = pa.inverse if oattr then # update dependent snapshot with the owner, since the owner snapshot is taken when fetched but the # owner might be set when the fetched dependent is merged into the owner dependent attribute. merged.enumerate do |dep| if dep.fetched? then dep.snapshot[oattr] = self logger.debug { "Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}." } end end end end merged end
ruby
def load_reference(attribute) ldr = database.lazy_loader # bypass the singleton method and call the class instance method if the lazy loader is disabled return transient_value(attribute) unless ldr.enabled? # First disable lazy loading for the attribute, since the reader method is called by the loader. remove_lazy_loader(attribute) # load the fetched value merged = ldr.load(self, attribute) # update dependent snapshots if necessary pa = self.class.property(attribute) if pa.dependent? then # the owner attribute oattr = pa.inverse if oattr then # update dependent snapshot with the owner, since the owner snapshot is taken when fetched but the # owner might be set when the fetched dependent is merged into the owner dependent attribute. merged.enumerate do |dep| if dep.fetched? then dep.snapshot[oattr] = self logger.debug { "Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}." } end end end end merged end
[ "def", "load_reference", "(", "attribute", ")", "ldr", "=", "database", ".", "lazy_loader", "# bypass the singleton method and call the class instance method if the lazy loader is disabled", "return", "transient_value", "(", "attribute", ")", "unless", "ldr", ".", "enabled?", "# First disable lazy loading for the attribute, since the reader method is called by the loader.", "remove_lazy_loader", "(", "attribute", ")", "# load the fetched value", "merged", "=", "ldr", ".", "load", "(", "self", ",", "attribute", ")", "# update dependent snapshots if necessary", "pa", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", "if", "pa", ".", "dependent?", "then", "# the owner attribute", "oattr", "=", "pa", ".", "inverse", "if", "oattr", "then", "# update dependent snapshot with the owner, since the owner snapshot is taken when fetched but the", "# owner might be set when the fetched dependent is merged into the owner dependent attribute. ", "merged", ".", "enumerate", "do", "|", "dep", "|", "if", "dep", ".", "fetched?", "then", "dep", ".", "snapshot", "[", "oattr", "]", "=", "self", "logger", ".", "debug", "{", "\"Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}.\"", "}", "end", "end", "end", "end", "merged", "end" ]
Loads the reference attribute database value into this Persistable. @param [Symbol] attribute the attribute to load @return the attribute value merged from the database value
[ "Loads", "the", "reference", "attribute", "database", "value", "into", "this", "Persistable", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L498-L526
9,757
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.disable_singleton_method
def disable_singleton_method(name_or_sym) return unless singleton_methods.include?(name_or_sym.to_s) # dissociate the method from this instance method = self.method(name_or_sym.to_sym) method.unbind # JRuby unbind doesn't work in JRuby 1.1.6. In that case, redefine the singleton method to delegate # to the class instance method. if singleton_methods.include?(name_or_sym.to_s) then args = (1..method.arity).map { |argnum| "arg#{argnum}" }.join(', ') instance_eval "def #{name_or_sym}(#{args}); super; end" end end
ruby
def disable_singleton_method(name_or_sym) return unless singleton_methods.include?(name_or_sym.to_s) # dissociate the method from this instance method = self.method(name_or_sym.to_sym) method.unbind # JRuby unbind doesn't work in JRuby 1.1.6. In that case, redefine the singleton method to delegate # to the class instance method. if singleton_methods.include?(name_or_sym.to_s) then args = (1..method.arity).map { |argnum| "arg#{argnum}" }.join(', ') instance_eval "def #{name_or_sym}(#{args}); super; end" end end
[ "def", "disable_singleton_method", "(", "name_or_sym", ")", "return", "unless", "singleton_methods", ".", "include?", "(", "name_or_sym", ".", "to_s", ")", "# dissociate the method from this instance", "method", "=", "self", ".", "method", "(", "name_or_sym", ".", "to_sym", ")", "method", ".", "unbind", "# JRuby unbind doesn't work in JRuby 1.1.6. In that case, redefine the singleton method to delegate", "# to the class instance method.", "if", "singleton_methods", ".", "include?", "(", "name_or_sym", ".", "to_s", ")", "then", "args", "=", "(", "1", "..", "method", ".", "arity", ")", ".", "map", "{", "|", "argnum", "|", "\"arg#{argnum}\"", "}", ".", "join", "(", "', '", ")", "instance_eval", "\"def #{name_or_sym}(#{args}); super; end\"", "end", "end" ]
Disables the given singleton attribute accessor method. @param [String, Symbol] name_or_sym the accessor method to disable
[ "Disables", "the", "given", "singleton", "attribute", "accessor", "method", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L537-L548
9,758
jackhq/mercury
lib/mercury/helpers.rb
Sinatra.MercuryHelpers.sass
def sass(sassfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(sassfile, SASS))).render, mediatype end
ruby
def sass(sassfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(sassfile, SASS))).render, mediatype end
[ "def", "sass", "(", "sassfile", ",", "mediatype", "=", "\"all\"", ")", "render_style", "Sass", "::", "Engine", ".", "new", "(", "open_file", "(", "find_file", "(", "sassfile", ",", "SASS", ")", ")", ")", ".", "render", ",", "mediatype", "end" ]
renders sass files
[ "renders", "sass", "files" ]
1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c
https://github.com/jackhq/mercury/blob/1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c/lib/mercury/helpers.rb#L27-L29
9,759
jackhq/mercury
lib/mercury/helpers.rb
Sinatra.MercuryHelpers.scss
def scss(scssfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(scssfile, SCSS)), :syntax => :scss).render, mediatype end
ruby
def scss(scssfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(scssfile, SCSS)), :syntax => :scss).render, mediatype end
[ "def", "scss", "(", "scssfile", ",", "mediatype", "=", "\"all\"", ")", "render_style", "Sass", "::", "Engine", ".", "new", "(", "open_file", "(", "find_file", "(", "scssfile", ",", "SCSS", ")", ")", ",", ":syntax", "=>", ":scss", ")", ".", "render", ",", "mediatype", "end" ]
renders scss files
[ "renders", "scss", "files" ]
1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c
https://github.com/jackhq/mercury/blob/1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c/lib/mercury/helpers.rb#L32-L34
9,760
medcat/brandish
lib/brandish/application.rb
Brandish.Application.call
def call program_information configure_global_option directory_global_option command(:initialize) { |c| InitializeCommand.define(self, c) } command(:bench) { |c| BenchCommand.define(self, c) } command(:build) { |c| BuildCommand.define(self, c) } command(:serve) { |c| ServeCommand.define(self, c) } alias_command(:init, :initialize) default_command(:build) run! end
ruby
def call program_information configure_global_option directory_global_option command(:initialize) { |c| InitializeCommand.define(self, c) } command(:bench) { |c| BenchCommand.define(self, c) } command(:build) { |c| BuildCommand.define(self, c) } command(:serve) { |c| ServeCommand.define(self, c) } alias_command(:init, :initialize) default_command(:build) run! end
[ "def", "call", "program_information", "configure_global_option", "directory_global_option", "command", "(", ":initialize", ")", "{", "|", "c", "|", "InitializeCommand", ".", "define", "(", "self", ",", "c", ")", "}", "command", "(", ":bench", ")", "{", "|", "c", "|", "BenchCommand", ".", "define", "(", "self", ",", "c", ")", "}", "command", "(", ":build", ")", "{", "|", "c", "|", "BuildCommand", ".", "define", "(", "self", ",", "c", ")", "}", "command", "(", ":serve", ")", "{", "|", "c", "|", "ServeCommand", ".", "define", "(", "self", ",", "c", ")", "}", "alias_command", "(", ":init", ",", ":initialize", ")", "default_command", "(", ":build", ")", "run!", "end" ]
Defines and runs the command line interface. @see #program_information @see #configure_global_option @see #directory_global_option @see InitializeCommand.define @see BenchCommand.define @see BuildCommand.define @see ServeCommand.define @return [void]
[ "Defines", "and", "runs", "the", "command", "line", "interface", "." ]
c63f91dbb356aa0958351ad9bcbdab0c57e7f649
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L51-L62
9,761
medcat/brandish
lib/brandish/application.rb
Brandish.Application.program_information
def program_information program :name, "Brandish" program :version, Brandish::VERSION program :help_formatter, :compact program :help_paging, false program :description, "A multi-format document generator." program :help, "Author", "Jeremy Rodi <jeremy.rodi@medcat.me>" program :help, "License", "MIT License Copyright (c) 2017 Jeremy Rodi" end
ruby
def program_information program :name, "Brandish" program :version, Brandish::VERSION program :help_formatter, :compact program :help_paging, false program :description, "A multi-format document generator." program :help, "Author", "Jeremy Rodi <jeremy.rodi@medcat.me>" program :help, "License", "MIT License Copyright (c) 2017 Jeremy Rodi" end
[ "def", "program_information", "program", ":name", ",", "\"Brandish\"", "program", ":version", ",", "Brandish", "::", "VERSION", "program", ":help_formatter", ",", ":compact", "program", ":help_paging", ",", "false", "program", ":description", ",", "\"A multi-format document generator.\"", "program", ":help", ",", "\"Author\"", ",", "\"Jeremy Rodi <jeremy.rodi@medcat.me>\"", "program", ":help", ",", "\"License\"", ",", "\"MIT License Copyright (c) 2017 Jeremy Rodi\"", "end" ]
The program information. This is for use with Commander. @return [void]
[ "The", "program", "information", ".", "This", "is", "for", "use", "with", "Commander", "." ]
c63f91dbb356aa0958351ad9bcbdab0c57e7f649
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L67-L75
9,762
medcat/brandish
lib/brandish/application.rb
Brandish.Application.progress
def progress(array, &block) # rubocop:disable Style/GlobalVars width = $terminal.terminal_size[0] - PROGRESS_WIDTH # rubocop:enable Style/GlobalVars options = PROGRESS_OPTIONS.merge(width: width) super(array, options, &block) end
ruby
def progress(array, &block) # rubocop:disable Style/GlobalVars width = $terminal.terminal_size[0] - PROGRESS_WIDTH # rubocop:enable Style/GlobalVars options = PROGRESS_OPTIONS.merge(width: width) super(array, options, &block) end
[ "def", "progress", "(", "array", ",", "&", "block", ")", "# rubocop:disable Style/GlobalVars", "width", "=", "$terminal", ".", "terminal_size", "[", "0", "]", "-", "PROGRESS_WIDTH", "# rubocop:enable Style/GlobalVars", "options", "=", "PROGRESS_OPTIONS", ".", "merge", "(", "width", ":", "width", ")", "super", "(", "array", ",", "options", ",", "block", ")", "end" ]
Creates a progress bar on the terminal based off of the given array. This mostly passes everything on to the `progress` method provided by Commander, but with a few options added. @param array [::Array] The array of items that are being processed. @yield [item] Once for every item in the array. Once the block ends, the progress bar increments. @yieldparam item [::Object] One of the items in the array. @return [void]
[ "Creates", "a", "progress", "bar", "on", "the", "terminal", "based", "off", "of", "the", "given", "array", ".", "This", "mostly", "passes", "everything", "on", "to", "the", "progress", "method", "provided", "by", "Commander", "but", "with", "a", "few", "options", "added", "." ]
c63f91dbb356aa0958351ad9bcbdab0c57e7f649
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L122-L128
9,763
justfalter/align
lib/align/needleman_wunsch.rb
Align.NeedlemanWunsch.fill
def fill @matrix[0][0] = 0 # Set up the first column on each row. 1.upto(@rows-1) {|i| @matrix[i][0] = @matrix[i-1][0] + @scoring.score_delete(@seq1[i])} # Set up the first row 1.upto(@cols-1) {|j| @matrix[0][j] = @matrix[0][j-1] + @scoring.score_insert(@seq2[j])} 1.upto(@rows-1) do |i| prv_row = @matrix[i-1] cur_row = @matrix[i] 1.upto(@cols-1) do |j| seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] # Calculate the score. score_align = prv_row[j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = prv_row[j] + @scoring.score_delete(seq1_obj) score_insert = cur_row[j-1] + @scoring.score_insert(seq2_obj) max = max3(score_align, score_delete, score_insert) @matrix[i][j] = max end end end
ruby
def fill @matrix[0][0] = 0 # Set up the first column on each row. 1.upto(@rows-1) {|i| @matrix[i][0] = @matrix[i-1][0] + @scoring.score_delete(@seq1[i])} # Set up the first row 1.upto(@cols-1) {|j| @matrix[0][j] = @matrix[0][j-1] + @scoring.score_insert(@seq2[j])} 1.upto(@rows-1) do |i| prv_row = @matrix[i-1] cur_row = @matrix[i] 1.upto(@cols-1) do |j| seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] # Calculate the score. score_align = prv_row[j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = prv_row[j] + @scoring.score_delete(seq1_obj) score_insert = cur_row[j-1] + @scoring.score_insert(seq2_obj) max = max3(score_align, score_delete, score_insert) @matrix[i][j] = max end end end
[ "def", "fill", "@matrix", "[", "0", "]", "[", "0", "]", "=", "0", "# Set up the first column on each row.", "1", ".", "upto", "(", "@rows", "-", "1", ")", "{", "|", "i", "|", "@matrix", "[", "i", "]", "[", "0", "]", "=", "@matrix", "[", "i", "-", "1", "]", "[", "0", "]", "+", "@scoring", ".", "score_delete", "(", "@seq1", "[", "i", "]", ")", "}", "# Set up the first row ", "1", ".", "upto", "(", "@cols", "-", "1", ")", "{", "|", "j", "|", "@matrix", "[", "0", "]", "[", "j", "]", "=", "@matrix", "[", "0", "]", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_insert", "(", "@seq2", "[", "j", "]", ")", "}", "1", ".", "upto", "(", "@rows", "-", "1", ")", "do", "|", "i", "|", "prv_row", "=", "@matrix", "[", "i", "-", "1", "]", "cur_row", "=", "@matrix", "[", "i", "]", "1", ".", "upto", "(", "@cols", "-", "1", ")", "do", "|", "j", "|", "seq1_obj", "=", "@seq1", "[", "i", "-", "1", "]", "seq2_obj", "=", "@seq2", "[", "j", "-", "1", "]", "# Calculate the score.", "score_align", "=", "prv_row", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_align", "(", "seq1_obj", ",", "seq2_obj", ")", "score_delete", "=", "prv_row", "[", "j", "]", "+", "@scoring", ".", "score_delete", "(", "seq1_obj", ")", "score_insert", "=", "cur_row", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_insert", "(", "seq2_obj", ")", "max", "=", "max3", "(", "score_align", ",", "score_delete", ",", "score_insert", ")", "@matrix", "[", "i", "]", "[", "j", "]", "=", "max", "end", "end", "end" ]
Fills the matrix with the alignment map.
[ "Fills", "the", "matrix", "with", "the", "alignment", "map", "." ]
e95ac63253e99ee18d66c1e7d9695f5eb80036cf
https://github.com/justfalter/align/blob/e95ac63253e99ee18d66c1e7d9695f5eb80036cf/lib/align/needleman_wunsch.rb#L41-L66
9,764
justfalter/align
lib/align/needleman_wunsch.rb
Align.NeedlemanWunsch.traceback
def traceback i = @rows - 1 j = @cols - 1 while (i > 0 && j > 0) score = @matrix[i][j] seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] score_align = @matrix[i-1][j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = @matrix[i-1][j] + @scoring.score_delete(seq1_obj) score_insert = @matrix[i][j-1] + @scoring.score_insert(seq2_obj) flags = 0 need_select = false if score == score_align flags = :align i-=1 j-=1 elsif score == score_delete flags = :delete i-=1 else flags = :insert j-=1 end yield(i,j,flags) end # while while i > 0 i-=1 yield(i,j,:delete) end while j > 0 j-=1 yield(i,j,:insert) end end
ruby
def traceback i = @rows - 1 j = @cols - 1 while (i > 0 && j > 0) score = @matrix[i][j] seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] score_align = @matrix[i-1][j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = @matrix[i-1][j] + @scoring.score_delete(seq1_obj) score_insert = @matrix[i][j-1] + @scoring.score_insert(seq2_obj) flags = 0 need_select = false if score == score_align flags = :align i-=1 j-=1 elsif score == score_delete flags = :delete i-=1 else flags = :insert j-=1 end yield(i,j,flags) end # while while i > 0 i-=1 yield(i,j,:delete) end while j > 0 j-=1 yield(i,j,:insert) end end
[ "def", "traceback", "i", "=", "@rows", "-", "1", "j", "=", "@cols", "-", "1", "while", "(", "i", ">", "0", "&&", "j", ">", "0", ")", "score", "=", "@matrix", "[", "i", "]", "[", "j", "]", "seq1_obj", "=", "@seq1", "[", "i", "-", "1", "]", "seq2_obj", "=", "@seq2", "[", "j", "-", "1", "]", "score_align", "=", "@matrix", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_align", "(", "seq1_obj", ",", "seq2_obj", ")", "score_delete", "=", "@matrix", "[", "i", "-", "1", "]", "[", "j", "]", "+", "@scoring", ".", "score_delete", "(", "seq1_obj", ")", "score_insert", "=", "@matrix", "[", "i", "]", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_insert", "(", "seq2_obj", ")", "flags", "=", "0", "need_select", "=", "false", "if", "score", "==", "score_align", "flags", "=", ":align", "i", "-=", "1", "j", "-=", "1", "elsif", "score", "==", "score_delete", "flags", "=", ":delete", "i", "-=", "1", "else", "flags", "=", ":insert", "j", "-=", "1", "end", "yield", "(", "i", ",", "j", ",", "flags", ")", "end", "# while", "while", "i", ">", "0", "i", "-=", "1", "yield", "(", "i", ",", "j", ",", ":delete", ")", "end", "while", "j", ">", "0", "j", "-=", "1", "yield", "(", "i", ",", "j", ",", ":insert", ")", "end", "end" ]
fill Traces backward, finding the alignment. @yield [i,j,step] @yieldparam i [Integer] The location in sequence one @yieldparam j [Integer] The location in sequence two @yieldparam step [Integer] The direction we took
[ "fill", "Traces", "backward", "finding", "the", "alignment", "." ]
e95ac63253e99ee18d66c1e7d9695f5eb80036cf
https://github.com/justfalter/align/blob/e95ac63253e99ee18d66c1e7d9695f5eb80036cf/lib/align/needleman_wunsch.rb#L73-L114
9,765
ithouse/lolita-first-data
app/controllers/lolita_first_data/transactions_controller.rb
LolitaFirstData.TransactionsController.checkout
def checkout response = gateway.purchase(payment.price, currency: payment.currency.to_s, client_ip_addr: request.remote_ip, description: payment.description, language: payment.first_data_language) if response[:transaction_id] trx = LolitaFirstData::Transaction.add(payment, request, response) redirect_to gateway.redirect_url(trx.transaction_id) else if request.xhr? || !request.referer render text: I18n.t('fd.purchase_failed'), status: 400 else flash[:error] = I18n.t('fd.purchase_failed') redirect_to :back end end ensure LolitaFirstData.logger.info("[#{session_id}][#{payment.id}][checkout] #{response}") end
ruby
def checkout response = gateway.purchase(payment.price, currency: payment.currency.to_s, client_ip_addr: request.remote_ip, description: payment.description, language: payment.first_data_language) if response[:transaction_id] trx = LolitaFirstData::Transaction.add(payment, request, response) redirect_to gateway.redirect_url(trx.transaction_id) else if request.xhr? || !request.referer render text: I18n.t('fd.purchase_failed'), status: 400 else flash[:error] = I18n.t('fd.purchase_failed') redirect_to :back end end ensure LolitaFirstData.logger.info("[#{session_id}][#{payment.id}][checkout] #{response}") end
[ "def", "checkout", "response", "=", "gateway", ".", "purchase", "(", "payment", ".", "price", ",", "currency", ":", "payment", ".", "currency", ".", "to_s", ",", "client_ip_addr", ":", "request", ".", "remote_ip", ",", "description", ":", "payment", ".", "description", ",", "language", ":", "payment", ".", "first_data_language", ")", "if", "response", "[", ":transaction_id", "]", "trx", "=", "LolitaFirstData", "::", "Transaction", ".", "add", "(", "payment", ",", "request", ",", "response", ")", "redirect_to", "gateway", ".", "redirect_url", "(", "trx", ".", "transaction_id", ")", "else", "if", "request", ".", "xhr?", "||", "!", "request", ".", "referer", "render", "text", ":", "I18n", ".", "t", "(", "'fd.purchase_failed'", ")", ",", "status", ":", "400", "else", "flash", "[", ":error", "]", "=", "I18n", ".", "t", "(", "'fd.purchase_failed'", ")", "redirect_to", ":back", "end", "end", "ensure", "LolitaFirstData", ".", "logger", ".", "info", "(", "\"[#{session_id}][#{payment.id}][checkout] #{response}\"", ")", "end" ]
We get transaction_id from FirstData and if ok, then we redirect to web interface
[ "We", "get", "transaction_id", "from", "FirstData", "and", "if", "ok", "then", "we", "redirect", "to", "web", "interface" ]
f148588b06a50bfe274b92816700b20c2e899247
https://github.com/ithouse/lolita-first-data/blob/f148588b06a50bfe274b92816700b20c2e899247/app/controllers/lolita_first_data/transactions_controller.rb#L8-L27
9,766
ithouse/lolita-first-data
app/controllers/lolita_first_data/transactions_controller.rb
LolitaFirstData.TransactionsController.answer
def answer if trx = LolitaFirstData::Transaction.where(transaction_id: params[:trans_id]).first response = gateway.result(params[:trans_id], client_ip_addr: request.remote_ip) trx.process_result(response) redirect_to trx.return_path else render text: I18n.t('fd.wrong_request'), status: 400 end ensure if trx LolitaFirstData.logger.info("[#{session_id}][#{trx.paymentable_id}][answer] #{response}") end end
ruby
def answer if trx = LolitaFirstData::Transaction.where(transaction_id: params[:trans_id]).first response = gateway.result(params[:trans_id], client_ip_addr: request.remote_ip) trx.process_result(response) redirect_to trx.return_path else render text: I18n.t('fd.wrong_request'), status: 400 end ensure if trx LolitaFirstData.logger.info("[#{session_id}][#{trx.paymentable_id}][answer] #{response}") end end
[ "def", "answer", "if", "trx", "=", "LolitaFirstData", "::", "Transaction", ".", "where", "(", "transaction_id", ":", "params", "[", ":trans_id", "]", ")", ".", "first", "response", "=", "gateway", ".", "result", "(", "params", "[", ":trans_id", "]", ",", "client_ip_addr", ":", "request", ".", "remote_ip", ")", "trx", ".", "process_result", "(", "response", ")", "redirect_to", "trx", ".", "return_path", "else", "render", "text", ":", "I18n", ".", "t", "(", "'fd.wrong_request'", ")", ",", "status", ":", "400", "end", "ensure", "if", "trx", "LolitaFirstData", ".", "logger", ".", "info", "(", "\"[#{session_id}][#{trx.paymentable_id}][answer] #{response}\"", ")", "end", "end" ]
there we land after returning from FirstData server then we get transactions result and redirect to your given "finish" path
[ "there", "we", "land", "after", "returning", "from", "FirstData", "server", "then", "we", "get", "transactions", "result", "and", "redirect", "to", "your", "given", "finish", "path" ]
f148588b06a50bfe274b92816700b20c2e899247
https://github.com/ithouse/lolita-first-data/blob/f148588b06a50bfe274b92816700b20c2e899247/app/controllers/lolita_first_data/transactions_controller.rb#L31-L43
9,767
cwabbott/heart
app/helpers/heart/dashboards_helper.rb
Heart.DashboardsHelper.flot_array
def flot_array(metrics) replace = false hash = Hash.new if metrics.nil? || metrics.first.nil? || metrics.first.movingaverage.nil? replace = true metrics = Metric.aggregate_daily_moving_averages(0, "WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)") end if metrics.first.nil? return '' end movingaverage = metrics.first.movingaverage #TODO need to move all these options into the HEART js object, set these at runtime, make them easily customizable in the UI extraMeasurements = '' label_suffix = '' if replace == true extraMeasurements = "lines : { show : false, fill : false }," label_suffix = '' else if movingaverage.to_i > 0 extraMeasurements = 'points : { show : false, symbol : "circle" }, lines : { show : true, fill : false },' label_suffix = " [MA:#{movingaverage}] " end end#if replace = true #loop through for all the standard measurements metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time extraSettings = extraMeasurements label = t(att) + label_suffix hash[att] = "#{att} : {#{extraSettings} label : '#{label}', data : [" end # # Now start creating the data arrays for flot. [date_converted_to_integer, value_of_metric_for_date] # metrics.each do |metric| metric.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}]," end end # # Finished creating data arrays # metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} ], att_name : \"#{att}\",}," end flotdata = "flotData_#{movingaverage} : {" hash.each { |key, value| flotdata += value + "\n" } flotdata += "}," flotdata end
ruby
def flot_array(metrics) replace = false hash = Hash.new if metrics.nil? || metrics.first.nil? || metrics.first.movingaverage.nil? replace = true metrics = Metric.aggregate_daily_moving_averages(0, "WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)") end if metrics.first.nil? return '' end movingaverage = metrics.first.movingaverage #TODO need to move all these options into the HEART js object, set these at runtime, make them easily customizable in the UI extraMeasurements = '' label_suffix = '' if replace == true extraMeasurements = "lines : { show : false, fill : false }," label_suffix = '' else if movingaverage.to_i > 0 extraMeasurements = 'points : { show : false, symbol : "circle" }, lines : { show : true, fill : false },' label_suffix = " [MA:#{movingaverage}] " end end#if replace = true #loop through for all the standard measurements metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time extraSettings = extraMeasurements label = t(att) + label_suffix hash[att] = "#{att} : {#{extraSettings} label : '#{label}', data : [" end # # Now start creating the data arrays for flot. [date_converted_to_integer, value_of_metric_for_date] # metrics.each do |metric| metric.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}]," end end # # Finished creating data arrays # metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} ], att_name : \"#{att}\",}," end flotdata = "flotData_#{movingaverage} : {" hash.each { |key, value| flotdata += value + "\n" } flotdata += "}," flotdata end
[ "def", "flot_array", "(", "metrics", ")", "replace", "=", "false", "hash", "=", "Hash", ".", "new", "if", "metrics", ".", "nil?", "||", "metrics", ".", "first", ".", "nil?", "||", "metrics", ".", "first", ".", "movingaverage", ".", "nil?", "replace", "=", "true", "metrics", "=", "Metric", ".", "aggregate_daily_moving_averages", "(", "0", ",", "\"WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)\"", ")", "end", "if", "metrics", ".", "first", ".", "nil?", "return", "''", "end", "movingaverage", "=", "metrics", ".", "first", ".", "movingaverage", "#TODO need to move all these options into the HEART js object, set these at runtime, make them easily customizable in the UI", "extraMeasurements", "=", "''", "label_suffix", "=", "''", "if", "replace", "==", "true", "extraMeasurements", "=", "\"lines : { show : false, fill : false },\"", "label_suffix", "=", "''", "else", "if", "movingaverage", ".", "to_i", ">", "0", "extraMeasurements", "=", "'points : { show : false, symbol : \"circle\" }, lines : { show : true, fill : false },'", "label_suffix", "=", "\" [MA:#{movingaverage}] \"", "end", "end", "#if replace = true", "#loop through for all the standard measurements", "metrics", ".", "first", ".", "attributes", ".", "sort", ".", "each", "do", "|", "att", ",", "value", "|", "next", "unless", "value", ".", "respond_to?", ":to_f", "next", "if", "value", ".", "is_a?", "Time", "extraSettings", "=", "extraMeasurements", "label", "=", "t", "(", "att", ")", "+", "label_suffix", "hash", "[", "att", "]", "=", "\"#{att} : {#{extraSettings} label : '#{label}', data : [\"", "end", "#", "# Now start creating the data arrays for flot. [date_converted_to_integer, value_of_metric_for_date]", "#", "metrics", ".", "each", "do", "|", "metric", "|", "metric", ".", "attributes", ".", "sort", ".", "each", "do", "|", "att", ",", "value", "|", "next", "unless", "value", ".", "respond_to?", ":to_f", "next", "if", "value", ".", "is_a?", "Time", "hash", "[", "att", "]", "=", "\"#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}],\"", "end", "end", "#", "# Finished creating data arrays", "#", "metrics", ".", "first", ".", "attributes", ".", "sort", ".", "each", "do", "|", "att", ",", "value", "|", "next", "unless", "value", ".", "respond_to?", ":to_f", "next", "if", "value", ".", "is_a?", "Time", "hash", "[", "att", "]", "=", "\"#{hash[att]} ], att_name : \\\"#{att}\\\",},\"", "end", "flotdata", "=", "\"flotData_#{movingaverage} : {\"", "hash", ".", "each", "{", "|", "key", ",", "value", "|", "flotdata", "+=", "value", "+", "\"\\n\"", "}", "flotdata", "+=", "\"},\"", "flotdata", "end" ]
Creates javascript objects to use as hashes for flot graph data series + labels
[ "Creates", "javascript", "objects", "to", "use", "as", "hashes", "for", "flot", "graph", "data", "series", "+", "labels" ]
593740a96152fe896848155888ba866f5bbb3dc3
https://github.com/cwabbott/heart/blob/593740a96152fe896848155888ba866f5bbb3dc3/app/helpers/heart/dashboards_helper.rb#L31-L86
9,768
jtzero/vigilem-core
lib/vigilem/core/hooks/callback.rb
Vigilem::Core::Hooks.Callback.evaluate
def evaluate(context, *args, &block) self.result = if block context.define_singleton_method(:__callback__, &self) ret = context.send :__callback__, *args, &block context.class_eval { send :remove_method, :__callback__ } ret else context.instance_exec(*args, &self) end end
ruby
def evaluate(context, *args, &block) self.result = if block context.define_singleton_method(:__callback__, &self) ret = context.send :__callback__, *args, &block context.class_eval { send :remove_method, :__callback__ } ret else context.instance_exec(*args, &self) end end
[ "def", "evaluate", "(", "context", ",", "*", "args", ",", "&", "block", ")", "self", ".", "result", "=", "if", "block", "context", ".", "define_singleton_method", "(", ":__callback__", ",", "self", ")", "ret", "=", "context", ".", "send", ":__callback__", ",", "args", ",", "block", "context", ".", "class_eval", "{", "send", ":remove_method", ",", ":__callback__", "}", "ret", "else", "context", ".", "instance_exec", "(", "args", ",", "self", ")", "end", "end" ]
evaluates the Callback in the specified context @param context @param [Array] args @param [Proc] block @return [Array]
[ "evaluates", "the", "Callback", "in", "the", "specified", "context" ]
a35864229ee76800f5197e3c3c6fb2bf34a68495
https://github.com/jtzero/vigilem-core/blob/a35864229ee76800f5197e3c3c6fb2bf34a68495/lib/vigilem/core/hooks/callback.rb#L22-L31
9,769
pione/ruby-xes
lib/xes/attribute-accessor.rb
XES.AttributeAccessor.define_attribute
def define_attribute(name, type) _name = name.gsub(":", "_") define_method(_name) do var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).find do |attribute| attribute.key == name end.tap{|x| return x.value if x} end define_method("%s=" % _name) do |value| var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).tap do |attributes| if elt = __send__(_name) attributes.delete(elt) end attributes << XES.send(type, name, value) end end end
ruby
def define_attribute(name, type) _name = name.gsub(":", "_") define_method(_name) do var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).find do |attribute| attribute.key == name end.tap{|x| return x.value if x} end define_method("%s=" % _name) do |value| var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).tap do |attributes| if elt = __send__(_name) attributes.delete(elt) end attributes << XES.send(type, name, value) end end end
[ "def", "define_attribute", "(", "name", ",", "type", ")", "_name", "=", "name", ".", "gsub", "(", "\":\"", ",", "\"_\"", ")", "define_method", "(", "_name", ")", "do", "var", "=", "instance_variables", ".", "include?", "(", ":@meta", ")", "?", ":@meta", ":", ":@attributes", "instance_variable_get", "(", "var", ")", ".", "find", "do", "|", "attribute", "|", "attribute", ".", "key", "==", "name", "end", ".", "tap", "{", "|", "x", "|", "return", "x", ".", "value", "if", "x", "}", "end", "define_method", "(", "\"%s=\"", "%", "_name", ")", "do", "|", "value", "|", "var", "=", "instance_variables", ".", "include?", "(", ":@meta", ")", "?", ":@meta", ":", ":@attributes", "instance_variable_get", "(", "var", ")", ".", "tap", "do", "|", "attributes", "|", "if", "elt", "=", "__send__", "(", "_name", ")", "attributes", ".", "delete", "(", "elt", ")", "end", "attributes", "<<", "XES", ".", "send", "(", "type", ",", "name", ",", "value", ")", "end", "end", "end" ]
Define an attribute accessor. @param name [String] attribute name @param type [String] attribute type @return [void]
[ "Define", "an", "attribute", "accessor", "." ]
61501a8fd8027708f670264a150b1ce74fdccd74
https://github.com/pione/ruby-xes/blob/61501a8fd8027708f670264a150b1ce74fdccd74/lib/xes/attribute-accessor.rb#L11-L30
9,770
MrJoy/orderly_garden
lib/orderly_garden/dsl.rb
OrderlyGarden.DSL.with_tempfile
def with_tempfile(fname = nil, &_block) Tempfile.open("tmp") do |f| yield f.path, f.path.shellescape FileUtils.cp(f.path, fname) unless fname.nil? end end
ruby
def with_tempfile(fname = nil, &_block) Tempfile.open("tmp") do |f| yield f.path, f.path.shellescape FileUtils.cp(f.path, fname) unless fname.nil? end end
[ "def", "with_tempfile", "(", "fname", "=", "nil", ",", "&", "_block", ")", "Tempfile", ".", "open", "(", "\"tmp\"", ")", "do", "|", "f", "|", "yield", "f", ".", "path", ",", "f", ".", "path", ".", "shellescape", "FileUtils", ".", "cp", "(", "f", ".", "path", ",", "fname", ")", "unless", "fname", ".", "nil?", "end", "end" ]
Create and manage a temp file, replacing `fname` with the temp file, if `fname` is provided.
[ "Create", "and", "manage", "a", "temp", "file", "replacing", "fname", "with", "the", "temp", "file", "if", "fname", "is", "provided", "." ]
413bcf013de7b7c10650685f713d5131e19494a9
https://github.com/MrJoy/orderly_garden/blob/413bcf013de7b7c10650685f713d5131e19494a9/lib/orderly_garden/dsl.rb#L7-L12
9,771
MrJoy/orderly_garden
lib/orderly_garden/dsl.rb
OrderlyGarden.DSL.write_file
def write_file(file_name, file_contents) contents = file_contents .flatten .select { |line| line } .join("\n") File.open(file_name, "w") do |fh| fh.write(contents) fh.write("\n") end end
ruby
def write_file(file_name, file_contents) contents = file_contents .flatten .select { |line| line } .join("\n") File.open(file_name, "w") do |fh| fh.write(contents) fh.write("\n") end end
[ "def", "write_file", "(", "file_name", ",", "file_contents", ")", "contents", "=", "file_contents", ".", "flatten", ".", "select", "{", "|", "line", "|", "line", "}", ".", "join", "(", "\"\\n\"", ")", "File", ".", "open", "(", "file_name", ",", "\"w\"", ")", "do", "|", "fh", "|", "fh", ".", "write", "(", "contents", ")", "fh", ".", "write", "(", "\"\\n\"", ")", "end", "end" ]
Write an array of strings to a file, adding newline separators, and ensuring a trailing newline at the end of a file.
[ "Write", "an", "array", "of", "strings", "to", "a", "file", "adding", "newline", "separators", "and", "ensuring", "a", "trailing", "newline", "at", "the", "end", "of", "a", "file", "." ]
413bcf013de7b7c10650685f713d5131e19494a9
https://github.com/MrJoy/orderly_garden/blob/413bcf013de7b7c10650685f713d5131e19494a9/lib/orderly_garden/dsl.rb#L16-L25
9,772
rixth/guard-tay
lib/guard/tay.rb
Guard.Tay.munge_options
def munge_options(options) keys_to_munge = [:build_directory, :tayfile] munged = {} options.keys.each do |key| if keys_to_munge.include?(key) new_key = key.to_s.gsub(/_/, '-') end munged[new_key || key] = options[key] end munged end
ruby
def munge_options(options) keys_to_munge = [:build_directory, :tayfile] munged = {} options.keys.each do |key| if keys_to_munge.include?(key) new_key = key.to_s.gsub(/_/, '-') end munged[new_key || key] = options[key] end munged end
[ "def", "munge_options", "(", "options", ")", "keys_to_munge", "=", "[", ":build_directory", ",", ":tayfile", "]", "munged", "=", "{", "}", "options", ".", "keys", ".", "each", "do", "|", "key", "|", "if", "keys_to_munge", ".", "include?", "(", "key", ")", "new_key", "=", "key", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "'-'", ")", "end", "munged", "[", "new_key", "||", "key", "]", "=", "options", "[", "key", "]", "end", "munged", "end" ]
We're using Tay's CLI helpers and they expect string optiopns with dashes, rather than symbols and underscores. So munge!
[ "We", "re", "using", "Tay", "s", "CLI", "helpers", "and", "they", "expect", "string", "optiopns", "with", "dashes", "rather", "than", "symbols", "and", "underscores", ".", "So", "munge!" ]
7441325415571c8012a537ac68bf43e5ca61501d
https://github.com/rixth/guard-tay/blob/7441325415571c8012a537ac68bf43e5ca61501d/lib/guard/tay.rb#L52-L62
9,773
appdrones/page_record
lib/page_record/attributes.rb
PageRecord.Attributes.read_attribute
def read_attribute(attribute) if block_given? element = yield else element = send("#{attribute}?") end tag = element.tag_name input_field?(tag) ? element.value : element.text end
ruby
def read_attribute(attribute) if block_given? element = yield else element = send("#{attribute}?") end tag = element.tag_name input_field?(tag) ? element.value : element.text end
[ "def", "read_attribute", "(", "attribute", ")", "if", "block_given?", "element", "=", "yield", "else", "element", "=", "send", "(", "\"#{attribute}?\"", ")", "end", "tag", "=", "element", ".", "tag_name", "input_field?", "(", "tag", ")", "?", "element", ".", "value", ":", "element", ".", "text", "end" ]
Searches the record for the specified attribute and returns the text content. This method is called when you access an attribute of a record @return [String] the text content of the specified attribute @raise [AttributeNotFound] when the attribute is not found in the record
[ "Searches", "the", "record", "for", "the", "specified", "attribute", "and", "returns", "the", "text", "content", ".", "This", "method", "is", "called", "when", "you", "access", "an", "attribute", "of", "a", "record" ]
2a6d285cbfab906dad6f13f66fea1c09d354b762
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/attributes.rb#L27-L35
9,774
appdrones/page_record
lib/page_record/attributes.rb
PageRecord.Attributes.write_attribute
def write_attribute(attribute, value) element = send("#{attribute}?") tag = element.tag_name case tag when 'textarea', 'input' then element.set(value) when 'select'then element.select(value) else raise NotInputField end element end
ruby
def write_attribute(attribute, value) element = send("#{attribute}?") tag = element.tag_name case tag when 'textarea', 'input' then element.set(value) when 'select'then element.select(value) else raise NotInputField end element end
[ "def", "write_attribute", "(", "attribute", ",", "value", ")", "element", "=", "send", "(", "\"#{attribute}?\"", ")", "tag", "=", "element", ".", "tag_name", "case", "tag", "when", "'textarea'", ",", "'input'", "then", "element", ".", "set", "(", "value", ")", "when", "'select'", "then", "element", ".", "select", "(", "value", ")", "else", "raise", "NotInputField", "end", "element", "end" ]
Searches the record for the specified attribute and sets the value of the attribute This method is called when you set an attribute of a record @return [Capybara::Result] the text content of the specified attribute @raise [AttributeNotFound] when the attribute is not found in the record @raise [NotInputField] when the attribute is not a `TEXTAREA` or `INPUT` tag
[ "Searches", "the", "record", "for", "the", "specified", "attribute", "and", "sets", "the", "value", "of", "the", "attribute", "This", "method", "is", "called", "when", "you", "set", "an", "attribute", "of", "a", "record" ]
2a6d285cbfab906dad6f13f66fea1c09d354b762
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/attributes.rb#L46-L55
9,775
bottiger/Blog_Basic
app/models/blog_basic/blog_comment.rb
BlogBasic.BlogComment.request=
def request=(request) self.user_ip = request.remote_ip self.user_agent = request.env['HTTP_USER_AGENT'] self.referrer = request.env['HTTP_REFERER'] end
ruby
def request=(request) self.user_ip = request.remote_ip self.user_agent = request.env['HTTP_USER_AGENT'] self.referrer = request.env['HTTP_REFERER'] end
[ "def", "request", "=", "(", "request", ")", "self", ".", "user_ip", "=", "request", ".", "remote_ip", "self", ".", "user_agent", "=", "request", ".", "env", "[", "'HTTP_USER_AGENT'", "]", "self", ".", "referrer", "=", "request", ".", "env", "[", "'HTTP_REFERER'", "]", "end" ]
Used to set more tracking for akismet
[ "Used", "to", "set", "more", "tracking", "for", "akismet" ]
9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440
https://github.com/bottiger/Blog_Basic/blob/9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440/app/models/blog_basic/blog_comment.rb#L72-L76
9,776
jarrett/ichiban
lib/ichiban/loader.rb
Ichiban.Loader.delete_all
def delete_all @loaded_constants.each do |const_name| if Object.const_defined?(const_name) Object.send(:remove_const, const_name) end end Ichiban::HTMLCompiler::Context.clear_user_defined_helpers end
ruby
def delete_all @loaded_constants.each do |const_name| if Object.const_defined?(const_name) Object.send(:remove_const, const_name) end end Ichiban::HTMLCompiler::Context.clear_user_defined_helpers end
[ "def", "delete_all", "@loaded_constants", ".", "each", "do", "|", "const_name", "|", "if", "Object", ".", "const_defined?", "(", "const_name", ")", "Object", ".", "send", "(", ":remove_const", ",", "const_name", ")", "end", "end", "Ichiban", "::", "HTMLCompiler", "::", "Context", ".", "clear_user_defined_helpers", "end" ]
Calls Object.remove_const on all tracked modules. Also clears the compiler's list of user-defined helpers.
[ "Calls", "Object", ".", "remove_const", "on", "all", "tracked", "modules", ".", "Also", "clears", "the", "compiler", "s", "list", "of", "user", "-", "defined", "helpers", "." ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/loader.rb#L21-L28
9,777
ktonon/code_node
spec/fixtures/activerecord/src/active_record/dynamic_matchers.rb
ActiveRecord.DynamicMatchers.expand_attribute_names_for_aggregates
def expand_attribute_names_for_aggregates(attribute_names) attribute_names.map { |attribute_name| unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? aggregate_mapping(aggregation).map do |field_attr, _| field_attr.to_sym end else attribute_name.to_sym end }.flatten end
ruby
def expand_attribute_names_for_aggregates(attribute_names) attribute_names.map { |attribute_name| unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? aggregate_mapping(aggregation).map do |field_attr, _| field_attr.to_sym end else attribute_name.to_sym end }.flatten end
[ "def", "expand_attribute_names_for_aggregates", "(", "attribute_names", ")", "attribute_names", ".", "map", "{", "|", "attribute_name", "|", "unless", "(", "aggregation", "=", "reflect_on_aggregation", "(", "attribute_name", ".", "to_sym", ")", ")", ".", "nil?", "aggregate_mapping", "(", "aggregation", ")", ".", "map", "do", "|", "field_attr", ",", "_", "|", "field_attr", ".", "to_sym", "end", "else", "attribute_name", ".", "to_sym", "end", "}", ".", "flatten", "end" ]
Similar in purpose to +expand_hash_conditions_for_aggregates+.
[ "Similar", "in", "purpose", "to", "+", "expand_hash_conditions_for_aggregates", "+", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/dynamic_matchers.rb#L55-L65
9,778
redding/sanford
bench/report.rb
Bench.Runner.build_report
def build_report output "Running benchmark report..." REQUESTS.each do |name, params, times| self.benchmark_service(name, params, times, false) end output "Done running benchmark report" end
ruby
def build_report output "Running benchmark report..." REQUESTS.each do |name, params, times| self.benchmark_service(name, params, times, false) end output "Done running benchmark report" end
[ "def", "build_report", "output", "\"Running benchmark report...\"", "REQUESTS", ".", "each", "do", "|", "name", ",", "params", ",", "times", "|", "self", ".", "benchmark_service", "(", "name", ",", "params", ",", "times", ",", "false", ")", "end", "output", "\"Done running benchmark report\"", "end" ]
4 decimal places
[ "4", "decimal", "places" ]
8153d13ac0b87e5e56eaee3fadb165a5cc6576e9
https://github.com/redding/sanford/blob/8153d13ac0b87e5e56eaee3fadb165a5cc6576e9/bench/report.rb#L24-L32
9,779
RobertAudi/TaskList
lib/task-list/parser.rb
TaskList.Parser.parse!
def parse! unless @type.nil? || VALID_TASKS.include?(@type) raise TaskList::Exceptions::InvalidTaskTypeError.new type: @type end @files.each { |f| parsef! file: f } end
ruby
def parse! unless @type.nil? || VALID_TASKS.include?(@type) raise TaskList::Exceptions::InvalidTaskTypeError.new type: @type end @files.each { |f| parsef! file: f } end
[ "def", "parse!", "unless", "@type", ".", "nil?", "||", "VALID_TASKS", ".", "include?", "(", "@type", ")", "raise", "TaskList", "::", "Exceptions", "::", "InvalidTaskTypeError", ".", "new", "type", ":", "@type", "end", "@files", ".", "each", "{", "|", "f", "|", "parsef!", "file", ":", "f", "}", "end" ]
Parse all the collected files to find tasks and populate the tasks hash
[ "Parse", "all", "the", "collected", "files", "to", "find", "tasks", "and", "populate", "the", "tasks", "hash" ]
98ac82f449eec7a6958f88c19c9637845eae68f2
https://github.com/RobertAudi/TaskList/blob/98ac82f449eec7a6958f88c19c9637845eae68f2/lib/task-list/parser.rb#L28-L34
9,780
neiljohari/scram
lib/scram/dsl/model_conditions.rb
Scram::DSL.ModelConditions.method_missing
def method_missing(method, *args) if method.to_s.starts_with? "*" condition_name = method.to_s.split("*")[1].to_sym conditions = self.class.scram_conditions if conditions && !conditions[condition_name].nil? return conditions[condition_name].call(self) end end super end
ruby
def method_missing(method, *args) if method.to_s.starts_with? "*" condition_name = method.to_s.split("*")[1].to_sym conditions = self.class.scram_conditions if conditions && !conditions[condition_name].nil? return conditions[condition_name].call(self) end end super end
[ "def", "method_missing", "(", "method", ",", "*", "args", ")", "if", "method", ".", "to_s", ".", "starts_with?", "\"*\"", "condition_name", "=", "method", ".", "to_s", ".", "split", "(", "\"*\"", ")", "[", "1", "]", ".", "to_sym", "conditions", "=", "self", ".", "class", ".", "scram_conditions", "if", "conditions", "&&", "!", "conditions", "[", "condition_name", "]", ".", "nil?", "return", "conditions", "[", "condition_name", "]", ".", "call", "(", "self", ")", "end", "end", "super", "end" ]
Methods starting with an asterisk are tested for DSL defined conditions
[ "Methods", "starting", "with", "an", "asterisk", "are", "tested", "for", "DSL", "defined", "conditions" ]
df3e48e9e9cab4b363b1370df5991319d21c256d
https://github.com/neiljohari/scram/blob/df3e48e9e9cab4b363b1370df5991319d21c256d/lib/scram/dsl/model_conditions.rb#L27-L36
9,781
jamesmacaulay/sprockets_rails3_backport
lib/action_view/asset_paths.rb
ActionView.AssetPaths.compute_source_path
def compute_source_path(source, dir, ext) source = rewrite_extension(source, dir, ext) if ext File.join(config.assets_dir, dir, source) end
ruby
def compute_source_path(source, dir, ext) source = rewrite_extension(source, dir, ext) if ext File.join(config.assets_dir, dir, source) end
[ "def", "compute_source_path", "(", "source", ",", "dir", ",", "ext", ")", "source", "=", "rewrite_extension", "(", "source", ",", "dir", ",", "ext", ")", "if", "ext", "File", ".", "join", "(", "config", ".", "assets_dir", ",", "dir", ",", "source", ")", "end" ]
Return the filesystem path for the source
[ "Return", "the", "filesystem", "path", "for", "the", "source" ]
243de154606be141221b5ebd4cfe75857328e08a
https://github.com/jamesmacaulay/sprockets_rails3_backport/blob/243de154606be141221b5ebd4cfe75857328e08a/lib/action_view/asset_paths.rb#L34-L37
9,782
imathis/jekyll-stitch-plus
lib/jekyll-stitch-plus.rb
Jekyll.StitchPlus.cleanup
def cleanup(site, stitch) files = stitch.all_files.map{ |f| File.absolute_path(f)} files.concat stitch.deleted if files.size > 0 site.static_files.clone.each do |sf| if sf.kind_of?(Jekyll::StaticFile) and files.include? sf.path site.static_files.delete(sf) end end end end
ruby
def cleanup(site, stitch) files = stitch.all_files.map{ |f| File.absolute_path(f)} files.concat stitch.deleted if files.size > 0 site.static_files.clone.each do |sf| if sf.kind_of?(Jekyll::StaticFile) and files.include? sf.path site.static_files.delete(sf) end end end end
[ "def", "cleanup", "(", "site", ",", "stitch", ")", "files", "=", "stitch", ".", "all_files", ".", "map", "{", "|", "f", "|", "File", ".", "absolute_path", "(", "f", ")", "}", "files", ".", "concat", "stitch", ".", "deleted", "if", "files", ".", "size", ">", "0", "site", ".", "static_files", ".", "clone", ".", "each", "do", "|", "sf", "|", "if", "sf", ".", "kind_of?", "(", "Jekyll", "::", "StaticFile", ")", "and", "files", ".", "include?", "sf", ".", "path", "site", ".", "static_files", ".", "delete", "(", "sf", ")", "end", "end", "end", "end" ]
Remove files from Jekyll's static_files array
[ "Remove", "files", "from", "Jekyll", "s", "static_files", "array" ]
0ffd1f7061c2b36f37bb0b175b35f15e1561eeeb
https://github.com/imathis/jekyll-stitch-plus/blob/0ffd1f7061c2b36f37bb0b175b35f15e1561eeeb/lib/jekyll-stitch-plus.rb#L54-L66
9,783
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/tokens.rb
SlackBotManager.Tokens.get_id_from_token
def get_id_from_token(token) storage.get_all(tokens_key).each { |id, t| return id if t == token } false end
ruby
def get_id_from_token(token) storage.get_all(tokens_key).each { |id, t| return id if t == token } false end
[ "def", "get_id_from_token", "(", "token", ")", "storage", ".", "get_all", "(", "tokens_key", ")", ".", "each", "{", "|", "id", ",", "t", "|", "return", "id", "if", "t", "==", "token", "}", "false", "end" ]
Given a token, get id from tokens list
[ "Given", "a", "token", "get", "id", "from", "tokens", "list" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/tokens.rb#L88-L91
9,784
mswart/cany
lib/cany/recipe.rb
Cany.Recipe.exec
def exec(*args) args.flatten! Cany.logger.info args.join(' ') unless system(*args) raise CommandExecutionFailed.new args end end
ruby
def exec(*args) args.flatten! Cany.logger.info args.join(' ') unless system(*args) raise CommandExecutionFailed.new args end end
[ "def", "exec", "(", "*", "args", ")", "args", ".", "flatten!", "Cany", ".", "logger", ".", "info", "args", ".", "join", "(", "' '", ")", "unless", "system", "(", "args", ")", "raise", "CommandExecutionFailed", ".", "new", "args", "end", "end" ]
API to use inside the recipe @api public Run a command inside the build directory. In most cases it is not needed to call this method directly. Look at the other helper methods. The method expects as arguments the program name and additional parameters for the program. The arguments can be group with arguments, but must not: @example exec 'echo', %w(a b) exec ['echo', 'a', 'b'] exec 'echo', 'a', 'b' @raise [CommandExecutionFailed] if the executed program exists with a non-zero exit code.
[ "API", "to", "use", "inside", "the", "recipe" ]
0d2bf4d3704d4e9a222b11f6d764b57234ddf36d
https://github.com/mswart/cany/blob/0d2bf4d3704d4e9a222b11f6d764b57234ddf36d/lib/cany/recipe.rb#L69-L75
9,785
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.factory
def factory(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Factory.new(block || klass) end
ruby
def factory(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Factory.new(block || klass) end
[ "def", "factory", "(", "name", ",", "klass", "=", "nil", ",", "&", "block", ")", "@registry", "[", "name", ".", "to_sym", "]", "=", "Resolver", "::", "Factory", ".", "new", "(", "block", "||", "klass", ")", "end" ]
Registers a dependency which is resolved every time its value is fetched.
[ "Registers", "a", "dependency", "which", "is", "resolved", "every", "time", "its", "value", "is", "fetched", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L38-L40
9,786
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.singleton
def singleton(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Singleton.new(block || klass) end
ruby
def singleton(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Singleton.new(block || klass) end
[ "def", "singleton", "(", "name", ",", "klass", "=", "nil", ",", "&", "block", ")", "@registry", "[", "name", ".", "to_sym", "]", "=", "Resolver", "::", "Singleton", ".", "new", "(", "block", "||", "klass", ")", "end" ]
Registers a dependency which is only resolved the first time its value is fetched. On subsequent fetches, the cached value is returned.
[ "Registers", "a", "dependency", "which", "is", "only", "resolved", "the", "first", "time", "its", "value", "is", "fetched", ".", "On", "subsequent", "fetches", "the", "cached", "value", "is", "returned", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L50-L52
9,787
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.mixin
def mixin(args) # normalize the supplied argument (array or hash) into a hash of # { visibility => exports } pairs, where `visibility` is a symbol and # `exports` is a hash of { dependency_name => method_name } pairs if args.is_a?(Array) args = { @default_visibility => args } elsif !args.is_a?(Hash) raise ArgumentError, "invalid mixin argument: expected array or hash, got: #{args.class}" end # slurp each array of name (symbol) or name => alias (hash) imports into # a normalized hash of { dependency_name => method_name } pairs e.g.: # # before: # # [:foo, { :bar => :baz }, :quux] # # after: # # { :foo => :foo, :bar => :baz, :quux => :quux } # XXX transform_values isn't available in ruby 2.3 and we don't want to # pull in ActiveSupport just for one method (on this occasion) # # args = DEFAULT_EXPORTS.merge(args).transform_values do |exports| # exports = [exports] unless exports.is_a?(Array) # exports.reduce({}) do |a, b| # a.merge(b.is_a?(Hash) ? b : { b => b }) # end # end args = DEFAULT_EXPORTS.merge(args).each_with_object({}) do |(key, exports), merged| exports = [exports] unless exports.is_a?(Array) merged[key] = exports.reduce({}) do |a, b| a.merge(b.is_a?(Hash) ? b : { b => b }) end end @module_cache.get!(args) { module_for(args) } end
ruby
def mixin(args) # normalize the supplied argument (array or hash) into a hash of # { visibility => exports } pairs, where `visibility` is a symbol and # `exports` is a hash of { dependency_name => method_name } pairs if args.is_a?(Array) args = { @default_visibility => args } elsif !args.is_a?(Hash) raise ArgumentError, "invalid mixin argument: expected array or hash, got: #{args.class}" end # slurp each array of name (symbol) or name => alias (hash) imports into # a normalized hash of { dependency_name => method_name } pairs e.g.: # # before: # # [:foo, { :bar => :baz }, :quux] # # after: # # { :foo => :foo, :bar => :baz, :quux => :quux } # XXX transform_values isn't available in ruby 2.3 and we don't want to # pull in ActiveSupport just for one method (on this occasion) # # args = DEFAULT_EXPORTS.merge(args).transform_values do |exports| # exports = [exports] unless exports.is_a?(Array) # exports.reduce({}) do |a, b| # a.merge(b.is_a?(Hash) ? b : { b => b }) # end # end args = DEFAULT_EXPORTS.merge(args).each_with_object({}) do |(key, exports), merged| exports = [exports] unless exports.is_a?(Array) merged[key] = exports.reduce({}) do |a, b| a.merge(b.is_a?(Hash) ? b : { b => b }) end end @module_cache.get!(args) { module_for(args) } end
[ "def", "mixin", "(", "args", ")", "# normalize the supplied argument (array or hash) into a hash of", "# { visibility => exports } pairs, where `visibility` is a symbol and", "# `exports` is a hash of { dependency_name => method_name } pairs", "if", "args", ".", "is_a?", "(", "Array", ")", "args", "=", "{", "@default_visibility", "=>", "args", "}", "elsif", "!", "args", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ",", "\"invalid mixin argument: expected array or hash, got: #{args.class}\"", "end", "# slurp each array of name (symbol) or name => alias (hash) imports into", "# a normalized hash of { dependency_name => method_name } pairs e.g.:", "#", "# before:", "#", "# [:foo, { :bar => :baz }, :quux]", "#", "# after:", "#", "# { :foo => :foo, :bar => :baz, :quux => :quux }", "# XXX transform_values isn't available in ruby 2.3 and we don't want to", "# pull in ActiveSupport just for one method (on this occasion)", "#", "# args = DEFAULT_EXPORTS.merge(args).transform_values do |exports|", "# exports = [exports] unless exports.is_a?(Array)", "# exports.reduce({}) do |a, b|", "# a.merge(b.is_a?(Hash) ? b : { b => b })", "# end", "# end", "args", "=", "DEFAULT_EXPORTS", ".", "merge", "(", "args", ")", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "exports", ")", ",", "merged", "|", "exports", "=", "[", "exports", "]", "unless", "exports", ".", "is_a?", "(", "Array", ")", "merged", "[", "key", "]", "=", "exports", ".", "reduce", "(", "{", "}", ")", "do", "|", "a", ",", "b", "|", "a", ".", "merge", "(", "b", ".", "is_a?", "(", "Hash", ")", "?", "b", ":", "{", "b", "=>", "b", "}", ")", "end", "end", "@module_cache", ".", "get!", "(", "args", ")", "{", "module_for", "(", "args", ")", "}", "end" ]
Takes an array or hash specifying the dependencies to export, and returns a module which defines getters for those dependencies. class Test # hash (specify visibilities) include Services.mixin private: :foo, protected: %i[bar baz], public: :quux # or an array of imports using the default visibility (:private by default) include Services.mixin %i[foo bar baz quux] def test foo + bar + baz + quux # access the dependencies end end The visibility of the generated getters can be controlled by passing a hash with { visibility => imports } pairs, where imports is an array of import specifiers. An import specifier is a symbol (method name == dependency name) or a hash with { dependency_name => method_name } pairs (aliases). If there's only one import specifier, its enclosing array can be omitted e.g.: include Services.mixin(private: :foo, protected: { :baz => :quux }) is equivalent to: include Services.mixin(private: [:foo], protected: [{ :baz => :quux }])
[ "Takes", "an", "array", "or", "hash", "specifying", "the", "dependencies", "to", "export", "and", "returns", "a", "module", "which", "defines", "getters", "for", "those", "dependencies", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L81-L120
9,788
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.module_for
def module_for(args) registry = self mod = Module.new args.each do |visibility, exports| exports.each do |dependency_name, method_name| # equivalent to (e.g.): # # def foo # registry.fetch(:foo) # end mod.send(:define_method, method_name) do registry.fetch(dependency_name) end # equivalent to (e.g.): # # private :foo mod.send(visibility, method_name) end end mod end
ruby
def module_for(args) registry = self mod = Module.new args.each do |visibility, exports| exports.each do |dependency_name, method_name| # equivalent to (e.g.): # # def foo # registry.fetch(:foo) # end mod.send(:define_method, method_name) do registry.fetch(dependency_name) end # equivalent to (e.g.): # # private :foo mod.send(visibility, method_name) end end mod end
[ "def", "module_for", "(", "args", ")", "registry", "=", "self", "mod", "=", "Module", ".", "new", "args", ".", "each", "do", "|", "visibility", ",", "exports", "|", "exports", ".", "each", "do", "|", "dependency_name", ",", "method_name", "|", "# equivalent to (e.g.):", "#", "# def foo", "# registry.fetch(:foo)", "# end", "mod", ".", "send", "(", ":define_method", ",", "method_name", ")", "do", "registry", ".", "fetch", "(", "dependency_name", ")", "end", "# equivalent to (e.g.):", "#", "# private :foo", "mod", ".", "send", "(", "visibility", ",", "method_name", ")", "end", "end", "mod", "end" ]
Create a module with the specified exports
[ "Create", "a", "module", "with", "the", "specified", "exports" ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L128-L151
9,789
dgjnpr/Sloe
lib/sloe/junos.rb
Sloe.Junos.cli
def cli(cmd_str, attrs = { format: 'text' }) reply = rpc.command(cmd_str, attrs) reply.respond_to?(:text) ? reply.text : reply end
ruby
def cli(cmd_str, attrs = { format: 'text' }) reply = rpc.command(cmd_str, attrs) reply.respond_to?(:text) ? reply.text : reply end
[ "def", "cli", "(", "cmd_str", ",", "attrs", "=", "{", "format", ":", "'text'", "}", ")", "reply", "=", "rpc", ".", "command", "(", "cmd_str", ",", "attrs", ")", "reply", ".", "respond_to?", "(", ":text", ")", "?", "reply", ".", "text", ":", "reply", "end" ]
execute CLI commands over NETCONF transport returns plain text, rather than XML, by default @param cmd_str [String] A valid Junos CLI command. @param attrs [Hash] Supports same attributes as {http://rubydoc.info/gems/netconf/Netconf/RPC/Junos:command Junos#command} @return nil if command returns no text. Otherwise returns text in format requested (default is plain text)
[ "execute", "CLI", "commands", "over", "NETCONF", "transport", "returns", "plain", "text", "rather", "than", "XML", "by", "default" ]
7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355
https://github.com/dgjnpr/Sloe/blob/7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355/lib/sloe/junos.rb#L15-L18
9,790
dgjnpr/Sloe
lib/sloe/junos.rb
Sloe.Junos.apply_configuration
def apply_configuration(config, attrs = { format: 'text' }) rpc.lock_configuration rpc.load_configuration(config, attrs) rpc.commit_configuration rpc.unlock_configuration end
ruby
def apply_configuration(config, attrs = { format: 'text' }) rpc.lock_configuration rpc.load_configuration(config, attrs) rpc.commit_configuration rpc.unlock_configuration end
[ "def", "apply_configuration", "(", "config", ",", "attrs", "=", "{", "format", ":", "'text'", "}", ")", "rpc", ".", "lock_configuration", "rpc", ".", "load_configuration", "(", "config", ",", "attrs", ")", "rpc", ".", "commit_configuration", "rpc", ".", "unlock_configuration", "end" ]
Simplifies applying configuration to a Junos device. Uses Junos NETCONF extensions to apply the configuration. Returns to the previous committed config if any arror occurs @param config [String] Configuration to be applied the device @param attrs [Hash] Takes same attributes as {http://rubydoc.info/gems/netconf/Netconf/RPC/Junos:load_configuration Junos#load_configuration}
[ "Simplifies", "applying", "configuration", "to", "a", "Junos", "device", ".", "Uses", "Junos", "NETCONF", "extensions", "to", "apply", "the", "configuration", ".", "Returns", "to", "the", "previous", "committed", "config", "if", "any", "arror", "occurs" ]
7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355
https://github.com/dgjnpr/Sloe/blob/7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355/lib/sloe/junos.rb#L27-L32
9,791
geekyfox/tdp
lib/tdp.rb
TDP.PatchSet.<<
def <<(patch) known_patch = @patches[patch.name] if known_patch.nil? @patches[patch.name] = patch elsif patch.content != known_patch.content raise ContradictionError, [known_patch, patch] end end
ruby
def <<(patch) known_patch = @patches[patch.name] if known_patch.nil? @patches[patch.name] = patch elsif patch.content != known_patch.content raise ContradictionError, [known_patch, patch] end end
[ "def", "<<", "(", "patch", ")", "known_patch", "=", "@patches", "[", "patch", ".", "name", "]", "if", "known_patch", ".", "nil?", "@patches", "[", "patch", ".", "name", "]", "=", "patch", "elsif", "patch", ".", "content", "!=", "known_patch", ".", "content", "raise", "ContradictionError", ",", "[", "known_patch", ",", "patch", "]", "end", "end" ]
Adds a patch to the set. Raises ContradictionError in case if patch set already contains a patch with the same name and different content. patch :: Patch object to add
[ "Adds", "a", "patch", "to", "the", "set", ".", "Raises", "ContradictionError", "in", "case", "if", "patch", "set", "already", "contains", "a", "patch", "with", "the", "same", "name", "and", "different", "content", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L162-L169
9,792
geekyfox/tdp
lib/tdp.rb
TDP.DAO.patch_signature
def patch_signature(name) row = @db[:tdp_patch].select(:signature).where(name: name).first row.nil? ? nil : row[:signature] end
ruby
def patch_signature(name) row = @db[:tdp_patch].select(:signature).where(name: name).first row.nil? ? nil : row[:signature] end
[ "def", "patch_signature", "(", "name", ")", "row", "=", "@db", "[", ":tdp_patch", "]", ".", "select", "(", ":signature", ")", ".", "where", "(", "name", ":", "name", ")", ".", "first", "row", ".", "nil?", "?", "nil", ":", "row", "[", ":signature", "]", "end" ]
Looks up a signature of a patch by its name.
[ "Looks", "up", "a", "signature", "of", "a", "patch", "by", "its", "name", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L269-L272
9,793
geekyfox/tdp
lib/tdp.rb
TDP.Engine.<<
def <<(filename) if File.directory?(filename) Dir.foreach(filename) do |x| self << File.join(filename, x) unless x.start_with?('.') end elsif TDP.patch_file?(filename) @patches << Patch.new(filename) end end
ruby
def <<(filename) if File.directory?(filename) Dir.foreach(filename) do |x| self << File.join(filename, x) unless x.start_with?('.') end elsif TDP.patch_file?(filename) @patches << Patch.new(filename) end end
[ "def", "<<", "(", "filename", ")", "if", "File", ".", "directory?", "(", "filename", ")", "Dir", ".", "foreach", "(", "filename", ")", "do", "|", "x", "|", "self", "<<", "File", ".", "join", "(", "filename", ",", "x", ")", "unless", "x", ".", "start_with?", "(", "'.'", ")", "end", "elsif", "TDP", ".", "patch_file?", "(", "filename", ")", "@patches", "<<", "Patch", ".", "new", "(", "filename", ")", "end", "end" ]
Creates a new Engine object. db :: must be one of: * instance of Sequel::Database class * database URL that can be passed to Sequel.connect() Registers patch files in the engine. filename :: may be either a name of .sql file or a name of directory (which would be recursively scanned for .sql files)
[ "Creates", "a", "new", "Engine", "object", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L338-L346
9,794
geekyfox/tdp
lib/tdp.rb
TDP.Engine.plan
def plan ref = @dao.applied_patches @patches.select do |patch| signature = ref[patch.name] next false if signature == patch.signature next true if signature.nil? || patch.volatile? raise MismatchError, patch end end
ruby
def plan ref = @dao.applied_patches @patches.select do |patch| signature = ref[patch.name] next false if signature == patch.signature next true if signature.nil? || patch.volatile? raise MismatchError, patch end end
[ "def", "plan", "ref", "=", "@dao", ".", "applied_patches", "@patches", ".", "select", "do", "|", "patch", "|", "signature", "=", "ref", "[", "patch", ".", "name", "]", "next", "false", "if", "signature", "==", "patch", ".", "signature", "next", "true", "if", "signature", ".", "nil?", "||", "patch", ".", "volatile?", "raise", "MismatchError", ",", "patch", "end", "end" ]
Produces an ordered list of patches that need to be applied. May raise MismatchError in case if signatures of any permanent patches that are present in the definition don't match ones of the patches applied to the database.
[ "Produces", "an", "ordered", "list", "of", "patches", "that", "need", "to", "be", "applied", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L363-L371
9,795
geekyfox/tdp
lib/tdp.rb
TDP.Engine.validate_compatible
def validate_compatible validate_upgradable @patches.each do |patch| signature = @dao.patch_signature(patch.name) next if signature == patch.signature raise NotAppliedError, patch if signature.nil? raise MismatchError, patch end end
ruby
def validate_compatible validate_upgradable @patches.each do |patch| signature = @dao.patch_signature(patch.name) next if signature == patch.signature raise NotAppliedError, patch if signature.nil? raise MismatchError, patch end end
[ "def", "validate_compatible", "validate_upgradable", "@patches", ".", "each", "do", "|", "patch", "|", "signature", "=", "@dao", ".", "patch_signature", "(", "patch", ".", "name", ")", "next", "if", "signature", "==", "patch", ".", "signature", "raise", "NotAppliedError", ",", "patch", "if", "signature", ".", "nil?", "raise", "MismatchError", ",", "patch", "end", "end" ]
Validates that all patches are applied to the database. May raise MismatchError, NotConfiguredError or NotAppliedError in case if there are any problems.
[ "Validates", "that", "all", "patches", "are", "applied", "to", "the", "database", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L420-L429
9,796
jeremyd/virtualmonkey
lib/virtualmonkey/unified_application.rb
VirtualMonkey.UnifiedApplication.run_unified_application_check
def run_unified_application_check(dns_name, port=8000) url_base = "#{dns_name}:#{port}" behavior(:test_http_response, "html serving succeeded", "#{url_base}/index.html", port) behavior(:test_http_response, "configuration=succeeded", "#{url_base}/appserver/", port) behavior(:test_http_response, "I am in the db", "#{url_base}/dbread/", port) behavior(:test_http_response, "hostname=", "#{url_base}/serverid/", port) end
ruby
def run_unified_application_check(dns_name, port=8000) url_base = "#{dns_name}:#{port}" behavior(:test_http_response, "html serving succeeded", "#{url_base}/index.html", port) behavior(:test_http_response, "configuration=succeeded", "#{url_base}/appserver/", port) behavior(:test_http_response, "I am in the db", "#{url_base}/dbread/", port) behavior(:test_http_response, "hostname=", "#{url_base}/serverid/", port) end
[ "def", "run_unified_application_check", "(", "dns_name", ",", "port", "=", "8000", ")", "url_base", "=", "\"#{dns_name}:#{port}\"", "behavior", "(", ":test_http_response", ",", "\"html serving succeeded\"", ",", "\"#{url_base}/index.html\"", ",", "port", ")", "behavior", "(", ":test_http_response", ",", "\"configuration=succeeded\"", ",", "\"#{url_base}/appserver/\"", ",", "port", ")", "behavior", "(", ":test_http_response", ",", "\"I am in the db\"", ",", "\"#{url_base}/dbread/\"", ",", "port", ")", "behavior", "(", ":test_http_response", ",", "\"hostname=\"", ",", "\"#{url_base}/serverid/\"", ",", "port", ")", "end" ]
this is where ALL the generic application server checks live, this could get rather long but for now it's a single method with a sequence of checks
[ "this", "is", "where", "ALL", "the", "generic", "application", "server", "checks", "live", "this", "could", "get", "rather", "long", "but", "for", "now", "it", "s", "a", "single", "method", "with", "a", "sequence", "of", "checks" ]
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/unified_application.rb#L31-L37
9,797
seblindberg/ruby-adam6050
lib/adam6050/session.rb
ADAM6050.Session.validate!
def validate!(sender, time: monotonic_timestamp) key = session_key sender last_observed = @session.fetch(key) { raise UnknownSender, sender } raise InvalidSender, sender if expired? last_observed, time, @timeout @session[key] = time nil end
ruby
def validate!(sender, time: monotonic_timestamp) key = session_key sender last_observed = @session.fetch(key) { raise UnknownSender, sender } raise InvalidSender, sender if expired? last_observed, time, @timeout @session[key] = time nil end
[ "def", "validate!", "(", "sender", ",", "time", ":", "monotonic_timestamp", ")", "key", "=", "session_key", "sender", "last_observed", "=", "@session", ".", "fetch", "(", "key", ")", "{", "raise", "UnknownSender", ",", "sender", "}", "raise", "InvalidSender", ",", "sender", "if", "expired?", "last_observed", ",", "time", ",", "@timeout", "@session", "[", "key", "]", "=", "time", "nil", "end" ]
Renews the given sender if it is still valid within the session and raises an exception otherwise. @raise [UnknownSender] if the given sender is not registered. @raise [InvalidSender] if the given sender is not valid. @param sender [Socket::UDPSource] the udp client. @param time [Numeric] the current time. The current time will be used if not specified. @return [nil]
[ "Renews", "the", "given", "sender", "if", "it", "is", "still", "valid", "within", "the", "session", "and", "raises", "an", "exception", "otherwise", "." ]
7a8e8c344cc770b25d18ddf43f105d0f19e14d50
https://github.com/seblindberg/ruby-adam6050/blob/7a8e8c344cc770b25d18ddf43f105d0f19e14d50/lib/adam6050/session.rb#L98-L105
9,798
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.new
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_new]) @tag = LatoBlog::Tag.new if params[:language] set_current_language params[:language] end if params[:parent] @tag_parent = LatoBlog::TagParent.find_by(id: params[:parent]) end end
ruby
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_new]) @tag = LatoBlog::Tag.new if params[:language] set_current_language params[:language] end if params[:parent] @tag_parent = LatoBlog::TagParent.find_by(id: params[:parent]) end end
[ "def", "new", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":tags_new", "]", ")", "@tag", "=", "LatoBlog", "::", "Tag", ".", "new", "if", "params", "[", ":language", "]", "set_current_language", "params", "[", ":language", "]", "end", "if", "params", "[", ":parent", "]", "@tag_parent", "=", "LatoBlog", "::", "TagParent", ".", "find_by", "(", "id", ":", "params", "[", ":parent", "]", ")", "end", "end" ]
This function shows the view to create a new tag.
[ "This", "function", "shows", "the", "view", "to", "create", "a", "new", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L27-L38
9,799
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.create
def create @tag = LatoBlog::Tag.new(new_tag_params) if !@tag.save flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.new_tag_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_create_success] redirect_to lato_blog.tag_path(@tag.id) end
ruby
def create @tag = LatoBlog::Tag.new(new_tag_params) if !@tag.save flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.new_tag_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_create_success] redirect_to lato_blog.tag_path(@tag.id) end
[ "def", "create", "@tag", "=", "LatoBlog", "::", "Tag", ".", "new", "(", "new_tag_params", ")", "if", "!", "@tag", ".", "save", "flash", "[", ":danger", "]", "=", "@tag", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "new_tag_path", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":tag_create_success", "]", "redirect_to", "lato_blog", ".", "tag_path", "(", "@tag", ".", "id", ")", "end" ]
This function creates a new tag.
[ "This", "function", "creates", "a", "new", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L41-L52