id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
400
12spokes/tandem
app/helpers/tandem/pages_helper.rb
Tandem.PagesHelper.tandem_navigation_tag
def tandem_navigation_tag(active_page, pages_collection = nil, html_options = {}) html_options, pages_collection = pages_collection, nil if pages_collection.is_a?(Hash) html_options[:class] ||= 'nav' page_groups = (pages_collection || Page.all).inject({}) do |groups, page| if groups[page.parent_id.to_s] groups[page.parent_id.to_s] << page else groups[page.parent_id.to_s] = [page] end groups end # generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope generate = nil iterate = Proc.new do |parent_id| #very important to delete the group from the collection, or it is possible users can create looping relationships (page_groups.delete(parent_id.to_s) || {}).inject(''.html_safe) do |buffer, page| buffer + generate.call(page) end end generate = Proc.new do |page| content_tag_for(:li, page, :tandem, class: "#{page == active_page ? 'active' : ''}") do link_to(page.link_label, tandem.page_path(page), class: "#{page == active_page ? 'active' : ''}") + content_tag(:ul) do iterate.call(page.id) end end end content_tag(:ul, html_options) do iterate.call(page_groups.keys.first) end end
ruby
def tandem_navigation_tag(active_page, pages_collection = nil, html_options = {}) html_options, pages_collection = pages_collection, nil if pages_collection.is_a?(Hash) html_options[:class] ||= 'nav' page_groups = (pages_collection || Page.all).inject({}) do |groups, page| if groups[page.parent_id.to_s] groups[page.parent_id.to_s] << page else groups[page.parent_id.to_s] = [page] end groups end # generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope generate = nil iterate = Proc.new do |parent_id| #very important to delete the group from the collection, or it is possible users can create looping relationships (page_groups.delete(parent_id.to_s) || {}).inject(''.html_safe) do |buffer, page| buffer + generate.call(page) end end generate = Proc.new do |page| content_tag_for(:li, page, :tandem, class: "#{page == active_page ? 'active' : ''}") do link_to(page.link_label, tandem.page_path(page), class: "#{page == active_page ? 'active' : ''}") + content_tag(:ul) do iterate.call(page.id) end end end content_tag(:ul, html_options) do iterate.call(page_groups.keys.first) end end
[ "def", "tandem_navigation_tag", "(", "active_page", ",", "pages_collection", "=", "nil", ",", "html_options", "=", "{", "}", ")", "html_options", ",", "pages_collection", "=", "pages_collection", ",", "nil", "if", "pages_collection", ".", "is_a?", "(", "Hash", ")", "html_options", "[", ":class", "]", "||=", "'nav'", "page_groups", "=", "(", "pages_collection", "||", "Page", ".", "all", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "groups", ",", "page", "|", "if", "groups", "[", "page", ".", "parent_id", ".", "to_s", "]", "groups", "[", "page", ".", "parent_id", ".", "to_s", "]", "<<", "page", "else", "groups", "[", "page", ".", "parent_id", ".", "to_s", "]", "=", "[", "page", "]", "end", "groups", "end", "# generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope", "generate", "=", "nil", "iterate", "=", "Proc", ".", "new", "do", "|", "parent_id", "|", "#very important to delete the group from the collection, or it is possible users can create looping relationships", "(", "page_groups", ".", "delete", "(", "parent_id", ".", "to_s", ")", "||", "{", "}", ")", ".", "inject", "(", "''", ".", "html_safe", ")", "do", "|", "buffer", ",", "page", "|", "buffer", "+", "generate", ".", "call", "(", "page", ")", "end", "end", "generate", "=", "Proc", ".", "new", "do", "|", "page", "|", "content_tag_for", "(", ":li", ",", "page", ",", ":tandem", ",", "class", ":", "\"#{page == active_page ? 'active' : ''}\"", ")", "do", "link_to", "(", "page", ".", "link_label", ",", "tandem", ".", "page_path", "(", "page", ")", ",", "class", ":", "\"#{page == active_page ? 'active' : ''}\"", ")", "+", "content_tag", "(", ":ul", ")", "do", "iterate", ".", "call", "(", "page", ".", "id", ")", "end", "end", "end", "content_tag", "(", ":ul", ",", "html_options", ")", "do", "iterate", ".", "call", "(", "page_groups", ".", "keys", ".", "first", ")", "end", "end" ]
todo... document this
[ "todo", "...", "document", "this" ]
6ad1cd041158c721c84a8c27809c1ddac1dbf6ce
https://github.com/12spokes/tandem/blob/6ad1cd041158c721c84a8c27809c1ddac1dbf6ce/app/helpers/tandem/pages_helper.rb#L137-L173
401
CryptoProcessing/cryptoprocessing.rb
lib/cryptoprocessing/connection.rb
Cryptoprocessing.Connection.get
def get(path, params = {}) uri = path if params.count > 0 uri += "?#{URI.encode_www_form(params)}" end headers = {} request('GET', uri, nil, headers) do |resp| if params[:fetch_all] == true && resp.body.has_key?('pagination') && resp.body['pagination']['next_uri'] != nil params[:starting_after] = resp.body['data'].last['id'] get(path, params) do |page| body = resp.body body['data'] += page.data resp.body = body yield(resp) if block_given? end else yield(resp) if block_given? end end end
ruby
def get(path, params = {}) uri = path if params.count > 0 uri += "?#{URI.encode_www_form(params)}" end headers = {} request('GET', uri, nil, headers) do |resp| if params[:fetch_all] == true && resp.body.has_key?('pagination') && resp.body['pagination']['next_uri'] != nil params[:starting_after] = resp.body['data'].last['id'] get(path, params) do |page| body = resp.body body['data'] += page.data resp.body = body yield(resp) if block_given? end else yield(resp) if block_given? end end end
[ "def", "get", "(", "path", ",", "params", "=", "{", "}", ")", "uri", "=", "path", "if", "params", ".", "count", ">", "0", "uri", "+=", "\"?#{URI.encode_www_form(params)}\"", "end", "headers", "=", "{", "}", "request", "(", "'GET'", ",", "uri", ",", "nil", ",", "headers", ")", "do", "|", "resp", "|", "if", "params", "[", ":fetch_all", "]", "==", "true", "&&", "resp", ".", "body", ".", "has_key?", "(", "'pagination'", ")", "&&", "resp", ".", "body", "[", "'pagination'", "]", "[", "'next_uri'", "]", "!=", "nil", "params", "[", ":starting_after", "]", "=", "resp", ".", "body", "[", "'data'", "]", ".", "last", "[", "'id'", "]", "get", "(", "path", ",", "params", ")", "do", "|", "page", "|", "body", "=", "resp", ".", "body", "body", "[", "'data'", "]", "+=", "page", ".", "data", "resp", ".", "body", "=", "body", "yield", "(", "resp", ")", "if", "block_given?", "end", "else", "yield", "(", "resp", ")", "if", "block_given?", "end", "end", "end" ]
HTTP GET method @param [String] path
[ "HTTP", "GET", "method" ]
54cd6c697e47cd1124dd348e96b0f11facac9b79
https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L79-L102
402
CryptoProcessing/cryptoprocessing.rb
lib/cryptoprocessing/connection.rb
Cryptoprocessing.Connection.put
def put(path, params) headers = {} request('PUT', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
ruby
def put(path, params) headers = {} request('PUT', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
[ "def", "put", "(", "path", ",", "params", ")", "headers", "=", "{", "}", "request", "(", "'PUT'", ",", "path", ",", "params", ".", "to_json", ",", "headers", ")", "do", "|", "resp", "|", "yield", "(", "resp", ")", "if", "block_given?", "end", "end" ]
HTTP PUT method @param [String] path
[ "HTTP", "PUT", "method" ]
54cd6c697e47cd1124dd348e96b0f11facac9b79
https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L108-L114
403
CryptoProcessing/cryptoprocessing.rb
lib/cryptoprocessing/connection.rb
Cryptoprocessing.Connection.post
def post(path, params) headers = {} request('POST', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
ruby
def post(path, params) headers = {} request('POST', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
[ "def", "post", "(", "path", ",", "params", ")", "headers", "=", "{", "}", "request", "(", "'POST'", ",", "path", ",", "params", ".", "to_json", ",", "headers", ")", "do", "|", "resp", "|", "yield", "(", "resp", ")", "if", "block_given?", "end", "end" ]
HTTP POST method @param [String] path
[ "HTTP", "POST", "method" ]
54cd6c697e47cd1124dd348e96b0f11facac9b79
https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L120-L126
404
CryptoProcessing/cryptoprocessing.rb
lib/cryptoprocessing/connection.rb
Cryptoprocessing.Connection.delete
def delete(path, params) headers = {} request('DELETE', path, nil, headers) do |resp| yield(resp) if block_given? end end
ruby
def delete(path, params) headers = {} request('DELETE', path, nil, headers) do |resp| yield(resp) if block_given? end end
[ "def", "delete", "(", "path", ",", "params", ")", "headers", "=", "{", "}", "request", "(", "'DELETE'", ",", "path", ",", "nil", ",", "headers", ")", "do", "|", "resp", "|", "yield", "(", "resp", ")", "if", "block_given?", "end", "end" ]
HTTP DELETE method @param [String] path
[ "HTTP", "DELETE", "method" ]
54cd6c697e47cd1124dd348e96b0f11facac9b79
https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L132-L138
405
huffpostdata/ruby-pollster
lib/pollster/api.rb
Pollster.Api.charts_slug_get
def charts_slug_get(slug, opts = {}) data, _status_code, _headers = charts_slug_get_with_http_info(slug, opts) return data end
ruby
def charts_slug_get(slug, opts = {}) data, _status_code, _headers = charts_slug_get_with_http_info(slug, opts) return data end
[ "def", "charts_slug_get", "(", "slug", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "charts_slug_get_with_http_info", "(", "slug", ",", "opts", ")", "return", "data", "end" ]
Chart A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change. @param slug Unique identifier for a Chart @param [Hash] opts the optional parameters @return [Chart]
[ "Chart", "A", "Chart", "is", "chosen", "by", "Pollster", "editors", ".", "One", "example", "is", "\\", "Obama", "job", "approval", "-", "Democrats", "\\", ".", "It", "is", "always", "based", "upon", "a", "single", "Question", ".", "Users", "should", "strongly", "consider", "basing", "their", "analysis", "on", "Questions", "instead", ".", "Charts", "are", "derived", "data", ";", "Pollster", "editors", "publish", "them", "and", "change", "them", "as", "editorial", "priorities", "change", "." ]
32fb81b58e7fb39787a7591b8ede579301cd2b8b
https://github.com/huffpostdata/ruby-pollster/blob/32fb81b58e7fb39787a7591b8ede579301cd2b8b/lib/pollster/api.rb#L78-L81
406
huffpostdata/ruby-pollster
lib/pollster/api.rb
Pollster.Api.polls_slug_get
def polls_slug_get(slug, opts = {}) data, _status_code, _headers = polls_slug_get_with_http_info(slug, opts) return data end
ruby
def polls_slug_get(slug, opts = {}) data, _status_code, _headers = polls_slug_get_with_http_info(slug, opts) return data end
[ "def", "polls_slug_get", "(", "slug", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "polls_slug_get_with_http_info", "(", "slug", ",", "opts", ")", "return", "data", "end" ]
Poll A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database. @param slug Unique Poll identifier. For example: &#x60;gallup-26892&#x60;. @param [Hash] opts the optional parameters @return [Poll]
[ "Poll", "A", "Poll", "on", "Pollster", "is", "a", "collection", "of", "questions", "and", "responses", "published", "by", "a", "reputable", "survey", "house", ".", "This", "endpoint", "provides", "raw", "data", "from", "the", "survey", "house", "plus", "Pollster", "-", "provided", "metadata", "about", "each", "question", ".", "Pollster", "editors", "don", "t", "include", "every", "question", "when", "they", "enter", "Polls", "and", "they", "don", "t", "necessarily", "enter", "every", "subpopulation", "for", "the", "responses", "they", "_do_", "enter", ".", "They", "make", "editorial", "decisions", "about", "which", "questions", "belong", "in", "the", "database", "." ]
32fb81b58e7fb39787a7591b8ede579301cd2b8b
https://github.com/huffpostdata/ruby-pollster/blob/32fb81b58e7fb39787a7591b8ede579301cd2b8b/lib/pollster/api.rb#L317-L320
407
dark-prince/currency_converter
lib/currency_converter/xe.rb
CurrencyConverter.XE.exchange_rate
def exchange_rate url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}" uri = URI.parse('https://www.xe.com') request = Net::HTTP.new(uri.host, uri.port) request.use_ssl = true response = request.get(url) doc = Nokogiri::HTML(response.body) result = doc.css('span.uccResultAmount').text regexp = Regexp.new('(\\d+(?:\\.\\d+)?)') regexp.match result return $1 rescue Timeout::Error raise StandardError, 'Please check your internet connection' end
ruby
def exchange_rate url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}" uri = URI.parse('https://www.xe.com') request = Net::HTTP.new(uri.host, uri.port) request.use_ssl = true response = request.get(url) doc = Nokogiri::HTML(response.body) result = doc.css('span.uccResultAmount').text regexp = Regexp.new('(\\d+(?:\\.\\d+)?)') regexp.match result return $1 rescue Timeout::Error raise StandardError, 'Please check your internet connection' end
[ "def", "exchange_rate", "url", "=", "\"/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}\"", "uri", "=", "URI", ".", "parse", "(", "'https://www.xe.com'", ")", "request", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "request", ".", "use_ssl", "=", "true", "response", "=", "request", ".", "get", "(", "url", ")", "doc", "=", "Nokogiri", "::", "HTML", "(", "response", ".", "body", ")", "result", "=", "doc", ".", "css", "(", "'span.uccResultAmount'", ")", ".", "text", "regexp", "=", "Regexp", ".", "new", "(", "'(\\\\d+(?:\\\\.\\\\d+)?)'", ")", "regexp", ".", "match", "result", "return", "$1", "rescue", "Timeout", "::", "Error", "raise", "StandardError", ",", "'Please check your internet connection'", "end" ]
Returns the Float value of rate or nil
[ "Returns", "the", "Float", "value", "of", "rate", "or", "nil" ]
5aa6cc5f4a5f500dcd227bd5516e22ca43ffce46
https://github.com/dark-prince/currency_converter/blob/5aa6cc5f4a5f500dcd227bd5516e22ca43ffce46/lib/currency_converter/xe.rb#L40-L57
408
dpla/KriKri
lib/krikri/logger.rb
Krikri.Logger.log
def log(priority, msg) @logger.tagged(Time.now.to_s, Process.pid, to_s) do @logger.send(priority, msg) end end
ruby
def log(priority, msg) @logger.tagged(Time.now.to_s, Process.pid, to_s) do @logger.send(priority, msg) end end
[ "def", "log", "(", "priority", ",", "msg", ")", "@logger", ".", "tagged", "(", "Time", ".", "now", ".", "to_s", ",", "Process", ".", "pid", ",", "to_s", ")", "do", "@logger", ".", "send", "(", "priority", ",", "msg", ")", "end", "end" ]
Log a message, tagged for application-wide consistency @param [Symbol] priority a priority tag @param [string] msg the message to log
[ "Log", "a", "message", "tagged", "for", "application", "-", "wide", "consistency" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/logger.rb#L32-L36
409
theodi/breasal
lib/breasal/latlng.rb
Breasal.LatLng.to_WGS84
def to_WGS84 if @type == :ie @a = 6377340.189 @b = 6356034.447 else @a = 6377563.396 @b = 6356256.909 end @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @phi = deg_to_rad(@latitude) @lambda = deg_to_rad(@longitude) @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phi))) @H = 0 @x = (@v + @H) * Math.cos(@phi) * Math.cos(@lambda) @y = (@v + @H) * Math.cos(@phi) * Math.sin(@lambda) @z = ((1 - @eSquared) * @v + @H) * Math.sin(@phi) @tx = 446.448 @ty = -124.157 @tz = 542.060 @s = -0.0000204894 @rx = deg_to_rad( 0.00004172222) @ry = deg_to_rad( 0.00006861111) @rz = deg_to_rad( 0.00023391666) @xB = @tx + (@x * (1 + @s)) + (-@rx * @y) + (@ry * @z) @yB = @ty + (@rz * @x) + (@y * (1 + @s)) + (-@rx * @z) @zB = @tz + (-@ry * @x) + (@rx * @y) + (@z * (1 + @s)) @a = 6378137.000 @b = 6356752.3141 @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @lambdaB = rad_to_deg(Math.atan(@yB / @xB)) @p = Math.sqrt((@xB * @xB) + (@yB * @yB)) @phiN = Math.atan(@zB / (@p * (1 - @eSquared))) (1..10).each do |i| @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phiN))) @phiN1 = Math.atan((@zB + (@eSquared * @v * Math.sin(@phiN))) / @p) @phiN = @phiN1 end @phiB = rad_to_deg(@phiN) { :latitude => @phiB, :longitude => @lambdaB } end
ruby
def to_WGS84 if @type == :ie @a = 6377340.189 @b = 6356034.447 else @a = 6377563.396 @b = 6356256.909 end @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @phi = deg_to_rad(@latitude) @lambda = deg_to_rad(@longitude) @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phi))) @H = 0 @x = (@v + @H) * Math.cos(@phi) * Math.cos(@lambda) @y = (@v + @H) * Math.cos(@phi) * Math.sin(@lambda) @z = ((1 - @eSquared) * @v + @H) * Math.sin(@phi) @tx = 446.448 @ty = -124.157 @tz = 542.060 @s = -0.0000204894 @rx = deg_to_rad( 0.00004172222) @ry = deg_to_rad( 0.00006861111) @rz = deg_to_rad( 0.00023391666) @xB = @tx + (@x * (1 + @s)) + (-@rx * @y) + (@ry * @z) @yB = @ty + (@rz * @x) + (@y * (1 + @s)) + (-@rx * @z) @zB = @tz + (-@ry * @x) + (@rx * @y) + (@z * (1 + @s)) @a = 6378137.000 @b = 6356752.3141 @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @lambdaB = rad_to_deg(Math.atan(@yB / @xB)) @p = Math.sqrt((@xB * @xB) + (@yB * @yB)) @phiN = Math.atan(@zB / (@p * (1 - @eSquared))) (1..10).each do |i| @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phiN))) @phiN1 = Math.atan((@zB + (@eSquared * @v * Math.sin(@phiN))) / @p) @phiN = @phiN1 end @phiB = rad_to_deg(@phiN) { :latitude => @phiB, :longitude => @lambdaB } end
[ "def", "to_WGS84", "if", "@type", "==", ":ie", "@a", "=", "6377340.189", "@b", "=", "6356034.447", "else", "@a", "=", "6377563.396", "@b", "=", "6356256.909", "end", "@eSquared", "=", "(", "(", "@a", "*", "@a", ")", "-", "(", "@b", "*", "@b", ")", ")", "/", "(", "@a", "*", "@a", ")", "@phi", "=", "deg_to_rad", "(", "@latitude", ")", "@lambda", "=", "deg_to_rad", "(", "@longitude", ")", "@v", "=", "@a", "/", "(", "Math", ".", "sqrt", "(", "1", "-", "@eSquared", "*", "sin_pow_2", "(", "@phi", ")", ")", ")", "@H", "=", "0", "@x", "=", "(", "@v", "+", "@H", ")", "*", "Math", ".", "cos", "(", "@phi", ")", "*", "Math", ".", "cos", "(", "@lambda", ")", "@y", "=", "(", "@v", "+", "@H", ")", "*", "Math", ".", "cos", "(", "@phi", ")", "*", "Math", ".", "sin", "(", "@lambda", ")", "@z", "=", "(", "(", "1", "-", "@eSquared", ")", "*", "@v", "+", "@H", ")", "*", "Math", ".", "sin", "(", "@phi", ")", "@tx", "=", "446.448", "@ty", "=", "-", "124.157", "@tz", "=", "542.060", "@s", "=", "-", "0.0000204894", "@rx", "=", "deg_to_rad", "(", "0.00004172222", ")", "@ry", "=", "deg_to_rad", "(", "0.00006861111", ")", "@rz", "=", "deg_to_rad", "(", "0.00023391666", ")", "@xB", "=", "@tx", "+", "(", "@x", "*", "(", "1", "+", "@s", ")", ")", "+", "(", "-", "@rx", "*", "@y", ")", "+", "(", "@ry", "*", "@z", ")", "@yB", "=", "@ty", "+", "(", "@rz", "*", "@x", ")", "+", "(", "@y", "*", "(", "1", "+", "@s", ")", ")", "+", "(", "-", "@rx", "*", "@z", ")", "@zB", "=", "@tz", "+", "(", "-", "@ry", "*", "@x", ")", "+", "(", "@rx", "*", "@y", ")", "+", "(", "@z", "*", "(", "1", "+", "@s", ")", ")", "@a", "=", "6378137.000", "@b", "=", "6356752.3141", "@eSquared", "=", "(", "(", "@a", "*", "@a", ")", "-", "(", "@b", "*", "@b", ")", ")", "/", "(", "@a", "*", "@a", ")", "@lambdaB", "=", "rad_to_deg", "(", "Math", ".", "atan", "(", "@yB", "/", "@xB", ")", ")", "@p", "=", "Math", ".", "sqrt", "(", "(", "@xB", "*", "@xB", ")", "+", "(", "@yB", "*", "@yB", ")", ")", "@phiN", "=", "Math", ".", "atan", "(", "@zB", "/", "(", "@p", "*", "(", "1", "-", "@eSquared", ")", ")", ")", "(", "1", "..", "10", ")", ".", "each", "do", "|", "i", "|", "@v", "=", "@a", "/", "(", "Math", ".", "sqrt", "(", "1", "-", "@eSquared", "*", "sin_pow_2", "(", "@phiN", ")", ")", ")", "@phiN1", "=", "Math", ".", "atan", "(", "(", "@zB", "+", "(", "@eSquared", "*", "@v", "*", "Math", ".", "sin", "(", "@phiN", ")", ")", ")", "/", "@p", ")", "@phiN", "=", "@phiN1", "end", "@phiB", "=", "rad_to_deg", "(", "@phiN", ")", "{", ":latitude", "=>", "@phiB", ",", ":longitude", "=>", "@lambdaB", "}", "end" ]
Takes OSGB36 or TM75 Latitude and Longitude coords and returns WGS84 Latitude and Longitude
[ "Takes", "OSGB36", "or", "TM75", "Latitude", "and", "Longitude", "coords", "and", "returns", "WGS84", "Latitude", "and", "Longitude" ]
3f191f9f4fc32d9e52a111ed1acea9caf8a965fc
https://github.com/theodi/breasal/blob/3f191f9f4fc32d9e52a111ed1acea9caf8a965fc/lib/breasal/latlng.rb#L15-L66
410
dpla/KriKri
lib/krikri/enrichments/timespan_split.rb
Krikri::Enrichments.TimespanSplit.populate_timespan
def populate_timespan(timespan) return timespan unless (timespan.begin.empty? || timespan.end.empty?) && !timespan.providedLabel.empty? parsed = parse_labels(timespan.providedLabel) return timespan if parsed.empty? parsed.each do |date| begin_date, end_date = span_from_date(date) timespan.begin << begin_date timespan.end << end_date end reduce_to_largest_span(timespan) return timespan end
ruby
def populate_timespan(timespan) return timespan unless (timespan.begin.empty? || timespan.end.empty?) && !timespan.providedLabel.empty? parsed = parse_labels(timespan.providedLabel) return timespan if parsed.empty? parsed.each do |date| begin_date, end_date = span_from_date(date) timespan.begin << begin_date timespan.end << end_date end reduce_to_largest_span(timespan) return timespan end
[ "def", "populate_timespan", "(", "timespan", ")", "return", "timespan", "unless", "(", "timespan", ".", "begin", ".", "empty?", "||", "timespan", ".", "end", ".", "empty?", ")", "&&", "!", "timespan", ".", "providedLabel", ".", "empty?", "parsed", "=", "parse_labels", "(", "timespan", ".", "providedLabel", ")", "return", "timespan", "if", "parsed", ".", "empty?", "parsed", ".", "each", "do", "|", "date", "|", "begin_date", ",", "end_date", "=", "span_from_date", "(", "date", ")", "timespan", ".", "begin", "<<", "begin_date", "timespan", ".", "end", "<<", "end_date", "end", "reduce_to_largest_span", "(", "timespan", ")", "return", "timespan", "end" ]
Populates a timespan with a begin and end date. @param timespan [DPLA::MAP::TimeSpan] @return [DPLA::MAP::TimeSpan]
[ "Populates", "a", "timespan", "with", "a", "begin", "and", "end", "date", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/timespan_split.rb#L65-L78
411
dpla/KriKri
lib/krikri/enrichments/timespan_split.rb
Krikri::Enrichments.TimespanSplit.span_from_date
def span_from_date(date) return [nil, nil] if date.nil? if date.is_a?(Date) return [date, date] if date.precision == :day return [date, (date.succ - 1)] end [(date.respond_to?(:first) ? date.first : date.from), (date.respond_to?(:last) ? date.last : date.to)] end
ruby
def span_from_date(date) return [nil, nil] if date.nil? if date.is_a?(Date) return [date, date] if date.precision == :day return [date, (date.succ - 1)] end [(date.respond_to?(:first) ? date.first : date.from), (date.respond_to?(:last) ? date.last : date.to)] end
[ "def", "span_from_date", "(", "date", ")", "return", "[", "nil", ",", "nil", "]", "if", "date", ".", "nil?", "if", "date", ".", "is_a?", "(", "Date", ")", "return", "[", "date", ",", "date", "]", "if", "date", ".", "precision", "==", ":day", "return", "[", "date", ",", "(", "date", ".", "succ", "-", "1", ")", "]", "end", "[", "(", "date", ".", "respond_to?", "(", ":first", ")", "?", "date", ".", "first", ":", "date", ".", "from", ")", ",", "(", "date", ".", "respond_to?", "(", ":last", ")", "?", "date", ".", "last", ":", "date", ".", "to", ")", "]", "end" ]
Converts an EDTF date to a begin and end date. @param date [Date, DateTime, EDTF::Interval] a date, with or without EDTF precision features; or an interval. @return [Array<Date, DateTime>] an array of two elements containing the begin and end dates.
[ "Converts", "an", "EDTF", "date", "to", "a", "begin", "and", "end", "date", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/timespan_split.rb#L94-L102
412
dpla/KriKri
lib/krikri/enrichments/timespan_split.rb
Krikri::Enrichments.TimespanSplit.reduce_to_largest_span
def reduce_to_largest_span(timespan) timespan.begin = timespan.begin.sort.first timespan.end = timespan.end.sort.last timespan end
ruby
def reduce_to_largest_span(timespan) timespan.begin = timespan.begin.sort.first timespan.end = timespan.end.sort.last timespan end
[ "def", "reduce_to_largest_span", "(", "timespan", ")", "timespan", ".", "begin", "=", "timespan", ".", "begin", ".", "sort", ".", "first", "timespan", ".", "end", "=", "timespan", ".", "end", ".", "sort", ".", "last", "timespan", "end" ]
Reduces a timespan with multiple begin or end dates to a single earliest begin date and a single latest end date. @param timespan [DPLA::MAP::TimeSpan] the timespan to reduce @return [DPLA::MAP::TimeSpan] an updated timespan
[ "Reduces", "a", "timespan", "with", "multiple", "begin", "or", "end", "dates", "to", "a", "single", "earliest", "begin", "date", "and", "a", "single", "latest", "end", "date", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/timespan_split.rb#L111-L115
413
dpla/KriKri
app/models/krikri/activity.rb
Krikri.Activity.run
def run if block_given? update_attribute(:end_time, nil) if ended? Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is running") set_start_time begin yield agent_instance, rdf_subject rescue => e Krikri::Logger.log(:error, "Error performing Activity: #{id}\n" \ "#{e.message}\n#{e.backtrace}") raise e ensure set_end_time Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is done") end end end
ruby
def run if block_given? update_attribute(:end_time, nil) if ended? Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is running") set_start_time begin yield agent_instance, rdf_subject rescue => e Krikri::Logger.log(:error, "Error performing Activity: #{id}\n" \ "#{e.message}\n#{e.backtrace}") raise e ensure set_end_time Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is done") end end end
[ "def", "run", "if", "block_given?", "update_attribute", "(", ":end_time", ",", "nil", ")", "if", "ended?", "Krikri", "::", "Logger", ".", "log", "(", ":info", ",", "\"Activity #{agent.constantize}-#{id} is running\"", ")", "set_start_time", "begin", "yield", "agent_instance", ",", "rdf_subject", "rescue", "=>", "e", "Krikri", "::", "Logger", ".", "log", "(", ":error", ",", "\"Error performing Activity: #{id}\\n\"", "\"#{e.message}\\n#{e.backtrace}\"", ")", "raise", "e", "ensure", "set_end_time", "Krikri", "::", "Logger", ".", "log", "(", ":info", ",", "\"Activity #{agent.constantize}-#{id} is done\"", ")", "end", "end", "end" ]
Runs the block, setting the start and end time of the run. The given block is passed an instance of the agent, and a URI representing this Activity. Handles logging of activity start/stop and failure states. @raise [RuntimeError] re-raises logged errors on Activity failure
[ "Runs", "the", "block", "setting", "the", "start", "and", "end", "time", "of", "the", "run", ".", "The", "given", "block", "is", "passed", "an", "instance", "of", "the", "agent", "and", "a", "URI", "representing", "this", "Activity", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/models/krikri/activity.rb#L72-L90
414
basgys/emailvision
lib/emailvision/api.rb
Emailvision.Api.close_connection
def close_connection if connected? get.connect.close.call else return false end rescue Emailvision::Exception => e ensure invalidate_token! not connected? end
ruby
def close_connection if connected? get.connect.close.call else return false end rescue Emailvision::Exception => e ensure invalidate_token! not connected? end
[ "def", "close_connection", "if", "connected?", "get", ".", "connect", ".", "close", ".", "call", "else", "return", "false", "end", "rescue", "Emailvision", "::", "Exception", "=>", "e", "ensure", "invalidate_token!", "not", "connected?", "end" ]
Logout from Emailvision API @return [Boolean] true if the connection has been destroyed
[ "Logout", "from", "Emailvision", "API" ]
ce163ace77e46062448979debce76e8020ec9509
https://github.com/basgys/emailvision/blob/ce163ace77e46062448979debce76e8020ec9509/lib/emailvision/api.rb#L56-L66
415
rafmagana/prowly
lib/prowly/interface.rb
Prowly.Interface.call
def call(command, params) @command = command request = Net::HTTP::Get.new(uri.request_uri + "?" + params) response = http.request(request) Response.new(response.body, response) end
ruby
def call(command, params) @command = command request = Net::HTTP::Get.new(uri.request_uri + "?" + params) response = http.request(request) Response.new(response.body, response) end
[ "def", "call", "(", "command", ",", "params", ")", "@command", "=", "command", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", "+", "\"?\"", "+", "params", ")", "response", "=", "http", ".", "request", "(", "request", ")", "Response", ".", "new", "(", "response", ".", "body", ",", "response", ")", "end" ]
Make the actual call to the prowl api
[ "Make", "the", "actual", "call", "to", "the", "prowl", "api" ]
d71cd7b7aa6b541808b7259db37469c93ab5b3f9
https://github.com/rafmagana/prowly/blob/d71cd7b7aa6b541808b7259db37469c93ab5b3f9/lib/prowly/interface.rb#L25-L30
416
dpla/KriKri
app/models/krikri/search_index_document.rb
Krikri.SearchIndexDocument.aggregation
def aggregation agg = DPLA::MAP::Aggregation.new(id) return nil unless agg.exists? agg.get agg end
ruby
def aggregation agg = DPLA::MAP::Aggregation.new(id) return nil unless agg.exists? agg.get agg end
[ "def", "aggregation", "agg", "=", "DPLA", "::", "MAP", "::", "Aggregation", ".", "new", "(", "id", ")", "return", "nil", "unless", "agg", ".", "exists?", "agg", ".", "get", "agg", "end" ]
Get the aggregation, populated with data from Marmotta, which corresponds to this SearchIndexDocument @return [DPLA::MAP::Aggregation, nil]
[ "Get", "the", "aggregation", "populated", "with", "data", "from", "Marmotta", "which", "corresponds", "to", "this", "SearchIndexDocument" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/models/krikri/search_index_document.rb#L21-L26
417
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.ClassMethods.find_inheritable_template_folder
def find_inheritable_template_folder(view_context, name, partial, formats, param = nil) find_inheritable_template_folder_cached(view_context, name, partial, formats, param) do find_inheritable_artifact(param) do |folder| view_context.template_exists?(name, folder, partial) end end end
ruby
def find_inheritable_template_folder(view_context, name, partial, formats, param = nil) find_inheritable_template_folder_cached(view_context, name, partial, formats, param) do find_inheritable_artifact(param) do |folder| view_context.template_exists?(name, folder, partial) end end end
[ "def", "find_inheritable_template_folder", "(", "view_context", ",", "name", ",", "partial", ",", "formats", ",", "param", "=", "nil", ")", "find_inheritable_template_folder_cached", "(", "view_context", ",", "name", ",", "partial", ",", "formats", ",", "param", ")", "do", "find_inheritable_artifact", "(", "param", ")", "do", "|", "folder", "|", "view_context", ".", "template_exists?", "(", "name", ",", "folder", ",", "partial", ")", "end", "end", "end" ]
Performs a lookup for the given filename and returns the most specific folder that contains the file.
[ "Performs", "a", "lookup", "for", "the", "given", "filename", "and", "returns", "the", "most", "specific", "folder", "that", "contains", "the", "file", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L36-L42
418
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.ClassMethods.inheritance_lookup_path
def inheritance_lookup_path path = [self] until path.last == inheritable_root_controller path << path.last.superclass end path.collect(&:controller_path) end
ruby
def inheritance_lookup_path path = [self] until path.last == inheritable_root_controller path << path.last.superclass end path.collect(&:controller_path) end
[ "def", "inheritance_lookup_path", "path", "=", "[", "self", "]", "until", "path", ".", "last", "==", "inheritable_root_controller", "path", "<<", "path", ".", "last", ".", "superclass", "end", "path", ".", "collect", "(", ":controller_path", ")", "end" ]
The inheritance path of controllers that is used as default lookup path.
[ "The", "inheritance", "path", "of", "controllers", "that", "is", "used", "as", "default", "lookup", "path", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L72-L78
419
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.ClassMethods.find_inheritable_template_folder_cached
def find_inheritable_template_folder_cached(view_context, name, partial, formats, param = nil) prefix = inheritable_cache_get(formats, name, partial, param) return prefix if prefix prefix = yield if prefix template = view_context.find_template_without_lookup(name, prefix, partial) inheritable_cache_set(template.formats, name, partial, param, prefix) end prefix end
ruby
def find_inheritable_template_folder_cached(view_context, name, partial, formats, param = nil) prefix = inheritable_cache_get(formats, name, partial, param) return prefix if prefix prefix = yield if prefix template = view_context.find_template_without_lookup(name, prefix, partial) inheritable_cache_set(template.formats, name, partial, param, prefix) end prefix end
[ "def", "find_inheritable_template_folder_cached", "(", "view_context", ",", "name", ",", "partial", ",", "formats", ",", "param", "=", "nil", ")", "prefix", "=", "inheritable_cache_get", "(", "formats", ",", "name", ",", "partial", ",", "param", ")", "return", "prefix", "if", "prefix", "prefix", "=", "yield", "if", "prefix", "template", "=", "view_context", ".", "find_template_without_lookup", "(", "name", ",", "prefix", ",", "partial", ")", "inheritable_cache_set", "(", "template", ".", "formats", ",", "name", ",", "partial", ",", "param", ",", "prefix", ")", "end", "prefix", "end" ]
Performs a lookup for a template folder using the cache.
[ "Performs", "a", "lookup", "for", "a", "template", "folder", "using", "the", "cache", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L92-L103
420
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.ClassMethods.inheritable_cache
def inheritable_cache #:nodoc: # do not store keys on each access, only return default structure @inheritable_cache ||= Hash.new do |h1, k1| Hash.new do |h2, k2| Hash.new do |h3, k3| Hash.new end end end end
ruby
def inheritable_cache #:nodoc: # do not store keys on each access, only return default structure @inheritable_cache ||= Hash.new do |h1, k1| Hash.new do |h2, k2| Hash.new do |h3, k3| Hash.new end end end end
[ "def", "inheritable_cache", "#:nodoc:", "# do not store keys on each access, only return default structure", "@inheritable_cache", "||=", "Hash", ".", "new", "do", "|", "h1", ",", "k1", "|", "Hash", ".", "new", "do", "|", "h2", ",", "k2", "|", "Hash", ".", "new", "do", "|", "h3", ",", "k3", "|", "Hash", ".", "new", "end", "end", "end", "end" ]
A simple template lookup cache for each controller.
[ "A", "simple", "template", "lookup", "cache", "for", "each", "controller", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L106-L115
421
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.ClassMethods.inheritable_cache_get
def inheritable_cache_get(formats, name, partial, param) prefixes = formats.collect { |format| inheritable_cache[format.to_sym][partial][name][param] } prefixes.compact! prefixes.empty? ? nil : prefixes.first end
ruby
def inheritable_cache_get(formats, name, partial, param) prefixes = formats.collect { |format| inheritable_cache[format.to_sym][partial][name][param] } prefixes.compact! prefixes.empty? ? nil : prefixes.first end
[ "def", "inheritable_cache_get", "(", "formats", ",", "name", ",", "partial", ",", "param", ")", "prefixes", "=", "formats", ".", "collect", "{", "|", "format", "|", "inheritable_cache", "[", "format", ".", "to_sym", "]", "[", "partial", "]", "[", "name", "]", "[", "param", "]", "}", "prefixes", ".", "compact!", "prefixes", ".", "empty?", "?", "nil", ":", "prefixes", ".", "first", "end" ]
Gets the prefix from the cache. Returns nil if it's not there yet.
[ "Gets", "the", "prefix", "from", "the", "cache", ".", "Returns", "nil", "if", "it", "s", "not", "there", "yet", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L118-L122
422
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.ClassMethods.inheritable_cache_set
def inheritable_cache_set(formats, name, partial, param, prefix) formats.each do |format| # assign hash default values to respective key inheritable_cache[format.to_sym] = hf = inheritable_cache[format.to_sym] hf[partial] = hp = hf[partial] hp[name] = hn = hp[name] # finally store prefix in the deepest hash hn[param] = prefix end end
ruby
def inheritable_cache_set(formats, name, partial, param, prefix) formats.each do |format| # assign hash default values to respective key inheritable_cache[format.to_sym] = hf = inheritable_cache[format.to_sym] hf[partial] = hp = hf[partial] hp[name] = hn = hp[name] # finally store prefix in the deepest hash hn[param] = prefix end end
[ "def", "inheritable_cache_set", "(", "formats", ",", "name", ",", "partial", ",", "param", ",", "prefix", ")", "formats", ".", "each", "do", "|", "format", "|", "# assign hash default values to respective key ", "inheritable_cache", "[", "format", ".", "to_sym", "]", "=", "hf", "=", "inheritable_cache", "[", "format", ".", "to_sym", "]", "hf", "[", "partial", "]", "=", "hp", "=", "hf", "[", "partial", "]", "hp", "[", "name", "]", "=", "hn", "=", "hp", "[", "name", "]", "# finally store prefix in the deepest hash", "hn", "[", "param", "]", "=", "prefix", "end", "end" ]
Stores the found prefix in the cache.
[ "Stores", "the", "found", "prefix", "in", "the", "cache", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L125-L134
423
codez/render_inheritable
lib/render_inheritable.rb
RenderInheritable.View.find_template_with_lookup
def find_template_with_lookup(name, prefix = nil, partial = false) if prefix == controller_path folder = controller.find_inheritable_template_folder(name, partial) prefix = folder if folder end find_template_without_lookup(name, prefix, partial) end
ruby
def find_template_with_lookup(name, prefix = nil, partial = false) if prefix == controller_path folder = controller.find_inheritable_template_folder(name, partial) prefix = folder if folder end find_template_without_lookup(name, prefix, partial) end
[ "def", "find_template_with_lookup", "(", "name", ",", "prefix", "=", "nil", ",", "partial", "=", "false", ")", "if", "prefix", "==", "controller_path", "folder", "=", "controller", ".", "find_inheritable_template_folder", "(", "name", ",", "partial", ")", "prefix", "=", "folder", "if", "folder", "end", "find_template_without_lookup", "(", "name", ",", "prefix", ",", "partial", ")", "end" ]
Perform a template lookup if the prefix corresponds to the current controller's path.
[ "Perform", "a", "template", "lookup", "if", "the", "prefix", "corresponds", "to", "the", "current", "controller", "s", "path", "." ]
ec1ce2d104a1c1fe80a81e38559554dce211a678
https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L145-L151
424
schrodingersbox/meter_cat
app/models/meter_cat/cache.rb
MeterCat.Cache.add
def add(name, value, created_on) meter = fetch(name, nil) # If the name isn't cached, cache it and return return cache(name, value, created_on) unless meter # If the cached value is for a different day, flush it, cache the new value and return if meter.created_on != created_on flush(name) cache(name, value, created_on) return end # Add the new value to the cached value and flush if expired meter.value += value flush(name) if meter.expired? end
ruby
def add(name, value, created_on) meter = fetch(name, nil) # If the name isn't cached, cache it and return return cache(name, value, created_on) unless meter # If the cached value is for a different day, flush it, cache the new value and return if meter.created_on != created_on flush(name) cache(name, value, created_on) return end # Add the new value to the cached value and flush if expired meter.value += value flush(name) if meter.expired? end
[ "def", "add", "(", "name", ",", "value", ",", "created_on", ")", "meter", "=", "fetch", "(", "name", ",", "nil", ")", "# If the name isn't cached, cache it and return", "return", "cache", "(", "name", ",", "value", ",", "created_on", ")", "unless", "meter", "# If the cached value is for a different day, flush it, cache the new value and return", "if", "meter", ".", "created_on", "!=", "created_on", "flush", "(", "name", ")", "cache", "(", "name", ",", "value", ",", "created_on", ")", "return", "end", "# Add the new value to the cached value and flush if expired", "meter", ".", "value", "+=", "value", "flush", "(", "name", ")", "if", "meter", ".", "expired?", "end" ]
Adds the given value to the hash Flushes expired data to DB
[ "Adds", "the", "given", "value", "to", "the", "hash", "Flushes", "expired", "data", "to", "DB" ]
b20d579749ef2facbf3b308d4fb39215a7eac2a1
https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/models/meter_cat/cache.rb#L15-L31
425
schrodingersbox/meter_cat
app/models/meter_cat/cache.rb
MeterCat.Cache.cache
def cache(name, value, created_on) meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now) store(name, meter) end
ruby
def cache(name, value, created_on) meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now) store(name, meter) end
[ "def", "cache", "(", "name", ",", "value", ",", "created_on", ")", "meter", "=", "Meter", ".", "new", "(", "name", ":", "name", ",", "value", ":", "value", ",", "created_on", ":", "created_on", ",", "created_at", ":", "Time", ".", "now", ")", "store", "(", "name", ",", "meter", ")", "end" ]
Creates a new Meter and stores is in the hash
[ "Creates", "a", "new", "Meter", "and", "stores", "is", "in", "the", "hash" ]
b20d579749ef2facbf3b308d4fb39215a7eac2a1
https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/models/meter_cat/cache.rb#L35-L38
426
dpla/KriKri
lib/krikri/mapping_dsl.rb
Krikri.MappingDSL.add_child
def add_child(name, opts = {}, &block) delete_property(name) properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block) end
ruby
def add_child(name, opts = {}, &block) delete_property(name) properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block) end
[ "def", "add_child", "(", "name", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "delete_property", "(", "name", ")", "properties", "<<", "ChildDeclaration", ".", "new", "(", "name", ",", "opts", ".", "delete", "(", ":class", ")", ",", "opts", ",", "block", ")", "end" ]
Add a ChildDeclaration to this mapping @param [Symbol] name @param [Hash] opts accepts options; expected options: :class @return [ChildDeclaration]
[ "Add", "a", "ChildDeclaration", "to", "this", "mapping" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/mapping_dsl.rb#L50-L53
427
dpla/KriKri
lib/krikri/mapping_dsl.rb
Krikri.MappingDSL.add_property
def add_property(name, value = nil, &block) delete_property(name) properties << PropertyDeclaration.new(name, value, &block) end
ruby
def add_property(name, value = nil, &block) delete_property(name) properties << PropertyDeclaration.new(name, value, &block) end
[ "def", "add_property", "(", "name", ",", "value", "=", "nil", ",", "&", "block", ")", "delete_property", "(", "name", ")", "properties", "<<", "PropertyDeclaration", ".", "new", "(", "name", ",", "value", ",", "block", ")", "end" ]
Add a PropertyDeclaration to this mapping @param [Symbol] name @param [Hash] value ; defaults to nil @return [ChildDeclaration]
[ "Add", "a", "PropertyDeclaration", "to", "this", "mapping" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/mapping_dsl.rb#L62-L65
428
iagox86/nesser
lib/nesser/packets/packet.rb
Nesser.Packet.to_bytes
def to_bytes() packer = Packer.new() full_flags = ((@qr << 15) & 0x8000) | ((@opcode << 11) & 0x7800) | ((@flags << 7) & 0x0780) | ((@rcode << 0) & 0x000F) packer.pack('nnnnnn', @trn_id, # trn_id full_flags, # qr, opcode, flags, rcode @questions.length(), # qdcount @answers.length(), # ancount 0, # nscount (we don't handle) 0, # arcount (we don't handle) ) questions.each do |q| q.pack(packer) end answers.each do |a| a.pack(packer) end return packer.get() end
ruby
def to_bytes() packer = Packer.new() full_flags = ((@qr << 15) & 0x8000) | ((@opcode << 11) & 0x7800) | ((@flags << 7) & 0x0780) | ((@rcode << 0) & 0x000F) packer.pack('nnnnnn', @trn_id, # trn_id full_flags, # qr, opcode, flags, rcode @questions.length(), # qdcount @answers.length(), # ancount 0, # nscount (we don't handle) 0, # arcount (we don't handle) ) questions.each do |q| q.pack(packer) end answers.each do |a| a.pack(packer) end return packer.get() end
[ "def", "to_bytes", "(", ")", "packer", "=", "Packer", ".", "new", "(", ")", "full_flags", "=", "(", "(", "@qr", "<<", "15", ")", "&", "0x8000", ")", "|", "(", "(", "@opcode", "<<", "11", ")", "&", "0x7800", ")", "|", "(", "(", "@flags", "<<", "7", ")", "&", "0x0780", ")", "|", "(", "(", "@rcode", "<<", "0", ")", "&", "0x000F", ")", "packer", ".", "pack", "(", "'nnnnnn'", ",", "@trn_id", ",", "# trn_id", "full_flags", ",", "# qr, opcode, flags, rcode", "@questions", ".", "length", "(", ")", ",", "# qdcount", "@answers", ".", "length", "(", ")", ",", "# ancount", "0", ",", "# nscount (we don't handle)", "0", ",", "# arcount (we don't handle)", ")", "questions", ".", "each", "do", "|", "q", "|", "q", ".", "pack", "(", "packer", ")", "end", "answers", ".", "each", "do", "|", "a", "|", "a", ".", "pack", "(", "packer", ")", "end", "return", "packer", ".", "get", "(", ")", "end" ]
Serialize the packet to an array of bytes.
[ "Serialize", "the", "packet", "to", "an", "array", "of", "bytes", "." ]
1d84cf1d0a9de3d6c5a9b418d0731b5214d14667
https://github.com/iagox86/nesser/blob/1d84cf1d0a9de3d6c5a9b418d0731b5214d14667/lib/nesser/packets/packet.rb#L158-L184
429
rondale-sc/EspnRb
lib/espn_rb/headline.rb
EspnRb.Headline.get_results
def get_results(resource, method) http = Net::HTTP.new("api.espn.com") request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}") HeadlineResponse.new JSON.parse(http.request(request).body) end
ruby
def get_results(resource, method) http = Net::HTTP.new("api.espn.com") request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}") HeadlineResponse.new JSON.parse(http.request(request).body) end
[ "def", "get_results", "(", "resource", ",", "method", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "\"api.espn.com\"", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "\"/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}\"", ")", "HeadlineResponse", ".", "new", "JSON", ".", "parse", "(", "http", ".", "request", "(", "request", ")", ".", "body", ")", "end" ]
The final request to ESPN api after all option parsing has been completed. @return [HeadlineResponse] a headline response object.
[ "The", "final", "request", "to", "ESPN", "api", "after", "all", "option", "parsing", "has", "been", "completed", "." ]
fd2723dd80a2f5cd26f9a62c24d4db06606b4693
https://github.com/rondale-sc/EspnRb/blob/fd2723dd80a2f5cd26f9a62c24d4db06606b4693/lib/espn_rb/headline.rb#L29-L33
430
dpla/KriKri
lib/krikri/util/extended_date_parser.rb
Krikri::Util.ExtendedDateParser.parse
def parse(date_str, allow_interval = false) str = preprocess(date_str.dup) date = parse_interval(str) if allow_interval date ||= parse_m_d_y(str) date ||= Date.edtf(str.gsub('.', '-')) date ||= partial_edtf(str) date ||= decade_hyphen(str) date ||= month_year(str) date ||= decade_s(str) date ||= hyphenated_partial_range(str) date ||= parse_date(str) # Only do this if certian letters are present to avoid infinite loops. date ||= circa(str) if str.match(/[circabout]/i) date = date.first if date.is_a? EDTF::Set date || nil end
ruby
def parse(date_str, allow_interval = false) str = preprocess(date_str.dup) date = parse_interval(str) if allow_interval date ||= parse_m_d_y(str) date ||= Date.edtf(str.gsub('.', '-')) date ||= partial_edtf(str) date ||= decade_hyphen(str) date ||= month_year(str) date ||= decade_s(str) date ||= hyphenated_partial_range(str) date ||= parse_date(str) # Only do this if certian letters are present to avoid infinite loops. date ||= circa(str) if str.match(/[circabout]/i) date = date.first if date.is_a? EDTF::Set date || nil end
[ "def", "parse", "(", "date_str", ",", "allow_interval", "=", "false", ")", "str", "=", "preprocess", "(", "date_str", ".", "dup", ")", "date", "=", "parse_interval", "(", "str", ")", "if", "allow_interval", "date", "||=", "parse_m_d_y", "(", "str", ")", "date", "||=", "Date", ".", "edtf", "(", "str", ".", "gsub", "(", "'.'", ",", "'-'", ")", ")", "date", "||=", "partial_edtf", "(", "str", ")", "date", "||=", "decade_hyphen", "(", "str", ")", "date", "||=", "month_year", "(", "str", ")", "date", "||=", "decade_s", "(", "str", ")", "date", "||=", "hyphenated_partial_range", "(", "str", ")", "date", "||=", "parse_date", "(", "str", ")", "# Only do this if certian letters are present to avoid infinite loops.", "date", "||=", "circa", "(", "str", ")", "if", "str", ".", "match", "(", "/", "/i", ")", "date", "=", "date", ".", "first", "if", "date", ".", "is_a?", "EDTF", "::", "Set", "date", "||", "nil", "end" ]
Attempts to parse a string into a valid EDTF or `Date` format. - Attempts to split `#providedLabel` on '-', '/', '..', 'to', 'until', and looks for EDTF and `Date.parse` patterns on either side, setting them to `#begin` and `#end`. Both split and unsplit dates are parsed as follows: - Attempts to parse `#providedLabel` as an EDTF interval and populates begin and end with their respective values. - Attempts to match to a number of regular expressions which specify ranges informally. - Attempts to parse `#providedLabel` as a single date value with `Date.parse` and enters that value to both `#begin` and `#end`. @param date_str [String] a string which may contain a date range @param allow_interval [Boolean] a flag specifing whethe to use #range_match to look for range values. @return [Date, EDTF::Epoch, EDTF::Interval, nil] the date parsed or nil @see http://www.loc.gov/standards/datetime/
[ "Attempts", "to", "parse", "a", "string", "into", "a", "valid", "EDTF", "or", "Date", "format", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L26-L41
431
dpla/KriKri
lib/krikri/util/extended_date_parser.rb
Krikri::Util.ExtendedDateParser.range_match
def range_match(str) str = str.gsub('to', '-').gsub('until', '-') regexp = %r{ ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) \s*[-\.]+\s* ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) }x regexp.match(str) do |m| [m[1], m[2]] end end
ruby
def range_match(str) str = str.gsub('to', '-').gsub('until', '-') regexp = %r{ ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) \s*[-\.]+\s* ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) }x regexp.match(str) do |m| [m[1], m[2]] end end
[ "def", "range_match", "(", "str", ")", "str", "=", "str", ".", "gsub", "(", "'to'", ",", "'-'", ")", ".", "gsub", "(", "'until'", ",", "'-'", ")", "regexp", "=", "%r{", "\\s", "\\d", "\\-", "\\/", "\\.", "\\?", "\\~", "\\s", "\\d", "\\d", "\\-", "\\d", "\\-", "\\.", "\\?", "\\~", "\\s", "\\.", "\\s", "\\s", "\\d", "\\-", "\\/", "\\.", "\\?", "\\~", "\\s", "\\d", "\\d", "\\-", "\\d", "\\-", "\\.", "\\?", "\\~", "}x", "regexp", ".", "match", "(", "str", ")", "do", "|", "m", "|", "[", "m", "[", "1", "]", ",", "m", "[", "2", "]", "]", "end", "end" ]
Matches a wide variety of date ranges separated by '..' or '-' @param str [String] a string which may contain a date range @return [Array(String)] the begining and ending dates of an identified range
[ "Matches", "a", "wide", "variety", "of", "date", "ranges", "separated", "by", "..", "or", "-" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L49-L61
432
dpla/KriKri
lib/krikri/util/extended_date_parser.rb
Krikri::Util.ExtendedDateParser.preprocess
def preprocess(str) str.gsub!(/late/i, '') str.gsub!(/early/i, '') str.strip! str.gsub!(/\s+/, ' ') str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/) str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/) str end
ruby
def preprocess(str) str.gsub!(/late/i, '') str.gsub!(/early/i, '') str.strip! str.gsub!(/\s+/, ' ') str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/) str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/) str end
[ "def", "preprocess", "(", "str", ")", "str", ".", "gsub!", "(", "/", "/i", ",", "''", ")", "str", ".", "gsub!", "(", "/", "/i", ",", "''", ")", "str", ".", "strip!", "str", ".", "gsub!", "(", "/", "\\s", "/", ",", "' '", ")", "str", ".", "gsub!", "(", "'0s'", ",", "'x'", ")", "if", "str", ".", "match", "(", "/", "/", ")", "str", ".", "gsub!", "(", "'-'", ",", "'x'", ")", "if", "str", ".", "match", "(", "/", "\\-", "/", ")", "str", "end" ]
Preprocess the date string to remove extra whitespace and convert ad hoc formatting to equivalent EDTF. @todo should '-` be intepreted as 'x' or '?' @see http://www.loc.gov/standards/datetime/pre-submission.html#maskedprecision
[ "Preprocess", "the", "date", "string", "to", "remove", "extra", "whitespace", "and", "convert", "ad", "hoc", "formatting", "to", "equivalent", "EDTF", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L69-L77
433
dpla/KriKri
lib/krikri/util/extended_date_parser.rb
Krikri::Util.ExtendedDateParser.circa
def circa(str) run = str.gsub!(/.*c[irca\.]*/i, '') run ||= str.gsub!(/.*about/i, '') date = parse(str) if run return nil if date.nil? # The EDTF grammar does not support uncertainty on masked precision dates if date.respond_to? :uncertain! date.uncertain! elsif date.is_a? EDTF::Interval # Interval uncertainty is scoped to the begin and end dates; # to be safe, we mark both. date.from = date.from.uncertain! if date.from.respond_to? :uncertain! date.to = date.to.uncertain! if date.to.respond_to? :uncertain! end date end
ruby
def circa(str) run = str.gsub!(/.*c[irca\.]*/i, '') run ||= str.gsub!(/.*about/i, '') date = parse(str) if run return nil if date.nil? # The EDTF grammar does not support uncertainty on masked precision dates if date.respond_to? :uncertain! date.uncertain! elsif date.is_a? EDTF::Interval # Interval uncertainty is scoped to the begin and end dates; # to be safe, we mark both. date.from = date.from.uncertain! if date.from.respond_to? :uncertain! date.to = date.to.uncertain! if date.to.respond_to? :uncertain! end date end
[ "def", "circa", "(", "str", ")", "run", "=", "str", ".", "gsub!", "(", "/", "\\.", "/i", ",", "''", ")", "run", "||=", "str", ".", "gsub!", "(", "/", "/i", ",", "''", ")", "date", "=", "parse", "(", "str", ")", "if", "run", "return", "nil", "if", "date", ".", "nil?", "# The EDTF grammar does not support uncertainty on masked precision dates", "if", "date", ".", "respond_to?", ":uncertain!", "date", ".", "uncertain!", "elsif", "date", ".", "is_a?", "EDTF", "::", "Interval", "# Interval uncertainty is scoped to the begin and end dates;", "# to be safe, we mark both.", "date", ".", "from", "=", "date", ".", "from", ".", "uncertain!", "if", "date", ".", "from", ".", "respond_to?", ":uncertain!", "date", ".", "to", "=", "date", ".", "to", ".", "uncertain!", "if", "date", ".", "to", ".", "respond_to?", ":uncertain!", "end", "date", "end" ]
Remove 'circa' or 'about' or variations and return an uncertian ETDF dates. @param str [String] @return [Date, nil] an EDTF date, marked uncertian; or `nil` @see #parse
[ "Remove", "circa", "or", "about", "or", "variations", "and", "return", "an", "uncertian", "ETDF", "dates", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L86-L104
434
railsmachine/shadow_puppet
lib/shadow_puppet/manifest.rb
ShadowPuppet.Manifest.execute
def execute(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e false else not transaction.any_failed? ensure @executed = true end
ruby
def execute(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e false else not transaction.any_failed? ensure @executed = true end
[ "def", "execute", "(", "force", "=", "false", ")", "return", "false", "if", "executed?", "&&", "!", "force", "evaluate_recipes", "transaction", "=", "apply", "rescue", "Exception", "=>", "e", "false", "else", "not", "transaction", ".", "any_failed?", "ensure", "@executed", "=", "true", "end" ]
Execute this manifest, applying all resources defined. Execute returns true if successfull, and false if unsucessfull. By default, this will only execute a manifest that has not already been executed?. The +force+ argument, if true, removes this check.
[ "Execute", "this", "manifest", "applying", "all", "resources", "defined", ".", "Execute", "returns", "true", "if", "successfull", "and", "false", "if", "unsucessfull", ".", "By", "default", "this", "will", "only", "execute", "a", "manifest", "that", "has", "not", "already", "been", "executed?", ".", "The", "+", "force", "+", "argument", "if", "true", "removes", "this", "check", "." ]
92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a
https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L242-L252
435
railsmachine/shadow_puppet
lib/shadow_puppet/manifest.rb
ShadowPuppet.Manifest.execute!
def execute!(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e raise e else not transaction.any_failed? ensure @executed = true end
ruby
def execute!(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e raise e else not transaction.any_failed? ensure @executed = true end
[ "def", "execute!", "(", "force", "=", "false", ")", "return", "false", "if", "executed?", "&&", "!", "force", "evaluate_recipes", "transaction", "=", "apply", "rescue", "Exception", "=>", "e", "raise", "e", "else", "not", "transaction", ".", "any_failed?", "ensure", "@executed", "=", "true", "end" ]
Execute this manifest, applying all resources defined. Execute returns true if successfull, and raises an exception if not. By default, this will only execute a manifest that has not already been executed?. The +force+ argument, if true, removes this check.
[ "Execute", "this", "manifest", "applying", "all", "resources", "defined", ".", "Execute", "returns", "true", "if", "successfull", "and", "raises", "an", "exception", "if", "not", ".", "By", "default", "this", "will", "only", "execute", "a", "manifest", "that", "has", "not", "already", "been", "executed?", ".", "The", "+", "force", "+", "argument", "if", "true", "removes", "this", "check", "." ]
92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a
https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L258-L268
436
railsmachine/shadow_puppet
lib/shadow_puppet/manifest.rb
ShadowPuppet.Manifest.evaluate_recipes
def evaluate_recipes self.class.recipes.each do |meth, args| case arity = method(meth).arity when 1, -1 send(meth, args) else send(meth) end end end
ruby
def evaluate_recipes self.class.recipes.each do |meth, args| case arity = method(meth).arity when 1, -1 send(meth, args) else send(meth) end end end
[ "def", "evaluate_recipes", "self", ".", "class", ".", "recipes", ".", "each", "do", "|", "meth", ",", "args", "|", "case", "arity", "=", "method", "(", "meth", ")", ".", "arity", "when", "1", ",", "-", "1", "send", "(", "meth", ",", "args", ")", "else", "send", "(", "meth", ")", "end", "end", "end" ]
Evaluate the methods calls queued in self.recipes
[ "Evaluate", "the", "methods", "calls", "queued", "in", "self", ".", "recipes" ]
92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a
https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L299-L308
437
railsmachine/shadow_puppet
lib/shadow_puppet/manifest.rb
ShadowPuppet.Manifest.reference
def reference(type, title, params = {}) Puppet::Resource.new(type.name.to_s.capitalize, title.to_s) end
ruby
def reference(type, title, params = {}) Puppet::Resource.new(type.name.to_s.capitalize, title.to_s) end
[ "def", "reference", "(", "type", ",", "title", ",", "params", "=", "{", "}", ")", "Puppet", "::", "Resource", ".", "new", "(", "type", ".", "name", ".", "to_s", ".", "capitalize", ",", "title", ".", "to_s", ")", "end" ]
Create a reference to another Puppet Resource.
[ "Create", "a", "reference", "to", "another", "Puppet", "Resource", "." ]
92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a
https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L338-L340
438
railsmachine/shadow_puppet
lib/shadow_puppet/manifest.rb
ShadowPuppet.Manifest.add_resource
def add_resource(type, title, params = {}) catalog.add_resource(new_resource(type, title, params)) end
ruby
def add_resource(type, title, params = {}) catalog.add_resource(new_resource(type, title, params)) end
[ "def", "add_resource", "(", "type", ",", "title", ",", "params", "=", "{", "}", ")", "catalog", ".", "add_resource", "(", "new_resource", "(", "type", ",", "title", ",", "params", ")", ")", "end" ]
Creates a new Puppet Resource and adds it to the Catalog.
[ "Creates", "a", "new", "Puppet", "Resource", "and", "adds", "it", "to", "the", "Catalog", "." ]
92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a
https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L343-L345
439
dpla/KriKri
app/controllers/krikri/reports_controller.rb
Krikri.ReportsController.index
def index @current_provider = params[:provider] report = Krikri::ValidationReport.new report.provider_id = @current_provider @validation_reports = report.all if @current_provider @provider = Krikri::Provider.find(@current_provider) @qa_reports = Array(Krikri::QAReport.find_by(provider: @current_provider)) else @qa_reports = Krikri::QAReport.all end end
ruby
def index @current_provider = params[:provider] report = Krikri::ValidationReport.new report.provider_id = @current_provider @validation_reports = report.all if @current_provider @provider = Krikri::Provider.find(@current_provider) @qa_reports = Array(Krikri::QAReport.find_by(provider: @current_provider)) else @qa_reports = Krikri::QAReport.all end end
[ "def", "index", "@current_provider", "=", "params", "[", ":provider", "]", "report", "=", "Krikri", "::", "ValidationReport", ".", "new", "report", ".", "provider_id", "=", "@current_provider", "@validation_reports", "=", "report", ".", "all", "if", "@current_provider", "@provider", "=", "Krikri", "::", "Provider", ".", "find", "(", "@current_provider", ")", "@qa_reports", "=", "Array", "(", "Krikri", "::", "QAReport", ".", "find_by", "(", "provider", ":", "@current_provider", ")", ")", "else", "@qa_reports", "=", "Krikri", "::", "QAReport", ".", "all", "end", "end" ]
Renders the index view, giving `@validation_reports` and `@qa_reports` for the specified provider.
[ "Renders", "the", "index", "view", "giving" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/controllers/krikri/reports_controller.rb#L11-L23
440
nbulaj/alpha_card
lib/alpha_card/resources/order.rb
AlphaCard.Order.attributes_for_request
def attributes_for_request(*) attributes = filled_attributes.dup billing = attributes.delete(:billing) attributes.merge!(billing.attributes_for_request) if billing shipping = attributes.delete(:shipping) attributes.merge!(shipping.attributes_for_request) if shipping super(attributes) end
ruby
def attributes_for_request(*) attributes = filled_attributes.dup billing = attributes.delete(:billing) attributes.merge!(billing.attributes_for_request) if billing shipping = attributes.delete(:shipping) attributes.merge!(shipping.attributes_for_request) if shipping super(attributes) end
[ "def", "attributes_for_request", "(", "*", ")", "attributes", "=", "filled_attributes", ".", "dup", "billing", "=", "attributes", ".", "delete", "(", ":billing", ")", "attributes", ".", "merge!", "(", "billing", ".", "attributes_for_request", ")", "if", "billing", "shipping", "=", "attributes", ".", "delete", "(", ":shipping", ")", "attributes", ".", "merge!", "(", "shipping", ".", "attributes_for_request", ")", "if", "shipping", "super", "(", "attributes", ")", "end" ]
Overloaded method to return all the attributes from the sale + billing + shipping objects. @return [Hash] Filled attributes with the original Alpha Card Services transaction variables names. @example billing = AlphaCard::Billing.new(email: 'test@example.com') shipping = AlphaCard::Shipping.new(first_name: 'John', last_name: 'Doe') order = AlphaCard::Order.new(id: '1', billing: billing, shipping: shipping) order.attributes_for_request #=> { orderid: '1', email: 'test@example.com', shipping_first_name: 'John', shipping_last_name: 'Doe' }
[ "Overloaded", "method", "to", "return", "all", "the", "attributes", "from", "the", "sale", "+", "billing", "+", "shipping", "objects", "." ]
06fefc2dbbf0e7002fabb2be361b8d72a178f559
https://github.com/nbulaj/alpha_card/blob/06fefc2dbbf0e7002fabb2be361b8d72a178f559/lib/alpha_card/resources/order.rb#L40-L50
441
mikemackintosh/ruby-easyrsa
lib/easyrsa/revoke.rb
EasyRSA.Revoke.revoke!
def revoke!(cakey=nil, crl=nil, next_update=36000) if cakey.nil? fail EasyRSA::Revoke::MissingCARootKey, 'Please provide the root CA cert for the CRL' end # Get cert details if it's in a file unless cakey.is_a? OpenSSL::PKey::RSA if cakey.include?('BEGIN RSA PRIVATE KEY') cakey = OpenSSL::PKey::RSA.new cakey else begin cakey = OpenSSL::PKey::RSA.new File.read cakey rescue OpenSSL::PKey::RSAError => e fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end end end # This is not a private key unless cakey.private? fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end # Create or load the CRL unless crl.nil? begin @crl = OpenSSL::X509::CRL.new crl rescue fail EasyRSA::Revoke::InvalidCertificateRevocationList, 'Invalid CRL provided.' end else @crl = OpenSSL::X509::CRL.new end # Add the revoked cert @crl.add_revoked(@revoked) # Needed CRL options @crl.last_update = @revoked.time @crl.next_update = Time.now + next_update @crl.version = 1 # Update the CRL issuer @crl.issuer = EasyRSA::gen_issuer # Sign the CRL @updated_crl = @crl.sign(cakey, OpenSSL::Digest::SHA256.new) @updated_crl end
ruby
def revoke!(cakey=nil, crl=nil, next_update=36000) if cakey.nil? fail EasyRSA::Revoke::MissingCARootKey, 'Please provide the root CA cert for the CRL' end # Get cert details if it's in a file unless cakey.is_a? OpenSSL::PKey::RSA if cakey.include?('BEGIN RSA PRIVATE KEY') cakey = OpenSSL::PKey::RSA.new cakey else begin cakey = OpenSSL::PKey::RSA.new File.read cakey rescue OpenSSL::PKey::RSAError => e fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end end end # This is not a private key unless cakey.private? fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end # Create or load the CRL unless crl.nil? begin @crl = OpenSSL::X509::CRL.new crl rescue fail EasyRSA::Revoke::InvalidCertificateRevocationList, 'Invalid CRL provided.' end else @crl = OpenSSL::X509::CRL.new end # Add the revoked cert @crl.add_revoked(@revoked) # Needed CRL options @crl.last_update = @revoked.time @crl.next_update = Time.now + next_update @crl.version = 1 # Update the CRL issuer @crl.issuer = EasyRSA::gen_issuer # Sign the CRL @updated_crl = @crl.sign(cakey, OpenSSL::Digest::SHA256.new) @updated_crl end
[ "def", "revoke!", "(", "cakey", "=", "nil", ",", "crl", "=", "nil", ",", "next_update", "=", "36000", ")", "if", "cakey", ".", "nil?", "fail", "EasyRSA", "::", "Revoke", "::", "MissingCARootKey", ",", "'Please provide the root CA cert for the CRL'", "end", "# Get cert details if it's in a file", "unless", "cakey", ".", "is_a?", "OpenSSL", "::", "PKey", "::", "RSA", "if", "cakey", ".", "include?", "(", "'BEGIN RSA PRIVATE KEY'", ")", "cakey", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "cakey", "else", "begin", "cakey", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "File", ".", "read", "cakey", "rescue", "OpenSSL", "::", "PKey", "::", "RSAError", "=>", "e", "fail", "EasyRSA", "::", "Revoke", "::", "InvalidCARootPrivateKey", ",", "'This is not a valid Private key file.'", "end", "end", "end", "# This is not a private key", "unless", "cakey", ".", "private?", "fail", "EasyRSA", "::", "Revoke", "::", "InvalidCARootPrivateKey", ",", "'This is not a valid Private key file.'", "end", "# Create or load the CRL", "unless", "crl", ".", "nil?", "begin", "@crl", "=", "OpenSSL", "::", "X509", "::", "CRL", ".", "new", "crl", "rescue", "fail", "EasyRSA", "::", "Revoke", "::", "InvalidCertificateRevocationList", ",", "'Invalid CRL provided.'", "end", "else", "@crl", "=", "OpenSSL", "::", "X509", "::", "CRL", ".", "new", "end", "# Add the revoked cert", "@crl", ".", "add_revoked", "(", "@revoked", ")", "# Needed CRL options", "@crl", ".", "last_update", "=", "@revoked", ".", "time", "@crl", ".", "next_update", "=", "Time", ".", "now", "+", "next_update", "@crl", ".", "version", "=", "1", "# Update the CRL issuer", "@crl", ".", "issuer", "=", "EasyRSA", "::", "gen_issuer", "# Sign the CRL", "@updated_crl", "=", "@crl", ".", "sign", "(", "cakey", ",", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", ")", "@updated_crl", "end" ]
Lets get revoking
[ "Lets", "get", "revoking" ]
a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a
https://github.com/mikemackintosh/ruby-easyrsa/blob/a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a/lib/easyrsa/revoke.rb#L35-L87
442
scryptmouse/dux
lib/dux/enum.rb
Dux.Enum.with_return_type
def with_return_type(value) if value.nil? && allow_nil? if allow_nil? nil else # :nocov: raise ArgumentError, "Cannot return `nil` without allow_nil: true" # :nocov: end elsif @return_type == :symbol value.to_sym elsif @return_type == :string value.to_s end end
ruby
def with_return_type(value) if value.nil? && allow_nil? if allow_nil? nil else # :nocov: raise ArgumentError, "Cannot return `nil` without allow_nil: true" # :nocov: end elsif @return_type == :symbol value.to_sym elsif @return_type == :string value.to_s end end
[ "def", "with_return_type", "(", "value", ")", "if", "value", ".", "nil?", "&&", "allow_nil?", "if", "allow_nil?", "nil", "else", "# :nocov:", "raise", "ArgumentError", ",", "\"Cannot return `nil` without allow_nil: true\"", "# :nocov:", "end", "elsif", "@return_type", "==", ":symbol", "value", ".", "to_sym", "elsif", "@return_type", "==", ":string", "value", ".", "to_s", "end", "end" ]
Ensure the value is returned with the correct type @param [String, Symbol, nil] value @return [String, Symbol, nil]
[ "Ensure", "the", "value", "is", "returned", "with", "the", "correct", "type" ]
94a9b05fcfede36369e93d9c3a339365e55dc38a
https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/enum.rb#L115-L129
443
scryptmouse/dux
lib/dux/enum.rb
Dux.Enum.valid_fallback?
def valid_fallback?(fallback) return true if fallback.nil? && allow_nil? return true if include? fallback false end
ruby
def valid_fallback?(fallback) return true if fallback.nil? && allow_nil? return true if include? fallback false end
[ "def", "valid_fallback?", "(", "fallback", ")", "return", "true", "if", "fallback", ".", "nil?", "&&", "allow_nil?", "return", "true", "if", "include?", "fallback", "false", "end" ]
Check if the provided `fallback` is valid @param [String, Symbol, nil] fallback
[ "Check", "if", "the", "provided", "fallback", "is", "valid" ]
94a9b05fcfede36369e93d9c3a339365e55dc38a
https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/enum.rb#L164-L169
444
scryptmouse/dux
lib/dux/enum.rb
Dux.Enum.set_default
def set_default(fallback) if valid_fallback?(fallback) || fallback == NO_DEFAULT @default = fallback else raise InvalidFallback, "Cannot set #{fallback.inspect} as default", caller end end
ruby
def set_default(fallback) if valid_fallback?(fallback) || fallback == NO_DEFAULT @default = fallback else raise InvalidFallback, "Cannot set #{fallback.inspect} as default", caller end end
[ "def", "set_default", "(", "fallback", ")", "if", "valid_fallback?", "(", "fallback", ")", "||", "fallback", "==", "NO_DEFAULT", "@default", "=", "fallback", "else", "raise", "InvalidFallback", ",", "\"Cannot set #{fallback.inspect} as default\"", ",", "caller", "end", "end" ]
Set the default fallback value. @param [String, Symbol, nil] fallback @return [void]
[ "Set", "the", "default", "fallback", "value", "." ]
94a9b05fcfede36369e93d9c3a339365e55dc38a
https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/enum.rb#L175-L181
445
dark-panda/active-profiling
lib/active-profiling/gc_statistics.rb
ActiveProfiling.GCStatistics.gc_statistics
def gc_statistics(*args) options = Rails.application.config.active_profiling.gc_statistics.merge(args.extract_options!) result, gc_report = gc_statistics_report(options) do yield end ActiveSupport::Notifications.instrument('gc_statistics.active_profiling', { :report => gc_report, :title => options[:title] || args.first }) result end
ruby
def gc_statistics(*args) options = Rails.application.config.active_profiling.gc_statistics.merge(args.extract_options!) result, gc_report = gc_statistics_report(options) do yield end ActiveSupport::Notifications.instrument('gc_statistics.active_profiling', { :report => gc_report, :title => options[:title] || args.first }) result end
[ "def", "gc_statistics", "(", "*", "args", ")", "options", "=", "Rails", ".", "application", ".", "config", ".", "active_profiling", ".", "gc_statistics", ".", "merge", "(", "args", ".", "extract_options!", ")", "result", ",", "gc_report", "=", "gc_statistics_report", "(", "options", ")", "do", "yield", "end", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'gc_statistics.active_profiling'", ",", "{", ":report", "=>", "gc_report", ",", ":title", "=>", "options", "[", ":title", "]", "||", "args", ".", "first", "}", ")", "result", "end" ]
Profiles a block, capturing information on the garbage collector. The return value is an Array containing the result of the yielded block and a String with a report on the profiling results. Options: * +:disable_gc+ - disables garbage collection for the duration of the block and then renables it immediately afterwards. This allows you to control when GC is run and see the results. * +:title+ - a title to use for logging. More options for this method can be found in the default settings, located in ActiveProfiling::Railtie::DEFAULT_GC_STATISTICS_OPTIONS. This method only works with versions of Ruby that implement GC::Profiler or that have been patched to implement some additional garbage collection statistics. In older versions, such as version 1.8.7, you can either use Ruby Enterprise Edition or patch your build with the GC statistics patch found here: http://blog.pluron.com/2008/02/memory-profilin.html
[ "Profiles", "a", "block", "capturing", "information", "on", "the", "garbage", "collector", ".", "The", "return", "value", "is", "an", "Array", "containing", "the", "result", "of", "the", "yielded", "block", "and", "a", "String", "with", "a", "report", "on", "the", "profiling", "results", "." ]
c9931255325444d0eab08e46ed4fa8a6d9618f1e
https://github.com/dark-panda/active-profiling/blob/c9931255325444d0eab08e46ed4fa8a6d9618f1e/lib/active-profiling/gc_statistics.rb#L88-L101
446
kschiess/zack
lib/zack/server.rb
Zack.Server.process_request
def process_request(control, sym, args) instance = factory.call(control) instance.send(sym, *args) end
ruby
def process_request(control, sym, args) instance = factory.call(control) instance.send(sym, *args) end
[ "def", "process_request", "(", "control", ",", "sym", ",", "args", ")", "instance", "=", "factory", ".", "call", "(", "control", ")", "instance", ".", "send", "(", "sym", ",", "args", ")", "end" ]
Processes exactly one request, but doesn't define how the request gets here. @private
[ "Processes", "exactly", "one", "request", "but", "doesn", "t", "define", "how", "the", "request", "gets", "here", "." ]
a9ac7cc672f1760961fae45bfe8f4be68b2ca7d9
https://github.com/kschiess/zack/blob/a9ac7cc672f1760961fae45bfe8f4be68b2ca7d9/lib/zack/server.rb#L63-L67
447
kschiess/zack
lib/zack/server.rb
Zack.Server.exception_handling
def exception_handling(exception_handler, control) begin yield rescue => exception # If we have an exception handler, it gets handed all the exceptions. # No exceptions stop the operation. if exception_handler exception_handler.call(exception, control) else raise end end end
ruby
def exception_handling(exception_handler, control) begin yield rescue => exception # If we have an exception handler, it gets handed all the exceptions. # No exceptions stop the operation. if exception_handler exception_handler.call(exception, control) else raise end end end
[ "def", "exception_handling", "(", "exception_handler", ",", "control", ")", "begin", "yield", "rescue", "=>", "exception", "# If we have an exception handler, it gets handed all the exceptions. ", "# No exceptions stop the operation. ", "if", "exception_handler", "exception_handler", ".", "call", "(", "exception", ",", "control", ")", "else", "raise", "end", "end", "end" ]
Defines how the server handles exception.
[ "Defines", "how", "the", "server", "handles", "exception", "." ]
a9ac7cc672f1760961fae45bfe8f4be68b2ca7d9
https://github.com/kschiess/zack/blob/a9ac7cc672f1760961fae45bfe8f4be68b2ca7d9/lib/zack/server.rb#L110-L123
448
dpla/KriKri
lib/krikri/ldp/rdf_source.rb
Krikri::LDP.RdfSource.save_with_provenance
def save_with_provenance(activity_uri) predicate = exists? ? REVISED_URI : GENERATED_URI self << RDF::Statement(self, predicate, activity_uri) save end
ruby
def save_with_provenance(activity_uri) predicate = exists? ? REVISED_URI : GENERATED_URI self << RDF::Statement(self, predicate, activity_uri) save end
[ "def", "save_with_provenance", "(", "activity_uri", ")", "predicate", "=", "exists?", "?", "REVISED_URI", ":", "GENERATED_URI", "self", "<<", "RDF", "::", "Statement", "(", "self", ",", "predicate", ",", "activity_uri", ")", "save", "end" ]
Adds an appropritate provenance statement with the given URI and saves the resource. This method treats RDFSources as stateful resources. This is in conflict with the PROV model, which assumes each revision is its own Resource. The internal predicate `dpla:wasRevisedBy` is used for non-generating revisions of stateful RDFSources. @todo Assuming a Marmotta LDP server, there are version URIs available (via Memento) which could be used for a direct PROV implementation. Consider options for doing that either alongside or in place of this approach. @param activity_uri [#to_term] the URI of the prov:Activity to mark as generating or revising the saved resource. @see #save @see http://www.w3.org/TR/prov-primer/ @see http://www.w3.org/TR/2013/REC-prov-o-20130430/
[ "Adds", "an", "appropritate", "provenance", "statement", "with", "the", "given", "URI", "and", "saves", "the", "resource", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/ldp/rdf_source.rb#L85-L89
449
dpla/KriKri
lib/krikri/entity_consumer.rb
Krikri.EntityConsumer.assign_generator_activity!
def assign_generator_activity!(opts) if opts.include?(:generator_uri) generator_uri = opts.delete(:generator_uri) @entity_source = @generator_activity = Krikri::Activity.from_uri(generator_uri) end end
ruby
def assign_generator_activity!(opts) if opts.include?(:generator_uri) generator_uri = opts.delete(:generator_uri) @entity_source = @generator_activity = Krikri::Activity.from_uri(generator_uri) end end
[ "def", "assign_generator_activity!", "(", "opts", ")", "if", "opts", ".", "include?", "(", ":generator_uri", ")", "generator_uri", "=", "opts", ".", "delete", "(", ":generator_uri", ")", "@entity_source", "=", "@generator_activity", "=", "Krikri", "::", "Activity", ".", "from_uri", "(", "generator_uri", ")", "end", "end" ]
Store this agent's generator activity, which is the activity that produced the target entities upon which the current agent will operate. It is assumed that the agent class will define #entity_behavior, which returns the class of the appropriate behavior. `generator_uri' can be a string or RDF::URI. In the future, we might want to take a `generator_activity' parameter, because not every activity will modify its entities with provenance messages; an indexing activity, in particular. In this case an LDP URI representing the activity is not relevant. @see Krikri::Mapper::Agent @see Krikri::Harvester
[ "Store", "this", "agent", "s", "generator", "activity", "which", "is", "the", "activity", "that", "produced", "the", "target", "entities", "upon", "which", "the", "current", "agent", "will", "operate", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/entity_consumer.rb#L41-L47
450
ninjudd/deep_clonable
lib/deep_clonable.rb
DeepClonable.InstanceMethods.deep_vars
def deep_vars instance_variables.select do |var| value = instance_variable_get(var) value.kind_of?(Array) or value.kind_of?(Hash) or value.kind_of?(DeepClonable::InstanceMethods) end end
ruby
def deep_vars instance_variables.select do |var| value = instance_variable_get(var) value.kind_of?(Array) or value.kind_of?(Hash) or value.kind_of?(DeepClonable::InstanceMethods) end end
[ "def", "deep_vars", "instance_variables", ".", "select", "do", "|", "var", "|", "value", "=", "instance_variable_get", "(", "var", ")", "value", ".", "kind_of?", "(", "Array", ")", "or", "value", ".", "kind_of?", "(", "Hash", ")", "or", "value", ".", "kind_of?", "(", "DeepClonable", "::", "InstanceMethods", ")", "end", "end" ]
You can override deep_vars in your class to specify which instance_variables should be deep cloned. As it is, all Arrays and Hashes are deep cloned.
[ "You", "can", "override", "deep_vars", "in", "your", "class", "to", "specify", "which", "instance_variables", "should", "be", "deep", "cloned", ".", "As", "it", "is", "all", "Arrays", "and", "Hashes", "are", "deep", "cloned", "." ]
71be86f190c7643a07f44eb9b32ab48f88f0cbc4
https://github.com/ninjudd/deep_clonable/blob/71be86f190c7643a07f44eb9b32ab48f88f0cbc4/lib/deep_clonable.rb#L31-L36
451
nudded/GoogleReaderAPI
lib/google-reader-api/api.rb
GoogleReaderApi.Api.post_request
def post_request(url,args) uri = URI.parse(url) req = Net::HTTP::Post.new(uri.path) req.set_form_data(args) request(uri,req) end
ruby
def post_request(url,args) uri = URI.parse(url) req = Net::HTTP::Post.new(uri.path) req.set_form_data(args) request(uri,req) end
[ "def", "post_request", "(", "url", ",", "args", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "path", ")", "req", ".", "set_form_data", "(", "args", ")", "request", "(", "uri", ",", "req", ")", "end" ]
url as a string the post data as a hash
[ "url", "as", "a", "string", "the", "post", "data", "as", "a", "hash" ]
1773adf4011ade0ac20c4e9057eaeffce1c5f7c9
https://github.com/nudded/GoogleReaderAPI/blob/1773adf4011ade0ac20c4e9057eaeffce1c5f7c9/lib/google-reader-api/api.rb#L48-L53
452
rubinius/rubinius-core-api
lib/rubinius/kernel/common/tuple.rb
Rubinius.Tuple.swap
def swap(a, b) temp = at(a) put a, at(b) put b, temp end
ruby
def swap(a, b) temp = at(a) put a, at(b) put b, temp end
[ "def", "swap", "(", "a", ",", "b", ")", "temp", "=", "at", "(", "a", ")", "put", "a", ",", "at", "(", "b", ")", "put", "b", ",", "temp", "end" ]
Swap elements of the two indexes.
[ "Swap", "elements", "of", "the", "two", "indexes", "." ]
8d01207061518355da9b53274fe8766ecf85fdfe
https://github.com/rubinius/rubinius-core-api/blob/8d01207061518355da9b53274fe8766ecf85fdfe/lib/rubinius/kernel/common/tuple.rb#L113-L117
453
tlux/vnstat-ruby
lib/vnstat/utils.rb
Vnstat.Utils.system_call
def system_call(*args) result = SystemCall.call(*args) return result.success_result if result.success? return yield(result.error_result) if block_given? result.error_result end
ruby
def system_call(*args) result = SystemCall.call(*args) return result.success_result if result.success? return yield(result.error_result) if block_given? result.error_result end
[ "def", "system_call", "(", "*", "args", ")", "result", "=", "SystemCall", ".", "call", "(", "args", ")", "return", "result", ".", "success_result", "if", "result", ".", "success?", "return", "yield", "(", "result", ".", "error_result", ")", "if", "block_given?", "result", ".", "error_result", "end" ]
Initiates a system call with the given arguments. @param [Array] args The arguments for the system call. @overload system_call(*args) @return [String] The output of STDOUT or STDERR, depending of the exit status of the called command. @overload system_call(*args, &block) @yield [error_result] A block yielded when the called command exited unsuccessfully. @yieldparam [String] error_result The STDERR output. @return [Object] The value the called block returns.
[ "Initiates", "a", "system", "call", "with", "the", "given", "arguments", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/utils.rb#L25-L31
454
spox/splib
lib/splib/monitor.rb
Splib.Monitor.signal
def signal synchronize do while(t = @threads.shift) if(t && t.alive? && t.stop?) t.wakeup break else next end end end end
ruby
def signal synchronize do while(t = @threads.shift) if(t && t.alive? && t.stop?) t.wakeup break else next end end end end
[ "def", "signal", "synchronize", "do", "while", "(", "t", "=", "@threads", ".", "shift", ")", "if", "(", "t", "&&", "t", ".", "alive?", "&&", "t", ".", "stop?", ")", "t", ".", "wakeup", "break", "else", "next", "end", "end", "end", "end" ]
Wake up earliest thread
[ "Wake", "up", "earliest", "thread" ]
fd4451243ce4c9a319e74b33e6decdd09a509f43
https://github.com/spox/splib/blob/fd4451243ce4c9a319e74b33e6decdd09a509f43/lib/splib/monitor.rb#L58-L69
455
spox/splib
lib/splib/monitor.rb
Splib.Monitor.broadcast
def broadcast synchronize do @threads.dup.each do |t| t.wakeup if t.alive? && t.stop? end end end
ruby
def broadcast synchronize do @threads.dup.each do |t| t.wakeup if t.alive? && t.stop? end end end
[ "def", "broadcast", "synchronize", "do", "@threads", ".", "dup", ".", "each", "do", "|", "t", "|", "t", ".", "wakeup", "if", "t", ".", "alive?", "&&", "t", ".", "stop?", "end", "end", "end" ]
Wake up all threads
[ "Wake", "up", "all", "threads" ]
fd4451243ce4c9a319e74b33e6decdd09a509f43
https://github.com/spox/splib/blob/fd4451243ce4c9a319e74b33e6decdd09a509f43/lib/splib/monitor.rb#L71-L77
456
spox/splib
lib/splib/monitor.rb
Splib.Monitor.try_lock
def try_lock locked = false Thread.exclusive do clean unless(locked?(false)) do_lock locked = true else locked = owner?(Thread.current) end end locked end
ruby
def try_lock locked = false Thread.exclusive do clean unless(locked?(false)) do_lock locked = true else locked = owner?(Thread.current) end end locked end
[ "def", "try_lock", "locked", "=", "false", "Thread", ".", "exclusive", "do", "clean", "unless", "(", "locked?", "(", "false", ")", ")", "do_lock", "locked", "=", "true", "else", "locked", "=", "owner?", "(", "Thread", ".", "current", ")", "end", "end", "locked", "end" ]
Attempt to lock. Returns true if lock is aquired and false if not.
[ "Attempt", "to", "lock", ".", "Returns", "true", "if", "lock", "is", "aquired", "and", "false", "if", "not", "." ]
fd4451243ce4c9a319e74b33e6decdd09a509f43
https://github.com/spox/splib/blob/fd4451243ce4c9a319e74b33e6decdd09a509f43/lib/splib/monitor.rb#L94-L106
457
spox/splib
lib/splib/monitor.rb
Splib.Monitor.clean
def clean @locks.delete_if{|t|!t.alive?} if(@lock_owner && !@lock_owner.alive?) @lock_owner = @locks.empty? ? nil : @locks.shift @lock_owner.wakeup if @lock_owner && !owner?(Thread.current) end end
ruby
def clean @locks.delete_if{|t|!t.alive?} if(@lock_owner && !@lock_owner.alive?) @lock_owner = @locks.empty? ? nil : @locks.shift @lock_owner.wakeup if @lock_owner && !owner?(Thread.current) end end
[ "def", "clean", "@locks", ".", "delete_if", "{", "|", "t", "|", "!", "t", ".", "alive?", "}", "if", "(", "@lock_owner", "&&", "!", "@lock_owner", ".", "alive?", ")", "@lock_owner", "=", "@locks", ".", "empty?", "?", "nil", ":", "@locks", ".", "shift", "@lock_owner", ".", "wakeup", "if", "@lock_owner", "&&", "!", "owner?", "(", "Thread", ".", "current", ")", "end", "end" ]
This is a simple helper method to help keep threads from ending up stuck waiting for a lock when a thread locks the monitor and then decides to die without unlocking. It is only called when new locks are attempted or a check is made if the monitor is currently locked.
[ "This", "is", "a", "simple", "helper", "method", "to", "help", "keep", "threads", "from", "ending", "up", "stuck", "waiting", "for", "a", "lock", "when", "a", "thread", "locks", "the", "monitor", "and", "then", "decides", "to", "die", "without", "unlocking", ".", "It", "is", "only", "called", "when", "new", "locks", "are", "attempted", "or", "a", "check", "is", "made", "if", "the", "monitor", "is", "currently", "locked", "." ]
fd4451243ce4c9a319e74b33e6decdd09a509f43
https://github.com/spox/splib/blob/fd4451243ce4c9a319e74b33e6decdd09a509f43/lib/splib/monitor.rb#L130-L136
458
spox/splib
lib/splib/monitor.rb
Splib.Monitor.do_unlock
def do_unlock unless(owner?(Thread.current)) raise ThreadError.new("Thread #{Thread.current} is not the current owner: #{@lock_owner}") end Thread.exclusive do @locks.delete_if{|t|!t.alive?} unless(@locks.empty?) old_owner = @lock_owner @lock_owner = @locks.shift @lock_owner.wakeup unless old_owner == @lock_owner else @lock_owner = nil end end end
ruby
def do_unlock unless(owner?(Thread.current)) raise ThreadError.new("Thread #{Thread.current} is not the current owner: #{@lock_owner}") end Thread.exclusive do @locks.delete_if{|t|!t.alive?} unless(@locks.empty?) old_owner = @lock_owner @lock_owner = @locks.shift @lock_owner.wakeup unless old_owner == @lock_owner else @lock_owner = nil end end end
[ "def", "do_unlock", "unless", "(", "owner?", "(", "Thread", ".", "current", ")", ")", "raise", "ThreadError", ".", "new", "(", "\"Thread #{Thread.current} is not the current owner: #{@lock_owner}\"", ")", "end", "Thread", ".", "exclusive", "do", "@locks", ".", "delete_if", "{", "|", "t", "|", "!", "t", ".", "alive?", "}", "unless", "(", "@locks", ".", "empty?", ")", "old_owner", "=", "@lock_owner", "@lock_owner", "=", "@locks", ".", "shift", "@lock_owner", ".", "wakeup", "unless", "old_owner", "==", "@lock_owner", "else", "@lock_owner", "=", "nil", "end", "end", "end" ]
Unlock the monitor
[ "Unlock", "the", "monitor" ]
fd4451243ce4c9a319e74b33e6decdd09a509f43
https://github.com/spox/splib/blob/fd4451243ce4c9a319e74b33e6decdd09a509f43/lib/splib/monitor.rb#L162-L176
459
spox/splib
lib/splib/monitor.rb
Splib.Monitor.start_timer
def start_timer @timer = Thread.new do begin until(@stop) do cur = [] t = 0.0 Thread.exclusive do t = @timers.values.min cur = @timers.dup end t = 0.0 if !t.nil? && t < 0.0 a = 0.0 begin a = Splib.sleep(t) rescue Wakeup # do nothing of importance ensure next if t.nil? Thread.exclusive do cur.each_pair do |thread, value| value -= a if(value <= 0.0) thread.wakeup @timers.delete(thread) else @timers[thread] = value end end end end end rescue retry end end end
ruby
def start_timer @timer = Thread.new do begin until(@stop) do cur = [] t = 0.0 Thread.exclusive do t = @timers.values.min cur = @timers.dup end t = 0.0 if !t.nil? && t < 0.0 a = 0.0 begin a = Splib.sleep(t) rescue Wakeup # do nothing of importance ensure next if t.nil? Thread.exclusive do cur.each_pair do |thread, value| value -= a if(value <= 0.0) thread.wakeup @timers.delete(thread) else @timers[thread] = value end end end end end rescue retry end end end
[ "def", "start_timer", "@timer", "=", "Thread", ".", "new", "do", "begin", "until", "(", "@stop", ")", "do", "cur", "=", "[", "]", "t", "=", "0.0", "Thread", ".", "exclusive", "do", "t", "=", "@timers", ".", "values", ".", "min", "cur", "=", "@timers", ".", "dup", "end", "t", "=", "0.0", "if", "!", "t", ".", "nil?", "&&", "t", "<", "0.0", "a", "=", "0.0", "begin", "a", "=", "Splib", ".", "sleep", "(", "t", ")", "rescue", "Wakeup", "# do nothing of importance", "ensure", "next", "if", "t", ".", "nil?", "Thread", ".", "exclusive", "do", "cur", ".", "each_pair", "do", "|", "thread", ",", "value", "|", "value", "-=", "a", "if", "(", "value", "<=", "0.0", ")", "thread", ".", "wakeup", "@timers", ".", "delete", "(", "thread", ")", "else", "@timers", "[", "thread", "]", "=", "value", "end", "end", "end", "end", "end", "rescue", "retry", "end", "end", "end" ]
Starts the timer for waiting threads with a timeout
[ "Starts", "the", "timer", "for", "waiting", "threads", "with", "a", "timeout" ]
fd4451243ce4c9a319e74b33e6decdd09a509f43
https://github.com/spox/splib/blob/fd4451243ce4c9a319e74b33e6decdd09a509f43/lib/splib/monitor.rb#L179-L214
460
nbulaj/alpha_card
lib/alpha_card/resource.rb
AlphaCard.Resource.attributes_for_request
def attributes_for_request(attrs = filled_attributes) return attrs if self.class::ORIGIN_TRANSACTION_VARIABLES.empty? attrs.each_with_object({}) do |(attr, value), request_attrs| request_attrs[self.class::ORIGIN_TRANSACTION_VARIABLES.fetch(attr, attr)] = value end end
ruby
def attributes_for_request(attrs = filled_attributes) return attrs if self.class::ORIGIN_TRANSACTION_VARIABLES.empty? attrs.each_with_object({}) do |(attr, value), request_attrs| request_attrs[self.class::ORIGIN_TRANSACTION_VARIABLES.fetch(attr, attr)] = value end end
[ "def", "attributes_for_request", "(", "attrs", "=", "filled_attributes", ")", "return", "attrs", "if", "self", ".", "class", "::", "ORIGIN_TRANSACTION_VARIABLES", ".", "empty?", "attrs", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "attr", ",", "value", ")", ",", "request_attrs", "|", "request_attrs", "[", "self", ".", "class", "::", "ORIGIN_TRANSACTION_VARIABLES", ".", "fetch", "(", "attr", ",", "attr", ")", "]", "=", "value", "end", "end" ]
Returns only filled attributes with the original Alpha Card Services transaction variables names. @param attrs [Hash] Attributes that must be converted to AlphaCard request params/ Default value is <code>filled_attributes</code>. @example order = AlphaCard::Order.new(id: '1', tax: nil, po_number: 'PO123') order.attributes_for_request #=> { orderid: '1', ponumber: 'PO123' }
[ "Returns", "only", "filled", "attributes", "with", "the", "original", "Alpha", "Card", "Services", "transaction", "variables", "names", "." ]
06fefc2dbbf0e7002fabb2be361b8d72a178f559
https://github.com/nbulaj/alpha_card/blob/06fefc2dbbf0e7002fabb2be361b8d72a178f559/lib/alpha_card/resource.rb#L26-L32
461
nbulaj/alpha_card
lib/alpha_card/resource.rb
AlphaCard.Resource.validate_required_attributes!
def validate_required_attributes! unless required_attributes? blank_attribute = required_attributes.detect { |attr| self[attr].nil? || self[attr].empty? } raise ValidationError, "#{blank_attribute} can't be blank" end end
ruby
def validate_required_attributes! unless required_attributes? blank_attribute = required_attributes.detect { |attr| self[attr].nil? || self[attr].empty? } raise ValidationError, "#{blank_attribute} can't be blank" end end
[ "def", "validate_required_attributes!", "unless", "required_attributes?", "blank_attribute", "=", "required_attributes", ".", "detect", "{", "|", "attr", "|", "self", "[", "attr", "]", ".", "nil?", "||", "self", "[", "attr", "]", ".", "empty?", "}", "raise", "ValidationError", ",", "\"#{blank_attribute} can't be blank\"", "end", "end" ]
Validate required attributes to be filled. Raises an exception if one of the attribute is not specified. @raise [AlphaCard::InvalidObjectError] error if required attributes not set
[ "Validate", "required", "attributes", "to", "be", "filled", ".", "Raises", "an", "exception", "if", "one", "of", "the", "attribute", "is", "not", "specified", "." ]
06fefc2dbbf0e7002fabb2be361b8d72a178f559
https://github.com/nbulaj/alpha_card/blob/06fefc2dbbf0e7002fabb2be361b8d72a178f559/lib/alpha_card/resource.rb#L58-L64
462
elastics/elastics
elastics-client/lib/elastics/utility_methods.rb
Elastics.UtilityMethods.dump_one
def dump_one(*vars) refresh_index(*vars) document = search_by_id({:params => {:_source => '*'}}, *vars) document.delete('_score') document end
ruby
def dump_one(*vars) refresh_index(*vars) document = search_by_id({:params => {:_source => '*'}}, *vars) document.delete('_score') document end
[ "def", "dump_one", "(", "*", "vars", ")", "refresh_index", "(", "vars", ")", "document", "=", "search_by_id", "(", "{", ":params", "=>", "{", ":_source", "=>", "'*'", "}", "}", ",", "vars", ")", "document", ".", "delete", "(", "'_score'", ")", "document", "end" ]
refresh and pull the full document from the index
[ "refresh", "and", "pull", "the", "full", "document", "from", "the", "index" ]
85517ec32fd30d3bb4b80223dc103fed482e4a3d
https://github.com/elastics/elastics/blob/85517ec32fd30d3bb4b80223dc103fed482e4a3d/elastics-client/lib/elastics/utility_methods.rb#L67-L72
463
elastics/elastics
elastics-client/lib/elastics/utility_methods.rb
Elastics.UtilityMethods.post_bulk_collection
def post_bulk_collection(collection, options={}) raise ArgumentError, "Array expected as :collection, got #{collection.inspect}" \ unless collection.is_a?(Array) bulk_string = '' collection.each do |d| bulk_string << build_bulk_string(d, options) end post_bulk_string(:bulk_string => bulk_string) unless bulk_string.empty? end
ruby
def post_bulk_collection(collection, options={}) raise ArgumentError, "Array expected as :collection, got #{collection.inspect}" \ unless collection.is_a?(Array) bulk_string = '' collection.each do |d| bulk_string << build_bulk_string(d, options) end post_bulk_string(:bulk_string => bulk_string) unless bulk_string.empty? end
[ "def", "post_bulk_collection", "(", "collection", ",", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "\"Array expected as :collection, got #{collection.inspect}\"", "unless", "collection", ".", "is_a?", "(", "Array", ")", "bulk_string", "=", "''", "collection", ".", "each", "do", "|", "d", "|", "bulk_string", "<<", "build_bulk_string", "(", "d", ",", "options", ")", "end", "post_bulk_string", "(", ":bulk_string", "=>", "bulk_string", ")", "unless", "bulk_string", ".", "empty?", "end" ]
You should use Elastics.post_bulk_string if you have an already formatted bulk data-string
[ "You", "should", "use", "Elastics", ".", "post_bulk_string", "if", "you", "have", "an", "already", "formatted", "bulk", "data", "-", "string" ]
85517ec32fd30d3bb4b80223dc103fed482e4a3d
https://github.com/elastics/elastics/blob/85517ec32fd30d3bb4b80223dc103fed482e4a3d/elastics-client/lib/elastics/utility_methods.rb#L75-L83
464
AnkurGel/dictionary-rb
lib/dictionary-rb/dictionary.rb
DictionaryRB.Dictionary.examples
def examples @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @example_results ||= @doc.css('.exsentences').map{ |x| x.text.strip }.reject(&:empty?).flatten @example_results #to prevent above computations on repeated call on object end
ruby
def examples @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @example_results ||= @doc.css('.exsentences').map{ |x| x.text.strip }.reject(&:empty?).flatten @example_results #to prevent above computations on repeated call on object end
[ "def", "examples", "@doc", "||=", "Nokogiri", "::", "HTML", "(", "open", "(", "PREFIX", "+", "CGI", "::", "escape", "(", "@word", ")", ")", ")", "@example_results", "||=", "@doc", ".", "css", "(", "'.exsentences'", ")", ".", "map", "{", "|", "x", "|", "x", ".", "text", ".", "strip", "}", ".", "reject", "(", ":empty?", ")", ".", "flatten", "@example_results", "#to prevent above computations on repeated call on object", "end" ]
Fetches and gives the examples for the word @example word.examples #=> ["There is an easy answer to this question, and it involves some good news and  some bad news.", "Then there was an awkward silence as though they were waiting for me to answer  another question.",..] @return [Array] containing the examples.
[ "Fetches", "and", "gives", "the", "examples", "for", "the", "word" ]
92566325aee598f46b584817373017e6097300b4
https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/dictionary.rb#L64-L68
465
AnkurGel/dictionary-rb
lib/dictionary-rb/dictionary.rb
DictionaryRB.Dictionary.similar_words
def similar_words @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @similar_words = @doc.css("#relatedwords .fla a").map(&:text).reject(&:empty?) @similar_words end
ruby
def similar_words @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @similar_words = @doc.css("#relatedwords .fla a").map(&:text).reject(&:empty?) @similar_words end
[ "def", "similar_words", "@doc", "||=", "Nokogiri", "::", "HTML", "(", "open", "(", "PREFIX", "+", "CGI", "::", "escape", "(", "@word", ")", ")", ")", "@similar_words", "=", "@doc", ".", "css", "(", "\"#relatedwords .fla a\"", ")", ".", "map", "(", ":text", ")", ".", "reject", "(", ":empty?", ")", "@similar_words", "end" ]
Fetches and gives synonyms for the word @example word.similar_words #=> => ["answer", "inquire", "question mark", "sentence",.. ] @return [Array] containing similar words
[ "Fetches", "and", "gives", "synonyms", "for", "the", "word" ]
92566325aee598f46b584817373017e6097300b4
https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/dictionary.rb#L75-L79
466
dpla/KriKri
lib/krikri/random_search_index_document_builder.rb
Krikri.RandomSearchIndexDocumentBuilder.query_params
def query_params params = { :id => '*:*', :sort => "random_#{rand(9999)} desc", :rows => 1 } return params unless provider_id.present? provider = RDF::URI(Krikri::Provider.base_uri) / provider_id params[:fq] = "provider_id:\"#{provider}\"" params end
ruby
def query_params params = { :id => '*:*', :sort => "random_#{rand(9999)} desc", :rows => 1 } return params unless provider_id.present? provider = RDF::URI(Krikri::Provider.base_uri) / provider_id params[:fq] = "provider_id:\"#{provider}\"" params end
[ "def", "query_params", "params", "=", "{", ":id", "=>", "'*:*'", ",", ":sort", "=>", "\"random_#{rand(9999)} desc\"", ",", ":rows", "=>", "1", "}", "return", "params", "unless", "provider_id", ".", "present?", "provider", "=", "RDF", "::", "URI", "(", "Krikri", "::", "Provider", ".", "base_uri", ")", "/", "provider_id", "params", "[", ":fq", "]", "=", "\"provider_id:\\\"#{provider}\\\"\"", "params", "end" ]
Parameters for the Solr request. Limits search by @provider_id if it has been specified.
[ "Parameters", "for", "the", "Solr", "request", ".", "Limits", "search", "by" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/random_search_index_document_builder.rb#L30-L39
467
dpla/KriKri
app/helpers/krikri/records_helper.rb
Krikri.RecordsHelper.random_record_id
def random_record_id(provider_id) doc = Krikri::RandomSearchIndexDocumentBuilder.new do self.provider_id = provider_id end.document doc.present? ? local_name(doc.id) : nil end
ruby
def random_record_id(provider_id) doc = Krikri::RandomSearchIndexDocumentBuilder.new do self.provider_id = provider_id end.document doc.present? ? local_name(doc.id) : nil end
[ "def", "random_record_id", "(", "provider_id", ")", "doc", "=", "Krikri", "::", "RandomSearchIndexDocumentBuilder", ".", "new", "do", "self", ".", "provider_id", "=", "provider_id", "end", ".", "document", "doc", ".", "present?", "?", "local_name", "(", "doc", ".", "id", ")", ":", "nil", "end" ]
Return the id of a document randomly selected from the search index. @param provider_id [String, nil] the id of the provider that the randomly selected document will belong to. @return [String, nil] the id of the randomly selected document. If none are available, gives `nil`
[ "Return", "the", "id", "of", "a", "document", "randomly", "selected", "from", "the", "search", "index", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/helpers/krikri/records_helper.rb#L11-L17
468
daytonn/architecture-js
lib/sprockets/lib/sprockets/pathname.rb
Sprockets.Pathname.find
def find(location, kind = :file) location = File.join(absolute_location, location) File.send("#{kind}?", location) ? Pathname.new(environment, location) : nil end
ruby
def find(location, kind = :file) location = File.join(absolute_location, location) File.send("#{kind}?", location) ? Pathname.new(environment, location) : nil end
[ "def", "find", "(", "location", ",", "kind", "=", ":file", ")", "location", "=", "File", ".", "join", "(", "absolute_location", ",", "location", ")", "File", ".", "send", "(", "\"#{kind}?\"", ",", "location", ")", "?", "Pathname", ".", "new", "(", "environment", ",", "location", ")", ":", "nil", "end" ]
Returns a Pathname for the location relative to this pathname's absolute location.
[ "Returns", "a", "Pathname", "for", "the", "location", "relative", "to", "this", "pathname", "s", "absolute", "location", "." ]
c0e891425e1a71b7eca21aa2513cff8b856636f0
https://github.com/daytonn/architecture-js/blob/c0e891425e1a71b7eca21aa2513cff8b856636f0/lib/sprockets/lib/sprockets/pathname.rb#L11-L14
469
dpla/KriKri
lib/krikri/search_results_helper_behavior.rb
Krikri.SearchResultsHelperBehavior.render_enriched_record
def render_enriched_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? JSON.pretty_generate(agg.to_jsonld['@graph']) end
ruby
def render_enriched_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? JSON.pretty_generate(agg.to_jsonld['@graph']) end
[ "def", "render_enriched_record", "(", "document", ")", "agg", "=", "document", ".", "aggregation", "return", "error_msg", "(", "'Aggregation not found.'", ")", "unless", "agg", ".", "present?", "JSON", ".", "pretty_generate", "(", "agg", ".", "to_jsonld", "[", "'@graph'", "]", ")", "end" ]
Render enriched record for view @param [Krikri::SearchIndexDocument] @return [String]
[ "Render", "enriched", "record", "for", "view" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_results_helper_behavior.rb#L25-L29
470
dpla/KriKri
lib/krikri/search_results_helper_behavior.rb
Krikri.SearchResultsHelperBehavior.render_original_record
def render_original_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? begin original_record = agg.original_record rescue StandardError => e logger.error e.message return error_msg(e.message) end return error_msg('Original record not found.') unless original_record.present? prettify_string(original_record.to_s, original_record.content_type) end
ruby
def render_original_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? begin original_record = agg.original_record rescue StandardError => e logger.error e.message return error_msg(e.message) end return error_msg('Original record not found.') unless original_record.present? prettify_string(original_record.to_s, original_record.content_type) end
[ "def", "render_original_record", "(", "document", ")", "agg", "=", "document", ".", "aggregation", "return", "error_msg", "(", "'Aggregation not found.'", ")", "unless", "agg", ".", "present?", "begin", "original_record", "=", "agg", ".", "original_record", "rescue", "StandardError", "=>", "e", "logger", ".", "error", "e", ".", "message", "return", "error_msg", "(", "e", ".", "message", ")", "end", "return", "error_msg", "(", "'Original record not found.'", ")", "unless", "original_record", ".", "present?", "prettify_string", "(", "original_record", ".", "to_s", ",", "original_record", ".", "content_type", ")", "end" ]
Render original record for view @param [Krikri::SearchIndexDocument] @return [String]
[ "Render", "original", "record", "for", "view" ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_results_helper_behavior.rb#L34-L48
471
KatanaCode/cookie_alert
app/controllers/cookie_alert/cookies_controller.rb
CookieAlert.CookiesController.cookie_accepted
def cookie_accepted # Get the visitor's current page URL or, if nil?, default to the application root. Resue block needed for bots visitor_current_url = begin cookies.signed[CookieAlert.config.cookie_name.to_sym].split(CookieAlert.config.cookie_value_text_separator)[1] rescue main_app.root_path end # Set the Cookie value to 'accepted' if CookieAlert.config.cookie_type == 'permanent' # Set a permanent cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' elsif CookieAlert.config.cookie_type == 'fixed_duration' # Set a fixed duration cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = { value: 'accepted', expires: CookieAlert.config.num_days_until_cookie_expires.days.from_now } else # Set a session cookie cookies.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' end # If the request is HTML then redirect the visitor back to their original page # If the request is javascript then render the javascript partial respond_to do |format| format.html { redirect_to(visitor_current_url) } format.js { render template: "cookie_alert/cookies/cookie_accepted" } end end
ruby
def cookie_accepted # Get the visitor's current page URL or, if nil?, default to the application root. Resue block needed for bots visitor_current_url = begin cookies.signed[CookieAlert.config.cookie_name.to_sym].split(CookieAlert.config.cookie_value_text_separator)[1] rescue main_app.root_path end # Set the Cookie value to 'accepted' if CookieAlert.config.cookie_type == 'permanent' # Set a permanent cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' elsif CookieAlert.config.cookie_type == 'fixed_duration' # Set a fixed duration cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = { value: 'accepted', expires: CookieAlert.config.num_days_until_cookie_expires.days.from_now } else # Set a session cookie cookies.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' end # If the request is HTML then redirect the visitor back to their original page # If the request is javascript then render the javascript partial respond_to do |format| format.html { redirect_to(visitor_current_url) } format.js { render template: "cookie_alert/cookies/cookie_accepted" } end end
[ "def", "cookie_accepted", "# Get the visitor's current page URL or, if nil?, default to the application root. Resue block needed for bots", "visitor_current_url", "=", "begin", "cookies", ".", "signed", "[", "CookieAlert", ".", "config", ".", "cookie_name", ".", "to_sym", "]", ".", "split", "(", "CookieAlert", ".", "config", ".", "cookie_value_text_separator", ")", "[", "1", "]", "rescue", "main_app", ".", "root_path", "end", "# Set the Cookie value to 'accepted'", "if", "CookieAlert", ".", "config", ".", "cookie_type", "==", "'permanent'", "# Set a permanent cookie", "cookies", ".", "permanent", ".", "signed", "[", "CookieAlert", ".", "config", ".", "cookie_name", ".", "to_sym", "]", "=", "'accepted'", "elsif", "CookieAlert", ".", "config", ".", "cookie_type", "==", "'fixed_duration'", "# Set a fixed duration cookie", "cookies", ".", "permanent", ".", "signed", "[", "CookieAlert", ".", "config", ".", "cookie_name", ".", "to_sym", "]", "=", "{", "value", ":", "'accepted'", ",", "expires", ":", "CookieAlert", ".", "config", ".", "num_days_until_cookie_expires", ".", "days", ".", "from_now", "}", "else", "# Set a session cookie", "cookies", ".", "signed", "[", "CookieAlert", ".", "config", ".", "cookie_name", ".", "to_sym", "]", "=", "'accepted'", "end", "# If the request is HTML then redirect the visitor back to their original page", "# If the request is javascript then render the javascript partial", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "(", "visitor_current_url", ")", "}", "format", ".", "js", "{", "render", "template", ":", "\"cookie_alert/cookies/cookie_accepted\"", "}", "end", "end" ]
Implement cookie acceptance when a visitor click the 'accept' button
[ "Implement", "cookie", "acceptance", "when", "a", "visitor", "click", "the", "accept", "button" ]
2b576deb563b1f5297cf867dd28879e47880ee21
https://github.com/KatanaCode/cookie_alert/blob/2b576deb563b1f5297cf867dd28879e47880ee21/app/controllers/cookie_alert/cookies_controller.rb#L7-L43
472
at1as/Terminal-Chess
lib/terminal_chess/board.rb
TerminalChess.Board.check?
def check?(color, proposed_manifest = @piece_locations, recurse_for_checkmate = false) enemy_attack_vectors = {} player_attack_vectors = {} king_loc = [] enemy_color = opposing_color(color) proposed_manifest.each do |piece, details| if details[:color] == enemy_color enemy_attack_vectors[piece] = possible_moves(piece, proposed_manifest) elsif details[:color] == color begin player_attack_vectors[piece] = possible_moves(piece, proposed_manifest) rescue # TODO: Fix possible_moves() so it doesn't throw exceptions # This happens because it is searching board for where pieces # will be, as as a result some pieces are nil end end king_loc = piece if details[:color] == color && details[:type] == :king end danger_vector = enemy_attack_vectors.values.flatten.uniq defence_vector = player_attack_vectors.values.flatten.uniq king_positions = possible_moves(king_loc, proposed_manifest) # The King is in the attackable locations by the opposing player return false unless danger_vector.include? king_loc # If all the positions the king piece can move to is also attackable by the opposing player if recurse_for_checkmate && (king_positions - danger_vector).empty? is_in_check = [] player_attack_vectors.each do |piece_index, piece_valid_moves| piece_valid_moves.each do |possible_new_location| # Check if board is still in check after piece moves to its new location @new_piece_locations = @piece_locations.clone @new_piece_locations[possible_new_location] = @new_piece_locations[piece_index] @new_piece_locations[piece_index] = { type: nil, number: nil, color: nil } is_in_check << check?(color, @new_piece_locations) end end return false if is_in_check.include?(false) @checkmate = true end true end
ruby
def check?(color, proposed_manifest = @piece_locations, recurse_for_checkmate = false) enemy_attack_vectors = {} player_attack_vectors = {} king_loc = [] enemy_color = opposing_color(color) proposed_manifest.each do |piece, details| if details[:color] == enemy_color enemy_attack_vectors[piece] = possible_moves(piece, proposed_manifest) elsif details[:color] == color begin player_attack_vectors[piece] = possible_moves(piece, proposed_manifest) rescue # TODO: Fix possible_moves() so it doesn't throw exceptions # This happens because it is searching board for where pieces # will be, as as a result some pieces are nil end end king_loc = piece if details[:color] == color && details[:type] == :king end danger_vector = enemy_attack_vectors.values.flatten.uniq defence_vector = player_attack_vectors.values.flatten.uniq king_positions = possible_moves(king_loc, proposed_manifest) # The King is in the attackable locations by the opposing player return false unless danger_vector.include? king_loc # If all the positions the king piece can move to is also attackable by the opposing player if recurse_for_checkmate && (king_positions - danger_vector).empty? is_in_check = [] player_attack_vectors.each do |piece_index, piece_valid_moves| piece_valid_moves.each do |possible_new_location| # Check if board is still in check after piece moves to its new location @new_piece_locations = @piece_locations.clone @new_piece_locations[possible_new_location] = @new_piece_locations[piece_index] @new_piece_locations[piece_index] = { type: nil, number: nil, color: nil } is_in_check << check?(color, @new_piece_locations) end end return false if is_in_check.include?(false) @checkmate = true end true end
[ "def", "check?", "(", "color", ",", "proposed_manifest", "=", "@piece_locations", ",", "recurse_for_checkmate", "=", "false", ")", "enemy_attack_vectors", "=", "{", "}", "player_attack_vectors", "=", "{", "}", "king_loc", "=", "[", "]", "enemy_color", "=", "opposing_color", "(", "color", ")", "proposed_manifest", ".", "each", "do", "|", "piece", ",", "details", "|", "if", "details", "[", ":color", "]", "==", "enemy_color", "enemy_attack_vectors", "[", "piece", "]", "=", "possible_moves", "(", "piece", ",", "proposed_manifest", ")", "elsif", "details", "[", ":color", "]", "==", "color", "begin", "player_attack_vectors", "[", "piece", "]", "=", "possible_moves", "(", "piece", ",", "proposed_manifest", ")", "rescue", "# TODO: Fix possible_moves() so it doesn't throw exceptions", "# This happens because it is searching board for where pieces", "# will be, as as a result some pieces are nil", "end", "end", "king_loc", "=", "piece", "if", "details", "[", ":color", "]", "==", "color", "&&", "details", "[", ":type", "]", "==", ":king", "end", "danger_vector", "=", "enemy_attack_vectors", ".", "values", ".", "flatten", ".", "uniq", "defence_vector", "=", "player_attack_vectors", ".", "values", ".", "flatten", ".", "uniq", "king_positions", "=", "possible_moves", "(", "king_loc", ",", "proposed_manifest", ")", "# The King is in the attackable locations by the opposing player", "return", "false", "unless", "danger_vector", ".", "include?", "king_loc", "# If all the positions the king piece can move to is also attackable by the opposing player", "if", "recurse_for_checkmate", "&&", "(", "king_positions", "-", "danger_vector", ")", ".", "empty?", "is_in_check", "=", "[", "]", "player_attack_vectors", ".", "each", "do", "|", "piece_index", ",", "piece_valid_moves", "|", "piece_valid_moves", ".", "each", "do", "|", "possible_new_location", "|", "# Check if board is still in check after piece moves to its new location", "@new_piece_locations", "=", "@piece_locations", ".", "clone", "@new_piece_locations", "[", "possible_new_location", "]", "=", "@new_piece_locations", "[", "piece_index", "]", "@new_piece_locations", "[", "piece_index", "]", "=", "{", "type", ":", "nil", ",", "number", ":", "nil", ",", "color", ":", "nil", "}", "is_in_check", "<<", "check?", "(", "color", ",", "@new_piece_locations", ")", "end", "end", "return", "false", "if", "is_in_check", ".", "include?", "(", "false", ")", "@checkmate", "=", "true", "end", "true", "end" ]
Return whether the player of a specified color has their king currently in check by checking the attack vectors of all the opponents players against the king location Also, check whether king currently in check, has all of their valid moves within their opponents attack vectors, and therefore are in checkmate (@checkmate)
[ "Return", "whether", "the", "player", "of", "a", "specified", "color", "has", "their", "king", "currently", "in", "check", "by", "checking", "the", "attack", "vectors", "of", "all", "the", "opponents", "players", "against", "the", "king", "location", "Also", "check", "whether", "king", "currently", "in", "check", "has", "all", "of", "their", "valid", "moves", "within", "their", "opponents", "attack", "vectors", "and", "therefore", "are", "in", "checkmate", "(" ]
330c03b6f9e730e93657b65be69e29046e5f37bc
https://github.com/at1as/Terminal-Chess/blob/330c03b6f9e730e93657b65be69e29046e5f37bc/lib/terminal_chess/board.rb#L194-L249
473
CryptoProcessing/cryptoprocessing.rb
lib/cryptoprocessing/models/account.rb
Cryptoprocessing.Account.transactions
def transactions(options = {}) agent.transactions(self['id'], options) do |data, resp| yield(data, resp) if block_given? end end
ruby
def transactions(options = {}) agent.transactions(self['id'], options) do |data, resp| yield(data, resp) if block_given? end end
[ "def", "transactions", "(", "options", "=", "{", "}", ")", "agent", ".", "transactions", "(", "self", "[", "'id'", "]", ",", "options", ")", "do", "|", "data", ",", "resp", "|", "yield", "(", "data", ",", "resp", ")", "if", "block_given?", "end", "end" ]
List of transactions
[ "List", "of", "transactions" ]
54cd6c697e47cd1124dd348e96b0f11facac9b79
https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/models/account.rb#L13-L17
474
CryptoProcessing/cryptoprocessing.rb
lib/cryptoprocessing/models/account.rb
Cryptoprocessing.Account.transactions_by_address
def transactions_by_address(address, options = {}) agent.transactions_by_address(self['id'], address, options) do |data, resp| yield(data, resp) if block_given? end end
ruby
def transactions_by_address(address, options = {}) agent.transactions_by_address(self['id'], address, options) do |data, resp| yield(data, resp) if block_given? end end
[ "def", "transactions_by_address", "(", "address", ",", "options", "=", "{", "}", ")", "agent", ".", "transactions_by_address", "(", "self", "[", "'id'", "]", ",", "address", ",", "options", ")", "do", "|", "data", ",", "resp", "|", "yield", "(", "data", ",", "resp", ")", "if", "block_given?", "end", "end" ]
List of transactions by address
[ "List", "of", "transactions", "by", "address" ]
54cd6c697e47cd1124dd348e96b0f11facac9b79
https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/models/account.rb#L20-L24
475
tlux/vnstat-ruby
lib/vnstat/interface_collection.rb
Vnstat.InterfaceCollection.[]
def [](id) interfaces_hash.fetch(id.to_s) do raise UnknownInterface.new(id.to_s), "Unknown interface: #{id}" end end
ruby
def [](id) interfaces_hash.fetch(id.to_s) do raise UnknownInterface.new(id.to_s), "Unknown interface: #{id}" end end
[ "def", "[]", "(", "id", ")", "interfaces_hash", ".", "fetch", "(", "id", ".", "to_s", ")", "do", "raise", "UnknownInterface", ".", "new", "(", "id", ".", "to_s", ")", ",", "\"Unknown interface: #{id}\"", "end", "end" ]
Returns traffic information for a certain interface. @param [String] id The name of the interface. @raise [UnknownInterface] An error that is raised if the specified interface is not tracked. @return [Interface]
[ "Returns", "traffic", "information", "for", "a", "certain", "interface", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/interface_collection.rb#L50-L55
476
mikemackintosh/ruby-easyrsa
lib/easyrsa/certificate.rb
EasyRSA.Certificate.gen_subject
def gen_subject subject_name = "/C=#{EasyRSA::Config.country}" subject_name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? subject_name += "/L=#{EasyRSA::Config.city}" subject_name += "/O=#{EasyRSA::Config.company}" subject_name += "/OU=#{EasyRSA::Config.orgunit}" subject_name += "/CN=#{@id}" subject_name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? subject_name += "/emailAddress=#{@email}" @cert.subject = OpenSSL::X509::Name.parse(subject_name) end
ruby
def gen_subject subject_name = "/C=#{EasyRSA::Config.country}" subject_name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? subject_name += "/L=#{EasyRSA::Config.city}" subject_name += "/O=#{EasyRSA::Config.company}" subject_name += "/OU=#{EasyRSA::Config.orgunit}" subject_name += "/CN=#{@id}" subject_name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? subject_name += "/emailAddress=#{@email}" @cert.subject = OpenSSL::X509::Name.parse(subject_name) end
[ "def", "gen_subject", "subject_name", "=", "\"/C=#{EasyRSA::Config.country}\"", "subject_name", "+=", "\"/ST=#{EasyRSA::Config.state}\"", "unless", "!", "EasyRSA", "::", "Config", ".", "state", "||", "EasyRSA", "::", "Config", ".", "state", ".", "empty?", "subject_name", "+=", "\"/L=#{EasyRSA::Config.city}\"", "subject_name", "+=", "\"/O=#{EasyRSA::Config.company}\"", "subject_name", "+=", "\"/OU=#{EasyRSA::Config.orgunit}\"", "subject_name", "+=", "\"/CN=#{@id}\"", "subject_name", "+=", "\"/name=#{EasyRSA::Config.name}\"", "unless", "!", "EasyRSA", "::", "Config", ".", "name", "||", "EasyRSA", "::", "Config", ".", "name", ".", "empty?", "subject_name", "+=", "\"/emailAddress=#{@email}\"", "@cert", ".", "subject", "=", "OpenSSL", "::", "X509", "::", "Name", ".", "parse", "(", "subject_name", ")", "end" ]
Cert subject for End-User
[ "Cert", "subject", "for", "End", "-", "User" ]
a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a
https://github.com/mikemackintosh/ruby-easyrsa/blob/a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a/lib/easyrsa/certificate.rb#L105-L116
477
tlux/vnstat-ruby
lib/vnstat/interface.rb
Vnstat.Interface.nick=
def nick=(nick) success = Utils.call_executable_returning_status( '-i', id, '--nick', nick, '--update' ) unless success raise Error, "Unable to set nickname for interface (#{id}). " \ 'Please make sure the vnstat daemon is not running while ' \ 'performing this operation.' end @nick = nick end
ruby
def nick=(nick) success = Utils.call_executable_returning_status( '-i', id, '--nick', nick, '--update' ) unless success raise Error, "Unable to set nickname for interface (#{id}). " \ 'Please make sure the vnstat daemon is not running while ' \ 'performing this operation.' end @nick = nick end
[ "def", "nick", "=", "(", "nick", ")", "success", "=", "Utils", ".", "call_executable_returning_status", "(", "'-i'", ",", "id", ",", "'--nick'", ",", "nick", ",", "'--update'", ")", "unless", "success", "raise", "Error", ",", "\"Unable to set nickname for interface (#{id}). \"", "'Please make sure the vnstat daemon is not running while '", "'performing this operation.'", "end", "@nick", "=", "nick", "end" ]
Sets the alias name for the interface. @raise [Error] Raised when a new nickname could not be set. @param [String] nick The alias name for the interface.
[ "Sets", "the", "alias", "name", "for", "the", "interface", "." ]
06939a65f8453b49b8bae749efcbe08ce86099e8
https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/interface.rb#L85-L95
478
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.open
def open # Create the background thread self.thread = Thread.new do EM.tick_loop do unless self.cmd_queue.empty? command = self.cmd_queue.pop self._execute_command(command) end end self.wamp.open end end
ruby
def open # Create the background thread self.thread = Thread.new do EM.tick_loop do unless self.cmd_queue.empty? command = self.cmd_queue.pop self._execute_command(command) end end self.wamp.open end end
[ "def", "open", "# Create the background thread", "self", ".", "thread", "=", "Thread", ".", "new", "do", "EM", ".", "tick_loop", "do", "unless", "self", ".", "cmd_queue", ".", "empty?", "command", "=", "self", ".", "cmd_queue", ".", "pop", "self", ".", "_execute_command", "(", "command", ")", "end", "end", "self", ".", "wamp", ".", "open", "end", "end" ]
Constructor for creating a client. Options are @param options [Hash] The different options to pass to the connection @option options [String] :name - The name of the WAMP Client @option options [WampClient::Connection] :wamp - Allows a different WAMP to be passed in @option options [String] :uri The uri of the WAMP router to connect to @option options [String] :realm The realm to connect to @option options [String, nil] :protocol The protocol (default if wamp.2.json) @option options [String, nil] :authid The id to authenticate with @option options [Array, nil] :authmethods The different auth methods that the client supports @option options [Hash] :headers Custom headers to include during the connection @option options [WampClient::Serializer::Base] :serializer The serializer to use (default is json) Opens the connection
[ "Constructor", "for", "creating", "a", "client", ".", "Options", "are" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L95-L106
479
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.add_procedure
def add_procedure(procedure, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_procedure" must be called BEFORE "open"') if self.thread self.registrations << WampRails::Command::Register.new(procedure, klass, options, self) end
ruby
def add_procedure(procedure, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_procedure" must be called BEFORE "open"') if self.thread self.registrations << WampRails::Command::Register.new(procedure, klass, options, self) end
[ "def", "add_procedure", "(", "procedure", ",", "klass", ",", "options", "=", "nil", ")", "options", "||=", "{", "}", "raise", "WampRails", "::", "Error", ".", "new", "(", "'\"add_procedure\" must be called BEFORE \"open\"'", ")", "if", "self", ".", "thread", "self", ".", "registrations", "<<", "WampRails", "::", "Command", "::", "Register", ".", "new", "(", "procedure", ",", "klass", ",", "options", ",", "self", ")", "end" ]
Adds a procedure to the client
[ "Adds", "a", "procedure", "to", "the", "client" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L125-L129
480
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.add_subscription
def add_subscription(topic, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_subscription" must be called BEFORE "open"') if self.thread self.subscriptions << WampRails::Command::Subscribe.new(topic, klass, options, self) end
ruby
def add_subscription(topic, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_subscription" must be called BEFORE "open"') if self.thread self.subscriptions << WampRails::Command::Subscribe.new(topic, klass, options, self) end
[ "def", "add_subscription", "(", "topic", ",", "klass", ",", "options", "=", "nil", ")", "options", "||=", "{", "}", "raise", "WampRails", "::", "Error", ".", "new", "(", "'\"add_subscription\" must be called BEFORE \"open\"'", ")", "if", "self", ".", "thread", "self", ".", "subscriptions", "<<", "WampRails", "::", "Command", "::", "Subscribe", ".", "new", "(", "topic", ",", "klass", ",", "options", ",", "self", ")", "end" ]
Adds a subscription to the client
[ "Adds", "a", "subscription", "to", "the", "client" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L132-L136
481
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.call
def call(procedure, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Call.new(procedure, args, kwargs, options, self) self._queue_command(command, callback) end
ruby
def call(procedure, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Call.new(procedure, args, kwargs, options, self) self._queue_command(command, callback) end
[ "def", "call", "(", "procedure", ",", "args", "=", "nil", ",", "kwargs", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "callback", ")", "command", "=", "WampRails", "::", "Command", "::", "Call", ".", "new", "(", "procedure", ",", "args", ",", "kwargs", ",", "options", ",", "self", ")", "self", ".", "_queue_command", "(", "command", ",", "callback", ")", "end" ]
endregion region WAMP Methods Performs a WAMP call @note This method is blocking if the callback is not nil
[ "endregion", "region", "WAMP", "Methods", "Performs", "a", "WAMP", "call" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L144-L147
482
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.publish
def publish(topic, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Publish.new(topic, args, kwargs, options, self) self._queue_command(command, callback) end
ruby
def publish(topic, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Publish.new(topic, args, kwargs, options, self) self._queue_command(command, callback) end
[ "def", "publish", "(", "topic", ",", "args", "=", "nil", ",", "kwargs", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "callback", ")", "command", "=", "WampRails", "::", "Command", "::", "Publish", ".", "new", "(", "topic", ",", "args", ",", "kwargs", ",", "options", ",", "self", ")", "self", ".", "_queue_command", "(", "command", ",", "callback", ")", "end" ]
Performs a WAMP publish @note This method is blocking if the callback is not nil
[ "Performs", "a", "WAMP", "publish" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L151-L154
483
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.register
def register(procedure, klass, options={}, &callback) command = WampRails::Command::Register.new(procedure, klass, options, self) self._queue_command(command, callback) end
ruby
def register(procedure, klass, options={}, &callback) command = WampRails::Command::Register.new(procedure, klass, options, self) self._queue_command(command, callback) end
[ "def", "register", "(", "procedure", ",", "klass", ",", "options", "=", "{", "}", ",", "&", "callback", ")", "command", "=", "WampRails", "::", "Command", "::", "Register", ".", "new", "(", "procedure", ",", "klass", ",", "options", ",", "self", ")", "self", ".", "_queue_command", "(", "command", ",", "callback", ")", "end" ]
Performs a WAMP register @note This method is blocking if the callback is not nil
[ "Performs", "a", "WAMP", "register" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L158-L161
484
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client.subscribe
def subscribe(topic, klass, options={}, &callback) command = WampRails::Command::Subscribe.new(topic, klass, options, self) self._queue_command(command, callback) end
ruby
def subscribe(topic, klass, options={}, &callback) command = WampRails::Command::Subscribe.new(topic, klass, options, self) self._queue_command(command, callback) end
[ "def", "subscribe", "(", "topic", ",", "klass", ",", "options", "=", "{", "}", ",", "&", "callback", ")", "command", "=", "WampRails", "::", "Command", "::", "Subscribe", ".", "new", "(", "topic", ",", "klass", ",", "options", ",", "self", ")", "self", ".", "_queue_command", "(", "command", ",", "callback", ")", "end" ]
Performs a WAMP subscribe @note This method is blocking if the callback is not nil
[ "Performs", "a", "WAMP", "subscribe" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L165-L168
485
ericchapman/ruby_wamp_rails
lib/wamp_rails/client.rb
WampRails.Client._queue_command
def _queue_command(command, callback=nil) # If the current thread is the EM thread, execute the command. Else put it in the queue if self.thread == Thread.current self._execute_command(command) else self.cmd_queue.push(command) end # If the callback is defined, block until it finishes if callback callback_args = command.queue.pop callback.call(callback_args.result, callback_args.error, callback_args.details) end end
ruby
def _queue_command(command, callback=nil) # If the current thread is the EM thread, execute the command. Else put it in the queue if self.thread == Thread.current self._execute_command(command) else self.cmd_queue.push(command) end # If the callback is defined, block until it finishes if callback callback_args = command.queue.pop callback.call(callback_args.result, callback_args.error, callback_args.details) end end
[ "def", "_queue_command", "(", "command", ",", "callback", "=", "nil", ")", "# If the current thread is the EM thread, execute the command. Else put it in the queue", "if", "self", ".", "thread", "==", "Thread", ".", "current", "self", ".", "_execute_command", "(", "command", ")", "else", "self", ".", "cmd_queue", ".", "push", "(", "command", ")", "end", "# If the callback is defined, block until it finishes", "if", "callback", "callback_args", "=", "command", ".", "queue", ".", "pop", "callback", ".", "call", "(", "callback_args", ".", "result", ",", "callback_args", ".", "error", ",", "callback_args", ".", "details", ")", "end", "end" ]
endregion region Private Methods Queues the command and blocks it the callback is not nil @param [WampRails::Command::Base] - The command to queue @param [Block] - The block to call when complete
[ "endregion", "region", "Private", "Methods", "Queues", "the", "command", "and", "blocks", "it", "the", "callback", "is", "not", "nil" ]
026672c759448d73348ac0e315ae8fbf35f51b9f
https://github.com/ericchapman/ruby_wamp_rails/blob/026672c759448d73348ac0e315ae8fbf35f51b9f/lib/wamp_rails/client.rb#L177-L191
486
elastics/elastics
elastics-admin/lib/elastics/admin_live_reindex.rb
Elastics.LiveReindex.track_external_change
def track_external_change(app_id, action, document) return unless Conf.redis Conf.redis.rpush("#{KEYS[:changes]}-#{app_id}", MultiJson.encode([action, document])) end
ruby
def track_external_change(app_id, action, document) return unless Conf.redis Conf.redis.rpush("#{KEYS[:changes]}-#{app_id}", MultiJson.encode([action, document])) end
[ "def", "track_external_change", "(", "app_id", ",", "action", ",", "document", ")", "return", "unless", "Conf", ".", "redis", "Conf", ".", "redis", ".", "rpush", "(", "\"#{KEYS[:changes]}-#{app_id}\"", ",", "MultiJson", ".", "encode", "(", "[", "action", ",", "document", "]", ")", ")", "end" ]
use this method when you are tracking the change of another app you must pass the app_id of the app being affected by the change
[ "use", "this", "method", "when", "you", "are", "tracking", "the", "change", "of", "another", "app", "you", "must", "pass", "the", "app_id", "of", "the", "app", "being", "affected", "by", "the", "change" ]
85517ec32fd30d3bb4b80223dc103fed482e4a3d
https://github.com/elastics/elastics/blob/85517ec32fd30d3bb4b80223dc103fed482e4a3d/elastics-admin/lib/elastics/admin_live_reindex.rb#L106-L109
487
appium/appium_doc_lint
lib/appium_doc_lint/lint.rb
Appium.Lint.report
def report data return nil if data.nil? || data.empty? result = '' data.each do |file_name, analysis| rel_path = File.join('.', File.expand_path(file_name).sub(Dir.pwd, '')) result += "\n#{rel_path}\n" analysis.each do |line_number, warning| result += " #{line_number}: #{warning.join(',')}\n" end end result.strip! result.empty? ? nil : result end
ruby
def report data return nil if data.nil? || data.empty? result = '' data.each do |file_name, analysis| rel_path = File.join('.', File.expand_path(file_name).sub(Dir.pwd, '')) result += "\n#{rel_path}\n" analysis.each do |line_number, warning| result += " #{line_number}: #{warning.join(',')}\n" end end result.strip! result.empty? ? nil : result end
[ "def", "report", "data", "return", "nil", "if", "data", ".", "nil?", "||", "data", ".", "empty?", "result", "=", "''", "data", ".", "each", "do", "|", "file_name", ",", "analysis", "|", "rel_path", "=", "File", ".", "join", "(", "'.'", ",", "File", ".", "expand_path", "(", "file_name", ")", ".", "sub", "(", "Dir", ".", "pwd", ",", "''", ")", ")", "result", "+=", "\"\\n#{rel_path}\\n\"", "analysis", ".", "each", "do", "|", "line_number", ",", "warning", "|", "result", "+=", "\" #{line_number}: #{warning.join(',')}\\n\"", "end", "end", "result", ".", "strip!", "result", ".", "empty?", "?", "nil", ":", "result", "end" ]
Format data into a report
[ "Format", "data", "into", "a", "report" ]
7774d7d382da6afe594a64188b198b52bb1dfe14
https://github.com/appium/appium_doc_lint/blob/7774d7d382da6afe594a64188b198b52bb1dfe14/lib/appium_doc_lint/lint.rb#L82-L95
488
scryptmouse/dux
lib/dux/blankness.rb
Dux.Blankness.blankish?
def blankish?(value) case value when nil, false true when Dux[:nan?] true when String, Symbol value.empty? || value =~ WHITESPACE_ONLY when Dux[:blank?] value.blank? when Hash value.empty? when Array, Enumerable Dux.attempt(value, :empty?) || value.all? { |val| blankish?(val) } when Dux[:empty?] value.empty? else false end end
ruby
def blankish?(value) case value when nil, false true when Dux[:nan?] true when String, Symbol value.empty? || value =~ WHITESPACE_ONLY when Dux[:blank?] value.blank? when Hash value.empty? when Array, Enumerable Dux.attempt(value, :empty?) || value.all? { |val| blankish?(val) } when Dux[:empty?] value.empty? else false end end
[ "def", "blankish?", "(", "value", ")", "case", "value", "when", "nil", ",", "false", "true", "when", "Dux", "[", ":nan?", "]", "true", "when", "String", ",", "Symbol", "value", ".", "empty?", "||", "value", "=~", "WHITESPACE_ONLY", "when", "Dux", "[", ":blank?", "]", "value", ".", "blank?", "when", "Hash", "value", ".", "empty?", "when", "Array", ",", "Enumerable", "Dux", ".", "attempt", "(", "value", ",", ":empty?", ")", "||", "value", ".", "all?", "{", "|", "val", "|", "blankish?", "(", "val", ")", "}", "when", "Dux", "[", ":empty?", "]", "value", ".", "empty?", "else", "false", "end", "end" ]
Check if a provided object is semantically empty. @param [Object] value
[ "Check", "if", "a", "provided", "object", "is", "semantically", "empty", "." ]
94a9b05fcfede36369e93d9c3a339365e55dc38a
https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/blankness.rb#L15-L34
489
dpla/KriKri
lib/krikri/qa_query_client.rb
Krikri.QAQueryClient.build_optional_patterns
def build_optional_patterns(predicates) return [[TYPE, predicates, VALUE]] unless predicates.is_a? Enumerable var1 = TYPE patterns = predicates.each_with_object([]) do |predicate, ps| var2 = (ps.count == predicates.size - 1) ? VALUE : "obj#{ps.count}".to_sym ps << [var1, predicate, var2] var1 = var2 end end
ruby
def build_optional_patterns(predicates) return [[TYPE, predicates, VALUE]] unless predicates.is_a? Enumerable var1 = TYPE patterns = predicates.each_with_object([]) do |predicate, ps| var2 = (ps.count == predicates.size - 1) ? VALUE : "obj#{ps.count}".to_sym ps << [var1, predicate, var2] var1 = var2 end end
[ "def", "build_optional_patterns", "(", "predicates", ")", "return", "[", "[", "TYPE", ",", "predicates", ",", "VALUE", "]", "]", "unless", "predicates", ".", "is_a?", "Enumerable", "var1", "=", "TYPE", "patterns", "=", "predicates", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "predicate", ",", "ps", "|", "var2", "=", "(", "ps", ".", "count", "==", "predicates", ".", "size", "-", "1", ")", "?", "VALUE", ":", "\"obj#{ps.count}\"", ".", "to_sym", "ps", "<<", "[", "var1", ",", "predicate", ",", "var2", "]", "var1", "=", "var2", "end", "end" ]
Builds patterns matching a predicate or chain of predicates given, assigning an unbound variable to each set of matches and passing it to the next pattern. @param predicates [#to_uri, Array<#to_uri>] a predicate or list of predicates to build patterns against. @return [Array<Array<#to_term>>] An array of pattern arrays @see RDF::Query @see RDF::Query::Pattern
[ "Builds", "patterns", "matching", "a", "predicate", "or", "chain", "of", "predicates", "given", "assigning", "an", "unbound", "variable", "to", "each", "set", "of", "matches", "and", "passing", "it", "to", "the", "next", "pattern", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/qa_query_client.rb#L141-L152
490
at1as/Terminal-Chess
lib/terminal_chess/move.rb
TerminalChess.Move.possible_moves
def possible_moves(p1, manifest, castling = false) return [] if manifest[p1][:type].nil? allowed = [] type = manifest[p1][:type] my_color = manifest[p1][:color] constants(manifest, my_color, type) return [] if unoccupied?(p1) if type == :king allowed += [move_lateral(p1, 1)].flatten allowed += [move_diagonal(p1, 1)].flatten allowed += [castle(p1)].flatten if castling elsif type == :queen allowed += [move_lateral(p1)].flatten allowed += [move_diagonal(p1)].flatten elsif type == :rook allowed += [move_lateral(p1)].flatten elsif type == :bishop allowed += [move_diagonal(p1)].flatten elsif type == :pawn allowed += [move_pawn(p1)].flatten elsif type == :knight allowed += [move_knight(p1)].flatten end allowed end
ruby
def possible_moves(p1, manifest, castling = false) return [] if manifest[p1][:type].nil? allowed = [] type = manifest[p1][:type] my_color = manifest[p1][:color] constants(manifest, my_color, type) return [] if unoccupied?(p1) if type == :king allowed += [move_lateral(p1, 1)].flatten allowed += [move_diagonal(p1, 1)].flatten allowed += [castle(p1)].flatten if castling elsif type == :queen allowed += [move_lateral(p1)].flatten allowed += [move_diagonal(p1)].flatten elsif type == :rook allowed += [move_lateral(p1)].flatten elsif type == :bishop allowed += [move_diagonal(p1)].flatten elsif type == :pawn allowed += [move_pawn(p1)].flatten elsif type == :knight allowed += [move_knight(p1)].flatten end allowed end
[ "def", "possible_moves", "(", "p1", ",", "manifest", ",", "castling", "=", "false", ")", "return", "[", "]", "if", "manifest", "[", "p1", "]", "[", ":type", "]", ".", "nil?", "allowed", "=", "[", "]", "type", "=", "manifest", "[", "p1", "]", "[", ":type", "]", "my_color", "=", "manifest", "[", "p1", "]", "[", ":color", "]", "constants", "(", "manifest", ",", "my_color", ",", "type", ")", "return", "[", "]", "if", "unoccupied?", "(", "p1", ")", "if", "type", "==", ":king", "allowed", "+=", "[", "move_lateral", "(", "p1", ",", "1", ")", "]", ".", "flatten", "allowed", "+=", "[", "move_diagonal", "(", "p1", ",", "1", ")", "]", ".", "flatten", "allowed", "+=", "[", "castle", "(", "p1", ")", "]", ".", "flatten", "if", "castling", "elsif", "type", "==", ":queen", "allowed", "+=", "[", "move_lateral", "(", "p1", ")", "]", ".", "flatten", "allowed", "+=", "[", "move_diagonal", "(", "p1", ")", "]", ".", "flatten", "elsif", "type", "==", ":rook", "allowed", "+=", "[", "move_lateral", "(", "p1", ")", "]", ".", "flatten", "elsif", "type", "==", ":bishop", "allowed", "+=", "[", "move_diagonal", "(", "p1", ")", "]", ".", "flatten", "elsif", "type", "==", ":pawn", "allowed", "+=", "[", "move_pawn", "(", "p1", ")", "]", ".", "flatten", "elsif", "type", "==", ":knight", "allowed", "+=", "[", "move_knight", "(", "p1", ")", "]", ".", "flatten", "end", "allowed", "end" ]
Calls methods below to return a list of positions which are valid moves for piece at index p1, given the current board layout as defined in manifest
[ "Calls", "methods", "below", "to", "return", "a", "list", "of", "positions", "which", "are", "valid", "moves", "for", "piece", "at", "index", "p1", "given", "the", "current", "board", "layout", "as", "defined", "in", "manifest" ]
330c03b6f9e730e93657b65be69e29046e5f37bc
https://github.com/at1as/Terminal-Chess/blob/330c03b6f9e730e93657b65be69e29046e5f37bc/lib/terminal_chess/move.rb#L22-L56
491
at1as/Terminal-Chess
lib/terminal_chess/move.rb
TerminalChess.Move.move_pawn
def move_pawn(p1) col = get_col_from_index(p1) valid = [] # Piece color defines direction of travel. Enemy presence defines # the validity of diagonal movements if Move.color == :red valid << (p1 - 8) if unoccupied?(p1 - 8) valid << (p1 - 7) if piece_color(p1 - 7) == Move.enemy_color && col < 8 valid << (p1 - 9) if piece_color(p1 - 9) == Move.enemy_color && col > 1 # Only if the pieces is unmoved, can it move forward two rows valid << (p1 - 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 - 8) && unoccupied?(p1 - 16) elsif Move.color == :black valid << (p1 + 8) if unoccupied?(p1 + 8) valid << (p1 + 7) if piece_color(p1 + 7) == Move.enemy_color && col > 1 valid << (p1 + 9) if piece_color(p1 + 9) == Move.enemy_color && col < 8 valid << (p1 + 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 + 8) && unoccupied?(p1 + 16) end valid end
ruby
def move_pawn(p1) col = get_col_from_index(p1) valid = [] # Piece color defines direction of travel. Enemy presence defines # the validity of diagonal movements if Move.color == :red valid << (p1 - 8) if unoccupied?(p1 - 8) valid << (p1 - 7) if piece_color(p1 - 7) == Move.enemy_color && col < 8 valid << (p1 - 9) if piece_color(p1 - 9) == Move.enemy_color && col > 1 # Only if the pieces is unmoved, can it move forward two rows valid << (p1 - 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 - 8) && unoccupied?(p1 - 16) elsif Move.color == :black valid << (p1 + 8) if unoccupied?(p1 + 8) valid << (p1 + 7) if piece_color(p1 + 7) == Move.enemy_color && col > 1 valid << (p1 + 9) if piece_color(p1 + 9) == Move.enemy_color && col < 8 valid << (p1 + 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 + 8) && unoccupied?(p1 + 16) end valid end
[ "def", "move_pawn", "(", "p1", ")", "col", "=", "get_col_from_index", "(", "p1", ")", "valid", "=", "[", "]", "# Piece color defines direction of travel. Enemy presence defines", "# the validity of diagonal movements", "if", "Move", ".", "color", "==", ":red", "valid", "<<", "(", "p1", "-", "8", ")", "if", "unoccupied?", "(", "p1", "-", "8", ")", "valid", "<<", "(", "p1", "-", "7", ")", "if", "piece_color", "(", "p1", "-", "7", ")", "==", "Move", ".", "enemy_color", "&&", "col", "<", "8", "valid", "<<", "(", "p1", "-", "9", ")", "if", "piece_color", "(", "p1", "-", "9", ")", "==", "Move", ".", "enemy_color", "&&", "col", ">", "1", "# Only if the pieces is unmoved, can it move forward two rows", "valid", "<<", "(", "p1", "-", "16", ")", "if", "!", "Move", ".", "pieces", "[", "p1", "]", "[", ":moved", "]", "&&", "unoccupied?", "(", "p1", "-", "8", ")", "&&", "unoccupied?", "(", "p1", "-", "16", ")", "elsif", "Move", ".", "color", "==", ":black", "valid", "<<", "(", "p1", "+", "8", ")", "if", "unoccupied?", "(", "p1", "+", "8", ")", "valid", "<<", "(", "p1", "+", "7", ")", "if", "piece_color", "(", "p1", "+", "7", ")", "==", "Move", ".", "enemy_color", "&&", "col", ">", "1", "valid", "<<", "(", "p1", "+", "9", ")", "if", "piece_color", "(", "p1", "+", "9", ")", "==", "Move", ".", "enemy_color", "&&", "col", "<", "8", "valid", "<<", "(", "p1", "+", "16", ")", "if", "!", "Move", ".", "pieces", "[", "p1", "]", "[", ":moved", "]", "&&", "unoccupied?", "(", "p1", "+", "8", ")", "&&", "unoccupied?", "(", "p1", "+", "16", ")", "end", "valid", "end" ]
Returns all valid positions a pawn at index p1 can move to
[ "Returns", "all", "valid", "positions", "a", "pawn", "at", "index", "p1", "can", "move", "to" ]
330c03b6f9e730e93657b65be69e29046e5f37bc
https://github.com/at1as/Terminal-Chess/blob/330c03b6f9e730e93657b65be69e29046e5f37bc/lib/terminal_chess/move.rb#L59-L81
492
at1as/Terminal-Chess
lib/terminal_chess/move.rb
TerminalChess.Move.move_knight
def move_knight(p1) row = get_row_from_index(p1) col = get_col_from_index(p1) valid = [] valid_moves_no_friendly_fire = [] # Valid knight moves based on its board position valid << (p1 + 17) if row < 7 && col < 8 valid << (p1 + 15) if row < 7 && col > 1 valid << (p1 + 10) if row < 8 && col < 7 valid << (p1 + 6) if row < 8 && col > 2 valid << (p1 - 6) if row > 1 && col < 7 valid << (p1 - 10) if row > 1 && col > 2 valid << (p1 - 15) if row > 2 && col < 8 valid << (p1 - 17) if row > 2 && col > 1 # All possible moves for the knight based on board boundaries will added # This iterator filters for friendly fire, and removes indexes pointing to same color pices valid.each do |pos| valid_moves_no_friendly_fire << pos unless piece_color(pos) == Move.color end valid_moves_no_friendly_fire end
ruby
def move_knight(p1) row = get_row_from_index(p1) col = get_col_from_index(p1) valid = [] valid_moves_no_friendly_fire = [] # Valid knight moves based on its board position valid << (p1 + 17) if row < 7 && col < 8 valid << (p1 + 15) if row < 7 && col > 1 valid << (p1 + 10) if row < 8 && col < 7 valid << (p1 + 6) if row < 8 && col > 2 valid << (p1 - 6) if row > 1 && col < 7 valid << (p1 - 10) if row > 1 && col > 2 valid << (p1 - 15) if row > 2 && col < 8 valid << (p1 - 17) if row > 2 && col > 1 # All possible moves for the knight based on board boundaries will added # This iterator filters for friendly fire, and removes indexes pointing to same color pices valid.each do |pos| valid_moves_no_friendly_fire << pos unless piece_color(pos) == Move.color end valid_moves_no_friendly_fire end
[ "def", "move_knight", "(", "p1", ")", "row", "=", "get_row_from_index", "(", "p1", ")", "col", "=", "get_col_from_index", "(", "p1", ")", "valid", "=", "[", "]", "valid_moves_no_friendly_fire", "=", "[", "]", "# Valid knight moves based on its board position", "valid", "<<", "(", "p1", "+", "17", ")", "if", "row", "<", "7", "&&", "col", "<", "8", "valid", "<<", "(", "p1", "+", "15", ")", "if", "row", "<", "7", "&&", "col", ">", "1", "valid", "<<", "(", "p1", "+", "10", ")", "if", "row", "<", "8", "&&", "col", "<", "7", "valid", "<<", "(", "p1", "+", "6", ")", "if", "row", "<", "8", "&&", "col", ">", "2", "valid", "<<", "(", "p1", "-", "6", ")", "if", "row", ">", "1", "&&", "col", "<", "7", "valid", "<<", "(", "p1", "-", "10", ")", "if", "row", ">", "1", "&&", "col", ">", "2", "valid", "<<", "(", "p1", "-", "15", ")", "if", "row", ">", "2", "&&", "col", "<", "8", "valid", "<<", "(", "p1", "-", "17", ")", "if", "row", ">", "2", "&&", "col", ">", "1", "# All possible moves for the knight based on board boundaries will added", "# This iterator filters for friendly fire, and removes indexes pointing to same color pices", "valid", ".", "each", "do", "|", "pos", "|", "valid_moves_no_friendly_fire", "<<", "pos", "unless", "piece_color", "(", "pos", ")", "==", "Move", ".", "color", "end", "valid_moves_no_friendly_fire", "end" ]
Returns valid positions a knight at index p1 can move to
[ "Returns", "valid", "positions", "a", "knight", "at", "index", "p1", "can", "move", "to" ]
330c03b6f9e730e93657b65be69e29046e5f37bc
https://github.com/at1as/Terminal-Chess/blob/330c03b6f9e730e93657b65be69e29046e5f37bc/lib/terminal_chess/move.rb#L84-L108
493
jgoizueta/acts_as_scd
lib/acts_as_scd/class_methods.rb
ActsAsScd.ClassMethods.find_by_identity
def find_by_identity(identity, at_date=nil) # (at_date.nil? ? current : at(at_date)).where(IDENTITY_COLUMN=>identity).first if at_date.nil? q = current else q = at(at_date) end q = q.where(IDENTITY_COLUMN=>identity) q.first end
ruby
def find_by_identity(identity, at_date=nil) # (at_date.nil? ? current : at(at_date)).where(IDENTITY_COLUMN=>identity).first if at_date.nil? q = current else q = at(at_date) end q = q.where(IDENTITY_COLUMN=>identity) q.first end
[ "def", "find_by_identity", "(", "identity", ",", "at_date", "=", "nil", ")", "# (at_date.nil? ? current : at(at_date)).where(IDENTITY_COLUMN=>identity).first", "if", "at_date", ".", "nil?", "q", "=", "current", "else", "q", "=", "at", "(", "at_date", ")", "end", "q", "=", "q", ".", "where", "(", "IDENTITY_COLUMN", "=>", "identity", ")", "q", ".", "first", "end" ]
Note that find_by_identity will return nil if there's not a current iteration of the identity
[ "Note", "that", "find_by_identity", "will", "return", "nil", "if", "there", "s", "not", "a", "current", "iteration", "of", "the", "identity" ]
29d01a673e24d42d2471f5b8e6f6fa92d82d6bda
https://github.com/jgoizueta/acts_as_scd/blob/29d01a673e24d42d2471f5b8e6f6fa92d82d6bda/lib/acts_as_scd/class_methods.rb#L60-L69
494
jgoizueta/acts_as_scd
lib/acts_as_scd/class_methods.rb
ActsAsScd.ClassMethods.create_identity
def create_identity(attributes, start=nil) start ||= START_OF_TIME create(attributes.merge(START_COLUMN=>start || START_OF_TIME)) end
ruby
def create_identity(attributes, start=nil) start ||= START_OF_TIME create(attributes.merge(START_COLUMN=>start || START_OF_TIME)) end
[ "def", "create_identity", "(", "attributes", ",", "start", "=", "nil", ")", "start", "||=", "START_OF_TIME", "create", "(", "attributes", ".", "merge", "(", "START_COLUMN", "=>", "start", "||", "START_OF_TIME", ")", ")", "end" ]
The first iteration can be defined with a specific start date, but that is in general a bad idea, since it complicates obtaining the first iteration
[ "The", "first", "iteration", "can", "be", "defined", "with", "a", "specific", "start", "date", "but", "that", "is", "in", "general", "a", "bad", "idea", "since", "it", "complicates", "obtaining", "the", "first", "iteration" ]
29d01a673e24d42d2471f5b8e6f6fa92d82d6bda
https://github.com/jgoizueta/acts_as_scd/blob/29d01a673e24d42d2471f5b8e6f6fa92d82d6bda/lib/acts_as_scd/class_methods.rb#L78-L81
495
mikemackintosh/ruby-easyrsa
lib/easyrsa/ca.rb
EasyRSA.CA.gen_issuer
def gen_issuer name = "/C=#{EasyRSA::Config.country}" name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? name += "/L=#{EasyRSA::Config.city}" name += "/O=#{EasyRSA::Config.company}" name += "/OU=#{EasyRSA::Config.orgunit}" name += "/CN=#{EasyRSA::Config.server}" name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? name += "/name=#{EasyRSA::Config.orgunit}" if !EasyRSA::Config.name || EasyRSA::Config.name.empty? name += "/emailAddress=#{EasyRSA::Config.email}" @ca_cert.issuer = OpenSSL::X509::Name.parse(name) end
ruby
def gen_issuer name = "/C=#{EasyRSA::Config.country}" name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? name += "/L=#{EasyRSA::Config.city}" name += "/O=#{EasyRSA::Config.company}" name += "/OU=#{EasyRSA::Config.orgunit}" name += "/CN=#{EasyRSA::Config.server}" name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? name += "/name=#{EasyRSA::Config.orgunit}" if !EasyRSA::Config.name || EasyRSA::Config.name.empty? name += "/emailAddress=#{EasyRSA::Config.email}" @ca_cert.issuer = OpenSSL::X509::Name.parse(name) end
[ "def", "gen_issuer", "name", "=", "\"/C=#{EasyRSA::Config.country}\"", "name", "+=", "\"/ST=#{EasyRSA::Config.state}\"", "unless", "!", "EasyRSA", "::", "Config", ".", "state", "||", "EasyRSA", "::", "Config", ".", "state", ".", "empty?", "name", "+=", "\"/L=#{EasyRSA::Config.city}\"", "name", "+=", "\"/O=#{EasyRSA::Config.company}\"", "name", "+=", "\"/OU=#{EasyRSA::Config.orgunit}\"", "name", "+=", "\"/CN=#{EasyRSA::Config.server}\"", "name", "+=", "\"/name=#{EasyRSA::Config.name}\"", "unless", "!", "EasyRSA", "::", "Config", ".", "name", "||", "EasyRSA", "::", "Config", ".", "name", ".", "empty?", "name", "+=", "\"/name=#{EasyRSA::Config.orgunit}\"", "if", "!", "EasyRSA", "::", "Config", ".", "name", "||", "EasyRSA", "::", "Config", ".", "name", ".", "empty?", "name", "+=", "\"/emailAddress=#{EasyRSA::Config.email}\"", "@ca_cert", ".", "issuer", "=", "OpenSSL", "::", "X509", "::", "Name", ".", "parse", "(", "name", ")", "end" ]
Cert issuer details
[ "Cert", "issuer", "details" ]
a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a
https://github.com/mikemackintosh/ruby-easyrsa/blob/a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a/lib/easyrsa/ca.rb#L71-L83
496
mikemackintosh/ruby-easyrsa
lib/easyrsa/ca.rb
EasyRSA.CA.add_extensions
def add_extensions ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = @ca_cert ef.issuer_certificate = @ca_cert @ca_cert.add_extension ef.create_extension('subjectKeyIdentifier', 'hash') @ca_cert.add_extension ef.create_extension('basicConstraints', 'CA:TRUE', true) @ca_cert.add_extension ef.create_extension('keyUsage', 'cRLSign,keyCertSign', true) end
ruby
def add_extensions ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = @ca_cert ef.issuer_certificate = @ca_cert @ca_cert.add_extension ef.create_extension('subjectKeyIdentifier', 'hash') @ca_cert.add_extension ef.create_extension('basicConstraints', 'CA:TRUE', true) @ca_cert.add_extension ef.create_extension('keyUsage', 'cRLSign,keyCertSign', true) end
[ "def", "add_extensions", "ef", "=", "OpenSSL", "::", "X509", "::", "ExtensionFactory", ".", "new", "ef", ".", "subject_certificate", "=", "@ca_cert", "ef", ".", "issuer_certificate", "=", "@ca_cert", "@ca_cert", ".", "add_extension", "ef", ".", "create_extension", "(", "'subjectKeyIdentifier'", ",", "'hash'", ")", "@ca_cert", ".", "add_extension", "ef", ".", "create_extension", "(", "'basicConstraints'", ",", "'CA:TRUE'", ",", "true", ")", "@ca_cert", ".", "add_extension", "ef", ".", "create_extension", "(", "'keyUsage'", ",", "'cRLSign,keyCertSign'", ",", "true", ")", "end" ]
Add Extensions needed
[ "Add", "Extensions", "needed" ]
a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a
https://github.com/mikemackintosh/ruby-easyrsa/blob/a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a/lib/easyrsa/ca.rb#L86-L95
497
arkes/sorting_table_for
lib/sorting_table_for/table_builder.rb
SortingTableFor.TableBuilder.render_tbody
def render_tbody if @lines and @lines.size > 0 return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join))) return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' })) end '' end
ruby
def render_tbody if @lines and @lines.size > 0 return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join))) return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' })) end '' end
[ "def", "render_tbody", "if", "@lines", "and", "@lines", ".", "size", ">", "0", "return", "Tools", "::", "html_safe", "(", "content_tag", "(", ":tbody", ",", "render_total_entries", "+", "Tools", "::", "html_safe", "(", "@lines", ".", "collect", "{", "|", "line", "|", "line", ".", "render_line", "}", ".", "join", ")", ")", ")", "return", "Tools", "::", "html_safe", "(", "content_tag", "(", ":tr", ",", "content_tag", "(", ":td", ",", "I18n", ".", "t", "(", ":total_entries", ",", ":scope", "=>", ":sorting_table_for", ",", ":value", "=>", "total_entries", ")", ",", "{", ":colspan", "=>", "max_cells", "}", ")", ",", "{", ":class", "=>", "'total-entries'", "}", ")", ")", "end", "''", "end" ]
Return the balise tbody and its content
[ "Return", "the", "balise", "tbody", "and", "its", "content" ]
cfc41f033ed1babd9b3536cd63ef854eafb6e94e
https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/table_builder.rb#L599-L605
498
arkes/sorting_table_for
lib/sorting_table_for/table_builder.rb
SortingTableFor.TableBuilder.render_total_entries
def render_total_entries if self.show_total_entries total_entries = @collection.total_entries rescue @collection.size header_total_cells = @header_line ? @header_line.total_cells : 0 max_cells = (@lines.first.total_cells > header_total_cells) ? @lines.first.total_cells : header_total_cells return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' })) end '' end
ruby
def render_total_entries if self.show_total_entries total_entries = @collection.total_entries rescue @collection.size header_total_cells = @header_line ? @header_line.total_cells : 0 max_cells = (@lines.first.total_cells > header_total_cells) ? @lines.first.total_cells : header_total_cells return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' })) end '' end
[ "def", "render_total_entries", "if", "self", ".", "show_total_entries", "total_entries", "=", "@collection", ".", "total_entries", "rescue", "@collection", ".", "size", "header_total_cells", "=", "@header_line", "?", "@header_line", ".", "total_cells", ":", "0", "max_cells", "=", "(", "@lines", ".", "first", ".", "total_cells", ">", "header_total_cells", ")", "?", "@lines", ".", "first", ".", "total_cells", ":", "header_total_cells", "return", "Tools", "::", "html_safe", "(", "content_tag", "(", ":tr", ",", "content_tag", "(", ":td", ",", "I18n", ".", "t", "(", ":total_entries", ",", ":value", "=>", "total_entries", ")", ",", "{", ":colspan", "=>", "max_cells", "}", ")", ",", "{", ":class", "=>", "'total-entries'", "}", ")", ")", "end", "''", "end" ]
Calculate the total entries Return a tr and td with a colspan of total entries
[ "Calculate", "the", "total", "entries", "Return", "a", "tr", "and", "td", "with", "a", "colspan", "of", "total", "entries" ]
cfc41f033ed1babd9b3536cd63ef854eafb6e94e
https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/table_builder.rb#L627-L635
499
dpla/KriKri
lib/krikri/search_index.rb
Krikri.SearchIndex.bulk_update_from_activity
def bulk_update_from_activity(activity) all_aggs = entities_as_json_hashes(activity) agg_batches = bulk_update_batches(all_aggs) agg_batches.each do |batch| index_with_error_handling(activity) { bulk_add(batch) } end end
ruby
def bulk_update_from_activity(activity) all_aggs = entities_as_json_hashes(activity) agg_batches = bulk_update_batches(all_aggs) agg_batches.each do |batch| index_with_error_handling(activity) { bulk_add(batch) } end end
[ "def", "bulk_update_from_activity", "(", "activity", ")", "all_aggs", "=", "entities_as_json_hashes", "(", "activity", ")", "agg_batches", "=", "bulk_update_batches", "(", "all_aggs", ")", "agg_batches", ".", "each", "do", "|", "batch", "|", "index_with_error_handling", "(", "activity", ")", "{", "bulk_add", "(", "batch", ")", "}", "end", "end" ]
Given an activity, use the bulk-update method to load its revised entities into the search index. Any errors on bulk adds are caught and logged, and the batch is skipped. @param activity [Krikri::Activity]
[ "Given", "an", "activity", "use", "the", "bulk", "-", "update", "method", "to", "load", "its", "revised", "entities", "into", "the", "search", "index", "." ]
0ac26e60ce1bba60caa40263a562796267cf833f
https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_index.rb#L56-L62